mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(docker): see Lambda container exits through one Docker events subscription, behind a flag (#9175)
Every running Lambda container held a /wait stream, a streaming connection and a thread, only to notice its runtime exiting. With floci.docker.events-exit-detection on (off by default), DockerExitEvents watches them all through one events subscription filtered to container die events, as the AWS ECS agent does. Because events are edge-triggered, a container is registered before it starts and the first subscription is confirmed before the registration returns; after the stream drops, it subscribes again and inspects every watched container, reporting the ones that exited or died in the gap and never one still being created. The exit code comes from an inspect, with the event's exitCode attribute as the fallback, and each exit is reported once, on a virtual thread. With the flag off, LambdaExitWatcher runs as before. A dropped or unconfirmed stream marks a sweep that the next subscription to start runs, whoever opened it. An inspect in the sweep that fails with anything but NotFound is tried again on a doubling delay, and only a subscription Docker confirms resets the reconnect backoff. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
05e54bee29
commit
9af8ca07a9
14 files changed
+643
-10
No files matched your search
@@ -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
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String, Registration> registered = new ConcurrentHashMap<>();
|
||||
private final Object subscriptionLock = new Object();
|
||||
private volatile ResultCallback.Adapter<Event> 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<Event> 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<Event> 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<Event> 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<String, String> 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<Event> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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<String, VpcLease> 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
|
||||
|
||||
Reference in new issue
Block a user