diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 6803981c14..5779e53444 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -62,6 +62,12 @@ if starts Ec2PublishedConnectionNightlyIntegrationTest; then ecr public.ecr.aws/docker/library/alpine:latest pull alpine/socat fi +# Ec2GuestShutdownDockerNightlyIntegrationTest launches ami-alpine and attaches a volume through the +# volume helper (floci.services.ec2.volume-helper-image). +if starts Ec2GuestShutdownDockerNightlyIntegrationTest; then + ecr public.ecr.aws/docker/library/alpine:latest + pull alpine:3.21 +fi test_image() { image="$(grep -oE "$1 *= *\"[^\"]+\"" "${TEST_IMAGES:-/dev/null}" | grep -oE '"[^"]+"' | tr -d '"')" [ -n "$image" ] || echo "$(date -u +%H:%M:%S) prefetch skipped: TestImages.$1 not readable" >> "$PREFETCH_LOG" diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 18444d2162..203a740b58 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -60,6 +60,8 @@ 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` | +A guest that shuts itself down (`shutdown -h now` or `poweroff` under the `systemd` guest runtime) exits its container. Floci then applies the instance's `InstanceInitiatedShutdownBehavior`, from `RunInstances`, its launch template or `ModifyInstanceAttribute`: `stop` (the default) moves it to `stopped`, and `terminate` to `terminated`, deleting its `DeleteOnTermination` volumes as `TerminateInstances` does. Either way `DescribeInstances` reports the state reason `Client.InstanceInitiatedShutdown`, until the instance is started again. An instance launched through CloudFormation, Auto Scaling or `CreateFleet` always stops, whatever shutdown behavior it was given. A reboot, or Floci stopping its containers when it shuts down, is not a guest shutdown. An instance whose container kept running across a Floci restart is watched again once it is next started. + 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: diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcher.java b/src/main/java/io/floci/aws/core/common/docker/ContainerExitWatcher.java similarity index 91% rename from src/main/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcher.java rename to src/main/java/io/floci/aws/core/common/docker/ContainerExitWatcher.java index eb8786845a..b23347158f 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcher.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerExitWatcher.java @@ -1,4 +1,4 @@ -package io.floci.aws.services.lambda.launcher; +package io.floci.aws.core.common.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerResponse; @@ -15,7 +15,7 @@ import java.util.function.IntConsumer; import java.util.function.LongSupplier; /** - * Reports when a Lambda container's main process exits, through Docker's wait-for-exit stream. + * Reports when a container's main process exits, through Docker's wait-for-exit stream. * *

The stream sends nothing until the container exits, so on a quiet container it ends with a read * timeout (the Docker client's response timeout) while the container still runs. A watch that simply @@ -33,9 +33,9 @@ import java.util.function.LongSupplier; *

The wait stream holds its connection for the container's whole lifetime, so it runs on the * streaming client; the inspect is a short call and stays on the control-plane client. */ -final class LambdaExitWatcher { +public final class ContainerExitWatcher { - private static final Logger LOG = Logger.getLogger(LambdaExitWatcher.class); + private static final Logger LOG = Logger.getLogger(ContainerExitWatcher.class); /** A stream that fails sooner than this after it was armed counts as a quick failure. */ static final Duration QUICK_FAILURE = Duration.ofSeconds(5); @@ -52,7 +52,7 @@ final class LambdaExitWatcher { private final LongSupplier nanoClock; private int quickFailures; - LambdaExitWatcher(DockerClient dockerClient, DockerClient streamingDocker, String containerId, + ContainerExitWatcher(DockerClient dockerClient, DockerClient streamingDocker, String containerId, IntConsumer onExit, BiConsumer scheduler, LongSupplier nanoClock) { this.dockerClient = dockerClient; this.streamingDocker = streamingDocker; @@ -63,9 +63,9 @@ final class LambdaExitWatcher { } /** Arms a watch that calls {@code onExit} with the exit status, at most once per exit. */ - static void watch(DockerClient dockerClient, DockerClient streamingDocker, String containerId, + public static void watch(DockerClient dockerClient, DockerClient streamingDocker, String containerId, IntConsumer onExit) { - new LambdaExitWatcher(dockerClient, streamingDocker, containerId, onExit, LambdaExitWatcher::schedule, + new ContainerExitWatcher(dockerClient, streamingDocker, containerId, onExit, ContainerExitWatcher::schedule, System::nanoTime).arm(); } diff --git a/src/main/java/io/floci/aws/core/common/docker/DockerExitEvents.java b/src/main/java/io/floci/aws/core/common/docker/DockerExitEvents.java index d3c9cb7e11..e97498061f 100644 --- a/src/main/java/io/floci/aws/core/common/docker/DockerExitEvents.java +++ b/src/main/java/io/floci/aws/core/common/docker/DockerExitEvents.java @@ -219,7 +219,7 @@ public class DockerExitEvents { } } - /** One container's check; an inspect that fails is tried again with a doubling delay, as LambdaExitWatcher does. */ + /** One container's check; an inspect that fails is tried again with a doubling delay, as ContainerExitWatcher does. */ private void sweep(Registration registration, int attempt) { if (shutdown || registration.reported().get() || registered.get(registration.containerId()) != registration) { return; 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 698b7d53c7..33154afae5 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.exception.NotModifiedException; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Frame; @@ -16,6 +17,7 @@ import io.floci.aws.core.common.RequestScopes; 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.ContainerExitWatcher; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLiveness; import io.floci.aws.core.common.docker.ContainerLogStreamer; @@ -158,6 +160,9 @@ public class Ec2ContainerManager { static long containerBridgeIpPollMillis = 500; private static final int PERSIST_ATTEMPTS = 5; private static final long PERSIST_RETRY_MILLIS = 100; + /** Inspects tried, the delay doubling from the first, before an exited container is left unconfirmed. */ + private static final int EXIT_PROBE_ATTEMPTS = 5; + private static final long EXIT_PROBE_FIRST_RETRY_MILLIS = 200; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -185,6 +190,9 @@ public class Ec2ContainerManager { * write would restore it as {@code pending} or {@code shutting-down} for good. */ private volatile Consumer persister = instance -> { }; + private volatile Consumer guestShutdownHandler = instance -> { }; + /** Containers Floci itself is stopping or restarting while their instance stays running. */ + private final Set flociStoppedContainers = ConcurrentHashMap.newKeySet(); /** 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. */ @@ -621,6 +629,7 @@ public class Ec2ContainerManager { return; } persist(instance); + watchForGuestShutdown(instance, containerId); LOG.infov("EC2 instance {0} running in container {1} (SSH host port {2})", instanceId, containerId, String.valueOf(sshHostPort)); @@ -863,6 +872,57 @@ public class Ec2ContainerManager { } } + /** + * Watches the container of a running instance for an exit Floci did not cause: a guest that powers + * itself off. A stop or terminate has moved the instance out of running first; a reboot or Floci's + * own shutdown marks the container instead, and a container running again after a reboot is no exit. + */ + private void watchForGuestShutdown(Instance instance, String containerId) { + flociStoppedContainers.remove(containerId); + ContainerExitWatcher.watch(dockerClient, lifecycleManager.getStreamingDockerClient(), containerId, + exitCode -> onContainerExit(instance, containerId, exitCode)); + } + + private void onContainerExit(Instance instance, String containerId, int exitCode) { + if (flociStoppedContainers.contains(containerId)) { + return; + } + synchronized (instance) { + if (!containerId.equals(instance.getDockerContainerId()) || !"running".equals(stateName(instance))) { + return; + } + } + // Only a container Docker reports stopped is a shutdown; one running again after a reboot is + // not. The watch has reported its one exit, so a failed inspect is tried again, not dropped. + ContainerLiveness liveness = lifecycleManager.probeContainer(containerId); + for (int attempt = 1; liveness == ContainerLiveness.UNKNOWN && attempt < EXIT_PROBE_ATTEMPTS; attempt++) { + if (!pause(EXIT_PROBE_FIRST_RETRY_MILLIS << (attempt - 1))) { + return; + } + liveness = lifecycleManager.probeContainer(containerId); + } + if (liveness != ContainerLiveness.NOT_RUNNING) { + if (liveness == ContainerLiveness.UNKNOWN) { + LOG.warnv("EC2 instance {0}: Docker could not confirm its container {1} stopped after it " + + "exited, so a shutdown from its guest is not applied", instance.getInstanceId(), containerId); + } + return; + } + LOG.infov("EC2 instance {0} shut down from its guest (container exit code {1})", + instance.getInstanceId(), String.valueOf(exitCode)); + try { + guestShutdownHandler.accept(instance); + } catch (Exception e) { + LOG.warnv("Could not apply the shutdown behavior of EC2 instance {0}: {1}", + instance.getInstanceId(), e.getMessage()); + } + } + + /** Called when an instance's guest shuts itself down, so its shutdown behavior can be applied. */ + void setGuestShutdownHandler(Consumer guestShutdownHandler) { + this.guestShutdownHandler = guestShutdownHandler; + } + void setPersister(Consumer persister) { this.persister = persister; } @@ -1112,6 +1172,7 @@ public class Ec2ContainerManager { if (containerId == null) { return; } + flociStoppedContainers.add(containerId); portForwardManager.unpublishAll(instance); try { dockerClient.stopContainerCmd(containerId).withTimeout(5).exec(); @@ -1167,6 +1228,8 @@ public class Ec2ContainerManager { dockerClient.stopContainerCmd(containerId).withTimeout(30).exec(); } catch (NotFoundException ignored) { // An already removed container needs no further stop. + } catch (NotModifiedException ignored) { + // An already stopped container, such as a guest that powered itself off, needs no stop. } catch (Exception e) { LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage()); } @@ -1274,6 +1337,7 @@ public class Ec2ContainerManager { return; } persist(instance); + watchForGuestShutdown(instance, containerId); if (postStart != null) { try { postStart.run(); @@ -1848,12 +1912,17 @@ public class Ec2ContainerManager { if (containerId == null) { return; } - executor.submit(() -> { + // Queued behind the container's other lifecycle operations, so one reboot's re-armed watch + // never sees the next reboot's restart. + submitLifecycleOperation(containerId, () -> { + flociStoppedContainers.add(containerId); try { dockerClient.restartContainerCmd(containerId).exec(); LOG.infov("Rebooted EC2 container {0}", containerId); } catch (Exception e) { LOG.warnv("Error rebooting EC2 container {0}: {1}", containerId, e.getMessage()); + } finally { + watchForGuestShutdown(instance, containerId); } }); } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index 72f352e245..01118439e6 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -970,12 +970,16 @@ public class Ec2QueryHandler { "You can specify true for DeleteOnTermination only when creating a new network interface.", 400); } + String shutdownBehavior = p.getFirst("InstanceInitiatedShutdownBehavior"); + if (shutdownBehavior == null && launchTemplateData != null) { + shutdownBehavior = launchTemplateData.getInstanceInitiatedShutdownBehavior(); + } Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount, keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn, associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions, creditSpecificationCpuCredits, userDataEncoded, dryRun(p), p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings, - "spot".equals(marketType), privateIpAddress, capacitySpecification); + "spot".equals(marketType), privateIpAddress, capacitySpecification, shutdownBehavior); // Apply an explicit NetworkInterface.1.DeleteOnTermination to the launched instance. if (explicitDeleteOnTermination != null) { @@ -1692,6 +1696,11 @@ public class Ec2QueryHandler { xml.start("disableApiStop").elem("value", String.valueOf(inst.isDisableApiStop())).end("disableApiStop"); } else if ("disableApiTermination".equals(attribute)) { xml.start("disableApiTermination").elem("value", String.valueOf(inst.isDisableApiTermination())).end("disableApiTermination"); + } else if ("instanceInitiatedShutdownBehavior".equals(attribute)) { + xml.start("instanceInitiatedShutdownBehavior") + .elem("value", inst.getInstanceInitiatedShutdownBehavior() == null + ? "stop" : inst.getInstanceInitiatedShutdownBehavior()) + .end("instanceInitiatedShutdownBehavior"); } else if ("groupSet".equals(attribute)) { xml.start("groupSet"); for (GroupIdentifier gi : inst.getSecurityGroups()) { @@ -1718,7 +1727,8 @@ public class Ec2QueryHandler { // Find which attribute is being modified String attrName = null; String attrValue = null; - for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value")) { + for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value", + "InstanceInitiatedShutdownBehavior.Value")) { String val = p.getFirst(attr); if (val != null) { attrName = attr.replace(".Value", ""); 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 0d8774b6b4..996c0dccab 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -1206,6 +1206,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } if (containerManager != null) { containerManager.setPersister(persister); + containerManager.setGuestShutdownHandler(this::applyGuestShutdown); } stampUntimedTerminatedRecords(); if (config.services().ec2().mock()) { @@ -4420,6 +4421,33 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List blockDeviceMappings, boolean spot, String privateIpAddress, LaunchTemplateData.CapacityReservationSpecification capacitySpecification) { + return runInstances(region, imageId, instanceType, minCount, maxCount, keyName, + securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn, + associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone, + metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy, + blockDeviceMappings, spot, privateIpAddress, capacitySpecification, null); + } + + /** + * @param instanceInitiatedShutdownBehavior InstanceInitiatedShutdownBehavior, or null for the + * default, stop. Set before any container launches, so a + * guest that powers off at once already finds it. + */ + public Reservation runInstances(String region, String imageId, String instanceType, + int minCount, int maxCount, String keyName, + List securityGroupIds, String subnetId, + String clientToken, List instanceTags, + String userData, String iamInstanceProfileArn, + Boolean associatePublicIp, String networkInterfaceId, + int networkInterfaceDeviceIndex, String availabilityZone, + LaunchTemplateData.MetadataOptions metadataOptions, + String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun, + String hostId, String tenancy, + List blockDeviceMappings, boolean spot, + String privateIpAddress, + LaunchTemplateData.CapacityReservationSpecification capacitySpecification, + String instanceInitiatedShutdownBehavior) { + requireShutdownBehavior(instanceInitiatedShutdownBehavior); String capacityPreference = capacitySpecification == null || capacitySpecification.getCapacityReservationPreference() == null ? "open" : capacitySpecification.getCapacityReservationPreference(); @@ -4685,6 +4713,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab inst.setRegion(region); inst.setUserData(userData); inst.setEncodedUserData(encodedUserData); + inst.setInstanceInitiatedShutdownBehavior(instanceInitiatedShutdownBehavior); inst.setIamInstanceProfileArn(iamInstanceProfileArn); if (launchProfile != null) { inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId()); @@ -5939,12 +5968,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab InstanceState prev = inst.getState(); synchronized (capacityReservationLock) { if ("stopped".equals(prev.getName()) || "stopping".equals(prev.getName())) { + String prevReasonCode = inst.getStateReasonCode(); + String prevReasonMessage = inst.getStateReasonMessage(); inst.setState(InstanceState.pending()); + inst.setStateReasonCode(null); + inst.setStateReasonMessage(null); try { instances.put(key(region, id), inst); acquireCapacity(region, List.of(inst)); } catch (RuntimeException failure) { inst.setState(prev); + inst.setStateReasonCode(prevReasonCode); + inst.setStateReasonMessage(prevReasonMessage); instances.put(key(region, id), inst); throw failure; } @@ -6464,10 +6499,43 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab inst.setSourceDestCheck(Boolean.parseBoolean(value)); } case "ebsOptimized" -> inst.setEbsOptimized(Boolean.parseBoolean(value)); + case "instanceInitiatedShutdownBehavior" -> { + requireShutdownBehavior(value); + inst.setInstanceInitiatedShutdownBehavior(value); + } } storeInstance(region, inst); } + private static void requireShutdownBehavior(String behavior) { + if (behavior != null && !"stop".equals(behavior) && !"terminate".equals(behavior)) { + throw new AwsException("InvalidParameterValue", "Value (" + behavior + + ") for parameter instanceInitiatedShutdownBehavior is invalid. Valid values are 'stop' and 'terminate'.", + 400); + } + } + + /** + * A guest that powered itself off: the instance stops, as on EC2, or terminates when launched with + * {@code InstanceInitiatedShutdownBehavior=terminate}. Runs off a request, as the instance's account. + */ + void applyGuestShutdown(Instance instance) { + String region = instance.getRegion(); + List ids = List.of(instance.getInstanceId()); + String owner = instance.getOwnerId() != null ? instance.getOwnerId() : defaultAccountId; + RequestScopes.runAs(owner, region, () -> { + Instance stored = instances.get(key(region, instance.getInstanceId())).orElse(instance); + stored.setStateReasonCode("Client.InstanceInitiatedShutdown"); + stored.setStateReasonMessage("Client.InstanceInitiatedShutdown: Instance initiated shutdown"); + storeInstance(region, stored); + if ("terminate".equals(stored.getInstanceInitiatedShutdownBehavior())) { + terminateInstances(region, ids); + } else { + stopInstances(region, ids); + } + }); + } + public record InstanceBlockDeviceMappingChange(String deviceName, String volumeId, boolean deleteOnTermination) {} public void checkInstanceBlockDeviceMappings(String region, String instanceId, 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 70cbecf1a0..f341b54164 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 @@ -67,6 +67,7 @@ public class Instance { // without model backing, a modify → plan cycle would show drift. Tracked as a known limitation. private boolean disableApiStop = false; private boolean disableApiTermination = false; + private String instanceInitiatedShutdownBehavior; // EC2's copy of an instance a cluster serves, its node, which a change through EC2 stores. private boolean clusterNodeCopy; @@ -307,6 +308,11 @@ public class Instance { public boolean isDisableApiTermination() { return disableApiTermination; } public void setDisableApiTermination(boolean disableApiTermination) { this.disableApiTermination = disableApiTermination; } + public String getInstanceInitiatedShutdownBehavior() { return instanceInitiatedShutdownBehavior; } + public void setInstanceInitiatedShutdownBehavior(String instanceInitiatedShutdownBehavior) { + this.instanceInitiatedShutdownBehavior = instanceInitiatedShutdownBehavior; + } + public boolean isClusterNodeCopy() { return clusterNodeCopy; } public void setClusterNodeCopy(boolean clusterNodeCopy) { this.clusterNodeCopy = clusterNodeCopy; } diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java index a152498a1e..74a80b593b 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java @@ -9,6 +9,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerExitWatcher; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerSpec; @@ -136,7 +137,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { private final LaunchedContainerAwsEnv awsEnv; private final LambdaExecutionRoleCredentials executionRoleCredentials; private final Ec2Service ec2Service; - /** When off, each container's exit is watched with its own wait stream (LambdaExitWatcher). */ + /** When off, each container's exit is watched with its own wait stream (ContainerExitWatcher). */ private final DockerExitEvents exitEvents; private final LambdaContainerReconciler containerReconciler; /** The VPC address each VpcConfig function's container holds, returned once it is removed. */ @@ -1472,11 +1473,11 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { *

Fires once per container exit, including an intentional {@code docker stop} during * normal teardown. {@link RuntimeApiServer#handleRuntimeProcessExited} itself distinguishes * a genuine crash from that case (its own {@code stopped}/{@code faulted} guard). The watch - * survives its stream timing out on a quiet container; see {@link LambdaExitWatcher}. + * survives its stream timing out on a quiet container; see {@link ContainerExitWatcher}. */ private void watchForUnexpectedExit(DockerClient dockerClient, String containerId, RuntimeApiServer runtimeApiServer) { - LambdaExitWatcher.watch(dockerClient, streamingDocker, containerId, + ContainerExitWatcher.watch(dockerClient, streamingDocker, containerId, runtimeApiServer::handleRuntimeProcessExited); } diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java index 8e6c29123f..cb99d183e0 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java @@ -115,7 +115,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher { /** * Nanosecond clock the grace is measured on, a package-private constructor argument so a test * can advance it and simulate a grace expiry without waiting it out in real time, as - * {@code LambdaExitWatcher}'s {@code nanoClock} does. + * {@code ContainerExitWatcher}'s {@code nanoClock} does. */ private final LongSupplier unschedulableClock; private final AtomicBoolean caConfigMapApplied = new AtomicBoolean(false); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcherTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerExitWatcherTest.java similarity index 93% rename from src/test/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcherTest.java rename to src/test/java/io/floci/aws/core/common/docker/ContainerExitWatcherTest.java index 2fb0fb4d55..4d66e98efa 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/LambdaExitWatcherTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerExitWatcherTest.java @@ -1,4 +1,4 @@ -package io.floci.aws.services.lambda.launcher; +package io.floci.aws.core.common.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerCmd; @@ -20,10 +20,10 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -class LambdaExitWatcherTest { +class ContainerExitWatcherTest { private static final String CONTAINER = "lambda-container"; - private static final long LONG_LIVED_NANOS = LambdaExitWatcher.QUICK_FAILURE.toNanos() + 1; + private static final long LONG_LIVED_NANOS = ContainerExitWatcher.QUICK_FAILURE.toNanos() + 1; private final List armed = new ArrayList<>(); private final List exits = new ArrayList<>(); @@ -50,7 +50,7 @@ class LambdaExitWatcherTest { /** A watch whose clock is {@link #now} and whose scheduler records each delay and runs the task at once. */ private void watch() { - new LambdaExitWatcher(docker, streamingDocker, CONTAINER, exits::add, (delay, task) -> { + new ContainerExitWatcher(docker, streamingDocker, CONTAINER, exits::add, (delay, task) -> { delays.add(delay); task.run(); }, () -> now).arm(); @@ -134,12 +134,12 @@ class LambdaExitWatcherTest { containerState(true, null); watch(); - for (int i = 0; i <= LambdaExitWatcher.MAX_QUICK_FAILURES; i++) { + for (int i = 0; i <= ContainerExitWatcher.MAX_QUICK_FAILURES; i++) { failLatestStream("Connection reset"); } assertEquals(seconds(1, 2, 4, 8, 16), delays); - assertEquals(LambdaExitWatcher.MAX_QUICK_FAILURES + 1, armed.size()); + assertEquals(ContainerExitWatcher.MAX_QUICK_FAILURES + 1, armed.size()); assertEquals(List.of(), exits); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java index 9692add418..abefe3ed90 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java @@ -14,8 +14,10 @@ import com.github.dockerjava.api.command.InspectExecResponse; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.command.PingCmd; import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.RestartContainerCmd; import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.api.exception.DockerException; import com.github.dockerjava.api.model.AccessMode; import com.github.dockerjava.api.model.Bind; @@ -27,6 +29,7 @@ import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Info; import com.github.dockerjava.api.model.NetworkSettings; import com.github.dockerjava.api.model.StreamType; +import com.github.dockerjava.api.model.WaitResponse; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.dns.EmbeddedDnsServer; @@ -34,6 +37,7 @@ import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerExecStubs; 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; @@ -1717,6 +1721,145 @@ class Ec2ContainerManagerTest { assertEquals(List.of("hook while pending, user data started: false"), events); } + @Test + void aGuestThatShutsDownWhileRunningIsReported() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchRunningInstance(harness, "i-guesthalt", exitWatches); + + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(130)); + + assertEquals(List.of(instance), shutDown); + } + + @Test + void aGuestShutdownIsReportedWhenDockerAnswersOnlyOnASecondCheck() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchRunningInstance(harness, "i-flakyprobe", exitWatches); + + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)) + .thenReturn(ContainerLiveness.UNKNOWN, ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(130)); + + assertEquals(List.of(instance), shutDown); + } + + @Test + void aGuestThatShutsDownAfterAStartIsReported() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + when(harness.dockerClient.stopContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StopContainerCmd.class, RETURNS_SELF)); + when(harness.dockerClient.startContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StartContainerCmd.class)); + Instance instance = launchRunningInstance(harness, "i-restarted", exitWatches); + harness.manager.stop(instance); + awaitUntil(() -> "stopped".equals(instance.getState().getName()), Duration.ofSeconds(5)); + + harness.manager.start(instance); + awaitUntil(() -> exitWatches.size() == 2, Duration.ofSeconds(5)); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(130)); + + assertEquals(List.of(instance), shutDown); + } + + @Test + void aRebootIsNotReportedAsAGuestShutdown() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchRunningInstance(harness, "i-reboot", exitWatches); + RestartContainerCmd restart = mock(RestartContainerCmd.class, RETURNS_SELF); + when(harness.dockerClient.restartContainerCmd(TEST_CONTAINER_ID)).thenReturn(restart); + ResultCallback beforeReboot = exitWatches.getLast(); + when(restart.exec()).thenAnswer(invocation -> { + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + beforeReboot.onNext(exitStatus(0)); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.RUNNING); + return null; + }); + + harness.manager.reboot(instance); + awaitUntil(() -> exitWatches.size() == 2, Duration.ofSeconds(5)); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(130)); + + assertEquals(1, shutDown.size(), "only the exit after the reboot is the guest's"); + } + + @Test + void aRebootRequestedWhileAnotherRunsIsNotReportedAsAGuestShutdown() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchRunningInstance(harness, "i-tworeboots", exitWatches); + RestartContainerCmd restart = mock(RestartContainerCmd.class, RETURNS_SELF); + when(harness.dockerClient.restartContainerCmd(TEST_CONTAINER_ID)).thenReturn(restart); + CountDownLatch firstRestartMayFinish = new CountDownLatch(1); + AtomicInteger restarts = new AtomicInteger(); + when(restart.exec()).thenAnswer(invocation -> { + if (restarts.incrementAndGet() == 1) { + firstRestartMayFinish.await(); + return null; + } + // The second restart's exit reaches the watch the first reboot re-armed. + awaitUntil(() -> exitWatches.size() >= 2, Duration.ofSeconds(5)); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(0)); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.RUNNING); + return null; + }); + + harness.manager.reboot(instance); + awaitUntil(() -> restarts.get() == 1, Duration.ofSeconds(5)); + harness.manager.reboot(instance); + firstRestartMayFinish.countDown(); + awaitUntil(() -> exitWatches.size() == 3, Duration.ofSeconds(10)); + + assertEquals(List.of(), shutDown); + } + + @Test + void anExitAfterAStopThroughFlociIsNotReportedAsAGuestShutdown() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + when(harness.dockerClient.stopContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StopContainerCmd.class, RETURNS_SELF)); + Instance instance = launchRunningInstance(harness, "i-apistop", exitWatches); + + harness.manager.stop(instance); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(0)); + + assertEquals(List.of(), shutDown); + } + + @Test + void anExitWhileFlociShutsDownIsNotReportedAsAGuestShutdown() throws Exception { + LaunchHarness harness = launchHarness(); + List> exitWatches = stubExitWatches(harness); + List shutDown = new CopyOnWriteArrayList<>(); + harness.manager.setGuestShutdownHandler(shutDown::add); + when(harness.dockerClient.stopContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StopContainerCmd.class, RETURNS_SELF)); + Instance instance = launchRunningInstance(harness, "i-flocistop", exitWatches); + + harness.manager.stopForShutdown(instance); + when(harness.lifecycleManager.probeContainer(TEST_CONTAINER_ID)).thenReturn(ContainerLiveness.NOT_RUNNING); + exitWatches.getLast().onNext(exitStatus(0)); + + assertEquals(List.of(), shutDown); + } + @Test void launchLabelsContainerWithResourceIdentity() throws Exception { LaunchHarness harness = launchHarness(); @@ -2687,6 +2830,38 @@ class Ec2ContainerManagerTest { return execCreate; } + private static List> stubExitWatches(LaunchHarness harness) { + List> watches = new CopyOnWriteArrayList<>(); + WaitContainerCmd wait = mock(WaitContainerCmd.class, RETURNS_SELF); + when(harness.streamingDockerClient.waitContainerCmd(TEST_CONTAINER_ID)).thenReturn(wait); + when(wait.exec(any())).thenAnswer(invocation -> { + ResultCallback callback = invocation.getArgument(0); + watches.add(callback); + return callback; + }); + return watches; + } + + private static Instance launchRunningInstance(LaunchHarness harness, String instanceId, + List> exitWatches) throws Exception { + harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0)); + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse response = inspectResponse("192.168.215.42"); + when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect); + when(inspect.exec()).thenReturn(response); + Instance instance = instance(instanceId); + harness.manager.launch(instance, ResolvedAmiImage.minimal("ubuntu:24.04"), null, "us-west-2"); + awaitUntil(() -> !exitWatches.isEmpty(), Duration.ofSeconds(5)); + assertEquals("running", instance.getState().getName()); + return instance; + } + + private static WaitResponse exitStatus(int statusCode) { + WaitResponse response = mock(WaitResponse.class); + when(response.getStatusCode()).thenReturn(statusCode); + return response; + } + private static LaunchHarness launchHarness() { return launchHarness(null, Duration.ofMinutes(30)); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2GuestShutdownDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2GuestShutdownDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..e00e2f8f13 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2GuestShutdownDockerNightlyIntegrationTest.java @@ -0,0 +1,105 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.ec2.model.LaunchTemplateData; +import io.floci.aws.services.ec2.model.Volume; +import io.floci.aws.services.ec2.model.VolumeAttachment; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.IndependentServiceSettingsProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +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.Assumptions.assumeTrue; + +/** + * A guest that ends its own container, which a Docker stop issued outside Floci stands in for here, + * gets its instance's shutdown behavior applied through the real EC2 service. + */ +@QuarkusTest +@TestProfile(IndependentServiceSettingsProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class Ec2GuestShutdownDockerNightlyIntegrationTest { + + private static final String REGION = "us-east-1"; + + @Inject + Ec2Service ec2Service; + + @Inject + DockerClient dockerClient; + + @BeforeEach + void requireDocker() { + assumeTrue(DockerAvailability.answers(dockerClient), "Docker must be available for EC2 guest shutdown tests"); + } + + @Test + void anInstanceWhoseGuestShutsDownStops() { + Instance instance = launch(List.of()); + try { + ec2Service.awaitContainerLaunch(instance); + + dockerClient.stopContainerCmd(instance.getDockerContainerId()).withTimeout(5).exec(); + + await().atMost(Duration.ofSeconds(60)).until(() -> "stopped".equals(state(instance))); + assertEquals("Client.InstanceInitiatedShutdown", ec2Service.describeInstances(REGION, + List.of(instance.getInstanceId()), Map.of()).getFirst().getInstances().getFirst() + .getStateReasonCode()); + } finally { + ec2Service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void anInstanceLaunchedToTerminateIsTerminatedWithItsDeleteOnTerminationVolumes() { + LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs(); + ebs.setVolumeSize(1); + ebs.setDeleteOnTermination(true); + LaunchTemplateData.BlockDeviceMapping data = new LaunchTemplateData.BlockDeviceMapping(); + data.setDeviceName("/dev/sdf"); + data.setEbs(ebs); + Instance instance = launch(List.of(data)); + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + ec2.modifyInstanceAttribute(r -> r.instanceId(instance.getInstanceId()) + .instanceInitiatedShutdownBehavior(v -> v.value("terminate"))); + } + ec2Service.awaitContainerLaunch(instance); + List volumeIds = ec2Service.instanceVolumeAttachments(List.of(instance)) + .getOrDefault(instance.getInstanceId(), List.of()).stream() + .map(VolumeAttachment::getVolumeId).toList(); + assertFalse(volumeIds.isEmpty(), "the launch must attach its volumes"); + + dockerClient.stopContainerCmd(instance.getDockerContainerId()).withTimeout(5).exec(); + + await().atMost(Duration.ofSeconds(60)).until(() -> "terminated".equals(state(instance))); + List remaining = ec2Service.describeVolumes(REGION, List.of(), Map.of()).stream() + .map(Volume::getVolumeId).filter(volumeIds::contains).toList(); + assertEquals(List.of(), remaining); + } + + private Instance launch(List blockDevices) { + return ec2Service.runInstances(REGION, "ami-alpine", "t3.micro", 1, 1, null, List.of(), + null, null, List.of(), null, null, null, null, 0, null, null, null, null, false, null, null, + blockDevices, false, null, null).getInstances().getFirst(); + } + + private String state(Instance instance) { + return ec2Service.describeInstances(REGION, List.of(instance.getInstanceId()), Map.of()).getFirst() + .getInstances().getFirst().getState().getName(); + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceInitiatedShutdownBehaviorIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceInitiatedShutdownBehaviorIntegrationTest.java new file mode 100644 index 0000000000..8b01fe81f2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceInitiatedShutdownBehaviorIntegrationTest.java @@ -0,0 +1,99 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.InstanceAttributeName; +import software.amazon.awssdk.services.ec2.model.ShutdownBehavior; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +class Ec2InstanceInitiatedShutdownBehaviorIntegrationTest { + + @Test + void anInstanceLaunchedWithoutAShutdownBehaviorStops() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String instanceId = ec2.runInstances(r -> r.imageId("ami-alpine").instanceType("t3.micro") + .minCount(1).maxCount(1)).instances().getFirst().instanceId(); + + assertEquals("stop", shutdownBehavior(ec2, instanceId)); + } + } + + @Test + void runInstancesKeepsTheShutdownBehaviorItIsGiven() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String instanceId = ec2.runInstances(r -> r.imageId("ami-alpine").instanceType("t3.micro") + .minCount(1).maxCount(1).instanceInitiatedShutdownBehavior(ShutdownBehavior.TERMINATE)) + .instances().getFirst().instanceId(); + + assertEquals("terminate", shutdownBehavior(ec2, instanceId)); + } + } + + @Test + void anInstanceLaunchedFromATemplateKeepsTheTemplatesShutdownBehavior() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String templateName = "halt-" + UUID.randomUUID(); + ec2.createLaunchTemplate(r -> r.launchTemplateName(templateName).launchTemplateData(d -> d + .imageId("ami-alpine").instanceType("t3.micro") + .instanceInitiatedShutdownBehavior(ShutdownBehavior.TERMINATE))); + + String instanceId = ec2.runInstances(r -> r.launchTemplate(t -> t.launchTemplateName(templateName)) + .minCount(1).maxCount(1)).instances().getFirst().instanceId(); + + assertEquals("terminate", shutdownBehavior(ec2, instanceId)); + } + } + + @Test + void modifyInstanceAttributeChangesTheShutdownBehavior() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String instanceId = ec2.runInstances(r -> r.imageId("ami-alpine").instanceType("t3.micro") + .minCount(1).maxCount(1)).instances().getFirst().instanceId(); + + ec2.modifyInstanceAttribute(r -> r.instanceId(instanceId) + .instanceInitiatedShutdownBehavior(v -> v.value("terminate"))); + + assertEquals("terminate", shutdownBehavior(ec2, instanceId)); + } + } + + @Test + void runInstancesRejectsAShutdownBehaviorThatIsNeitherStopNorTerminate() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + Ec2Exception rejected = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> r + .imageId("ami-alpine").instanceType("t3.micro").minCount(1).maxCount(1) + .instanceInitiatedShutdownBehavior("Terminate"))); + + assertEquals("InvalidParameterValue", rejected.awsErrorDetails().errorCode()); + } + } + + @Test + void modifyInstanceAttributeRejectsAShutdownBehaviorThatIsNeitherStopNorTerminate() { + try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + String instanceId = ec2.runInstances(r -> r.imageId("ami-alpine").instanceType("t3.micro") + .minCount(1).maxCount(1)).instances().getFirst().instanceId(); + + Ec2Exception rejected = assertThrows(Ec2Exception.class, () -> ec2.modifyInstanceAttribute(r -> r + .instanceId(instanceId).instanceInitiatedShutdownBehavior(v -> v.value("halt")))); + + assertEquals("InvalidParameterValue", rejected.awsErrorDetails().errorCode()); + assertEquals("stop", shutdownBehavior(ec2, instanceId)); + } + } + + private static String shutdownBehavior(Ec2Client ec2, String instanceId) { + return ec2.describeInstanceAttribute(r -> r.instanceId(instanceId) + .attribute(InstanceAttributeName.INSTANCE_INITIATED_SHUTDOWN_BEHAVIOR)) + .instanceInitiatedShutdownBehavior().value(); + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2RunInstancesPublicIpParamTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2RunInstancesPublicIpParamTest.java index a54c5df4c7..a8fdec661e 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2RunInstancesPublicIpParamTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2RunInstancesPublicIpParamTest.java @@ -106,7 +106,7 @@ class Ec2RunInstancesPublicIpParamTest { nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false), nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class), - nullable(LaunchTemplateData.CapacityReservationSpecification.class))) + nullable(LaunchTemplateData.CapacityReservationSpecification.class), nullable(String.class))) .thenReturn(new Reservation()); handler(service).handle("RunInstances", p, REGION); @@ -118,7 +118,7 @@ class Ec2RunInstancesPublicIpParamTest { associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false), nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class), - nullable(LaunchTemplateData.CapacityReservationSpecification.class)); + nullable(LaunchTemplateData.CapacityReservationSpecification.class), nullable(String.class)); return new Forwarded(groups.getValue(), associatePublicIp.getValue()); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index 1d0b49c0d7..9f3ba23603 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -2562,6 +2562,118 @@ class Ec2ServiceTest { assertNull(instance.getPublicIpAddress()); } + @Test + void anInstanceCarriesItsShutdownBehaviorBeforeItsContainerLaunches() { + Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class); + List behaviorsAtLaunch = new CopyOnWriteArrayList<>(); + doAnswer(invocation -> { + Instance launched = invocation.getArgument(0); + behaviorsAtLaunch.add(launched.getInstanceInitiatedShutdownBehavior()); + return null; + }).when(containerManager).launch(any(), any(ResolvedAmiImage.class), any(), any(), any(), any(), any(), any()); + AmiImageResolver images = mock(AmiImageResolver.class); + when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + Ec2Service service = new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class), + images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + + service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", 2, 2, null, List.of(), null, null, + List.of(), null, null, null, null, 0, null, null, null, null, false, null, null, null, false, null, + null, "terminate"); + + assertEquals(List.of("terminate", "terminate"), behaviorsAtLaunch); + } + + @Test + void aGuestShutdownStopsAnInstanceByDefault() { + Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class); + AmiImageResolver images = mock(AmiImageResolver.class); + when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + Ec2Service service = new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class), + images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String region = "us-east-1"; + Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.252.0.0/24"), + null); + + service.applyGuestShutdown(instance); + + verify(containerManager).stop(instance); + verify(containerManager, never()).terminate(eq(instance), any()); + } + + @Test + void aGuestShutdownRecordsAnInstanceInitiatedShutdownAsTheStateReason() { + Ec2Service service = guestShutdownService(); + String region = "us-east-1"; + Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.250.0.0/24"), + null); + + service.applyGuestShutdown(instance); + + Instance described = describedInstance(service, region, instance.getInstanceId()); + assertEquals("Client.InstanceInitiatedShutdown", described.getStateReasonCode()); + assertEquals("Client.InstanceInitiatedShutdown: Instance initiated shutdown", + described.getStateReasonMessage()); + } + + @Test + void aGuestShutdownThatTerminatesRecordsAnInstanceInitiatedShutdownAsTheStateReason() { + Ec2Service service = guestShutdownService(); + String region = "us-east-1"; + Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.249.0.0/24"), + null); + service.modifyInstanceAttribute(region, instance.getInstanceId(), "instanceInitiatedShutdownBehavior", + "terminate"); + + service.applyGuestShutdown(instance); + + assertEquals("Client.InstanceInitiatedShutdown", + describedInstance(service, region, instance.getInstanceId()).getStateReasonCode()); + } + + @Test + void anInstanceStartedAfterAGuestShutdownHasNoStateReason() { + Ec2Service service = guestShutdownService(); + String region = "us-east-1"; + Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.248.0.0/24"), + null); + service.applyGuestShutdown(instance); + instance.setState(InstanceState.stopped()); + + service.startInstances(region, List.of(instance.getInstanceId())); + + assertNull(describedInstance(service, region, instance.getInstanceId()).getStateReasonCode()); + } + + private Ec2Service guestShutdownService() { + AmiImageResolver images = mock(AmiImageResolver.class); + when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + return new Ec2Service(mockConfig(false), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), + images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + } + + private static Instance describedInstance(Ec2Service service, String region, String instanceId) { + return service.describeInstances(region, List.of(instanceId), Map.of()).getFirst().getInstances().getFirst(); + } + + @Test + void aGuestShutdownTerminatesAnInstanceWhoseShutdownBehaviorIsTerminate() { + Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class); + AmiImageResolver images = mock(AmiImageResolver.class); + when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + Ec2Service service = new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class), + images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory()); + String region = "us-east-1"; + Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.253.0.0/24"), + null); + service.modifyInstanceAttribute(region, instance.getInstanceId(), "instanceInitiatedShutdownBehavior", + "terminate"); + + service.applyGuestShutdown(instance); + + verify(containerManager).terminate(eq(instance), any()); + verify(containerManager, never()).stop(instance); + } + /** Ec2Service in container mode, with a container manager whose containers answer on loopback. */ private static Ec2Service containerModeService() { Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java index 6bf171c48f..f806b52439 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2SystemdGuestDockerIntegrationTest.java @@ -35,8 +35,10 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.util.List; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; @@ -265,4 +267,80 @@ class Ec2SystemdGuestDockerIntegrationTest { } } } + + @Test + void aGuestThatPowersOffIsReported() { + Ec2ContainerManager manager = guestShutdownManager(); + List shutDown = new CopyOnWriteArrayList<>(); + manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchSystemdGuest(manager, "i-halt"); + try { + powerOff(instance.getDockerContainerId()); + + await().atMost(Duration.ofSeconds(30)).until(() -> !shutDown.isEmpty()); + assertEquals(List.of(instance), shutDown); + } finally { + terminate(manager, instance); + } + } + + @Test + void aRebootIsNotReportedButAPowerOffAfterItIs() { + Ec2ContainerManager manager = guestShutdownManager(); + List shutDown = new CopyOnWriteArrayList<>(); + manager.setGuestShutdownHandler(shutDown::add); + Instance instance = launchSystemdGuest(manager, "i-reboot"); + try { + String containerId = instance.getDockerContainerId(); + String bootedAt = docker.inspectContainerCmd(containerId).exec().getState().getStartedAt(); + + manager.reboot(instance); + await().atMost(Duration.ofSeconds(60)).until(() -> { + InspectContainerResponse.ContainerState state = docker.inspectContainerCmd(containerId).exec().getState(); + return Boolean.TRUE.equals(state.getRunning()) && !bootedAt.equals(state.getStartedAt()); + }); + assertEquals(List.of(), shutDown, "a reboot is not the guest shutting down"); + powerOff(containerId); + + await().atMost(Duration.ofSeconds(30)).until(() -> !shutDown.isEmpty()); + assertEquals(List.of(instance), shutDown); + } finally { + terminate(manager, instance); + } + } + + private Ec2ContainerManager guestShutdownManager() { + return new Ec2ContainerManager(containerBuilder, lifecycleManager, + mock(ContainerLogStreamer.class), mock(ContainerDetector.class), dockerHostResolver, docker, + portAllocator, config, mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class), + regionResolver, mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class), + reachableEndpoint); + } + + private static Instance launchSystemdGuest(Ec2ContainerManager manager, String idPrefix) { + Instance instance = new Instance(); + instance.setInstanceId(idPrefix + UUID.randomUUID().toString().replace("-", "").substring(0, 8)); + instance.setRegion(REGION); + manager.launch(instance, + new ResolvedAmiImage(TestImages.PYTHON_ALPINE, ResolvedAmiImage.SYSTEMD_RUNTIME, false, null), + null, REGION); + await().atMost(Duration.ofSeconds(60)).until(() -> "running".equals(instance.getState().getName())); + return instance; + } + + /** Busybox's poweroff asks its init, PID 1 of the guest, to end, which exits the container. */ + private void powerOff(String containerId) { + String poweroff = docker.execCreateCmd(containerId).withCmd("poweroff").exec().getId(); + docker.execStartCmd(poweroff).withDetach(true).exec(new ResultCallback.Adapter<>()); + } + + private static void terminate(Ec2ContainerManager manager, Instance instance) { + CountDownLatch tornDown = new CountDownLatch(1); + manager.terminate(instance, tornDown::countDown); + try { + tornDown.await(60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } }