feat(docker): read long-lived service containers' logs on a timer (#9048)

* feat(docker): read long-lived service containers' logs on a timer
* test(memorydb): verify the polled log attach
* fix(docker): bound polled log reads, flush on a failed close read, and read Redshift's log before its removal
* fix(docker): hold a polled log record cut inside its timestamp
* fix(docker): read a polled log record's stamp only in the runtimes' nine-digit layout
* fix(docker): open a polled log record only where a frame can begin

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
Hector VenturaandPriamo authored and GitHub committed 2026-11-22 08:06:03 -04:00
1 parent 15d142819b
commit 076f6ed504
34 files changed
+883 -52

No files matched your search

@@ -247,6 +247,18 @@ class ApplicationDefaultsTest {
.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
void productionConfigDeclaresTheContainerLogPollIntervalAtItsDefault() throws IOException, NoSuchMethodException {
JsonNode interval = productionConfig().path("floci").path("docker").path("log-poll-interval-millis");
assertFalse(interval.isMissingNode(), "log-poll-interval-millis should be declared in application.yml");
assertEquals(1000, interval.asInt());
assertEquals("1000", EmulatorConfig.DockerConfig.class.getMethod("logPollIntervalMillis")
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
// Catches: warm-pool-max-total shipped unbounded again, so a stack of many functions keeps one
// warm container per function touched, or a yml value that disagrees with the @WithDefault.
@Test
@@ -0,0 +1,261 @@
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.LogContainerCmd;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.InOrder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class PolledLogHandleTest {
private final List<String> lines = Collections.synchronizedList(new ArrayList<>());
private PolledLogHandle handle(Instant since) {
return new PolledLogHandle(mock(DockerClient.class), "c1", since,
(stream, line) -> lines.add(stream + ":" + line));
}
private static byte[] record(String timestamp, String content) {
return (timestamp + " " + content).getBytes(StandardCharsets.UTF_8);
}
private static void read(PolledLogHandle handle, StreamType stream, byte[]... frames) {
handle.beginRead(true);
for (byte[] frame : frames) {
handle.accept(stream, frame);
}
}
// Catches: a whole-second since re-reading the records of the last second into CloudWatch Logs
// again, or a "last timestamp plus a nanosecond" cursor dropping a later record that shares a timestamp.
@Test
void recordsAreForwardedOnceAcrossOverlappingReadsEvenWhenTheyShareATimestamp() {
PolledLogHandle handle = handle(null);
String t1 = "2026-11-19T10:00:00.100000000Z";
String t2 = "2026-11-19T10:00:00.200000000Z";
String t3 = "2026-11-19T10:00:01.000000000Z";
read(handle, StreamType.STDOUT, record(t1, "a\n"), record(t2, "b\n"), record(t2, "c\n"));
read(handle, StreamType.STDOUT, record(t1, "a\n"), record(t2, "b\n"), record(t2, "c\n"),
record(t2, "d\n"), record(t3, "e\n"));
assertEquals(List.of("STDOUT:a", "STDOUT:b", "STDOUT:c", "STDOUT:d", "STDOUT:e"), lines);
}
// Catches: docker-java handing a Docker frame on in reads of up to 1024 bytes, one of which ends inside
// a record's timestamp, so that neither piece parses as a record and the line is dropped or forwarded
// with Docker's timestamp in front of it; or one that ends right after the stamp, so that a line whose
// text starts with an instant, as MySQL's error log does, is taken for an older record and dropped.
@Test
void aRecordCutAnywhereByTheTransportIsForwardedOnceWithoutItsTimestamp() {
assertForwardedOnceWhereverCut("2026-11-19T10:00:00.100000000Z", "2026-11-19T10:00:00.200000000Z",
"2026-11-19T10:00:01.000000000Z", "2026-11-19T10:00:01.500000000Z");
}
// Catches: the stamp Podman wrote before 5.8 (Go's time.RFC3339: whole seconds, in the daemon's offset)
// not being read as one, so that no line of a service container under that Podman is forwarded.
@Test
void aWholeSecondStampAsPodmanWroteBefore58IsReadWhereverTheRecordIsCut() {
assertForwardedOnceWhereverCut("2026-11-19T04:00:00-06:00", "2026-11-19T04:00:00-06:00",
"2026-11-19T04:00:01-06:00", "2026-11-19T04:00:02-06:00");
}
/** Four records, the last one's text opening with MySQL's instant, cut by the transport at every byte. */
private void assertForwardedOnceWhereverCut(String t1, String t2, String t3, String t4) {
byte[] stream = String.join("", t1 + " first\n", t2 + " second line\n", t3 + " third\n",
t4 + " 2026-11-19T10:00:00.099999Z 0 [System] ready\n").getBytes(StandardCharsets.UTF_8);
List<String> expected = List.of("STDOUT:first", "STDOUT:second line", "STDOUT:third",
"STDOUT:2026-11-19T10:00:00.099999Z 0 [System] ready");
for (int cut = 1; cut < stream.length; cut++) {
lines.clear();
read(handle(null), StreamType.STDOUT, Arrays.copyOfRange(stream, 0, cut),
Arrays.copyOfRange(stream, cut, stream.length));
assertEquals(expected, lines, "cut at byte " + cut);
}
lines.clear();
PolledLogHandle byteAtATime = handle(null);
byteAtATime.beginRead(true);
for (byte b : stream) {
byteAtATime.accept(StreamType.STDOUT, new byte[] {b});
}
assertEquals(expected, lines);
}
// Catches: a line over 16 KB, which Docker writes as several records with a newline only on the last,
// forwarded with a later record's stamp in its text, or that record dropped when the transport cuts it.
@Test
void aLineDockerSplitIntoRecordsIsForwardedWholeWhereverItsLaterRecordIsCut() {
byte[] first = record("2026-11-19T10:00:00.100000000Z", "partial-");
byte[] last = record("2026-11-19T10:00:00.200000000Z", "end\n");
for (int cut = 1; cut < last.length; cut++) {
lines.clear();
read(handle(null), StreamType.STDOUT, first, Arrays.copyOfRange(last, 0, cut),
Arrays.copyOfRange(last, cut, last.length));
assertEquals(List.of("STDOUT:partial-end"), lines, "cut at byte " + cut);
}
}
// Catches: digits ending a payload inside a record, held in case they open a stamp, lost when the read
// ends there and the rest of the line comes only in a later read.
@Test
void textHeldAtTheEndOfAReadIsForwardedWithItsLine() {
String t1 = "2026-11-19T10:00:00.100000000Z";
String t2 = "2026-11-19T10:00:00.200000000Z";
LogContainerCmd first = logRead(record(t1, "closing at "), "12:30".getBytes(StandardCharsets.UTF_8));
LogContainerCmd second = logRead(record(t1, "closing at 12:30"), record(t2, " done\n"));
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("c1")).thenReturn(first, second);
PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
handle.read();
handle.read();
assertEquals(List.of("closing at 12:30 done"), lines);
}
// Catches: a line the container had not finished writing at one read being split in two, or its
// first half being forwarded twice.
@Test
void aLineSplitAcrossReadsIsForwardedWhole() {
PolledLogHandle handle = handle(null);
String t1 = "2026-11-19T10:00:00.100000000Z";
String t2 = "2026-11-19T10:00:00.900000000Z";
read(handle, StreamType.STDERR, record(t1, "hel"));
read(handle, StreamType.STDERR, record(t1, "hel"), record(t2, "lo\n"));
assertEquals(List.of("STDERR:hello"), lines);
}
// Catches: an attach from now replaying the history of a container that ran before Floci started.
@Test
void anAttachFromNowSkipsWhatTheContainerWroteBefore() {
PolledLogHandle handle = handle(Instant.parse("2026-11-19T10:00:00.500000000Z"));
read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "old\n"),
record("2026-11-19T10:00:00.600000000Z", "new\n"));
assertEquals(List.of("STDOUT:new"), lines);
}
// Catches: an unterminated last line lost at close, or a read landing after the close duplicating it.
@Test
void finishFlushesTheUnterminatedTailAndIgnoresLaterReads() {
PolledLogHandle handle = handle(null);
read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "shutting down"));
handle.finish();
read(handle, StreamType.STDOUT, record("2026-11-19T10:00:02.000000000Z", "late\n"));
assertEquals(List.of("STDOUT:shutting down"), lines);
}
private static LogContainerCmd logRead(byte[]... records) {
LogContainerCmd command = mock(LogContainerCmd.class, Answers.RETURNS_SELF);
when(command.exec(any())).thenAnswer(invocation -> {
ResultCallback.Adapter<Frame> callback = invocation.getArgument(0);
for (byte[] record : records) {
callback.onNext(new Frame(StreamType.STDOUT, record));
}
callback.onComplete();
return callback;
});
return command;
}
// Catches: every read after the first decoding the container's whole log again (no tail bound), or a
// bounded read that more records than the bound arrived for skipping the ones before its first.
@Test
void aBoundedReadThatBeginsPastTheCursorIsMadeAgainWithoutTheBound() {
String t1 = "2026-11-19T10:00:00.100000000Z";
String t2 = "2026-11-19T10:00:00.200000000Z";
String t3 = "2026-11-19T10:00:00.300000000Z";
LogContainerCmd first = logRead(record(t1, "a\n"));
LogContainerCmd bounded = logRead(record(t3, "c\n"));
LogContainerCmd unbounded = logRead(record(t1, "a\n"), record(t2, "b\n"), record(t3, "c\n"));
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("c1")).thenReturn(first, bounded, unbounded);
PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
handle.read();
handle.read();
assertEquals(List.of("a", "b", "c"), lines);
verify(first, never()).withTail(anyInt());
verify(bounded).withTail(PolledLogHandle.TAIL_LINES);
verify(unbounded, never()).withTail(anyInt());
}
// Catches: a final read that fails at close skipping the flush of the unterminated last line.
@Test
void closeFlushesTheUnterminatedLineWhenTheLastReadFails() throws Exception {
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("c1")).thenThrow(new IllegalStateException("daemon gone"));
PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "shutting down"));
handle.close();
await().atMost(Duration.ofSeconds(5)).until(() -> lines.equals(List.of("shutting down")));
}
// Catches: a polled container's last lines lost, since a removed container's log can no longer be read.
@Test
void stopAndRemoveReadsAPolledLogBetweenTheStopAndTheRemoval() throws Exception {
DockerClient docker = mock(DockerClient.class);
StopContainerCmd stop = mock(StopContainerCmd.class, Answers.RETURNS_SELF);
when(docker.stopContainerCmd("c1")).thenReturn(stop);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, Answers.RETURNS_SELF);
when(docker.removeContainerCmd("c1")).thenReturn(remove);
LogContainerCmd logs = mock(LogContainerCmd.class);
when(docker.logContainerCmd("c1")).thenReturn(logs);
when(logs.withStdOut(anyBoolean())).thenReturn(logs);
when(logs.withStdErr(anyBoolean())).thenReturn(logs);
when(logs.withFollowStream(anyBoolean())).thenReturn(logs);
when(logs.withTimestamps(anyBoolean())).thenReturn(logs);
when(logs.withSince(anyInt())).thenReturn(logs);
when(logs.exec(any())).thenAnswer(invocation -> {
ResultCallback.Adapter<Frame> callback = invocation.getArgument(0);
callback.onNext(new Frame(StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "bye\n")));
callback.onComplete();
return callback;
});
PolledLogHandle polled = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
manager.stopAndRemove("c1", polled);
InOrder order = inOrder(stop, logs, remove);
order.verify(stop).exec();
order.verify(logs).exec(any());
order.verify(remove).exec();
assertEquals(List.of("bye"), lines);
}
}
@@ -187,7 +187,7 @@ class RabbitMqManagerTest {
manager.startContainer(broker);
assertEquals("/aws/amazonmq/broker/b-1/general", broker.generalLogGroup());
verify(logStreamer).attach(eq("container-id"), eq(broker.generalLogGroup()),
verify(logStreamer).attachPolled(eq("container-id"), eq(broker.generalLogGroup()),
any(), any(), eq("amazonmq:b-1"));
}
@@ -199,7 +199,7 @@ class DocDbContainerManagerTest {
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
lenient().when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString()))
lenient().when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenAnswer(call -> mock(Closeable.class));
EmulatorConfig config = mock(EmulatorConfig.class);
@@ -385,7 +385,7 @@ class EcrRegistryManagerTest {
.thenReturn(new ContainerLifecycleManager.ContainerInfo("second-container", Map.of()));
Closeable firstLogStream = Mockito.mock(Closeable.class);
Closeable secondLogStream = Mockito.mock(Closeable.class);
when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString()))
when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(firstLogStream, secondLogStream);
assertTrue(manager.tryEnsureStarted());
@@ -495,8 +495,8 @@ class EcrRegistryManagerTest {
manager.ensureStarted();
verify(logStreamer).attach(eq("container-id"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
verify(logStreamer, never()).attachFromNow(any(), any(), any(), any(), any());
verify(logStreamer).attachPolled(eq("container-id"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
verify(logStreamer, never()).attachPolledFromNow(any(), any(), any(), any(), any());
}
@Test
@@ -514,8 +514,8 @@ class EcrRegistryManagerTest {
manager.ensureStarted();
verify(logStreamer).attachFromNow(eq("0123456789abcdef"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
verify(logStreamer, never()).attach(any(), any(), any(), any(), any());
verify(logStreamer).attachPolledFromNow(eq("0123456789abcdef"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
verify(logStreamer, never()).attachPolled(any(), any(), any(), any(), any());
}
@Test
@@ -4246,9 +4246,9 @@ class EksClusterManagerTest {
logStreamer = Mockito.mock(ContainerLogStreamer.class);
mockHandle = Mockito.mock(Closeable.class);
when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(mockHandle);
when(logStreamer.attachFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
when(logStreamer.attachPolledFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(mockHandle);
manager = new EksClusterManager(containerBuilder, lifecycleManager,
@@ -4267,7 +4267,7 @@ class EksClusterManagerTest {
manager.setUpGuest(cluster);
verify(logStreamer).attachForAccount(
verify(logStreamer).attachPolledForAccount(
eq("000000000000"),
eq("container-id-123456789012345678901234567890"),
eq("/aws/eks/prod-cluster/cluster"),
@@ -4316,7 +4316,7 @@ class EksClusterManagerTest {
@Test
void attachmentFailureLogsWarningAndContinuesWithoutAborting() {
when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenThrow(new RuntimeException("Docker attach connection failed"));
Cluster cluster = new Cluster();
@@ -4352,7 +4352,7 @@ class EksClusterManagerTest {
manager.startCluster(stale);
manager.setUpGuest(stale);
Closeable freshHandle = Mockito.mock(Closeable.class);
when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(freshHandle);
Cluster recreated = new Cluster();
recreated.setName("prod-cluster");
@@ -4475,7 +4475,7 @@ class EksClusterManagerTest {
manager.setUpGuest(cluster);
verify(logStreamer).attachFromNowForAccount(
verify(logStreamer).attachPolledFromNowForAccount(
eq("000000000000"),
eq("adopted-container-id-12345678901234567890"),
eq("/aws/eks/prod-cluster/cluster"),
@@ -94,7 +94,7 @@ class ElastiCacheContainerManagerTest {
"io.floci.resource-id", "my-group",
"io.floci.account", "000000000000",
"io.floci.region", "eu-west-1"));
verify(logStreamer).attach(eq("container-id"), anyString(), any(), eq("eu-west-1"), anyString());
verify(logStreamer).attachPolled(eq("container-id"), anyString(), any(), eq("eu-west-1"), anyString());
}
}
@@ -106,7 +106,7 @@ class ElastiCacheContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 6379))));
when(lifecycleManager.isDockerReachable()).thenReturn(false);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(any(), any(), any(), any(), any()))
when(logStreamer.attachPolled(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
@@ -90,7 +90,7 @@ class ElastiCacheMemcachedContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 11211))));
when(lifecycleManager.isDockerReachable()).thenReturn(false);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(any(), any(), any(), any(), any()))
when(logStreamer.attachPolled(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
@@ -262,12 +262,12 @@ class MemoryDbContainerManagerTest {
assertEquals(List.of("floci-aws-memorydb-cache",
"floci-aws-memorydb-111111111111-eu-west-1-same",
"floci-aws-memorydb-111111111111_eu-west-1_same"), names.getAllValues());
verify(logs).attach("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
verify(logs).attachPolled("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
"us-east-1", "memorydb:" + defaultIdentity);
verify(logs).attach("collision-cid",
verify(logs).attachPolled("collision-cid",
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
"us-east-1", "memorydb:" + collisionIdentity);
verify(logs).attach("foreign-cid",
verify(logs).attachPolled("foreign-cid",
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
"eu-west-1", "memorydb:" + foreignIdentity);
responder.get(5, TimeUnit.SECONDS);
@@ -638,7 +638,7 @@ class RedpandaManagerTest {
ArgumentCaptor<ContainerSpec> specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
manager.startContainer(newCluster());
verify(logStreamer).attachForAccount(eq("000000000000"), eq("container-789"),
verify(logStreamer).attachPolledForAccount(eq("000000000000"), eq("container-789"),
eq("/aws/msk/cluster/test-cluster"), eq("log-stream"), eq("us-east-1"),
eq("msk:test-cluster"));
verify(lifecycleManager).createAndStart(specCaptor.capture());
@@ -638,7 +638,7 @@ class RdsContainerManagerTest {
verify(lifecycleManager).create(spec.capture());
assertEquals(dbPath.toString(), spec.getValue().binds().getFirst().getPath());
assertEquals("floci-aws-rds-db1", spec.getValue().name());
verify(logStreamer).attachForAccount(
verify(logStreamer).attachPolledForAccount(
"222222222222", "container-id", "/aws/rds/instance/db1/error",
"log-stream", "us-west-2", "rds:" + runtimeId);
}
@@ -1185,7 +1185,7 @@ class RdsContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
when(logStreamer.attachPolledForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"))
.thenReturn(null);
RdsContainerManager manager = new RdsContainerManager(
@@ -1221,7 +1221,7 @@ class RdsContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
when(logStreamer.attachPolledForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"));
doThrow(new IllegalStateException("Docker cleanup failed"))
.doNothing()
@@ -124,7 +124,7 @@ class RedshiftContainerManagerTest {
} else {
when(lifecycleManager.adopt(eq("cont-survivor"), any(), any())).thenReturn(
new ContainerInfo("cont-survivor", Map.of(5432, new EndpointInfo("localhost", 5432))));
when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
if ("readiness".equals(failureStage)) {
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
@@ -683,17 +683,17 @@ class RedshiftContainerManagerTest {
ContainerInfo info = new ContainerInfo("cont-stream", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
Closeable stream = mock(Closeable.class);
when(logStreamer.attach("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
when(logStreamer.attachPolled("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
.thenReturn(stream);
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
assertEquals(stream, handle.getLogStream());
verify(logStreamer).attach("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
verify(logStreamer).attachPolled("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
// When logStreamer throws, start still completes successfully
doThrow(new RuntimeException("stream error"))
.when(logStreamer).attach(anyString(), anyString(), anyString(), anyString(), anyString());
.when(logStreamer).attachPolled(anyString(), anyString(), anyString(), anyString(), anyString());
RedshiftContainerHandle handleTolerated = manager.start(ACCOUNT_ID, "test-cluster-2", "admin", "pass");
assertNotNull(handleTolerated);
assertNull(handleTolerated.getLogStream());
@@ -708,17 +708,17 @@ class RedshiftContainerManagerTest {
ContainerInfo adopted = new ContainerInfo("cont-adopt-stream", Map.of(5432, new EndpointInfo("localhost", 6000)));
when(lifecycleManager.adopt(eq("cont-adopt-stream"), any(), eq(Optional.empty()))).thenReturn(adopted);
Closeable stream = mock(Closeable.class);
when(logStreamer.attach("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
when(logStreamer.attachPolled("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
.thenReturn(stream);
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
assertEquals(stream, handle.getLogStream());
verify(logStreamer).attach("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
verify(logStreamer).attachPolled("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
// When logStreamer throws, adoptOrStart still completes successfully
doThrow(new RuntimeException("stream error"))
.when(logStreamer).attach(anyString(), anyString(), anyString(), anyString(), anyString());
.when(logStreamer).attachPolled(anyString(), anyString(), anyString(), anyString(), anyString());
RedshiftContainerHandle handleTolerated = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handleTolerated);
assertNull(handleTolerated.getLogStream());
@@ -787,6 +787,24 @@ class RedshiftContainerManagerTest {
verify(stream).close();
}
// Catches: the cluster's last log lines lost, since the forced removal leaves its polled log nothing to read.
@Test
void stopReadsThePolledLogBeforeTheRemoval() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-owned", Map.of(5432, new EndpointInfo("localhost", 5432))));
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "owned", "admin", "pass");
Closeable stream = mock(Closeable.class);
handle.setLogStream(stream);
manager.stop(ACCOUNT_ID, "owned");
InOrder order = inOrder(lifecycleManager);
order.verify(lifecycleManager).readLogBeforeRemoval(stream);
order.verify(lifecycleManager).removeIfExistsStrict("cont-owned", true);
}
@Test
void staleRemovalFailurePreventsReplacementCreation() {
doThrow(new IllegalStateException("Docker unavailable")).when(lifecycleManager)
@@ -802,7 +820,7 @@ class RedshiftContainerManagerTest {
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-unready", Map.of(5432, new EndpointInfo("localhost", 5432))));
Closeable stream = mock(Closeable.class);
when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
try {