From 197b1d798ba480047bc7135a04da5139ed8c8ef5 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 26 Nov 2026 13:01:03 -0600 Subject: [PATCH] perf: stop sidecars promptly under an init process and poll RDS and Redshift readiness every 200 ms (#9544) The CodeArtifact Kellnr and AppSync JS runtime sidecars run under Docker's init, so they stop on SIGTERM instead of waiting out the stop timeout, and an AppSync sidecar started without init is replaced rather than adopted. The Redshift readiness check and the RDS parameter-group server start poll every 200 ms against their existing deadlines. --- .../graphql/js/NodeAppSyncJsRuntime.java | 17 ++++++++- .../codeartifact/KellnrSidecarManager.java | 5 +++ .../rds/container/RdsContainerManager.java | 17 +++++++-- .../container/RedshiftContainerManager.java | 9 +++-- .../graphql/js/NodeAppSyncJsRuntimeTest.java | 35 ++++++++++++++++- .../KellnrSidecarManagerTest.java | 38 +++++++++++++++++++ 6 files changed, 112 insertions(+), 9 deletions(-) diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java b/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java index 36100411aa..99c03968f7 100644 --- a/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java +++ b/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java @@ -66,6 +66,12 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown * Adoption compares this and replaces the container when it differs. */ private static final String SCRIPT_LABEL = "io.floci.appsync.js-runtime.script"; + /** + * Label marking a container started under Docker's init process. The script digest cannot tell a + * sidecar from before the init process apart, and one adopted without it waits out the whole stop + * timeout on every reset and shutdown, so adoption replaces a container without this label. + */ + private static final String INIT_LABEL = "io.floci.appsync.js-runtime.init"; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -166,8 +172,13 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown .withEntrypoint(List.of("sh", "-c")) .withCmd(List.of(startCommand())) .withLabel(SCRIPT_LABEL, scriptDigest()) + .withLabel(INIT_LABEL, "true") .withDockerNetwork(jsRuntimeConfig().dockerNetwork()) - .withLogRotation(); + .withLogRotation() + // The server script installs no SIGTERM handler, and node exec'd as PID 1 + // ignores the stop request, so every reset and shutdown would wait out the + // whole stop timeout before Docker sends SIGKILL. + .withInit(); int configuredPort = jsRuntimeConfig().port(); if (configuredPort > 0) { specBuilder.withPortBinding(CONTAINER_INTERNAL_PORT, configuredPort); @@ -213,6 +224,10 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown + "script ({0}); replacing it", ranWith == null ? "unlabelled" : ranWith); return false; } + if (!"true".equals(labels.get(INIT_LABEL))) { + LOG.info("Existing AppSync JS runtime sidecar was started without an init process; replacing it"); + return false; + } try { this.containerId = existing.getId(); ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT), diff --git a/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java b/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java index d3dd85bf96..a96254e210 100644 --- a/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java +++ b/src/main/java/io/floci/aws/services/codeartifact/KellnrSidecarManager.java @@ -179,6 +179,11 @@ public class KellnrSidecarManager implements ContainerTeardown { .withDockerNetwork(config.services().dockerNetwork()) .withEmbeddedDns() .withLogRotation() + // The image's entrypoint is `sh -c "update-ca-certificates && ./kellnr"`, and + // Kellnr installs no SIGTERM handler. As PID 1 it ignores the stop request, so + // every reset, repository delete and shutdown would wait out the whole stop + // timeout for each repository's container. + .withInit() .build(); String containerId = lifecycleManager.create(spec); try { diff --git a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java index 4fc96dc755..08c0fc76dd 100644 --- a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java @@ -43,6 +43,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeMap; @@ -82,6 +83,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe private static final Map MYSQL_OPTION_NAMES = Map.of("time_zone", "default-time-zone"); /** How long a server started with a parameter group's options gets to start listening. */ private static final int PARAMETER_GROUP_START_SECONDS = 120; + private static final long PARAMETER_GROUP_POLL_MILLIS = 200; /** * The role RDS for PostgreSQL runs its own management tasks as ("rdsadmin – A role that's created to handle * many of the management tasks that the administrator with superuser privileges would perform on a @@ -1306,7 +1308,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe */ private void awaitServerWithParameterGroup(String containerName, String containerId, int enginePort) { String[] probe = {"bash", "-c", ": < /dev/tcp/127.0.0.1/" + enginePort}; - for (int attempt = 1; attempt <= PARAMETER_GROUP_START_SECONDS; attempt++) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(PARAMETER_GROUP_START_SECONDS); + String lastProbeError = null; + do { if (hasStopped(containerId)) { throw new ParameterGroupRefusedException(serverErrors(containerId)); } @@ -1315,15 +1319,20 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe return; } } catch (RuntimeException e) { - LOG.debugv("RDS container {0} is not accepting connections yet: {1}", containerName, e.getMessage()); + // Logged only when the reason changes: the probe repeats five times a second. + if (!Objects.equals(lastProbeError, e.getMessage())) { + lastProbeError = e.getMessage(); + LOG.debugv("RDS container {0} is not accepting connections yet: {1}", containerName, + lastProbeError); + } } try { - TimeUnit.SECONDS.sleep(1); + TimeUnit.MILLISECONDS.sleep(PARAMETER_GROUP_POLL_MILLIS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted waiting for the server in " + containerName, e); } - } + } while (System.nanoTime() < deadline); LOG.warnv("The server in RDS container {0} was still starting after {1} s", containerName, PARAMETER_GROUP_START_SECONDS); } diff --git a/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java b/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java index ce57fd3856..0dd8fa948c 100644 --- a/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java +++ b/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java @@ -38,6 +38,8 @@ public class RedshiftContainerManager { private static final String DEFAULT_DATABASE = "dev"; static final int DEFAULT_MAX_CONNECTIONS = 500; static final int LARGE_CLUSTER_MAX_CONNECTIONS = 2000; + private static final long READINESS_TIMEOUT_SECONDS = 60; + private static final long READINESS_POLL_MILLIS = 200; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -571,7 +573,8 @@ public class RedshiftContainerManager { private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description) { String lastOutput = ""; - for (int attempt = 1; attempt <= 60; attempt++) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(READINESS_TIMEOUT_SECONDS); + do { try { ContainerExec.Result result = execInContainer(containerId, cmd, 5); lastOutput = result.stderr(); @@ -583,12 +586,12 @@ public class RedshiftContainerManager { lastOutput = e.getMessage(); } try { - TimeUnit.SECONDS.sleep(1); + TimeUnit.MILLISECONDS.sleep(READINESS_POLL_MILLIS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted initializing " + description + " in " + containerName, e); } - } + } while (System.nanoTime() < deadline); throw new IllegalStateException("Timed out initializing " + description + " in " + containerName + ": " + lastOutput); } diff --git a/src/test/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java b/src/test/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java index 6e7130d687..da9e48a094 100644 --- a/src/test/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java +++ b/src/test/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntimeTest.java @@ -158,7 +158,8 @@ class NodeAppSyncJsRuntimeTest { String digest = Digests.sha256Hex(resource("appsync/appsync-js-runtime.mjs")).substring(0, 16); Container survivor = mock(Container.class); when(survivor.getId()).thenReturn("survivor"); - when(survivor.getLabels()).thenReturn(Map.of("io.floci.appsync.js-runtime.script", digest)); + when(survivor.getLabels()).thenReturn(Map.of("io.floci.appsync.js-runtime.script", digest, + "io.floci.appsync.js-runtime.init", "true")); when(lifecycleManager.findByName(anyString())).thenReturn(Optional.of(survivor)); when(lifecycleManager.adopt("survivor", List.of(4600), Optional.of("js-net"))).thenReturn( new ContainerInfo("survivor", Map.of(4600, @@ -198,9 +199,41 @@ class NodeAppSyncJsRuntimeTest { verify(lifecycleManager).stopAndRemove("old-script", null); verify(lifecycleManager, never()).adopt(anyString(), any(), any()); verify(lifecycleManager).createAndStart(any()); + verify(builder).withInit(); } + @Test + void aSidecarStartedWithoutAnInitProcessIsReplaced() throws IOException { + when(jsRuntime.url()).thenReturn(Optional.empty()); + when(jsRuntime.image()).thenReturn("node:22-alpine"); + when(jsRuntime.containerName()).thenReturn("appsync-js-runtime-test"); + when(jsRuntime.port()).thenReturn(0); + when(jsRuntime.startTimeoutSeconds()).thenReturn(5); + when(jsRuntime.dockerNetwork()).thenReturn(Optional.empty()); + when(containerDetector.isRunningInContainer()).thenReturn(false); + + String digest = Digests.sha256Hex(resource("appsync/appsync-js-runtime.mjs")).substring(0, 16); + Container withoutInit = mock(Container.class); + when(withoutInit.getId()).thenReturn("without-init"); + when(withoutInit.getLabels()).thenReturn(Map.of("io.floci.appsync.js-runtime.script", digest)); + when(lifecycleManager.findByName(anyString())).thenReturn(Optional.of(withoutInit)); + + ContainerBuilder.Builder builder = + mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(Answers.RETURNS_SELF)); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(builder.build()).thenReturn(new ContainerSpec("test-image")); + when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("with-init", + Map.of(4600, new EndpointInfo("127.0.0.1", server.getAddress().getPort())))); + + runtime.ensureStarted(); + + verify(lifecycleManager).stopAndRemove("without-init", null); + verify(lifecycleManager, never()).adopt(anyString(), any(), any()); + verify(builder).withInit(); + verify(builder).withLabel("io.floci.appsync.js-runtime.init", "true"); + } + /** * The window the concurrency fix closes: a failing evaluation used to clear containerId without * stopping the container, so the only handle to a live sidecar was dropped and teardown could diff --git a/src/test/java/io/floci/aws/services/codeartifact/KellnrSidecarManagerTest.java b/src/test/java/io/floci/aws/services/codeartifact/KellnrSidecarManagerTest.java index dbe9b47bb8..adea36e1be 100644 --- a/src/test/java/io/floci/aws/services/codeartifact/KellnrSidecarManagerTest.java +++ b/src/test/java/io/floci/aws/services/codeartifact/KellnrSidecarManagerTest.java @@ -3,13 +3,21 @@ package io.floci.aws.services.codeartifact; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.ContainerTeardown; +import io.floci.aws.core.common.dns.EmbeddedDnsServer; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.PerKeyContainerPool; +import io.floci.aws.testing.ParallelLocks; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.mockito.ArgumentCaptor; import java.lang.reflect.Field; import java.net.http.HttpClient; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -17,11 +25,14 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; /** * Checks teardown wiring and use leases without a Docker daemon. Containers are seeded directly @@ -52,6 +63,33 @@ class KellnrSidecarManagerTest { verify(lifecycleManager).stopAndRemoveStrict("tracked-kellnr-2", null); } + /** + * Kellnr installs no SIGTERM handler, so without an init process as PID 1 it ignores the stop + * request and every stop waits out the whole timeout. The start is failed right after the + * create, so the test needs neither Docker nor a health endpoint. + */ + @Test + @ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ) + void containerRunsUnderAnInitProcessSoAStopEndsItAtOnce() { + EmulatorConfig deepConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(deepConfig.services().codeartifact().cargoImage()).thenReturn("ghcr.io/kellnr/kellnr:5.14.1"); + when(deepConfig.services().dockerNetwork()).thenReturn(Optional.empty()); + when(deepConfig.docker().resourceNamespace()).thenReturn(Optional.empty()); + when(deepConfig.docker().logMaxSize()).thenReturn("10m"); + when(deepConfig.docker().logMaxFile()).thenReturn("3"); + ContainerBuilder realBuilder = new ContainerBuilder( + deepConfig, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class)); + when(lifecycleManager.startCreated(any(), any())).thenThrow(new IllegalStateException("no Docker here")); + KellnrSidecarManager manager = new KellnrSidecarManager(realBuilder, lifecycleManager, deepConfig, + new CodeArtifactContainerRuns(lifecycleManager, deepConfig).containers()); + + assertThrows(IllegalStateException.class, () -> manager.ensureReady("cargo-repo-1", "http://localhost:4566")); + + ArgumentCaptor spec = ArgumentCaptor.forClass(ContainerSpec.class); + verify(lifecycleManager).create(spec.capture()); + assertTrue(spec.getValue().init()); + } + @Test void stopManagedContainersIsANoOpWhenNothingWasEverStarted() { KellnrSidecarManager manager = manager();