diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index c0655bd2c6..7424988b58 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -137,6 +137,7 @@ floci: breaker-failure-threshold: 3 # Consecutive Docker call attempts (each retry counts) failing at the transport before Floci pings the daemon and fails calls fast if it is gone; 0 = off breaker-probe-interval-seconds: 5 # Seconds between pings while the daemon is unreachable max-concurrent-launches: 0 # Most container creates and starts at once; 0 = twice the CPUs, at least 4 + events-exit-detection: false # Watch Lambda exits through one Docker events stream instead of a wait per container log-poll-interval-millis: 1000 # How often a long-lived service container's log is read (it is not followed) docker-config-path: "" # Path to dir containing Docker's config.json (e.g. /root/.docker) registry-credentials: [] # Per-registry explicit credentials for private registries diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index 703f8c920f..7d544f80ea 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -163,6 +163,18 @@ floci: Environment variables: `FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_`, with the label in upper case (`FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_LAMBDA=50`) +### Container exits through Docker events + +Each running Lambda container holds a streaming connection whose only job is to notice its runtime exiting, so an invocation reports `Runtime.ExitError` at once instead of waiting out its timeout. With `events-exit-detection` on, Floci watches every Lambda container's exit through one Docker events subscription instead, which saves each container that connection and its thread. After the subscription drops (a daemon restart, a lost connection), Floci subscribes again and inspects every watched container, so an exit in the gap is still reported. It is off by default while it proves itself: + +```yaml +floci: + docker: + events-exit-detection: false +``` + +Environment variable: `FLOCI_DOCKER_EVENTS_EXIT_DETECTION` + ## Private Registry Authentication Any service that pulls a container image from a private registry (Lambda image functions, custom OpenSearch images, private Postgres images, etc.) needs Docker credentials. Two approaches are supported and can be combined. @@ -424,6 +436,7 @@ caller keeps its existing failure handling after retries are exhausted. | `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS` | `5` | Seconds between the pings that check whether an unreachable Docker daemon is back | | `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES` | `0` | Most container creates and starts sent to the daemon at once; `0` means twice the CPUs Floci sees, at least 4 | | `FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_` | _(none)_ | Most containers one service runs at once, by its `io.floci.service` label; unset means unlimited | +| `FLOCI_DOCKER_EVENTS_EXIT_DETECTION` | `false` | Watch Lambda containers' exits through one Docker events subscription instead of a wait stream per container | | `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `3072` | Connection pool size for streams that last a container's lifetime or a long command's run. Each live Lambda container holds two (log stream and exit watcher) plus one per extension, and each CodeBuild phase, SSM command, ECS Exec session, EKS audit follower, user data script and EMR bootstrap action one | | `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__SERVER` | _(unset)_ | Registry hostname for credential entry 0 | | `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__USERNAME` | _(unset)_ | Username for credential entry 0 | diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 7474ccb899..47dffcc6b8 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -152,6 +152,7 @@ This foundation release provides opt-in security-group filtering for EC2 Docker | `FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD` | `3` | Docker call attempts in a row (each retry counts) that fail before the daemon answers, after which a failed ping makes every Docker call fail at once until the daemon answers again; `0` turns this off. See [Docker Configuration](docker.md#unreachable-daemon) | | `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS` | `5` | Seconds between the pings that check whether an unreachable Docker daemon is back | | `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES` | `0` | Most container creates and starts sent to the Docker daemon at once; `0` means twice the CPUs Floci sees, at least 4. See [Docker Configuration](docker.md#concurrent-container-launches) | +| `FLOCI_DOCKER_EVENTS_EXIT_DETECTION` | `false` | Watch Lambda containers' exits through one Docker events subscription instead of a wait stream per container. See [Docker Configuration](docker.md#container-exits-through-docker-events) | | `FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_` | _(none)_ | Most containers one service runs at once, named by its `io.floci.service` label in upper case (`FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_LAMBDA=50`); a create past it fails with that service's own capacity error. A service not set is not limited. See [Docker Configuration](docker.md#per-service-container-budgets) | | `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` | `1000` | Milliseconds between the reads of a long-lived service container's log, read on a timer instead of followed; at least 100. See [Docker Configuration](docker.md#container-log-settings) | | `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` | _(none)_ | Optional registry/repository base for every Docker image Floci launches. When set, `postgres:16-alpine` resolves as `/postgres:16-alpine` and `public.ecr.aws/docker/library/ubuntu:24.04` resolves as `/public.ecr.aws/docker/library/ubuntu:24.04`. An image in a registry on `localhost` or a loopback address, Floci's own ECR among them, is launched as it is | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 5f09c33d05..8c286771e0 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -4583,6 +4583,14 @@ public interface EmulatorConfig { @WithDefault("0") int maxConcurrentLaunches(); + /** + * Whether Lambda containers' exits are seen through one Docker events subscription for the whole + * daemon rather than one {@code /wait} stream per container, which saves each running container a + * streaming connection and a thread. Off by default while it proves itself. + */ + @WithDefault("false") + boolean eventsExitDetection(); + /** * Most containers a service may run at once, keyed by its {@code io.floci.service} label * ({@code lambda}, {@code rds}, {@code elasticache}, ...). A create past it fails at once with the 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 new file mode 100644 index 0000000000..d3c9cb7e11 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/DockerExitEvents.java @@ -0,0 +1,339 @@ +package io.floci.aws.core.common.docker; + +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.model.Event; +import com.github.dockerjava.api.model.EventType; +import io.floci.aws.config.EmulatorConfig; +import io.quarkus.runtime.ShutdownEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.Closeable; +import java.io.IOException; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.IntConsumer; + +/** + * Container exits seen through one Docker events subscription for the whole daemon, instead of one + * {@code /wait} stream, with its streaming connection and thread, per watched container + * ({@code floci.docker.events-exit-detection}). The AWS ECS agent watches its containers the same way. + * + *

Events are edge-triggered where a wait is level-triggered: an exit the subscription was not + * connected for is never delivered. So a container is registered before it starts, the first + * subscription is confirmed before any registration returns, and after the stream drops (a daemon + * restart, a lost connection) the subscription is opened again and every registered container is + * inspected, which reports an exit the gap hid. Only {@code die} counts: {@code stop} fires on the + * request, before the exit, and an out-of-memory kill also ends in {@code die}. The exit code comes + * from an inspect, with the event's {@code exitCode} attribute as the fallback, and each container's + * exit is reported once, off the events thread. + */ +@ApplicationScoped +public class DockerExitEvents { + + private static final Logger LOG = Logger.getLogger(DockerExitEvents.class); + private static final Duration SUBSCRIBE_CONFIRMATION = Duration.ofSeconds(5); + private static final Duration FIRST_RESUBSCRIBE_DELAY = Duration.ofSeconds(1); + private static final Duration MAX_RESUBSCRIBE_DELAY = Duration.ofSeconds(30); + private static final Duration FIRST_INSPECT_RETRY_DELAY = Duration.ofMillis(200); + private static final int MAX_INSPECT_ATTEMPTS = 5; + + private final DockerClient dockerClient; + private final DockerClient streamingDocker; + private final boolean enabled; + private final Duration subscribeConfirmation; + private final Map registered = new ConcurrentHashMap<>(); + private final Object subscriptionLock = new Object(); + private volatile ResultCallback.Adapter subscription; + private volatile boolean shutdown; + /** Set while the stream may have missed events; the next subscription to start sweeps and clears it. */ + private final AtomicBoolean sweepPending = new AtomicBoolean(); + private int failedSubscriptions; + + @Inject + public DockerExitEvents(DockerClient dockerClient, @StreamingDocker DockerClient streamingDocker, + EmulatorConfig config) { + this(dockerClient, streamingDocker, config.docker().eventsExitDetection()); + } + + DockerExitEvents(DockerClient dockerClient, DockerClient streamingDocker, boolean enabled) { + this(dockerClient, streamingDocker, enabled, SUBSCRIBE_CONFIRMATION); + } + + DockerExitEvents(DockerClient dockerClient, DockerClient streamingDocker, boolean enabled, + Duration subscribeConfirmation) { + this.dockerClient = dockerClient; + this.streamingDocker = streamingDocker; + this.enabled = enabled; + this.subscribeConfirmation = subscribeConfirmation; + } + + /** Whether exits are watched through the events subscription rather than one wait per container. */ + public boolean enabled() { + return enabled; + } + + /** + * Watches {@code containerId} for its exit, calling {@code onExit} once with its exit code (-1 when + * unknown). Call it before the container starts; if the start fails, {@link #unregister} it. + */ + public void register(String containerId, IntConsumer onExit) { + registered.put(containerId, new Registration(containerId, onExit)); + ensureSubscribed(); + } + + /** Stops watching a container that never started or that its owner no longer needs watched. */ + public void unregister(String containerId) { + registered.remove(containerId); + } + + int registeredCount() { + return registered.size(); + } + + int failedSubscriptionCount() { + synchronized (subscriptionLock) { + return failedSubscriptions; + } + } + + private void ensureSubscribed() { + synchronized (subscriptionLock) { + if (subscription != null || shutdown) { + return; + } + subscribe(); + } + } + + /** Opens the subscription and waits for Docker to confirm it, so no exit after this returns is missed. */ + private void subscribe() { + ResultCallback.Adapter callback = new ResultCallback.Adapter<>() { + @Override + public void onStart(Closeable stream) { + super.onStart(stream); + sweepIfPending(); + } + + @Override + public void onNext(Event event) { + onEvent(event); + } + + @Override + public void onError(Throwable throwable) { + super.onError(throwable); + streamEnded(this, throwable); + } + + @Override + public void onComplete() { + super.onComplete(); + streamEnded(this, null); + } + }; + subscription = callback; + try { + streamingDocker.eventsCmd() + .withEventTypeFilter(EventType.CONTAINER) + .withEventFilter("die") + .exec(callback); + if (!callback.awaitStarted(subscribeConfirmation.toMillis(), TimeUnit.MILLISECONDS)) { + LOG.warnv("Docker did not confirm the container events subscription within {0} ms; exits are" + + " checked by inspect once it does", subscribeConfirmation.toMillis()); + awaitingConfirmation(callback); + } else { + synchronized (subscriptionLock) { + failedSubscriptions = 0; + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + awaitingConfirmation(callback); + } catch (RuntimeException e) { + streamEnded(callback, e); + } + } + + /** + * A registration returned before Docker confirmed the stream, so an exit in between could be missed: + * the stream sweeps once it starts, or now if it started while this was being set. + */ + private void awaitingConfirmation(ResultCallback.Adapter callback) { + sweepPending.set(true); + try { + if (callback.awaitStarted(0, TimeUnit.MILLISECONDS)) { + sweepIfPending(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private void sweepIfPending() { + if (sweepPending.getAndSet(false)) { + Thread.ofVirtual().name("floci-container-exit-sweep").start(this::sweep); + } + } + + private void streamEnded(ResultCallback.Adapter ended, Throwable cause) { + long delayMillis; + synchronized (subscriptionLock) { + if (subscription != ended || shutdown) { + return; + } + subscription = null; + sweepPending.set(true); + failedSubscriptions++; + delayMillis = Math.min(MAX_RESUBSCRIBE_DELAY.toMillis(), + FIRST_RESUBSCRIBE_DELAY.toMillis() << Math.min(failedSubscriptions - 1, 5)); + } + LOG.debugv("Docker container events stream ended ({0}); subscribing again in {1} ms", + cause == null ? "closed" : cause.toString(), delayMillis); + CompletableFuture.delayedExecutor(delayMillis, TimeUnit.MILLISECONDS).execute(this::resubscribe); + } + + /** Opens the stream again unless a registration already has; whichever stream starts first sweeps. */ + private void resubscribe() { + synchronized (subscriptionLock) { + if (subscription != null || shutdown) { + return; + } + subscribe(); + } + } + + /** Inspects every registered container, reporting the exits a gap in the subscription hid. */ + void sweep() { + for (Registration registration : registered.values()) { + sweep(registration, 1); + } + } + + /** One container's check; an inspect that fails is tried again with a doubling delay, as LambdaExitWatcher does. */ + private void sweep(Registration registration, int attempt) { + if (shutdown || registration.reported().get() || registered.get(registration.containerId()) != registration) { + return; + } + InspectContainerResponse.ContainerState state; + try { + state = dockerClient.inspectContainerCmd(registration.containerId()).exec().getState(); + } catch (NotFoundException e) { + registered.remove(registration.containerId(), registration); + return; + } catch (RuntimeException e) { + if (attempt >= MAX_INSPECT_ATTEMPTS) { + LOG.warnv("Could not inspect container {0} after the events stream reconnected, {1} attempts;" + + " its exit is reported only by a later event: {2}", + registration.containerId(), attempt, e.getMessage()); + return; + } + long delayMillis = FIRST_INSPECT_RETRY_DELAY.toMillis() << (attempt - 1); + LOG.debugv("Could not inspect container {0} after the events stream reconnected; trying again in {1} ms: {2}", + registration.containerId(), delayMillis, e.getMessage()); + CompletableFuture.delayedExecutor(delayMillis, TimeUnit.MILLISECONDS) + .execute(() -> sweep(registration, attempt + 1)); + return; + } + // "created" has not started yet; only a container that ran and ended has exited. + String status = state == null ? null : state.getStatus(); + if ("exited".equals(status) || "dead".equals(status)) { + Long exitCode = state.getExitCodeLong(); + report(registration, exitCode != null ? exitCode.intValue() : -1); + } + } + + void onEvent(Event event) { + if (event == null || !"die".equals(event.getAction() != null ? event.getAction() : event.getStatus())) { + return; + } + String containerId = event.getActor() != null && event.getActor().getId() != null + ? event.getActor().getId() : event.getId(); + Registration registration = containerId == null ? null : registered.get(containerId); + if (registration != null) { + report(registration, null, exitCodeAttribute(event)); + } + } + + private void report(Registration registration, int exitCode) { + report(registration, exitCode, exitCode); + } + + /** Reports an exit once, off the caller's thread; {@code known} is a code already read by inspect. */ + private void report(Registration registration, Integer known, int fallback) { + if (!registration.reported().compareAndSet(false, true)) { + return; + } + registered.remove(registration.containerId(), registration); + Thread.ofVirtual().name("floci-container-exit").start(() -> { + int exitCode = known != null ? known : inspectedExitCode(registration.containerId(), fallback); + try { + registration.onExit().accept(exitCode); + } catch (RuntimeException e) { + LOG.warnv(e, "Handling the exit of container {0} failed", registration.containerId()); + } + }); + } + + private int inspectedExitCode(String containerId, int fallback) { + try { + InspectContainerResponse.ContainerState state = dockerClient.inspectContainerCmd(containerId).exec().getState(); + Long exitCode = state == null ? null : state.getExitCodeLong(); + return exitCode != null ? exitCode.intValue() : fallback; + } catch (RuntimeException e) { + LOG.debugv("Could not inspect exited container {0}; using its event''s exit code: {1}", + containerId, e.getMessage()); + return fallback; + } + } + + /** The event's {@code exitCode} attribute, or -1 when it is missing or not a number. */ + static int exitCodeAttribute(Event event) { + Map attributes = event.getActor() == null ? null : event.getActor().getAttributes(); + String exitCode = attributes == null ? null : attributes.get("exitCode"); + if (exitCode == null) { + return -1; + } + try { + return Integer.parseInt(exitCode.trim()); + } catch (NumberFormatException e) { + LOG.debugv("Container event carried a non-numeric exit code: {0}", exitCode); + return -1; + } + } + + void onShutdown(@Observes ShutdownEvent event) { + close(); + } + + void close() { + ResultCallback.Adapter open; + synchronized (subscriptionLock) { + shutdown = true; + open = subscription; + subscription = null; + } + if (open != null) { + try { + open.close(); + } catch (IOException e) { + LOG.debugv("Could not close the Docker container events stream: {0}", e.getMessage()); + } + } + } + + private record Registration(String containerId, IntConsumer onExit, AtomicBoolean reported) { + Registration(String containerId, IntConsumer onExit) { + this(containerId, onExit, new AtomicBoolean()); + } + } +} diff --git a/src/main/java/io/floci/aws/core/common/docker/DockerJavaNativeSupport.java b/src/main/java/io/floci/aws/core/common/docker/DockerJavaNativeSupport.java index a50feb9f80..1aea820d4c 100644 --- a/src/main/java/io/floci/aws/core/common/docker/DockerJavaNativeSupport.java +++ b/src/main/java/io/floci/aws/core/common/docker/DockerJavaNativeSupport.java @@ -57,6 +57,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection; "com.github.dockerjava.api.model.DeviceRequest", "com.github.dockerjava.api.model.DockerObject", "com.github.dockerjava.api.model.Driver", + "com.github.dockerjava.api.model.Event", + "com.github.dockerjava.api.model.EventActor", + "com.github.dockerjava.api.model.EventType", "com.github.dockerjava.api.model.ExposedPort", "com.github.dockerjava.api.model.ExposedPorts", "com.github.dockerjava.api.model.ExternalCA", @@ -84,6 +87,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection; "com.github.dockerjava.api.model.Network$Ipam", "com.github.dockerjava.api.model.Network$Ipam$Config", "com.github.dockerjava.api.model.NetworkSettings", + "com.github.dockerjava.api.model.Node", "com.github.dockerjava.api.model.PeerNode", "com.github.dockerjava.api.model.PidsStatsConfig", "com.github.dockerjava.api.model.PortBinding", 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 fdf1716f3f..5401cab2ec 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 @@ -13,6 +13,7 @@ import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.DockerCapacityExceededException; +import io.floci.aws.core.common.docker.DockerExitEvents; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.DockerPlatforms; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; @@ -133,6 +134,8 @@ 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). */ + private final DockerExitEvents exitEvents; private final LambdaContainerReconciler containerReconciler; /** The VPC address each VpcConfig function's container holds, returned once it is removed. */ private final Map vpcLeases = new ConcurrentHashMap<>(); @@ -151,7 +154,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { LambdaLayerService layerService, LaunchedContainerAwsEnv awsEnv, LambdaExecutionRoleCredentials executionRoleCredentials, - Ec2Service ec2Service) { + Ec2Service ec2Service, + DockerExitEvents exitEvents) { + this.exitEvents = exitEvents; this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.streamingDocker = streamingDocker; @@ -459,9 +464,23 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { // Now start the container with code in place joinVpcNetwork(fn, containerId, lambdaAccountId, lambdaRegion); - lifecycleManager.startCreated(containerId, spec); + boolean exitByEvents = exitEvents.enabled(); + if (exitByEvents) { + // Events report only what happens after the subscription, so register before the start. + exitEvents.register(containerId, runtimeApiServer::handleRuntimeProcessExited); + } + try { + lifecycleManager.startCreated(containerId, spec); + } catch (RuntimeException e) { + if (exitByEvents) { + exitEvents.unregister(containerId); + } + throw e; + } runtimeApiServer.markContainerStarted(); - watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer); + if (!exitByEvents) { + watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer); + } // Extensions can log as soon as they start, which is before the container's own log stream // is attached below. Create the group/stream up front so those early lines are not dropped diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 0ec7652cb7..87d45042bb 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -445,6 +445,10 @@ floci: # Floci sees, at least 4. Keep in step with the @WithDefault on # EmulatorConfig.DockerConfig.maxConcurrentLaunches: a value set here WINS over the annotation. max-concurrent-launches: 0 + # FLOCI_DOCKER_EVENTS_EXIT_DETECTION: see Lambda containers exit through one Docker events + # subscription instead of a wait stream per container. Keep in step with the @WithDefault on + # EmulatorConfig.DockerConfig.eventsExitDetection: a value set here WINS over the annotation. + events-exit-detection: false # FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS: milliseconds between the reads of a long-lived service # container's log (databases, brokers, registries), read on a timer instead of a follow stream held # for the container's life; at least 100. Keep in step with the @WithDefault on diff --git a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java index e7e7079ff5..6042792894 100644 --- a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java +++ b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java @@ -247,6 +247,18 @@ class ApplicationDefaultsTest { .getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml"); } + // Catches: events-based exit detection switched on by default before it has proven itself, or the + // yml and the @WithDefault disagreeing. + @Test + void productionConfigKeepsEventsBasedExitDetectionOff() throws IOException, NoSuchMethodException { + JsonNode flag = productionConfig().path("floci").path("docker").path("events-exit-detection"); + + assertFalse(flag.isMissingNode(), "events-exit-detection should be declared in application.yml"); + assertFalse(flag.asBoolean(true)); + assertEquals("false", EmulatorConfig.DockerConfig.class.getMethod("eventsExitDetection") + .getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml"); + } + // Catches: log-poll-interval-millis missing from the shipped application.yml, or a yml value that // silently disagrees with its @WithDefault fallback. @Test diff --git a/src/test/java/io/floci/aws/core/common/docker/DockerExitEventsTest.java b/src/test/java/io/floci/aws/core/common/docker/DockerExitEventsTest.java new file mode 100644 index 0000000000..8f5f0720d1 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/DockerExitEventsTest.java @@ -0,0 +1,226 @@ +package io.floci.aws.core.common.docker; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.EventsCmd; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.Event; +import com.github.dockerjava.api.model.EventActor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +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.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DockerExitEventsTest { + + private final DockerClient docker = mock(DockerClient.class); + private final DockerClient streaming = mock(DockerClient.class); + private final List> subscriptions = new CopyOnWriteArrayList<>(); + private final List exits = new CopyOnWriteArrayList<>(); + private volatile boolean dockerConfirms = true; + private DockerExitEvents events; + + @BeforeEach + void subscribeOnDemand() { + EventsCmd command = mock(EventsCmd.class, Answers.RETURNS_SELF); + when(streaming.eventsCmd()).thenReturn(command); + when(command.exec(any())).thenAnswer(invocation -> { + ResultCallback.Adapter callback = invocation.getArgument(0); + subscriptions.add(callback); + if (dockerConfirms) { + callback.onStart(() -> { }); + } + return callback; + }); + events = new DockerExitEvents(docker, streaming, true); + } + + @AfterEach + void close() { + events.close(); + } + + private void inspected(String containerId, String status, Long exitCode) { + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse response = state(status, exitCode); + when(docker.inspectContainerCmd(containerId)).thenReturn(inspect); + when(inspect.exec()).thenReturn(response); + } + + private static InspectContainerResponse state(String status, Long exitCode) { + InspectContainerResponse response = mock(InspectContainerResponse.class); + InspectContainerResponse.ContainerState state = mock(InspectContainerResponse.ContainerState.class); + when(response.getState()).thenReturn(state); + when(state.getStatus()).thenReturn(status); + when(state.getExitCodeLong()).thenReturn(exitCode); + return response; + } + + private static Event die(String containerId, Map attributes) { + return new Event("die", containerId, "image", 0L).withAction("die") + .withEventActor(new EventActor().withId(containerId).withAttributes(attributes)); + } + + // Catches: an exit reported with the event's code when the inspect knows better, or not at all. + @Test + void aDieEventReportsTheInspectedExitCodeOnce() { + inspected("c1", "exited", 3L); + events.register("c1", code -> exits.add("c1=" + code)); + + subscriptions.get(0).onNext(die("c1", Map.of("exitCode", "137"))); + subscriptions.get(0).onNext(die("c1", Map.of("exitCode", "137"))); + + await("the exit should be reported").atMost(Duration.ofSeconds(5)).until(() -> exits.size() == 1); + assertEquals(List.of("c1=3"), exits); + assertEquals(0, events.registeredCount(), "a reported container is no longer watched"); + } + + // Catches: an exit that happened while the stream was down never being reported, or a container + // still being created reported as exited by the sweep. + @Test + void aDroppedStreamSubscribesAgainAndTheSweepReportsOnlyEndedContainers() { + inspected("ended", "exited", 1L); + inspected("starting", "created", 0L); + events.register("ended", code -> exits.add("ended=" + code)); + events.register("starting", code -> exits.add("starting=" + code)); + + subscriptions.get(0).onError(new RuntimeException("daemon restarted")); + + await("the stream should be opened again").atMost(Duration.ofSeconds(5)) + .until(() -> subscriptions.size() == 2); + await("the sweep should report the container that ended").atMost(Duration.ofSeconds(5)) + .until(() -> exits.size() == 1); + assertEquals(List.of("ended=1"), exits); + assertEquals(1, events.registeredCount(), "the container still being created stays watched"); + } + + // Catches: an event and the reconnect sweep both reporting the same exit. + @Test + void anEventAndTheSweepReportAnExitOnce() { + inspected("c1", "exited", 2L); + events.register("c1", code -> exits.add("c1=" + code)); + + subscriptions.get(0).onNext(die("c1", null)); + events.sweep(); + + await("the exit should be reported once").during(Duration.ofMillis(200)).atMost(Duration.ofSeconds(5)) + .until(() -> exits.size() == 1); + assertEquals(List.of("c1=2"), exits); + } + + // Catches: an exit the stream missed never being reported because the sweep's one inspect failed. + @Test + void aSweepRetriesAContainerItCouldNotInspect() { + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse exited = state("exited", 2L); + when(docker.inspectContainerCmd("c1")).thenReturn(inspect); + when(inspect.exec()).thenThrow(new RuntimeException("daemon busy")).thenReturn(exited); + events.register("c1", code -> exits.add("c1=" + code)); + + events.sweep(); + + await("the retried inspect should report the exit").atMost(Duration.ofSeconds(5)) + .until(() -> exits.size() == 1); + assertEquals(List.of("c1=2"), exits); + } + + // Catches: a registration reopening the stream during the reconnect backoff, so the delayed + // resubscribe finds a stream and never sweeps for the exits the gap hid. + @Test + void aRegistrationDuringTheBackoffStillSweeps() { + inspected("ended", "exited", 1L); + inspected("other", "running", null); + events.register("ended", code -> exits.add("ended=" + code)); + + subscriptions.get(0).onError(new RuntimeException("daemon restarted")); + events.register("other", code -> exits.add("other=" + code)); + + assertEquals(2, subscriptions.size(), "the registration should open the stream again at once"); + await("the reopened stream should sweep").atMost(Duration.ofSeconds(5)) + .until(() -> exits.contains("ended=1")); + } + + // Catches: a registration returning before Docker confirmed the stream and the exit in between + // never being reported, as the warning promises it is. + @Test + void anUnconfirmedSubscriptionSweepsOnceItStarts() { + events.close(); + dockerConfirms = false; + events = new DockerExitEvents(docker, streaming, true, Duration.ofMillis(50)); + inspected("c1", "exited", 137L); + + events.register("c1", code -> exits.add("c1=" + code)); + subscriptions.get(0).onStart(() -> { }); + + await("the stream should sweep once it starts").atMost(Duration.ofSeconds(5)) + .until(() -> exits.equals(List.of("c1=137"))); + } + + // Catches: a subscription Docker never confirmed resetting the reconnect backoff, so a daemon that + // refuses the connection is tried again every second instead of on a doubling delay. + @Test + void anUnconfirmedSubscriptionKeepsTheBackoffGrowing() { + events.close(); + dockerConfirms = false; + events = new DockerExitEvents(docker, streaming, true, Duration.ofMillis(50)); + events.register("c1", code -> exits.add("c1=" + code)); + + subscriptions.get(0).onError(new RuntimeException("Connection refused")); + await("the stream should be opened again").atMost(Duration.ofSeconds(5)) + .until(() -> subscriptions.size() == 2); + subscriptions.get(1).onError(new RuntimeException("Connection refused")); + + assertEquals(2, events.failedSubscriptionCount(), "two refused subscriptions in a row"); + } + + // Catches: a container removed while the stream was down staying registered forever. + @Test + void theSweepForgetsAContainerThatIsGone() { + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + when(docker.inspectContainerCmd("gone")).thenReturn(inspect); + when(inspect.exec()).thenThrow(new NotFoundException("No such container")); + events.register("gone", code -> exits.add("gone=" + code)); + + events.sweep(); + + assertEquals(0, events.registeredCount()); + assertTrue(exits.isEmpty()); + } + + // Catches: a stop event, which fires before the exit, being taken for the exit. + @Test + void onlyDieCounts() { + events.register("c1", code -> exits.add("c1=" + code)); + + events.onEvent(new Event("stop", "c1", "image", 0L).withAction("stop") + .withEventActor(new EventActor().withId("c1"))); + + assertEquals(1, events.registeredCount()); + verify(streaming, times(1)).eventsCmd(); + } + + @Test + void theExitCodeAttributeFallsBackToMinusOne() { + assertEquals(137, DockerExitEvents.exitCodeAttribute(die("c", Map.of("exitCode", "137")))); + assertEquals(-1, DockerExitEvents.exitCodeAttribute(die("c", Map.of("exitCode", "oops")))); + assertEquals(-1, DockerExitEvents.exitCodeAttribute(die("c", Map.of()))); + assertEquals(-1, DockerExitEvents.exitCodeAttribute(die("c", null))); + assertEquals(-1, DockerExitEvents.exitCodeAttribute(new Event("die", "c", "image", 0L))); + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java index ffacf6e8e6..7b1d783a5b 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java @@ -11,6 +11,7 @@ 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.ContainerSpec; +import io.floci.aws.core.common.docker.DockerExitEvents; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.core.storage.InMemoryStorage; @@ -258,7 +259,7 @@ class LambdaImageConfigTest { runtimeApiServerFactory, dockerHostResolver, config, new RegionResolver("us-east-1", "000000000000"), ecrRegistryManager, mock(LambdaLayerService.class), awsEnv, - mock(LambdaExecutionRoleCredentials.class), null); + mock(LambdaExecutionRoleCredentials.class), null, mock(DockerExitEvents.class)); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java index 89781d22c8..b664a13475 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.core.common.docker.DockerExitEvents; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.ecr.registry.EcrRegistryManager; @@ -71,7 +72,7 @@ class ContainerLauncherCodeVolumeReuseTest { mock(DockerHostResolver.class), config, new RegionResolver("us-east-1", "000000000000"), mock(EcrRegistryManager.class), mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class), - mock(LambdaExecutionRoleCredentials.class), null); + mock(LambdaExecutionRoleCredentials.class), null, mock(DockerExitEvents.class)); } @Override @@ -287,7 +288,8 @@ class ContainerLauncherCodeVolumeReuseTest { mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config, new RegionResolver("us-east-1", "000000000000"), mock(EcrRegistryManager.class), mock(LambdaLayerService.class), - mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), null); + mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), null, + mock(DockerExitEvents.class)); assertThrows(IllegalStateException.class, () -> real.populateCodeVolume("vol", fn("sha"), "img")); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java index 1cd877b614..935b04f7ff 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.lambda.launcher; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.DockerExitEvents; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -34,7 +35,7 @@ class ContainerLauncherCopyRetryTest { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().lambda().codeVolumePopulateConcurrency()).thenReturn(Optional.empty()); return new ContainerLauncher(null, null, null, null, null, null, null, config, null, null, null, null, null, - null); + null, mock(DockerExitEvents.class)); } @Test diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java index a7401d5e16..03678ad301 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java @@ -29,6 +29,7 @@ import io.floci.aws.core.common.docker.ContainerLogStreamer; import io.floci.aws.core.common.docker.ContainerReachableEndpoint; import io.floci.aws.core.common.docker.ContainerSpec; import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; +import io.floci.aws.core.common.docker.DockerExitEvents; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; @@ -258,7 +259,8 @@ class ContainerLauncherTest { new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), lifecycleManager, streamingDockerClient, logStreamer, imageResolver, runtimeApiServerFactory, dockerHostResolver, config, regionResolver, ecrRegistryManager, layers, - new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service); + new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service, + mock(DockerExitEvents.class)); LambdaFunction fn = new LambdaFunction(); fn.setFunctionName("background-layer"); fn.setFunctionArn("arn:aws:lambda:" + region + ":" + account + ":function:background-layer"); @@ -512,7 +514,7 @@ class ContainerLauncherTest { return new ContainerLauncher(builder, lifecycleManager, streamingDockerClient, logStreamer, selectedResolver, runtimeApiServerFactory, dockerHostResolver, config, regionResolver, ecrRegistryManager, layerService, new LaunchedContainerAwsEnv(endpoint), - executionRoleCredentials, ec2Service); + executionRoleCredentials, ec2Service, mock(DockerExitEvents.class)); } @ParameterizedTest @@ -2557,7 +2559,7 @@ class ContainerLauncherTest { ecrRegistryManager, mock(LambdaLayerService.class), new LaunchedContainerAwsEnv(reachableEndpoint), - executionRoleCredentials, ec2Service); + executionRoleCredentials, ec2Service, mock(DockerExitEvents.class)); stubExtensionDiscovery("otel-collector"); // Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.