perf(rds): wake PostgreSQL initialization on startup logs (#7877)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-10 08:25:25 -04:00
1 parent 8b48aafd44
commit 6565225234
4 files changed
+115 -11

No files matched your search

@@ -154,6 +154,11 @@ public class ContainerLogStreamer {
return follow(containerId, null, line -> logToConsole(logPrefix, line));
}
/** Observes reassembled lines from a newly created container without forwarding or logging them. */
public Closeable observe(String containerId, Consumer<String> observer) {
return follow(containerId, null, new LogReassemblyCallback(observer, 0));
}
/**
* A stream that logs each line written to it to the console logger as it arrives, as the attach methods
* log a container's: for the output of a command run in a container. A line is held only until its
@@ -448,11 +453,11 @@ public class ContainerLogStreamer {
}
}
// Called only once ContainerLifecycleManager has stopped (or confirmed the absence of) the Docker
// container. Give its follow-log reader a bounded chance to deliver any queued frames and terminal
// callback without blocking lifecycle teardown. If no terminal arrives, close that reader before
// Close after container shutdown or when an observation ends while the container still runs.
// Give the follow-log reader a bounded chance to deliver queued frames and a terminal callback
// without blocking the caller. If no terminal arrives, close that reader before
// flushing so frames cannot continue after the fallback finalization boundary.
void closeAfterContainerStopped() {
void closeWithDrainGrace() {
synchronized (emissionLock) {
synchronized (buffers) {
if (terminated || fallbackFinalization != null) {
@@ -546,9 +551,10 @@ public class ContainerLogStreamer {
}
/**
* The lifecycle-facing log handle. Closing it is valid only after the owning container has stopped;
* it gives Docker a bounded chance to deliver its terminal callback before a non-blocking fallback
* closes the reader and finalizes any tail.
* A log-stream handle for lifecycle forwarding or temporary observation. It can close after the
* container stops or end an observation while the container continues running. Closing gives Docker
* a bounded chance to deliver its terminal callback before a non-blocking fallback closes only the
* log reader and finalizes any tail.
*/
static final class ContainerLogHandle implements Closeable {
@@ -560,7 +566,7 @@ public class ContainerLogStreamer {
@Override
public void close() throws IOException {
callback.closeAfterContainerStopped();
callback.closeWithDrainGrace();
}
}
@@ -50,7 +50,9 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
@@ -907,6 +909,24 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
""";
}
static final class PostgresStartupSignal implements Consumer<String> {
final Semaphore signal = new Semaphore(0);
private boolean tcpListener;
private boolean signalled;
@Override
public synchronized void accept(String line) {
if (line.contains("listening on IPv4 address") || line.contains("listening on IPv6 address")) {
tcpListener = true;
}
if (tcpListener && !signalled && line.contains("database system is ready to accept connections")) {
signalled = true;
signal.release();
}
}
}
/**
* Connects over TCP loopback on purpose. The official image runs first-boot init against a
* temporary server that listens only on the Unix socket, so a socket connection can succeed
@@ -922,7 +942,13 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
"-d", "postgres",
"-c", postgresIamRoleInitSql()
};
execUntilSuccess(containerName, containerId, cmd, "PostgreSQL IAM role");
PostgresStartupSignal startup = new PostgresStartupSignal();
// This path receives a newly created container, so replay cannot include a prior start.
try (Closeable observation = logStreamer.observe(containerId, startup)) {
execUntilSuccess(containerName, containerId, cmd, "PostgreSQL IAM role", startup.signal);
} catch (IOException e) {
LOG.warnv(e, "Could not close PostgreSQL startup observation for {0}", containerName);
}
}
/**
@@ -1021,6 +1047,11 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
}
private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description) {
execUntilSuccess(containerName, containerId, cmd, description, new Semaphore(0));
}
private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description,
Semaphore startupSignal) {
String lastOutput = "";
for (int attempt = 1; attempt <= 60; attempt++) {
try {
@@ -1034,7 +1065,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
lastOutput = e.getMessage();
}
try {
TimeUnit.SECONDS.sleep(1);
startupSignal.tryAcquire(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted initializing " + description + " in " + containerName, e);
@@ -70,6 +70,27 @@ class ContainerLogStreamerTest {
return records.stream().map(record -> record.getParameters()[1]).toList();
}
@Test
void startupObservationReassemblesLinesAndClosesWithoutAContainerShutdown() throws Exception {
DockerClient docker = mock(DockerClient.class);
LogContainerCmd command = mock(LogContainerCmd.class, RETURNS_SELF);
when(docker.logContainerCmd("starting-db")).thenReturn(command);
ContainerLogStreamer streamer = new ContainerLogStreamer(docker, null);
List<String> observed = new ArrayList<>();
Closeable handle = streamer.observe("starting-db", observed::add);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(command).exec(captor.capture());
ResultCallback<Frame> callback = captor.getValue();
CountDownLatch closed = new CountDownLatch(1);
callback.onStart(closed::countDown);
callback.onNext(new Frame(StreamType.STDOUT, utf8("ready to ")));
assertTrue(observed.isEmpty());
callback.onNext(new Frame(StreamType.STDOUT, utf8("serve\n")));
assertEquals(List.of("ready to serve"), observed);
handle.close();
assertTrue(closed.await(1, TimeUnit.SECONDS));
}
@Test
void ensureLogGroupAndStreamUsesOwningAccount() {
CloudWatchLogsService cloudWatchLogsService = mock(CloudWatchLogsService.class);
@@ -525,7 +546,7 @@ class ContainerLogStreamerTest {
assertTrue(firstEmissionStarted.await(1, TimeUnit.SECONDS), "the first line should begin emitting");
Thread closer = new Thread(() -> {
cb.closeAfterContainerStopped();
cb.closeWithDrainGrace();
});
closer.start();
Thread terminal = new Thread(cb::onComplete);
@@ -0,0 +1,46 @@
package io.floci.aws.services.rds.container;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PostgresStartupSignalTest {
@Test
void ignoresTheTemporaryUnixOnlyServer() {
RdsContainerManager.PostgresStartupSignal startup = new RdsContainerManager.PostgresStartupSignal();
startup.accept("LOG: listening on Unix socket");
startup.accept("LOG: database system is ready to accept connections");
assertFalse(startup.signal.tryAcquire());
startup.accept("LOG: listening on IPv4 address");
assertFalse(startup.signal.tryAcquire());
startup.accept("LOG: database system is ready to accept connections");
assertTrue(startup.signal.tryAcquire());
}
@Test
void retainsAnEarlySignalUntilTheSqlRetryWaits() {
RdsContainerManager.PostgresStartupSignal startup = new RdsContainerManager.PostgresStartupSignal();
startup.accept("LOG: listening on IPv6 address");
startup.accept("LOG: database system is ready to accept connections");
assertTrue(startup.signal.tryAcquire());
assertFalse(startup.signal.tryAcquire());
}
@Test
void duplicateReadyLinesCannotConsumeTheRetryBudget() {
RdsContainerManager.PostgresStartupSignal startup = new RdsContainerManager.PostgresStartupSignal();
startup.accept("LOG: listening on IPv4 address");
startup.accept("LOG: database system is ready to accept connections");
startup.accept("LOG: database system is ready to accept connections");
assertTrue(startup.signal.tryAcquire());
assertFalse(startup.signal.tryAcquire());
}
@Test
void anUnsupportedLogFormatKeepsTheTimedFallback() {
RdsContainerManager.PostgresStartupSignal startup = new RdsContainerManager.PostgresStartupSignal();
startup.accept("custom database is ready");
assertFalse(startup.signal.tryAcquire());
}
}