fix(docker): hold Lambda extension and exit-watch streams on the streaming pool (#8498)

A Lambda extension's exec and the container's exit watcher each hold a
Docker connection for the container's whole lifetime, and both still ran
on the control-plane client. Enough warm containers, especially with
extensions, could fill that pool and stall every create, start, stop and
remove call, the failure the streaming split was made to prevent.

Both now use the @StreamingDocker client. The exit watcher's inspect is
a short call and stays on the control-plane client, with its retries.
The streaming transport now replays a container wait that fails before
the daemon answers, as the control-plane one does, so a stale socket
does not spend one of the watcher's re-arms. Exec starts and log and
attach streams are still never replayed.

Each live Lambda container now holds its log follow, its exit watcher and
one exec per extension on the streaming pool, so its default rises from
512 to 2048 to cover the 500 containers the runtime API port range allows
with two extensions each. The control-plane default stays at 1024.

Closes #2224
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 17:42:28 -04:00
1 parent ec9c19ff62
commit d51af1ecff
19 files changed
+252 -103

No files matched your search

@@ -16,6 +16,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class ApplicationDefaultsTest {
private static JsonNode productionConfig() throws IOException {
return new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
}
@Test
void productionConfigEnablesCloudTrailByDefault() throws IOException {
try (InputStream configStream = getClass().getClassLoader().getResourceAsStream("application.yml")) {
@@ -33,7 +37,7 @@ class ApplicationDefaultsTest {
@Test
void productionConfigUsesExpectedRequestSizeLimit() throws IOException {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
JsonNode config = productionConfig();
assertEquals(2048,
config.path("floci").path("protocols").path("max-request-size").asInt(),
@@ -42,7 +46,7 @@ class ApplicationDefaultsTest {
@Test
void productionConfigUsesTheAwsSqsMaximumMessageSize() throws IOException, NoSuchMethodException {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
JsonNode config = productionConfig();
assertEquals(1048576,
config.path("floci").path("services").path("sqs").path("max-message-size").asInt(),
@@ -58,7 +62,7 @@ class ApplicationDefaultsTest {
@Test
void productionConfigListensOnLoopbackWithoutNetworkExposureConsent() throws IOException, NoSuchMethodException {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
JsonNode config = productionConfig();
assertEquals("127.0.0.1", config.path("quarkus").path("http").path("host").asText(),
"production application.yml should listen on loopback by default");
@@ -74,7 +78,7 @@ class ApplicationDefaultsTest {
@Test
void productionConfigDoesNotSeedIamDeployerPrincipalByDefault() throws IOException {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
JsonNode config = productionConfig();
assertFalse(config.path("floci")
.path("services")
@@ -86,7 +90,7 @@ class ApplicationDefaultsTest {
@Test
void productionConfigRejectsPrivateJwtTargetsByDefault() throws Exception {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
JsonNode config = productionConfig();
assertFalse(config.path("floci")
.path("security")
@@ -111,19 +115,11 @@ class ApplicationDefaultsTest {
"a stock Floci should refuse a PostgreSQL IAM token generated for another endpoint, as RDS does");
}
// Catches: a max-connections in application.yml that silently disagrees with the @WithDefault fallback.
@Test
void productionConfigSizesTheDockerPoolForTheLambdaRuntimeApiPortRange() throws IOException, NoSuchMethodException {
JsonNode floci = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile())
.path("floci");
int maxConnections = floci.path("docker").path("max-connections").asInt();
JsonNode lambda = floci.path("services").path("lambda");
int runtimeApiPorts = lambda.path("runtime-api-max-port").asInt()
- lambda.path("runtime-api-base-port").asInt() + 1;
assertTrue(maxConnections >= 2 * runtimeApiPorts,
"each live Lambda container holds two Docker connections (log follow and exit watcher), so "
+ "max-connections " + maxConnections + " should cover the " + runtimeApiPorts
+ " containers the runtime API port range allows");
void productionConfigDeclaresTheDockerPoolAtItsDefault() throws IOException, NoSuchMethodException {
int maxConnections = productionConfig()
.path("floci").path("docker").path("max-connections").asInt();
WithDefault fallback = EmulatorConfig.DockerConfig.class
.getMethod("maxConnections")
@@ -133,23 +129,40 @@ class ApplicationDefaultsTest {
"the @WithDefault must match application.yml, which wins over it");
}
// Catches: a streaming pool too small for the Lambda containers the runtime API port range allows,
// so log streams, exit watchers and extensions fail to get a connection well before that limit.
@Test
void productionConfigSizesTheStreamingDockerPoolForTheLambdaRuntimeApiPortRange() throws IOException {
JsonNode floci = productionConfig()
.path("floci");
int streamingMaxConnections = floci.path("docker").path("streaming-max-connections").asInt();
JsonNode lambda = floci.path("services").path("lambda");
int runtimeApiPorts = lambda.path("runtime-api-max-port").asInt()
- lambda.path("runtime-api-base-port").asInt() + 1;
assertTrue(streamingMaxConnections >= 4 * runtimeApiPorts,
"each live Lambda container holds a streaming connection for its log follow, its exit watcher "
+ "and each extension, so streaming-max-connections " + streamingMaxConnections
+ " should cover the " + runtimeApiPorts
+ " containers the runtime API port range allows with two extensions each");
}
// Catches: streaming-max-connections declared and documented but absent from the shipped
// application.yml, or a yml value that silently disagrees with the @WithDefault fallback.
@Test
void productionConfigDeclaresTheStreamingDockerPoolAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode streamingMaxConnections = new YAMLMapper()
.readTree(Path.of("src/main/resources/application.yml").toFile())
JsonNode streamingMaxConnections = productionConfig()
.path("floci").path("docker").path("streaming-max-connections");
assertFalse(streamingMaxConnections.isMissingNode(),
"streaming-max-connections should be declared in application.yml");
assertEquals(512, streamingMaxConnections.asInt());
assertEquals(2048, streamingMaxConnections.asInt());
WithDefault fallback = EmulatorConfig.DockerConfig.class
.getMethod("streamingMaxConnections")
.getAnnotation(WithDefault.class);
assertNotNull(fallback, "streamingMaxConnections should declare a fallback default");
assertEquals("512", fallback.value(),
assertEquals("2048", fallback.value(),
"the @WithDefault must match application.yml, which wins over it");
}
@@ -157,8 +170,7 @@ class ApplicationDefaultsTest {
// value that silently disagrees with the @WithDefault fallback.
@Test
void productionConfigDeclaresTheDockerLeaseTimeoutAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode leaseTimeout = new YAMLMapper()
.readTree(Path.of("src/main/resources/application.yml").toFile())
JsonNode leaseTimeout = productionConfig()
.path("floci").path("docker").path("connection-request-timeout-seconds");
assertFalse(leaseTimeout.isMissingNode(),
@@ -177,8 +189,7 @@ class ApplicationDefaultsTest {
// silently disagrees with the @WithDefault fallback.
@Test
void productionConfigDeclaresTheDockerApiTimeoutAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode apiTimeout = new YAMLMapper()
.readTree(Path.of("src/main/resources/application.yml").toFile())
JsonNode apiTimeout = productionConfig()
.path("floci").path("docker").path("api-timeout-seconds");
assertFalse(apiTimeout.isMissingNode(), "api-timeout-seconds should be declared in application.yml");
@@ -337,6 +337,48 @@ class RetryingDockerHttpClientTest {
}
}
// Catches: a container wait on the streaming transport losing the replay the control-plane
// transport gives it, so each stale socket spends one of the Lambda exit watcher's few re-arms.
@Test
void containerWaitRetrierReplaysAWaitThroughRepeatedBrokenPipes() {
Response ok = mock(Response.class);
FakeTransport delegate = new FakeTransport(attempt -> {
if (attempt < 3) {
throw brokenPipe();
}
return ok;
});
RetryingDockerHttpClient client = RetryingDockerHttpClient.forContainerWaits(delegate, MAX_ATTEMPTS, 0L);
Request wait = Request.builder()
.method(Request.Method.POST)
.path("/containers/abc/wait?condition=not-running")
.build();
assertSame(ok, client.execute(wait));
assertEquals(3, delegate.calls.get());
}
// Catches: the wait-only decorator replaying anything else the streaming transport sends: an exec
// start would re-run its command, and log or attach streams are never replayed there.
@Test
void containerWaitRetrierReplaysNothingElse() {
for (Request request : List.of(
Request.builder().method(Request.Method.POST).path("/exec/abc/start")
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8)).build(),
Request.builder().method(Request.Method.GET).path("/containers/abc/logs?follow=1").build(),
Request.builder().method(Request.Method.POST).path("/containers/abc/attach?stream=1").build(),
Request.builder().method(Request.Method.GET).path("/_ping").build())) {
FakeTransport delegate = new FakeTransport(attempt -> {
throw brokenPipe();
});
RetryingDockerHttpClient client =
RetryingDockerHttpClient.forContainerWaits(delegate, MAX_ATTEMPTS, 0L);
assertThrows(RuntimeException.class, () -> client.execute(request), request.path());
assertEquals(1, delegate.calls.get(), request.path());
}
}
@Test
void retriesOnlyANamedVolumeCreate() {
// Catches: replaying an unnamed volume create, which makes a second volume and orphans the
@@ -512,17 +554,26 @@ class RetryingDockerHttpClientTest {
}
}
// Catches: the control-plane transport losing its retries, the streaming transport losing the
// container-wait replay, or the streaming transport replaying a log stream.
@Test
void producerWrapsControlPlaneTransportOnly() {
void producerWrapsEachTransportInItsOwnReplayPolicy() {
DockerHttpClient raw = new FakeTransport(attempt -> null);
DockerHttpClient controlPlane = DockerClientProducer.wrapForRole(raw, "control-plane");
DockerHttpClient streaming = DockerClientProducer.wrapForRole(raw, "streaming");
assertSame(RetryingDockerHttpClient.class, controlPlane.getClass(),
"the control-plane transport must be wrapped in the retry decorator");
assertNotSame(raw, controlPlane);
assertSame(raw, streaming,
"the streaming transport (log-follow, exec output) must stay unwrapped");
FakeTransport failing = new FakeTransport(attempt -> {
throw brokenPipe();
});
DockerHttpClient streaming = DockerClientProducer.wrapForRole(failing, "streaming");
Request logs = Request.builder().method(Request.Method.GET).path("/containers/abc/logs?follow=1").build();
assertInstanceOf(RetryingDockerHttpClient.class, streaming,
"the streaming transport must replay container waits");
assertThrows(RuntimeException.class, () -> streaming.execute(logs));
assertEquals(1, failing.calls.get(), "the streaming transport must never replay a log stream");
}
}
@@ -253,7 +253,8 @@ class LambdaImageConfigTest {
ContainerReachableEndpoint reachableEndpoint =
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, mock(DockerClient.class),
logStreamer, imageResolver,
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
mock(LambdaLayerService.class), awsEnv,
mock(LambdaExecutionRoleCredentials.class), null);
@@ -64,7 +64,8 @@ class ContainerLauncherCodeVolumeReuseTest {
RuntimeException populateFailure;
RecordingLauncher(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
super(mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
super(mock(ContainerBuilder.class), lifecycleManager, mock(DockerClient.class),
mock(ContainerLogStreamer.class),
mock(ImageResolver.class), mock(RuntimeApiServerFactory.class),
mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class),
mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class),
@@ -280,7 +281,7 @@ class ContainerLauncherCodeVolumeReuseTest {
when(containerBuilder.newContainer("img")).thenReturn(builder);
when(builder.build()).thenThrow(new IllegalStateException("stop before Docker"));
ContainerLauncher real = new ContainerLauncher(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ImageResolver.class),
mock(DockerClient.class), mock(ContainerLogStreamer.class), mock(ImageResolver.class),
mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config,
mock(EcrRegistryManager.class), mock(LambdaLayerService.class),
mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), null);
@@ -33,7 +33,7 @@ class ContainerLauncherCopyRetryTest {
// no longer builds; the copy paths under test read nothing else from it.
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, config, null, null, null, null, null);
return new ContainerLauncher(null, null, null, null, null, null, null, config, null, null, null, null, null);
}
@Test
@@ -10,6 +10,7 @@ import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.WaitContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.ContainerConfig;
@@ -109,6 +110,7 @@ class ContainerLauncherTest {
@Mock EmbeddedDnsServer embeddedDnsServer;
@Mock RuntimeApiServer runtimeApiServer;
@Mock DockerClient dockerClient;
@Mock DockerClient streamingDockerClient;
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
@Mock LambdaLayerService layerService;
@Mock Ec2Service ec2Service;
@@ -256,7 +258,7 @@ class ContainerLauncherTest {
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
ContainerLauncher backgroundLauncher = new ContainerLauncher(
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
lifecycleManager, logStreamer, imageResolver, runtimeApiServerFactory,
lifecycleManager, streamingDockerClient, logStreamer, imageResolver, runtimeApiServerFactory,
dockerHostResolver, config, ecrRegistryManager, layers,
new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service);
LambdaFunction fn = new LambdaFunction();
@@ -509,7 +511,7 @@ class ContainerLauncherTest {
networkResolver, new ContainerEngineDetector(dockerClient));
ContainerReachableEndpoint endpoint =
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
return new ContainerLauncher(builder, lifecycleManager, logStreamer, selectedResolver,
return new ContainerLauncher(builder, lifecycleManager, streamingDockerClient, logStreamer, selectedResolver,
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
layerService, new LaunchedContainerAwsEnv(endpoint),
executionRoleCredentials, ec2Service);
@@ -2448,7 +2450,7 @@ class ContainerLauncherTest {
launchCmds.add(launchCmd);
return launchCmd;
});
lenient().when(dockerClient.execStartCmd(argThat(id -> id != null && id.startsWith("exec-launch-"))))
lenient().when(streamingDockerClient.execStartCmd(launchedExecId()))
.thenAnswer(invocation -> {
ExecStartCmd start = mock(ExecStartCmd.class);
when(start.exec(any())).thenAnswer(startInvocation -> {
@@ -2463,11 +2465,16 @@ class ContainerLauncherTest {
return launchCmds;
}
/** Matches the id of an exec {@link #stubExtensionDiscoveryFromTar} created for an extension launch. */
private static String launchedExecId() {
return argThat(id -> id != null && id.startsWith("exec-launch-"));
}
/** Overrides the default exec-start stub so the callback the launcher supplies is driven with a
* real STDOUT {@link Frame} carrying {@code output}, exercising the frame-to-CloudWatch path
* rather than only completing the callback. */
private void stubExecStartEmittingFrame(String output) {
lenient().when(dockerClient.execStartCmd(argThat(id -> id != null && id.startsWith("exec-launch-"))))
lenient().when(streamingDockerClient.execStartCmd(launchedExecId()))
.thenAnswer(invocation -> {
ExecStartCmd start = mock(ExecStartCmd.class);
when(start.exec(any())).thenAnswer(startInvocation -> {
@@ -2517,6 +2524,28 @@ class ContainerLauncherTest {
inOrder.verify(dockerClient, atLeastOnce()).execCreateCmd("container-123");
}
// Catches: the extension exec or the exit watch running on the control-plane client, where
// each warm container would hold a lease for its whole lifetime and starve short Docker calls.
@Test
void launchFunction_holdsExtensionAndExitStreamsOnTheStreamingClient() throws Exception {
stubExtensionDiscovery("lambda-adapter");
WaitContainerCmd wait = mock(WaitContainerCmd.class);
when(streamingDockerClient.waitContainerCmd("container-123")).thenReturn(wait);
when(wait.exec(any())).thenAnswer(invocation -> invocation.getArgument(0));
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("streaming-pool-fn");
fn.setPackageType("Image");
fn.setImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/repo:latest");
launcher.launch(fn);
verify(streamingDockerClient).execStartCmd(launchedExecId());
verify(streamingDockerClient).waitContainerCmd("container-123");
verify(dockerClient, never()).execStartCmd(anyString());
verify(dockerClient, never()).waitContainerCmd(anyString());
}
/**
* Extension stdout/stderr must reach the function's CloudWatch log group. `docker logs` — and
* therefore ContainerLogStreamer.attach(), which uses logContainerCmd — only covers the
@@ -2534,7 +2563,8 @@ class ContainerLauncherTest {
ContainerLauncher launcherWithRealStreamer = new ContainerLauncher(
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
lifecycleManager,
new ContainerLogStreamer(dockerClient, cloudWatchLogs),
streamingDockerClient,
new ContainerLogStreamer(streamingDockerClient, cloudWatchLogs),
imageResolver, runtimeApiServerFactory, dockerHostResolver, config,
ecrRegistryManager,
mock(LambdaLayerService.class),
@@ -30,13 +30,15 @@ class LambdaExitWatcherTest {
private final List<Duration> delays = new ArrayList<>();
private long now;
private DockerClient docker;
private DockerClient streamingDocker;
private InspectContainerCmd inspect;
@BeforeEach
void setUp() {
docker = mock(DockerClient.class);
streamingDocker = mock(DockerClient.class);
WaitContainerCmd wait = mock(WaitContainerCmd.class);
when(docker.waitContainerCmd(CONTAINER)).thenReturn(wait);
when(streamingDocker.waitContainerCmd(CONTAINER)).thenReturn(wait);
when(wait.exec(any())).thenAnswer(invocation -> {
WaitContainerResultCallback callback = invocation.getArgument(0);
armed.add(callback);
@@ -48,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, CONTAINER, exits::add, (delay, task) -> {
new LambdaExitWatcher(docker, streamingDocker, CONTAINER, exits::add, (delay, task) -> {
delays.add(delay);
task.run();
}, () -> now).arm();