diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 9f89637b2c..7cbb6fbef3 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -49,7 +49,20 @@ A systemd guest gets a private cgroup namespace, as kind runs its nodes, so its | `running → shutting-down → terminated` | `docker rm -f` | | Reboot | `docker restart` | -Terminated instances remain queryable for 1 hour (matching real EC2 tombstone behavior) before being pruned. +Terminated instances remain queryable for 1 hour (matching real EC2 tombstone behavior) before being pruned. A sweep that runs every minute removes the expired ones, with their tags, for every account. + +Every state change the container manager makes in the background is written to the store as it happens, so a Floci process that is killed or restarted never restores a record stuck in a transitional state. On startup Floci settles any it still finds: + +| Stored state | Settled as | +|---|---| +| `shutting-down` | The termination is finished and the container removed: `terminated` | +| `pending`, no container recorded | The launch is treated as failed: `terminated` | +| `pending`, container running | `running` | +| `pending`, container not running or not reachable | The container is stopped and kept so the instance can be started again: `stopped` | +| `stopping` | The container is stopped: `stopped` | +| `terminated`, recorded without a time | The retention clock starts at this startup | + +A record is settled as `stopped` only once Docker confirms that its container stopped or is gone. When Docker cannot confirm it (it is unreachable, for one), the record keeps its state and the next start tries again, and an instance that cannot be settled is named in an error in the log. The releases of a termination (port forwards, firewall rules, addresses) are independent of the container removal, so one that fails neither skips it nor keeps the instance from terminating. The sweep that removes expired instances carries on past one that cannot be removed and reports the failure when it ends. ## Instance Resource Limits diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java index e325994cc8..1ad16d9d7b 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -17,6 +17,7 @@ import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLiveness; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.core.common.docker.ContainerSpec; @@ -144,6 +145,8 @@ public class Ec2ContainerManager { static int containerBridgeIpAttempts = 30; static long containerBridgeIpPollMillis = 500; + private static final int PERSIST_ATTEMPTS = 5; + private static final long PERSIST_RETRY_MILLIS = 100; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -164,6 +167,13 @@ public class Ec2ContainerManager { private final ExecutorService executor; private final Semaphore metadataSetupSlots = new Semaphore(METADATA_SETUP_CONCURRENCY); private final Map> lifecycleOperations = new ConcurrentHashMap<>(); + /** + * Writes an instance back to the store. The state changes made here run on executor threads + * after the request that started them has returned, so nothing else would persist them: the + * stored record would keep the state that request wrote, and a process stopped before the next + * write would restore it as {@code pending} or {@code shutting-down} for good. + */ + private volatile Consumer persister = instance -> { }; /** Instances whose service-network lookup failed and is retried on the next address read. */ private final Set serviceNetworkRetries = ConcurrentHashMap.newKeySet(); /** The latest service-network lookup started per instance; only that one may publish. */ @@ -583,6 +593,7 @@ public class Ec2ContainerManager { failLaunch(instance, leasedPrivateIp); return; } + persist(instance); LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})", instanceId, containerId, String.valueOf(sshHostPort)); @@ -818,6 +829,60 @@ public class Ec2ContainerManager { } } + void setPersister(Consumer persister) { + this.persister = persister; + } + + /** + * Writes the instance's current state, and narrows the window in which an older state can be + * the last one the store commits. A store may take its snapshot of the instance before it + * commits it, as the write-ahead log does, so a slow writer can commit an older state after a + * newer one. When the state moved on while a write was in flight the instance is written + * again, without a lock around the store. + * + *

This is a mitigation, not an ordering guarantee. The check and the corrective write are not + * atomic with the store's commit, and they cover only the writes made here: those the request + * threads make through the service are not covered. + * + *

A write that fails is retried a few times before it is reported. + */ + private void persist(Instance instance) { + for (int attempt = 1; attempt <= PERSIST_ATTEMPTS; attempt++) { + String writing = stateName(instance); + try { + persister.accept(instance); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not persist the state of EC2 instance {0} (attempt {1} of {2})", + instance.getInstanceId(), attempt, PERSIST_ATTEMPTS); + if (!pause(PERSIST_RETRY_MILLIS)) { + return; + } + continue; + } + if (writing.equals(stateName(instance))) { + return; + } + } + LOG.errorv("Could not confirm that the current state of EC2 instance {0} reached the store; " + + "a later write or the next start will correct it", instance.getInstanceId()); + } + + private static String stateName(Instance instance) { + InstanceState state = instance.getState(); + return state == null ? "" : state.getName(); + } + + /** Sleeps; false when the thread was interrupted, which also restores its interrupt flag. */ + private static boolean pause(long millis) { + try { + Thread.sleep(millis); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + private void failLaunch(Instance instance) { failLaunch(instance, instance.getPrivateIpAddress()); } @@ -844,7 +909,7 @@ public class Ec2ContainerManager { && instance.getDockerContainerId() == null && instance.getSshHostPort() <= 0 && (instance.getContainerBridgeIp() == null || instance.getContainerBridgeIp().isBlank()); - instance.setState(InstanceState.terminated()); + instance.markTerminated(System.currentTimeMillis()); containerId = instance.getDockerContainerId(); sshHostPort = instance.getSshHostPort(); containerIp = instance.getContainerBridgeIp(); @@ -855,6 +920,7 @@ public class Ec2ContainerManager { serviceNetworkRetries.remove(instance.getInstanceId()); serviceNetworkLookups.remove(instance.getInstanceId()); } + persist(instance); if (alreadyCleaned) { return; } @@ -911,7 +977,7 @@ public class Ec2ContainerManager { if ("running".equals(state)) { return false; } - instance.setState(InstanceState.terminated()); + instance.markTerminated(System.currentTimeMillis()); } failLaunch(instance); return true; @@ -995,6 +1061,7 @@ public class Ec2ContainerManager { */ private void markContainerlessRunning(Instance instance) { if (markRunning(instance)) { + persist(instance); LOG.infov("EC2 instance {0} is running without a backing container (no Docker daemon reachable)", instance.getInstanceId()); } @@ -1069,7 +1136,9 @@ public class Ec2ContainerManager { } catch (Exception e) { LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage()); } - instance.compareAndSetState(stopping, InstanceState.stopped()); + if (instance.compareAndSetState(stopping, InstanceState.stopped())) { + persist(instance); + } }); } @@ -1151,13 +1220,17 @@ public class Ec2ContainerManager { setUpMetadataEndpoint = namespace == null; } } catch (InterruptedException e) { - instance.compareAndSetState(pending, InstanceState.stopped()); + if (instance.compareAndSetState(pending, InstanceState.stopped())) { + persist(instance); + } rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); Thread.currentThread().interrupt(); return; } catch (Exception e) { LOG.warnv("Error starting EC2 container {0}: {1}", containerId, e.getMessage()); - instance.compareAndSetState(pending, InstanceState.stopped()); + if (instance.compareAndSetState(pending, InstanceState.stopped())) { + persist(instance); + } rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); return; } @@ -1166,6 +1239,7 @@ public class Ec2ContainerManager { rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); return; } + persist(instance); if (postStart != null) { try { postStart.run(); @@ -1618,6 +1692,11 @@ public class Ec2ContainerManager { * removal itself failed would attempt work Docker is bound to refuse with no later retry * behind it. A skip is logged. Anything the callback throws is logged and swallowed rather * than killing the executor task. + * + *

Every release of the teardown is best effort and independent of the container removal, so + * one that fails neither skips the removal nor keeps the instance from terminating. The + * instance ends {@code terminated} even when Docker refuses the removal; the callback is then + * skipped, and the container is collected on the next start. */ public void terminate(Instance instance, Runnable afterTeardown) { String containerId; @@ -1639,47 +1718,36 @@ public class Ec2ContainerManager { } executor.submit(() -> { // The post-teardown hook's only precondition; see the Javadoc above for why. - boolean containerGone = false; + boolean containerGone = containerId == null; try { - portForwardManager.unpublishAll(instance); - if (containerId == null) { - // Nothing was ever launched, so there is no container to hold the image. - containerGone = true; - } + cleanupStep(instance, "port forwards", () -> portForwardManager.unpublishAll(instance)); if (containerId != null) { - try { - dockerClient.removeContainerCmd(containerId).withForce(true).exec(); - containerGone = true; - } catch (NotFoundException e) { - // already gone - containerGone = true; - } catch (Exception e) { - LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage()); - } - try { - // iptables/veth teardown lags behind container removal; prevents port-reuse conflicts. - Thread.sleep(500); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - } + containerGone = removeContainer(containerId); + // iptables/veth teardown lags behind container removal; prevents port-reuse conflicts. + pause(500); } if (firewallManager != null && firewallManager.enabled() && firewallEniId != null) { - firewallManager.unregister(firewallEniId); + cleanupStep(instance, "firewall registration", () -> firewallManager.unregister(firewallEniId)); } if (sshHostPort > 0) { - portAllocator.release(sshHostPort); + cleanupStep(instance, "SSH host port", () -> portAllocator.release(sshHostPort)); } - metadataServer.unregisterContainer(containerIp, instance); - metadataServer.unregisterContainer(imdsSourceIp, instance); - metadataServer.unregisterInstance(instance); + cleanupStep(instance, "metadata registrations", () -> { + metadataServer.unregisterContainer(containerIp, instance); + metadataServer.unregisterContainer(imdsSourceIp, instance); + metadataServer.unregisterInstance(instance); + }); // Give the address back only now that the container is gone: releasing it while // Docker still holds the endpoint would hand the same IP to the next launch and // have Docker refuse it. - vpcNetworkManager.releasePrivateIp(instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(), - instance.getPrivateIpAddress()); - instance.setState(InstanceState.terminated()); - instance.setTerminatedAt(System.currentTimeMillis()); + cleanupStep(instance, "private address", () -> vpcNetworkManager.releasePrivateIp( + instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(), + instance.getPrivateIpAddress())); } finally { + // Whatever the teardown managed, the instance must not stay shutting-down: nothing + // else would ever finish it, and a leftover container is collected on the next start. + instance.markTerminated(System.currentTimeMillis()); + persist(instance); if (afterTeardown != null && containerGone) { try { afterTeardown.run(); @@ -1696,6 +1764,48 @@ public class Ec2ContainerManager { }); } + /** + * @return true when the container is gone, including when it was already absent + */ + private boolean removeContainer(String containerId) { + try { + dockerClient.removeContainerCmd(containerId).withForce(true).exec(); + return true; + } catch (NotFoundException e) { + return true; + } catch (Exception e) { + LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage()); + return false; + } + } + + /** + * Runs one best-effort release during teardown. Each release is independent of the others, and + * above all of the container removal, so one that fails is logged and the rest still run. + */ + private void cleanupStep(Instance instance, String step, Runnable release) { + try { + release.run(); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not release the {0} of EC2 instance {1} during termination; " + + "continuing with the rest", step, instance.getInstanceId()); + } + } + + /** + * Stops an instance's container for startup recovery and reports whether it is confirmed + * stopped or gone. A Docker error while stopping, or while checking afterwards, is not + * confirmation: the container may still be running. + */ + boolean stopAndConfirm(Instance instance) { + String containerId = instance.getDockerContainerId(); + if (containerId == null) { + return true; + } + stopForShutdown(instance); + return lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING; + } + /** * Reboots an instance via docker restart. */ diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 638de8a38f..2bca299d71 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -157,6 +157,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiPredicate; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; @@ -175,6 +176,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private static final Logger LOG = Logger.getLogger(Ec2Service.class); + /** How long a terminated instance stays listed, as EC2 keeps one visible for about an hour. */ + static final Duration TERMINATED_INSTANCE_RETENTION = Duration.ofHours(1); + /** * The availability zones every region is modelled with. DescribeAvailabilityZones publishes * exactly these, the seeded default subnets sit in them, and CreateSubnet refuses a zone id @@ -1083,13 +1087,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab @PostConstruct void restoreMetadataRegistrations() { migrateTagsToRegionKeys(); + Consumer persister = inst -> { + if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) { + putInstanceForOwner(key(inst.getRegion(), inst.getInstanceId()), inst); + } + }; if (portForwardManager != null) { - portForwardManager.setPersister(inst -> { - if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) { - putInstanceForOwner(key(inst.getRegion(), inst.getInstanceId()), inst); - } - }); + portForwardManager.setPersister(persister); } + if (containerManager != null) { + containerManager.setPersister(persister); + } + stampUntimedTerminatedRecords(); if (config.services().ec2().mock()) { return; } @@ -1097,10 +1106,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab restoreVpcNetworks(); int restored = 0; + Set registered = new HashSet<>(); for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(instances)) { if (needsMetadataRegistration(entry.value()) && RequestScopes.callAs(entry.accountId(), entry.value().getRegion(), () -> restoreInstance(entry))) { restored++; + registered.add(entry.accountId() + "/" + entry.key()); } } if (restored > 0) { @@ -1109,12 +1120,135 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (volumeBlockDeviceManager != null && volumeBlockDeviceManager.isAvailable()) { restoreAttachedVolumesOnStartup(); } + resumeInterruptedLifecycles(registered); // Runs after the restore loop, so anything legitimately revived above is already // accounted for and only genuine leftovers are left to collect. containerManager.reconcileOrphanedContainers(this::instanceContainerStillWanted); } + /** + * Starts the retention clock of terminated records that have none. Records written before + * every terminal path stamped {@code terminatedAt} (a launch that failed, for one) carry zero, + * which {@link #pruneTerminatedInstances(Instant)} reads as "not yet expired" for ever. + */ + private void stampUntimedTerminatedRecords() { + long now = System.currentTimeMillis(); + int stamped = 0; + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(instances)) { + Instance instance = entry.value(); + if (instance != null && instance.getState() != null + && "terminated".equals(instance.getState().getName()) && instance.getTerminatedAt() <= 0) { + instance.markTerminated(now); + putForOwner(instances, entry, instance); + stamped++; + } + } + if (stamped > 0) { + LOG.infov("Started the retention clock of {0} terminated EC2 instance(s) recorded without one", + stamped); + } + } + + /** + * Settles instances a previous run left mid-transition. The thread that would have finished + * each of them died with that run, so without this a record stays {@code pending}, + * {@code stopping} or {@code shutting-down} for good, whatever its container is doing. + * + *

    + *
  • {@code shutting-down}: the termination is finished, container and all.
  • + *
  • {@code pending} with no container: the launch never produced one, so it ends as a + * failed launch does.
  • + *
  • {@code pending} with a container: running if the container is, which is what the + * restore loop just re-registered, otherwise the container is stopped and the record + * settles as stopped. The container is never discarded, because the record may be a + * stopped instance that was being started.
  • + *
  • {@code stopping}: the container is stopped and the record settles as stopped.
  • + *
+ * + *

A record settles as stopped only when Docker confirms its container stopped or gone. When + * it cannot (Docker unreachable, for one) the record keeps its state and the next start tries + * again, because writing {@code stopped} for a container that may be running would be wrong. + * + * @param registered the accounts and keys whose running container the restore loop registered + */ + private void resumeInterruptedLifecycles(Set registered) { + List unsettled = new ArrayList<>(); + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(instances)) { + Instance instance = entry.value(); + if (instance == null || instance.getState() == null) { + continue; + } + boolean containerRegistered = registered.contains(entry.accountId() + "/" + entry.key()); + // One instance that cannot be settled must neither stop the others being settled nor + // stop Floci starting, so a failure is kept apart and reported below. + try { + boolean settled = RequestScopes.callAs(entry.accountId(), instance.getRegion(), + () -> resumeInterruptedLifecycle(entry, containerRegistered)); + if (!settled) { + unsettled.add(instance.getInstanceId()); + } + } catch (RuntimeException e) { + LOG.warnv(e, "Could not settle EC2 instance {0} left in state {1} by a previous run", + instance.getInstanceId(), instance.getState().getName()); + unsettled.add(instance.getInstanceId()); + } + } + if (!unsettled.isEmpty()) { + LOG.errorv("{0} EC2 instance(s) left mid-transition by a previous run could not be settled and " + + "keep their state until the next start: {1}", unsettled.size(), unsettled); + } + } + + /** + * @return false when the instance could not be settled and was left as it was + */ + private boolean resumeInterruptedLifecycle(AccountAwareStorageBackend.AccountEntry entry, + boolean containerRegistered) { + Instance instance = entry.value(); + String state = instance.getState().getName(); + boolean hasContainer = instance.getDockerContainerId() != null; + if ("shutting-down".equals(state) || ("pending".equals(state) && !hasContainer)) { + LOG.infov("Finishing the termination of EC2 instance {0} left {1} by a previous run", + instance.getInstanceId(), state); + finishTermination(entry); + } else if ("pending".equals(state)) { + if (!containerRegistered && !containerManager.stopAndConfirm(instance)) { + LOG.warnv("The container of EC2 instance {0}, left pending by a previous run, could not be " + + "confirmed stopped, so the instance stays pending", instance.getInstanceId()); + return false; + } + instance.setState(containerRegistered ? InstanceState.running() : InstanceState.stopped()); + putForOwner(instances, entry, instance); + LOG.infov("EC2 instance {0} left pending by a previous run is now {1}", instance.getInstanceId(), + instance.getState().getName()); + } else if ("stopping".equals(state)) { + if (hasContainer && !containerManager.stopAndConfirm(instance)) { + LOG.warnv("The container of EC2 instance {0}, left stopping by a previous run, could not be " + + "confirmed stopped, so the instance stays stopping", instance.getInstanceId()); + return false; + } + instance.setState(InstanceState.stopped()); + putForOwner(instances, entry, instance); + LOG.infov("EC2 instance {0} left stopping by a previous run is now stopped", instance.getInstanceId()); + } + return true; + } + + private void finishTermination(AccountAwareStorageBackend.AccountEntry entry) { + Instance instance = entry.value(); + String region = instance.getRegion(); + String owner = entry.accountId(); + containerManager.terminate(instance, () -> RequestScopes.runAs(owner, + () -> reclaimCapturesPinnedBy(region, instance, Set.of(instance.getInstanceId())))); + detachAttachedVolumesOnTermination(region, instance); + releaseStandaloneInterfacesOnTermination(region, instance); + putForOwner(instances, entry, instance); + synchronized (capacityReservationLock) { + reconcileCapacityMembership(region); + } + } + /** * Runs as the instance's own account, so the security groups, prefix lists and port-forward * writes it resolves along the way come from that account rather than the default one. @@ -5369,11 +5503,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (config.services().ec2().mock()) { // Under the instance's lock, so a concurrent Elastic IP write sees the new state. synchronized (inst) { - inst.setState(InstanceState.terminated()); + inst.markTerminated(System.currentTimeMillis()); // Termination also disassociates an Elastic IP, so nothing public is left. clearPublicAddress(inst); } - inst.setTerminatedAt(System.currentTimeMillis()); } else { // Also attempt the reclaim once this container is really gone. The synchronous // attempt below runs while teardown is still scheduled, so for a batch whose @@ -5707,21 +5840,62 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } - /** Removes terminated instances older than 1 hour. Called periodically by lifecycle. */ public void pruneTerminatedInstances() { - long cutoff = System.currentTimeMillis() - 3_600_000L; - for (String storeKey : new ArrayList<>(instances.keys())) { - Instance inst = instances.get(storeKey).orElse(null); - if (inst != null - && "terminated".equals(inst.getState().getName()) - && inst.getTerminatedAt() > 0 - && inst.getTerminatedAt() < cutoff) { - instances.delete(storeKey); - if (inst.getRegion() != null) { - removeTags(inst.getRegion(), inst.getInstanceId()); + pruneTerminatedInstances(Instant.now()); + } + + /** + * Removes terminated instances older than {@link #TERMINATED_INSTANCE_RETENTION}, of every + * account, with their tags. {@link Ec2TerminatedInstanceScheduler} calls it on a timer. + * + *

Whatever termination left attached is released first: a launch that failed ends + * terminated without TerminateInstances having run, so its volumes and interfaces are settled + * here rather than left pointing at a record that no longer exists. + */ + public void pruneTerminatedInstances(Instant now) { + long cutoff = now.minus(TERMINATED_INSTANCE_RETENTION).toEpochMilli(); + List failed = new ArrayList<>(); + RuntimeException failure = null; + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(instances)) { + Instance inst = entry.value(); + if (inst == null || inst.getState() == null + || !"terminated".equals(inst.getState().getName()) + || inst.getTerminatedAt() <= 0 + || inst.getTerminatedAt() >= cutoff) { + continue; + } + // A record that cannot be removed must not keep the others from expiring, so every + // failure is collected and reported once the sweep has been through all of them. + try { + RequestScopes.runAs(entry.accountId(), inst.getRegion(), () -> pruneTerminatedInstance(entry)); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove terminated EC2 instance {0}", inst.getInstanceId()); + failed.add(inst.getInstanceId()); + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); } } } + if (failure != null) { + throw new IllegalStateException("Could not remove " + failed.size() + + " expired terminated EC2 instance(s), they are tried again on the next sweep: " + failed, + failure); + } + } + + void pruneTerminatedInstance(AccountAwareStorageBackend.AccountEntry entry) { + Instance inst = entry.value(); + String region = inst.getRegion(); + if (region != null) { + detachAttachedVolumesOnTermination(region, inst); + releaseStandaloneInterfacesOnTermination(region, inst); + } + deleteForOwner(instances, entry); + if (region != null) { + removeTags(entry.accountId(), region, inst.getInstanceId()); + } } public List describeInstanceStatus(String region, List instanceIds) { diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceScheduler.java b/src/main/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceScheduler.java new file mode 100644 index 0000000000..3e6a07fc03 --- /dev/null +++ b/src/main/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceScheduler.java @@ -0,0 +1,19 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.SweepScheduler; +import io.floci.aws.core.common.SweepWorker; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +/** Removes terminated EC2 instances once they have been listed for the retention period. */ +@ApplicationScoped +public class Ec2TerminatedInstanceScheduler extends SweepScheduler { + private static final long SWEEP_INTERVAL_SECONDS = 60; + + @Inject + public Ec2TerminatedInstanceScheduler(Ec2Service service, EmulatorConfig config) { + super(new SweepWorker("ec2-terminated-instance-pruning", config.services().ec2().enabled(), + SWEEP_INTERVAL_SECONDS, false, service::pruneTerminatedInstances)); + } +} diff --git a/src/main/java/io/floci/aws/services/ec2/model/Instance.java b/src/main/java/io/floci/aws/services/ec2/model/Instance.java index 67e0f646d4..f3400ca0ba 100644 --- a/src/main/java/io/floci/aws/services/ec2/model/Instance.java +++ b/src/main/java/io/floci/aws/services/ec2/model/Instance.java @@ -129,6 +129,17 @@ public class Instance { return true; } + /** + * Moves the instance to {@code terminated} and starts its retention clock. The clock starts + * once: terminating an already terminated record never extends how long it stays listed. + */ + public synchronized void markTerminated(long nowMillis) { + state = InstanceState.terminated(); + if (terminatedAt <= 0) { + terminatedAt = nowMillis; + } + } + public String getStateTransitionReason() { return stateTransitionReason; } public void setStateTransitionReason(String stateTransitionReason) { this.stateTransitionReason = stateTransitionReason; } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2LifecycleRecoveryTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2LifecycleRecoveryTest.java new file mode 100644 index 0000000000..3d5431fb12 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2LifecycleRecoveryTest.java @@ -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 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 removeBehaviour; + private boolean registered; + private ContainerLiveness liveness = ContainerLiveness.NOT_RUNNING; + private boolean stopFails; + private Consumer beforeStartup; + + Options removing(Consumer 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 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(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceRetentionTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceRetentionTest.java new file mode 100644 index 0000000000..c1fe50b52e --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2TerminatedInstanceRetentionTest.java @@ -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 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 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 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 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 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 store = factory.create( + "ec2", "ec2-volumes.json", new TypeReference>() { }); + 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); + } +} diff --git a/src/test/java/io/floci/aws/testing/Ec2LifecycleFixtures.java b/src/test/java/io/floci/aws/testing/Ec2LifecycleFixtures.java new file mode 100644 index 0000000000..5a9f6e346e --- /dev/null +++ b/src/test/java/io/floci/aws/testing/Ec2LifecycleFixtures.java @@ -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 store = factory.create( + "ec2", "ec2-instances.json", new TypeReference>() { }); + 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 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(); + } +}