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
@@ -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
|
||||
|
||||
@@ -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<ResultCallback.Adapter<Event>> subscriptions = new CopyOnWriteArrayList<>();
|
||||
private final List<String> 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<Event> 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<String, String> 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)));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
+4
-2
@@ -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"));
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user