mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): settle interrupted lifecycle states and prune terminated instances (#8779)
* fix(ec2): settle interrupted lifecycle states and prune terminated instances * fix(ec2): address review findings on lifecycle recovery and pruning * test(ec2): use Awaitility in the EC2 lifecycle tests
This commit is contained in:
1 parent
39cdaa5075
commit
90b6d46317
8 files changed
+1187
-54
No files matched your search
@@ -0,0 +1,356 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.RemoveContainerCmd;
|
||||
import com.github.dockerjava.api.command.StopContainerCmd;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLiveness;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.testing.StorageFactories;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.ACCOUNT;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.REGION;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.config;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.instance;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.manager;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.persistedState;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.persistedTerminatedAt;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.seed;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Answers.RETURNS_SELF;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The EC2 lifecycle against persisted state. Every test runs a real {@link Ec2Service} and
|
||||
* {@link Ec2ContainerManager} over real persistent storage, with only Docker mocked, and judges
|
||||
* the outcome by the records on disk and by what DescribeInstances returns, so a state that was
|
||||
* changed in memory and never written is a failure.
|
||||
*/
|
||||
class Ec2LifecycleRecoveryTest {
|
||||
|
||||
private static final long WAIT_SECONDS = 10;
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private final List<Node> nodes = new ArrayList<>();
|
||||
|
||||
@AfterEach
|
||||
void stopNodes() {
|
||||
nodes.forEach(node -> node.manager.stop());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminationReachesTheStoreAsTerminatedWithTheTimeItHappened() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-terminate", InstanceState.running(), "container-terminate"));
|
||||
Node node = startNode();
|
||||
|
||||
node.service.terminateInstances(REGION, List.of("i-terminate"));
|
||||
|
||||
awaitPersisted("i-terminate", "terminated");
|
||||
assertTrue(persistedTerminatedAt(dir, "i-terminate") > 0, "the retention clock must be on disk");
|
||||
assertEquals("terminated", describedState(node, "i-terminate"));
|
||||
verify(node.docker).removeContainerCmd("container-terminate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaunchThatFailsIsStampedWhenItTerminates() {
|
||||
Instance launching = instance("i-failed-launch", InstanceState.pending(), null);
|
||||
Node node = startNode();
|
||||
|
||||
assertTrue(node.manager.cancelLaunch(launching));
|
||||
|
||||
assertEquals("terminated", launching.getState().getName());
|
||||
assertTrue(launching.getTerminatedAt() > 0, "a failed launch must start its retention clock");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceLeftShuttingDownIsTerminatedOnTheNextStart() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-shutting", InstanceState.shuttingDown(), "container-shutting"));
|
||||
|
||||
Node node = startNode();
|
||||
|
||||
awaitPersisted("i-shutting", "terminated");
|
||||
assertTrue(persistedTerminatedAt(dir, "i-shutting") > 0);
|
||||
assertEquals("terminated", describedState(node, "i-shutting"));
|
||||
verify(node.docker, timeout(WAIT_SECONDS * 1000)).removeContainerCmd("container-shutting");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProcessKilledWhileTearingDownLeavesNothingStuck() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-killed", InstanceState.running(), "container-killed"));
|
||||
CountDownLatch removing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Node first = startNode(new Options().removing(remove -> doAnswer(call -> {
|
||||
removing.countDown();
|
||||
release.await(WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
return null;
|
||||
}).when(remove).exec()));
|
||||
|
||||
first.service.terminateInstances(REGION, List.of("i-killed"));
|
||||
assertTrue(removing.await(WAIT_SECONDS, TimeUnit.SECONDS), "the teardown must be under way");
|
||||
awaitPersisted("i-killed", "shutting-down");
|
||||
|
||||
// The first process never gets to finish: a second one starts on the same files.
|
||||
Node second = startNode();
|
||||
try {
|
||||
awaitPersisted("i-killed", "terminated");
|
||||
assertTrue(persistedTerminatedAt(dir, "i-killed") > 0);
|
||||
assertEquals("terminated", describedState(second, "i-killed"));
|
||||
} finally {
|
||||
release.countDown();
|
||||
// Let the first process finish its teardown before the directory it writes to is removed.
|
||||
await().atMost(Duration.ofSeconds(WAIT_SECONDS)).pollInterval(Duration.ofMillis(100))
|
||||
.untilAsserted(() -> assertEquals("terminated", describedState(first, "i-killed"),
|
||||
"the first process to finish its teardown"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLaunchThatNeverCreatedAContainerEndsTerminatedOnTheNextStart() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-no-container", InstanceState.pending(), null));
|
||||
|
||||
Node node = startNode();
|
||||
|
||||
awaitPersisted("i-no-container", "terminated");
|
||||
assertTrue(persistedTerminatedAt(dir, "i-no-container") > 0);
|
||||
assertEquals("terminated", describedState(node, "i-no-container"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPendingInstanceWhoseContainerIsRunningIsRunningOnTheNextStart() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-pending-up", InstanceState.pending(), "container-pending-up"));
|
||||
|
||||
Node node = startNode(new Options().registered());
|
||||
|
||||
awaitPersisted("i-pending-up", "running");
|
||||
assertEquals("running", describedState(node, "i-pending-up"));
|
||||
verify(node.docker, never()).removeContainerCmd(anyString());
|
||||
verify(node.docker, never()).stopContainerCmd(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPendingInstanceWhoseContainerIsNotRunningIsStoppedNotDiscarded() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-pending-down", InstanceState.pending(), "container-pending-down"));
|
||||
|
||||
Node node = startNode();
|
||||
|
||||
awaitPersisted("i-pending-down", "stopped");
|
||||
assertEquals("stopped", describedState(node, "i-pending-down"));
|
||||
verify(node.docker, never()).removeContainerCmd(anyString());
|
||||
verify(node.docker).stopContainerCmd("container-pending-down");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceLeftStoppingIsStoppedOnTheNextStart() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-stopping", InstanceState.stopping(), "container-stopping"));
|
||||
|
||||
Node node = startNode();
|
||||
|
||||
awaitPersisted("i-stopping", "stopped");
|
||||
assertEquals("stopped", describedState(node, "i-stopping"));
|
||||
verify(node.docker).stopContainerCmd("container-stopping");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = ContainerLiveness.class, names = {"RUNNING", "UNKNOWN"})
|
||||
void aStopThatCannotBeConfirmedLeavesTheInstanceInItsTransitionalState(ContainerLiveness liveness) throws Exception {
|
||||
seed(config(dir, false, true),
|
||||
ACCOUNT,
|
||||
instance("i-pending-unconfirmed", InstanceState.pending(), "container-pending-unconfirmed"),
|
||||
instance("i-stopping-unconfirmed", InstanceState.stopping(), "container-stopping-unconfirmed"));
|
||||
|
||||
Node node = startNode(new Options().liveness(liveness).stopFailing());
|
||||
|
||||
verify(node.docker).stopContainerCmd("container-pending-unconfirmed");
|
||||
verify(node.docker).stopContainerCmd("container-stopping-unconfirmed");
|
||||
assertEquals("pending", persistedState(dir, "i-pending-unconfirmed"),
|
||||
"a container that may still be running must not be recorded as stopped");
|
||||
assertEquals("stopping", persistedState(dir, "i-stopping-unconfirmed"));
|
||||
assertEquals("pending", describedState(node, "i-pending-unconfirmed"));
|
||||
assertEquals("stopping", describedState(node, "i-stopping-unconfirmed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceThatCannotBeSettledDoesNotStopTheOthersBeingSettled() throws Exception {
|
||||
seed(config(dir, false, true),
|
||||
ACCOUNT,
|
||||
instance("i-cannot-settle", InstanceState.stopping(), "container-cannot-settle"),
|
||||
instance("i-settles", InstanceState.shuttingDown(), "container-settles"));
|
||||
|
||||
Node node = startNode(new Options().beforeStartup(spied -> doThrow(new IllegalStateException("docker is unreachable"))
|
||||
.when(spied).stopForShutdown(argThat(candidate -> "i-cannot-settle".equals(candidate.getInstanceId())))));
|
||||
|
||||
awaitPersisted("i-settles", "terminated");
|
||||
assertEquals("stopping", persistedState(dir, "i-cannot-settle"), "it is left as it was, for the next start");
|
||||
assertEquals("stopping", describedState(node, "i-cannot-settle"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminatedRecordWrittenWithoutATimeGetsItOnTheNextStart() throws Exception {
|
||||
Instance untimed = instance("i-untimed", InstanceState.terminated(), null);
|
||||
Instance timed = instance("i-timed", InstanceState.terminated(), null);
|
||||
timed.setTerminatedAt(1_700_000_000_000L);
|
||||
seed(config(dir, false, true), ACCOUNT, untimed, timed);
|
||||
|
||||
startNode();
|
||||
|
||||
assertTrue(persistedTerminatedAt(dir, "i-untimed") > 0, "an untimed record must start its clock");
|
||||
assertEquals(1_700_000_000_000L, persistedTerminatedAt(dir, "i-timed"), "a timed record keeps its time");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCleanupStepThatThrowsDoesNotSkipTheContainerRemovalAndTheInstanceEndsTerminated() throws Exception {
|
||||
seed(config(dir, false, true), ACCOUNT, instance("i-throws", InstanceState.running(), "container-throws"));
|
||||
Node node = startNode();
|
||||
doThrow(new IllegalStateException("port forwards are gone")).when(node.portForwards).unpublishAll(any());
|
||||
|
||||
node.service.terminateInstances(REGION, List.of("i-throws"));
|
||||
|
||||
awaitPersisted("i-throws", "terminated");
|
||||
assertTrue(persistedTerminatedAt(dir, "i-throws") > 0);
|
||||
verify(node.docker).removeContainerCmd("container-throws");
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeInstancesAreLeftAloneByAStart() throws Exception {
|
||||
seed(config(dir, false, true),
|
||||
ACCOUNT,
|
||||
instance("i-running", InstanceState.running(), null),
|
||||
instance("i-stopped", InstanceState.stopped(), "container-stopped"));
|
||||
|
||||
Node node = startNode();
|
||||
|
||||
assertEquals("running", describedState(node, "i-running"));
|
||||
assertEquals("stopped", describedState(node, "i-stopped"));
|
||||
assertEquals("running", persistedState(dir, "i-running"));
|
||||
assertEquals("stopped", persistedState(dir, "i-stopped"));
|
||||
}
|
||||
|
||||
private Node startNode() {
|
||||
return startNode(new Options());
|
||||
}
|
||||
|
||||
private Node startNode(Options options) {
|
||||
Node node = new Node(options);
|
||||
nodes.add(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** What a test changes about the process it starts; everything else is a quiet mock. */
|
||||
private static final class Options {
|
||||
private Consumer<RemoveContainerCmd> removeBehaviour;
|
||||
private boolean registered;
|
||||
private ContainerLiveness liveness = ContainerLiveness.NOT_RUNNING;
|
||||
private boolean stopFails;
|
||||
private Consumer<Ec2ContainerManager> beforeStartup;
|
||||
|
||||
Options removing(Consumer<RemoveContainerCmd> behaviour) {
|
||||
this.removeBehaviour = behaviour;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The restore loop re-registers a running container for pending records. */
|
||||
Options registered() {
|
||||
this.registered = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
Options liveness(ContainerLiveness liveness) {
|
||||
this.liveness = liveness;
|
||||
return this;
|
||||
}
|
||||
|
||||
Options stopFailing() {
|
||||
this.stopFails = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
Options beforeStartup(Consumer<Ec2ContainerManager> setup) {
|
||||
this.beforeStartup = setup;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/** One Floci process over the shared directory: loads the stored records and runs its startup. */
|
||||
private final class Node {
|
||||
final DockerClient docker = mock(DockerClient.class);
|
||||
final Ec2PortForwardManager portForwards = mock(Ec2PortForwardManager.class);
|
||||
final Ec2ContainerManager manager;
|
||||
final Ec2Service service;
|
||||
|
||||
Node(Options options) {
|
||||
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
|
||||
if (options.removeBehaviour != null) {
|
||||
options.removeBehaviour.accept(remove);
|
||||
}
|
||||
when(docker.removeContainerCmd(anyString())).thenReturn(remove);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
|
||||
if (options.stopFails) {
|
||||
doThrow(new IllegalStateException("docker is unreachable")).when(stop).exec();
|
||||
}
|
||||
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
|
||||
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycle.probeContainer(anyString())).thenReturn(options.liveness);
|
||||
EmulatorConfig config = config(dir, false, true);
|
||||
manager = spy(manager(config, docker, lifecycle, portForwards));
|
||||
doReturn(options.registered).when(manager).restoreMetadataRegistration(any());
|
||||
if (options.beforeStartup != null) {
|
||||
options.beforeStartup.accept(manager);
|
||||
}
|
||||
service = new Ec2Service(config, manager, portForwards, mock(AmiImageResolver.class),
|
||||
mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
StorageFactories.open(config, "persistent"));
|
||||
service.restoreMetadataRegistrations();
|
||||
}
|
||||
}
|
||||
|
||||
private static String describedState(Node node, String id) {
|
||||
return node.service.describeInstances(REGION, List.of(id), Map.of()).getFirst().getInstances().getFirst()
|
||||
.getState().getName();
|
||||
}
|
||||
|
||||
private void awaitPersisted(String id, String state) {
|
||||
await().atMost(Duration.ofSeconds(WAIT_SECONDS)).pollInterval(Duration.ofMillis(100))
|
||||
.untilAsserted(() -> assertEquals(state, readState(id), "the stored record of " + id));
|
||||
}
|
||||
|
||||
private String readState(String id) {
|
||||
try {
|
||||
return persistedState(dir, id);
|
||||
} catch (IOException e) {
|
||||
return "unreadable: " + e.getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.RemoveContainerCmd;
|
||||
import com.github.dockerjava.api.command.StopContainerCmd;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.services.ec2.model.VolumeAttachment;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.testing.StorageFactories;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.ACCOUNT;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.REGION;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.config;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.instance;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.manager;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.persistedRecord;
|
||||
import static io.floci.aws.testing.Ec2LifecycleFixtures.seed;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Answers.RETURNS_SELF;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Terminated instances stay listed for an hour and are then removed, as the EC2 documentation
|
||||
* promises. Each test judges the stored records on disk and what DescribeInstances returns.
|
||||
*/
|
||||
class Ec2TerminatedInstanceRetentionTest {
|
||||
|
||||
private static final String OTHER_ACCOUNT = "111111111111";
|
||||
private static final Instant NOW = Instant.parse("2026-11-16T12:00:00Z");
|
||||
private static final long WAIT_SECONDS = 10;
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void aTerminatedInstanceIsListedUntilTheRetentionPassesThenRemovedFromTheStore() throws Exception {
|
||||
seed(config(dir, true, true), ACCOUNT, terminated("i-expiring", NOW.minus(Duration.ofMinutes(30))));
|
||||
Ec2Service service = service();
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Duration.ofMinutes(29)));
|
||||
assertTrue(listed(service, "i-expiring"), "still inside the hour");
|
||||
assertNotNull(persisted("i-expiring"));
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Duration.ofMinutes(31)));
|
||||
assertFalse(listed(service, "i-expiring"), "past the hour");
|
||||
assertNull(persisted("i-expiring"), "and gone from the stored records");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRetentionIsExactlyOneHour() throws Exception {
|
||||
seed(config(dir, true, true), ACCOUNT, terminated("i-boundary", NOW));
|
||||
Ec2Service service = service();
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Ec2Service.TERMINATED_INSTANCE_RETENTION));
|
||||
assertNotNull(persisted("i-boundary"), "the hour itself has not passed yet");
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Ec2Service.TERMINATED_INSTANCE_RETENTION).plusMillis(1));
|
||||
assertNull(persisted("i-boundary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeInstancesAreNeverPruned() throws Exception {
|
||||
List<Instance> active = new ArrayList<>();
|
||||
for (InstanceState state : List.of(InstanceState.pending(), InstanceState.running(),
|
||||
InstanceState.stopping(), InstanceState.stopped(), InstanceState.shuttingDown())) {
|
||||
// The ancient time is on purpose: only a terminated record may be removed for age.
|
||||
Instance instance = instance("i-" + state.getName(), state, null);
|
||||
instance.setTerminatedAt(NOW.minus(Duration.ofDays(30)).toEpochMilli());
|
||||
active.add(instance);
|
||||
}
|
||||
seed(config(dir, true, true), ACCOUNT, active.toArray(new Instance[0]));
|
||||
Ec2Service service = service();
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Duration.ofDays(3650)));
|
||||
|
||||
for (Instance instance : active) {
|
||||
assertNotNull(persisted(instance.getInstanceId()), instance.getInstanceId() + " must survive");
|
||||
assertTrue(listed(service, instance.getInstanceId()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminatedRecordWithNoTimeIsNeverPrunedForAge() throws Exception {
|
||||
seed(config(dir, true, true), ACCOUNT, instance("i-untimed", InstanceState.terminated(), null));
|
||||
Ec2Service service = service();
|
||||
|
||||
service.pruneTerminatedInstances(NOW.plus(Duration.ofDays(3650)));
|
||||
|
||||
assertNotNull(persisted("i-untimed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pruningRemovesEveryAccountsExpiredInstancesAndTheirTags() throws Exception {
|
||||
EmulatorConfig config = config(dir, true, true);
|
||||
seed(config, ACCOUNT, terminated("i-default", NOW.minus(Duration.ofHours(2))));
|
||||
seed(config, OTHER_ACCOUNT, terminated("i-other", NOW.minus(Duration.ofHours(2))),
|
||||
terminated("i-other-fresh", NOW.minus(Duration.ofMinutes(5))));
|
||||
Ec2Service service = service();
|
||||
service.createTags(REGION, List.of("i-default"), List.of(new Tag("env", "qa")));
|
||||
|
||||
service.pruneTerminatedInstances(NOW);
|
||||
|
||||
assertNull(persisted("i-default"));
|
||||
assertNull(persisted("i-other"), "another account's expired instance is removed too");
|
||||
assertNotNull(persisted("i-other-fresh"), "and its fresh one is kept");
|
||||
assertTrue(service.resourceTags(REGION, "i-default").isEmpty());
|
||||
assertFalse(Files.readString(dir.resolve("ec2-tags.json")).contains("i-default"),
|
||||
"the tags are gone from the stored records");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pruningReleasesTheVolumesAFailedLaunchLeftAttached() throws Exception {
|
||||
seed(config(dir, true, true), ACCOUNT, terminated("i-gone", NOW.minus(Duration.ofHours(2))));
|
||||
seedVolume("vol-left-attached", "i-gone");
|
||||
Ec2Service service = service();
|
||||
|
||||
service.pruneTerminatedInstances(NOW);
|
||||
|
||||
JsonNode volume = persistedRecord(dir, "ec2-volumes.json", "vol-left-attached");
|
||||
assertEquals("available", volume.path("state").asText());
|
||||
assertEquals(0, volume.path("attachments").size(), "no attachment may point at a removed instance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailureRemovingOneInstanceDoesNotBlockTheOthersAndIsReportedToTheCaller() throws Exception {
|
||||
seed(config(dir, true, true), ACCOUNT,
|
||||
terminated("i-good-1", NOW.minus(Duration.ofHours(2))),
|
||||
terminated("i-bad", NOW.minus(Duration.ofHours(2))),
|
||||
terminated("i-good-2", NOW.minus(Duration.ofHours(2))));
|
||||
Ec2Service service = spy(service());
|
||||
doThrow(new IllegalStateException("the attached volumes cannot be released")).when(service)
|
||||
.pruneTerminatedInstance(argThat((AccountAwareStorageBackend.AccountEntry<Instance> entry) ->
|
||||
"i-bad".equals(entry.value().getInstanceId())));
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> service.pruneTerminatedInstances(NOW));
|
||||
|
||||
assertTrue(failure.getMessage().contains("i-bad"), failure.getMessage());
|
||||
assertNull(persisted("i-good-1"), "one record failing must not keep the others from expiring");
|
||||
assertNull(persisted("i-good-2"));
|
||||
assertNotNull(persisted("i-bad"), "the failed record stays, to be tried again on the next sweep");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSchedulerPrunesThroughTheServiceOnEachSweep() throws Exception {
|
||||
EmulatorConfig config = config(dir, true, true);
|
||||
seed(config, ACCOUNT, terminated("i-swept", NOW.minus(Duration.ofHours(2))),
|
||||
terminated("i-recent", NOW.minusSeconds(60)));
|
||||
Ec2TerminatedInstanceScheduler scheduler = new Ec2TerminatedInstanceScheduler(service(config), config);
|
||||
|
||||
assertTrue(scheduler.active(), "a background sweep exists while EC2 is enabled");
|
||||
scheduler.tick(NOW);
|
||||
|
||||
assertNull(persisted("i-swept"));
|
||||
assertNotNull(persisted("i-recent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSchedulerHasNoBackgroundSweepWhileEc2IsDisabled() {
|
||||
EmulatorConfig config = config(dir, true, false);
|
||||
|
||||
assertFalse(new Ec2TerminatedInstanceScheduler(service(config), config).active());
|
||||
}
|
||||
|
||||
@Test
|
||||
void markTerminatedStartsTheClockOnceAndKeepsTheFirstTime() {
|
||||
Instance instance = instance("i-clock", InstanceState.running(), null);
|
||||
|
||||
instance.markTerminated(1_000L);
|
||||
instance.markTerminated(9_000L);
|
||||
|
||||
assertEquals("terminated", instance.getState().getName());
|
||||
assertEquals(1_000L, instance.getTerminatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedLaunchIsWrittenBackToTheStoreWhenItTerminates() {
|
||||
List<Instance> written = new ArrayList<>();
|
||||
Ec2ContainerManager manager = quietManager();
|
||||
manager.setPersister(written::add);
|
||||
Instance launching = instance("i-failed-launch", InstanceState.pending(), null);
|
||||
|
||||
assertTrue(manager.cancelLaunch(launching));
|
||||
|
||||
assertEquals(List.of(launching), written, "the terminal state must be handed to the store");
|
||||
assertEquals("terminated", written.getFirst().getState().getName());
|
||||
assertTrue(written.getFirst().getTerminatedAt() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteThatFailsIsRetriedSoTheStoredStateDoesNotStayStale() {
|
||||
List<String> written = new ArrayList<>();
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
Ec2ContainerManager manager = quietManager();
|
||||
manager.setPersister(instance -> {
|
||||
if (calls.getAndIncrement() == 0) {
|
||||
throw new IllegalStateException("the store is busy");
|
||||
}
|
||||
written.add(instance.getState().getName());
|
||||
});
|
||||
|
||||
assertTrue(manager.cancelLaunch(instance("i-retried", InstanceState.pending(), null)));
|
||||
|
||||
assertEquals(List.of("terminated"), written, "the first write failed and must be made again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOlderSnapshotIsNeverTheLastStateWritten() throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
when(docker.stopContainerCmd(anyString())).thenReturn(mock(StopContainerCmd.class, RETURNS_SELF));
|
||||
when(docker.removeContainerCmd(anyString())).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
|
||||
Ec2ContainerManager manager = manager(config(dir, true, false), docker,
|
||||
mock(ContainerLifecycleManager.class), mock(Ec2PortForwardManager.class));
|
||||
List<String> written = new CopyOnWriteArrayList<>();
|
||||
CountDownLatch stopSnapshotTaken = new CountDownLatch(1);
|
||||
CountDownLatch commitTheStopSnapshot = new CountDownLatch(1);
|
||||
AtomicInteger writes = new AtomicInteger();
|
||||
// A store that, like the write-ahead log, takes its snapshot of the instance first and
|
||||
// commits it later, so a slow writer can commit an older snapshot after a newer one.
|
||||
manager.setPersister(instance -> {
|
||||
String snapshot = instance.getState().getName();
|
||||
if (writes.getAndIncrement() == 0) {
|
||||
stopSnapshotTaken.countDown();
|
||||
try {
|
||||
commitTheStopSnapshot.await(WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
written.add(snapshot);
|
||||
});
|
||||
Instance instance = instance("i-race", InstanceState.running(), "container-race");
|
||||
try {
|
||||
manager.stop(instance);
|
||||
assertTrue(stopSnapshotTaken.await(WAIT_SECONDS, TimeUnit.SECONDS), "the stop's write must be waiting");
|
||||
manager.terminate(instance, null);
|
||||
await().atMost(Duration.ofSeconds(WAIT_SECONDS)).pollInterval(Duration.ofMillis(100))
|
||||
.untilAsserted(() -> assertTrue(written.contains("terminated"),
|
||||
() -> "the termination to be written, but the writes were " + written));
|
||||
|
||||
commitTheStopSnapshot.countDown();
|
||||
|
||||
await().atMost(Duration.ofSeconds(WAIT_SECONDS)).pollInterval(Duration.ofMillis(100))
|
||||
.untilAsserted(() -> assertTrue(written.size() >= 2 && "terminated".equals(written.getLast()),
|
||||
() -> "the last write to be the termination, but the writes were " + written));
|
||||
} finally {
|
||||
manager.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private Ec2ContainerManager quietManager() {
|
||||
return manager(config(dir, true, false), mock(DockerClient.class),
|
||||
mock(ContainerLifecycleManager.class), mock(Ec2PortForwardManager.class));
|
||||
}
|
||||
|
||||
private Ec2Service service() {
|
||||
return service(config(dir, true, true));
|
||||
}
|
||||
|
||||
private Ec2Service service(EmulatorConfig config) {
|
||||
return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
StorageFactories.open(config, "persistent"));
|
||||
}
|
||||
|
||||
private void seedVolume(String volumeId, String instanceId) {
|
||||
StorageFactory factory = StorageFactories.open(config(dir, true, true), "persistent");
|
||||
try {
|
||||
AccountAwareStorageBackend<Volume> store = factory.create(
|
||||
"ec2", "ec2-volumes.json", new TypeReference<Map<String, Volume>>() { });
|
||||
Volume volume = new Volume();
|
||||
volume.setVolumeId(volumeId);
|
||||
volume.setRegion(REGION);
|
||||
volume.setState("in-use");
|
||||
VolumeAttachment attachment = new VolumeAttachment();
|
||||
attachment.setInstanceId(instanceId);
|
||||
attachment.setDevice("/dev/sdf");
|
||||
attachment.setState("attached");
|
||||
volume.getAttachments().add(attachment);
|
||||
store.put(REGION + "::" + volumeId, volume);
|
||||
} finally {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
private static Instance terminated(String id, Instant at) {
|
||||
Instance instance = instance(id, InstanceState.terminated(), null);
|
||||
instance.setTerminatedAt(at.toEpochMilli());
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static boolean listed(Ec2Service service, String id) {
|
||||
return service.describeInstances(REGION, List.of(), Map.of()).stream()
|
||||
.flatMap(reservation -> reservation.getInstances().stream())
|
||||
.anyMatch(instance -> id.equals(instance.getInstanceId()));
|
||||
}
|
||||
|
||||
private JsonNode persisted(String id) throws IOException {
|
||||
return persistedRecord(dir, "ec2-instances.json", id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.DockerHostResolver;
|
||||
import io.floci.aws.core.common.docker.PortAllocator;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.ContainerNetworkReachability;
|
||||
import io.floci.aws.services.ec2.Ec2ContainerManager;
|
||||
import io.floci.aws.services.ec2.Ec2MetadataServer;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Shared setup for the EC2 lifecycle tests, which run a real {@link Ec2ContainerManager} (and
|
||||
* usually a real {@code Ec2Service}) over real persistent storage with only Docker mocked, and judge
|
||||
* the outcome by the records on disk.
|
||||
*/
|
||||
public final class Ec2LifecycleFixtures {
|
||||
|
||||
public static final String ACCOUNT = "000000000000";
|
||||
public static final String REGION = "us-east-1";
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private Ec2LifecycleFixtures() {
|
||||
}
|
||||
|
||||
/** Persistent storage under {@code dir} for {@link #ACCOUNT}, with EC2 in mock or container mode. */
|
||||
public static EmulatorConfig config(Path dir, boolean mock, boolean enabled) {
|
||||
EmulatorConfig config = StorageFactories.config(dir, ACCOUNT);
|
||||
when(config.services().ec2().mock()).thenReturn(mock);
|
||||
when(config.services().ec2().enabled()).thenReturn(enabled);
|
||||
return config;
|
||||
}
|
||||
|
||||
/** A manager whose collaborators are mocks, except the three a test cares about. */
|
||||
public static Ec2ContainerManager manager(EmulatorConfig config, DockerClient docker,
|
||||
ContainerLifecycleManager lifecycle,
|
||||
Ec2PortForwardManager portForwards) {
|
||||
return new Ec2ContainerManager(
|
||||
mock(ContainerBuilder.class), lifecycle, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), mock(DockerHostResolver.class), docker,
|
||||
mock(PortAllocator.class), config, mock(Ec2MetadataServer.class), portForwards,
|
||||
mock(RegionResolver.class), mock(ContainerNetworkReachability.class),
|
||||
mock(VpcNetworkManager.class), mock(ContainerReachableEndpoint.class));
|
||||
}
|
||||
|
||||
public static Instance instance(String id, InstanceState state, String containerId) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(id);
|
||||
instance.setRegion(REGION);
|
||||
instance.setState(state);
|
||||
instance.setDockerContainerId(containerId);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** Writes {@code instances} to the EC2 instance store of {@code account}, then closes the store. */
|
||||
public static void seed(EmulatorConfig config, String account, Instance... instances) {
|
||||
StorageFactory factory = StorageFactories.open(config, "persistent");
|
||||
try {
|
||||
AccountAwareStorageBackend<Instance> store = factory.create(
|
||||
"ec2", "ec2-instances.json", new TypeReference<Map<String, Instance>>() { });
|
||||
for (Instance instance : instances) {
|
||||
store.putForAccount(account, REGION + "::" + instance.getInstanceId(), instance);
|
||||
}
|
||||
} finally {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
/** The stored record whose key ends with {@code id}, read straight from the JSON file, or null. */
|
||||
public static JsonNode persistedRecord(Path dir, String file, String id) throws IOException {
|
||||
JsonNode records = JSON.readTree(Files.readString(dir.resolve(file)));
|
||||
for (Map.Entry<String, JsonNode> entry : records.properties()) {
|
||||
if (entry.getKey().endsWith("::" + id)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The state name stored for instance {@code id}, or null when no such record is stored. */
|
||||
public static String persistedState(Path dir, String id) throws IOException {
|
||||
JsonNode record = persistedRecord(dir, "ec2-instances.json", id);
|
||||
return record == null ? null : record.path("state").path("name").asText();
|
||||
}
|
||||
|
||||
/** The {@code terminatedAt} stored for instance {@code id}, or -1 when no such record is stored. */
|
||||
public static long persistedTerminatedAt(Path dir, String id) throws IOException {
|
||||
JsonNode record = persistedRecord(dir, "ec2-instances.json", id);
|
||||
return record == null ? -1 : record.path("terminatedAt").asLong();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user