feat(docker): opt-in log-driver mode for long-lived service containers' logs (#9236)

With floci.docker.log-driver-mode on (off by default), the long-lived service containers Floci attaches to are created with Docker's gelf log driver pointed at a TCP listener in Floci, and the daemon pushes each line instead of Floci reading the log on a timer. Flink TaskManagers and ephemeral RDS instances keep json-file.

Each container carries a random tag, as a label and in every message. A message whose tag no attached container claimed is dropped, and lines that arrive before the attach are held for it. The listener takes a fixed port, floci.docker.log-driver-port (12201), and opens before Floci starts any container, so a stopped container adopted after a restart starts again. A container created under another port or host is read on a timer from the daemon's local copy, with a warning. The listener accepts at most 1024 connections.

The json-file max-size and max-file settings map to the local copy's cache-max-size and cache-max-file.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-23 20:31:48 -04:00
1 parent 0cef64ebad
commit 2ee676ca6c
24 files changed
+918 -11

No files matched your search

@@ -288,4 +288,28 @@ class ApplicationDefaultsTest {
assertEquals("128", fallback.value(),
"the @WithDefault must match application.yml, which wins over it");
}
// Catches: the log-driver mode switched on by default, which breaks Docker-in-Docker and remote
// daemons, or the yml and the @WithDefault disagreeing.
@Test
void productionConfigKeepsTheLogDriverModeOff() throws IOException, NoSuchMethodException {
JsonNode mode = productionConfig().path("floci").path("docker").path("log-driver-mode");
assertFalse(mode.isMissingNode(), "log-driver-mode should be declared in application.yml");
assertFalse(mode.asBoolean(true));
assertEquals("false", EmulatorConfig.DockerConfig.class.getMethod("logDriverMode")
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
// Catches: the log listener's port made ephemeral again, so a container created in the log-driver
// mode can no longer start after Floci restarts, or the yml and the @WithDefault disagreeing.
@Test
void productionConfigFixesTheLogDriverPort() throws IOException, NoSuchMethodException {
JsonNode port = productionConfig().path("floci").path("docker").path("log-driver-port");
assertFalse(port.isMissingNode(), "log-driver-port should be declared in application.yml");
assertEquals(12201, port.asInt());
assertEquals("12201", EmulatorConfig.DockerConfig.class.getMethod("logDriverPort")
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
}
@@ -15,6 +15,7 @@ import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;
@@ -23,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -148,4 +150,37 @@ class ContainerLifecycleManagerStartTest {
assertEquals(1, execCalls.get());
}
// Catches: a stopped container created in the log-driver mode, the ECR registry or a Redshift cluster
// after a restart of Docker, started before anything listens where its gelf driver dials, so Docker
// refuses the start with "gelf: cannot connect to GELF endpoint".
@Test
void adoptStartsTheLogListenerBeforeTheStoppedContainer() throws IOException {
GelfLogListener listener = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1");
try {
AtomicInteger execCalls = new AtomicInteger();
DockerClient docker = dockerWhoseStartExec(execCalls, attempt -> {
assertTrue(listener.started(), "the listener is up before Docker starts the container");
String address = listener.ensureStarted();
int port = Integer.parseInt(address.substring(address.lastIndexOf(':') + 1));
try (Socket daemon = new Socket("127.0.0.1", port)) {
assertTrue(daemon.isConnected());
} catch (IOException e) {
throw new AssertionError("the gelf driver's dial is refused", e);
}
});
InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
when(inspect.getState().getRunning()).thenReturn(Boolean.FALSE);
InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class);
when(inspectCmd.exec()).thenReturn(inspect);
when(docker.inspectContainerCmd("container-abc")).thenReturn(inspectCmd);
new ContainerLifecycleManager(docker, imageCacheService, containerDetector, config, listener)
.adopt("container-abc", List.of());
assertEquals(1, execCalls.get());
} finally {
listener.close();
}
}
}
@@ -2,8 +2,13 @@ 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.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
import io.floci.aws.testutil.LogCapture;
@@ -13,24 +18,29 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
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 java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -131,6 +141,74 @@ class ContainerLogStreamerTest {
eq("555555555555"), eq("/aws/lambda/example"), eq("stream"), anyList(), eq("us-east-1"));
}
private static DockerClient dockerWithLogTag(String containerId, String token, String gelfAddress) {
DockerClient docker = mock(DockerClient.class);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse response = mock(InspectContainerResponse.class);
ContainerConfig containerConfig = mock(ContainerConfig.class);
when(docker.inspectContainerCmd(containerId)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
when(response.getConfig()).thenReturn(containerConfig);
when(containerConfig.getLabels()).thenReturn(Map.of(GelfLogListener.LOG_TOKEN_LABEL, token));
when(response.getHostConfig()).thenReturn(new HostConfig().withLogConfig(
new LogConfig(LogConfig.LoggingType.GELF, Map.of("gelf-address", gelfAddress))));
when(docker.logContainerCmd(containerId)).thenReturn(mock(LogContainerCmd.class, RETURNS_SELF));
return docker;
}
private static ContainerLogStreamer streamerWith(DockerClient docker, CloudWatchLogsService cloudWatch,
GelfLogListener listener) {
return new ContainerLogStreamer(docker, docker, cloudWatch, Duration.ofHours(1), listener);
}
// Catches: a container tagged for the log-driver mode not claimed by the listener, so its pushed log
// never reaches CloudWatch Logs.
@Test
void aTaggedContainerDialingThisListenerHasItsLogPushed() throws IOException {
GelfLogListener listener = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1");
try {
String address = listener.logConfigFor("token-a", Map.of()).getConfig().get("gelf-address");
CloudWatchLogsService cloudWatch = mock(CloudWatchLogsService.class);
ContainerLogStreamer streamer = streamerWith(
dockerWithLogTag("container-1", "token-a", address), cloudWatch, listener);
Closeable handle = streamer.attachPolled("container-1", "/aws/rds/instance/db/error", "stream",
"us-east-1", "rds:db");
listener.readMessages(new ByteArrayInputStream(
utf8("{\"short_message\":\"ready\",\"level\":6,\"_tag\":\"token-a\"}\0")));
assertFalse(handle instanceof PolledLogHandle, "the log is pushed, not read on a timer");
verify(cloudWatch).putLogEventsForAccount(any(), eq("/aws/rds/instance/db/error"), eq("stream"),
argThat(events -> "ready".equals(events.getFirst().get("message"))), eq("us-east-1"));
} finally {
listener.close();
}
}
// Catches: a container kept across a restart of Floci, which still dials the old listener's address,
// attached to a listener that never hears from it, instead of being read on a timer with a warning.
@Test
void aContainerDialingAnotherListenerIsReadOnATimerWithAWarning() throws IOException {
GelfLogListener listener = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1");
try {
listener.ensureStarted();
ContainerLogStreamer streamer = streamerWith(
dockerWithLogTag("container-1", "token-a", "tcp://127.0.0.1:1"),
mock(CloudWatchLogsService.class), listener);
List<Closeable> handles = new ArrayList<>();
List<LogRecord> records = LogCapture.capture(ContainerLogStreamer.class, () -> handles.add(
streamer.attachPolled("container-1", "/aws/rds/instance/db/error", "stream", "us-east-1",
"rds:db")));
assertInstanceOf(PolledLogHandle.class, handles.getFirst());
assertTrue(records.stream().anyMatch(record -> record.getLevel().intValue() >= Level.WARNING.intValue()), records.toString());
handles.getFirst().close();
} finally {
listener.close();
}
}
@Test
void attachedStreamStillReachesCloudWatchAndConsole() {
DockerClient dockerClient = mock(DockerClient.class);
@@ -0,0 +1,208 @@
package io.floci.aws.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.config.EmulatorConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GelfLogListenerTest {
private final List<String> lines = new CopyOnWriteArrayList<>();
private final GelfLogListener listener = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1");
private GelfLogListener restarted;
@AfterEach
void close() {
listener.close();
if (restarted != null) {
restarted.close();
}
}
private static final Map<String, String> ROTATION = Map.of("max-size", "10m", "max-file", "3");
private static byte[] messages(String... documents) {
StringBuilder stream = new StringBuilder();
for (String document : documents) {
stream.append(document).append('\0');
}
return stream.toString().getBytes(StandardCharsets.UTF_8);
}
// Catches: a line reaching the wrong container's log, standard error read as standard output, or a
// message another container sent under an unknown tag being accepted.
@Test
void eachMessageReachesTheContainerItsTagNames() throws IOException {
listener.register("token-a", (stream, line) -> lines.add("a " + stream + " " + line));
listener.register("token-b", (stream, line) -> lines.add("b " + stream + " " + line));
listener.readMessages(new ByteArrayInputStream(messages(
"{\"version\":\"1.1\",\"short_message\":\"ready\",\"level\":6,\"_tag\":\"token-a\"}",
"{\"version\":\"1.1\",\"short_message\":\"oops\",\"level\":3,\"_tag\":\"token-b\"}",
"{\"version\":\"1.1\",\"short_message\":\"spoofed\",\"level\":6,\"_tag\":\"guess\"}",
"not json")));
assertEquals(List.of("a STDOUT ready", "b STDERR oops"), lines);
}
// Catches: lines still forwarded for a container whose log handle was closed.
@Test
void anUnregisteredTagIsDropped() throws IOException {
BiConsumer<StreamType, String> sink = (stream, line) -> lines.add(line);
listener.register("token-a", sink);
listener.unregister("token-a", sink);
listener.readMessages(new ByteArrayInputStream(messages("{\"short_message\":\"late\",\"_tag\":\"token-a\"}")));
assertTrue(lines.isEmpty());
}
// Catches: the delayed close of a container's earlier log handle removing the attach that replaced it,
// so the container's later lines are dropped.
@Test
void anEarlierHandlesCloseLeavesALaterAttachOfTheSameContainer() throws IOException {
BiConsumer<StreamType, String> earlier = (stream, line) -> lines.add("earlier " + line);
listener.register("token-a", earlier);
listener.register("token-a", (stream, line) -> lines.add("later " + line));
listener.unregister("token-a", earlier);
listener.readMessages(new ByteArrayInputStream(messages("{\"short_message\":\"up\",\"_tag\":\"token-a\"}")));
assertEquals(List.of("later up"), lines);
}
// Catches: a container kept across a restart of Floci dialing a port the new listener does not take,
// so it cannot start and its log never arrives; or one created for another port being claimed.
@Test
void aRestartedListenerTakesTheSamePortAndClaimsOnlyContainersDialingIt() throws IOException {
int port;
try (ServerSocket free = new ServerSocket(0)) {
port = free.getLocalPort();
}
GelfLogListener before = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1", port, 8);
String created = before.logConfigFor("token-a", ROTATION).getConfig().get("gelf-address");
before.close();
restarted = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1", port, 8);
assertFalse(restarted.started());
assertTrue(restarted.listensAt(created), "the restarted listener takes the port the container dials");
assertTrue(restarted.started());
String elsewhere = listener.logConfigFor("token-b", ROTATION).getConfig().get("gelf-address");
assertFalse(restarted.listensAt(elsewhere), "a listener answers only for its own address");
assertFalse(restarted.listensAt(null));
}
// Catches: the log configuration not pointing the daemon at the listener it opened.
@Test
void theLogConfigSendsGelfOverTcpToTheListener() throws Exception {
LogConfig logConfig = listener.logConfigFor("token-a", ROTATION);
assertEquals(LogConfig.LoggingType.GELF, logConfig.getType());
assertEquals("token-a", logConfig.getConfig().get("tag"));
assertEquals("10m", logConfig.getConfig().get("cache-max-size"), "the rotation bounds the daemon's copy");
assertEquals("3", logConfig.getConfig().get("cache-max-file"));
String address = logConfig.getConfig().get("gelf-address");
assertTrue(address.startsWith("tcp://127.0.0.1:"), address);
listener.register("token-a", (stream, line) -> lines.add(line));
int port = Integer.parseInt(address.substring(address.lastIndexOf(':') + 1));
try (Socket daemon = new Socket("127.0.0.1", port); OutputStream out = daemon.getOutputStream()) {
out.write(messages("{\"short_message\":\"over tcp\",\"level\":6,\"_tag\":\"token-a\"}"));
}
await().until(() -> !lines.isEmpty());
assertEquals(List.of("over tcp"), lines);
}
// Catches: the mode switching a container nobody attaches (a Flink TaskManager, an ephemeral RDS
// instance, a Lambda) to the gelf driver, or leaving an attached one on json-file without its tag.
@Test
void onlyContainersMarkedForPushedLogsGetTheGelfDriverAndATag() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
when(config.docker()).thenReturn(docker);
when(docker.logDriverMode()).thenReturn(true);
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
ContainerBuilder builder = new ContainerBuilder(config, null, null, null, null, listener);
ContainerSpec jobManager = builder.newContainer("flink:1.20")
.withLabels(Map.of(ContainerStorageHelper.SERVICE_LABEL, "kinesisanalytics"))
.withLogRotation()
.withPushedLogs()
.build();
ContainerSpec taskManager = builder.newContainer("flink:1.20")
.withLabels(Map.of(ContainerStorageHelper.SERVICE_LABEL, "kinesisanalytics"))
.withLogRotation()
.build();
assertEquals(LogConfig.LoggingType.GELF, jobManager.logConfig().getType());
assertEquals(jobManager.logConfig().getConfig().get("tag"),
jobManager.labels().get(GelfLogListener.LOG_TOKEN_LABEL));
assertEquals("10m", jobManager.logConfig().getConfig().get("cache-max-size"));
assertEquals(LogConfig.LoggingType.JSON_FILE, taskManager.logConfig().getType());
assertNull(taskManager.labels().get(GelfLogListener.LOG_TOKEN_LABEL));
assertFalse(taskManager.labels().containsKey(GelfLogListener.LOG_TOKEN_LABEL));
}
// Catches: a local process holding connections open until the daemon's own connections are refused,
// or a closed connection never returning its place.
@Test
void connectionsOverTheLimitAreClosedAndAClosedOneFreesItsPlace() throws Exception {
restarted = new GelfLogListener(mock(DockerClient.class), true, "127.0.0.1", 0, 1);
String address = restarted.logConfigFor("token-a", ROTATION).getConfig().get("gelf-address");
int port = Integer.parseInt(address.substring(address.lastIndexOf(':') + 1));
restarted.register("token-a", (stream, line) -> lines.add(line));
try (Socket held = new Socket("127.0.0.1", port)) {
try (Socket refused = new Socket("127.0.0.1", port); InputStream in = refused.getInputStream()) {
refused.setSoTimeout(5000);
assertEquals(-1, in.read(), "the listener closes a connection over its limit");
}
held.getOutputStream().write(messages("{\"short_message\":\"held\",\"_tag\":\"token-a\"}"));
await().until(() -> lines.contains("held"));
}
await().untilAsserted(() -> {
try (Socket next = new Socket("127.0.0.1", port); OutputStream out = next.getOutputStream()) {
out.write(messages("{\"short_message\":\"next\",\"_tag\":\"token-a\"}"));
}
assertTrue(lines.contains("next"));
});
}
// Catches: the lines a container writes between its start and its attach, its startup banner, lost.
@Test
void linesSentBeforeTheAttachAreHeldForIt() throws IOException {
listener.logConfigFor("token-a", ROTATION);
listener.readMessages(new ByteArrayInputStream(messages(
"{\"short_message\":\"starting\",\"level\":6,\"_tag\":\"token-a\"}")));
listener.register("token-a", (stream, line) -> lines.add(line));
listener.readMessages(new ByteArrayInputStream(messages(
"{\"short_message\":\"ready\",\"level\":6,\"_tag\":\"token-a\"}")));
assertEquals(List.of("starting", "ready"), lines);
}
}