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

@@ -4648,6 +4648,29 @@ public interface EmulatorConfig {
@WithDefault("1000")
int logPollIntervalMillis();
/**
* Opt-in: long-lived service containers send their logs to Floci through Docker's {@code gelf}
* log driver instead of being read on a timer, so they hold no Docker connection at all. Needs a
* daemon that can reach Floci (Docker Desktop, or a daemon on Floci's host), not Docker-in-Docker
* or a remote daemon.
*/
@WithDefault("false")
boolean logDriverMode();
/**
* The host the daemon dials to reach Floci's log listener in the log-driver mode. Unset, it is
* {@code host.docker.internal} on Docker Desktop and {@code 127.0.0.1} otherwise.
*/
Optional<String> logDriverHost();
/**
* The port Floci's log listener takes in the log-driver mode. It is fixed because Docker keeps the
* address in each container's log configuration and dials it on every start, including a start of a
* container Floci adopts after a restart. The default is GELF's standard port.
*/
@WithDefault("12201")
int logDriverPort();
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
@@ -53,17 +53,28 @@ public class ContainerBuilder {
private final EmbeddedDnsServer embeddedDnsServer;
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
private final ContainerEngineDetector containerEngineDetector;
private final GelfLogListener gelfLogListener;
@Inject
public ContainerBuilder(EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
ContainerEngineDetector containerEngineDetector) {
ContainerEngineDetector containerEngineDetector,
GelfLogListener gelfLogListener) {
this.config = config;
this.dockerHostResolver = dockerHostResolver;
this.embeddedDnsServer = embeddedDnsServer;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.containerEngineDetector = containerEngineDetector;
this.gelfLogListener = gelfLogListener;
}
public ContainerBuilder(EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
CurrentContainerNetworkResolver currentContainerNetworkResolver,
ContainerEngineDetector containerEngineDetector) {
this(config, dockerHostResolver, embeddedDnsServer, currentContainerNetworkResolver,
containerEngineDetector, GelfLogListener.disabled());
}
public ContainerBuilder(EmulatorConfig config, DockerHostResolver dockerHostResolver,
@@ -84,8 +95,12 @@ public class ContainerBuilder {
* @return a new Builder instance
*/
public Builder newContainer(String image) {
return new Builder(resolveImage(image), config, dockerHostResolver, embeddedDnsServer,
Builder builder = new Builder(resolveImage(image), config, dockerHostResolver, embeddedDnsServer,
currentContainerNetworkResolver, containerEngineDetector);
if (gelfLogListener.enabled()) {
builder.logDriver = gelfLogListener;
}
return builder;
}
/**
@@ -251,6 +266,8 @@ public class ContainerBuilder {
private boolean javaTrustStore;
private String dnsName;
private final List<String> joinedNetworks = new ArrayList<>();
private GelfLogListener logDriver;
private boolean pushedLogs;
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
@@ -612,6 +629,16 @@ public class ContainerBuilder {
return this;
}
/**
* Marks a container whose owner attaches its log with one of the {@code attachPolled} methods of
* {@link ContainerLogStreamer}. In the opt-in log-driver mode the daemon then pushes that log to Floci
* instead of Floci reading it on a timer; a container nobody attaches keeps its json-file log.
*/
public Builder withPushedLogs() {
this.pushedLogs = true;
return this;
}
/**
* Sets a custom log configuration.
*/
@@ -869,6 +896,16 @@ public class ContainerBuilder {
* Builds the immutable ContainerSpec.
*/
public ContainerSpec build() {
LogConfig effectiveLogConfig = logConfig;
Map<String, String> effectiveLabels = labels;
if (pushedLogs && logDriver != null && logConfig != null
&& logConfig.getType() == LogConfig.LoggingType.JSON_FILE) {
// The opt-in log-driver mode: the daemon pushes this container's log to Floci.
String token = GelfLogListener.newToken();
effectiveLabels = new HashMap<>(labels);
effectiveLabels.put(GelfLogListener.LOG_TOKEN_LABEL, token);
effectiveLogConfig = logDriver.logConfigFor(token, logConfig.getConfig());
}
return new ContainerSpec(
image,
name,
@@ -884,8 +921,8 @@ public class ContainerBuilder {
List.copyOf(binds),
List.copyOf(volumesFrom),
List.copyOf(extraHosts),
Map.copyOf(labels),
logConfig,
Map.copyOf(effectiveLabels),
effectiveLogConfig,
privileged,
cgroupnsMode,
List.copyOf(dnsServers),
@@ -101,6 +101,7 @@ public class ContainerLifecycleManager {
private final long archiveRetryBackoffMillis;
private final LongSupplier nanoTime;
private final CreateWait createWait;
private final GelfLogListener gelfLogListener;
/** Volumes whose shared-ownership root has already been initialised this process (run-once guard). */
private final ConcurrentHashMap<String, Boolean> initializedSharedVolumes = new ConcurrentHashMap<>();
@@ -116,9 +117,20 @@ public class ContainerLifecycleManager {
@StreamingDocker DockerClient streamingDockerClient,
ImageCacheService imageCacheService,
ContainerDetector containerDetector,
EmulatorConfig config,
GelfLogListener gelfLogListener) {
this(dockerClient, streamingDockerClient, imageCacheService, containerDetector, config,
RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep,
gelfLogListener);
}
public ContainerLifecycleManager(DockerClient dockerClient,
DockerClient streamingDockerClient,
ImageCacheService imageCacheService,
ContainerDetector containerDetector,
EmulatorConfig config) {
this(dockerClient, streamingDockerClient, imageCacheService, containerDetector, config,
RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep);
GelfLogListener.disabled());
}
ContainerLifecycleManager(DockerClient dockerClient,
@@ -138,7 +150,16 @@ public class ContainerLifecycleManager {
LongSupplier nanoTime,
CreateWait createWait) {
this(dockerClient, dockerClient, imageCacheService, containerDetector, config, archiveRetryBackoffMillis,
nanoTime, createWait);
nanoTime, createWait, GelfLogListener.disabled());
}
ContainerLifecycleManager(DockerClient dockerClient,
ImageCacheService imageCacheService,
ContainerDetector containerDetector,
EmulatorConfig config,
GelfLogListener gelfLogListener) {
this(dockerClient, dockerClient, imageCacheService, containerDetector, config,
RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep, gelfLogListener);
}
private ContainerLifecycleManager(DockerClient dockerClient,
@@ -148,7 +169,9 @@ public class ContainerLifecycleManager {
EmulatorConfig config,
long archiveRetryBackoffMillis,
LongSupplier nanoTime,
CreateWait createWait) {
CreateWait createWait,
GelfLogListener gelfLogListener) {
this.gelfLogListener = gelfLogListener;
this.dockerClient = dockerClient;
this.streamingDockerClient = streamingDockerClient;
this.imageCacheService = imageCacheService;
@@ -159,6 +182,20 @@ public class ContainerLifecycleManager {
this.createWait = createWait;
}
// A container created in the log-driver mode dials the listener as it starts, a stopped one adopted
// after a restart of Floci included, and the start fails when nothing listens there.
private void startLogListener() {
if (!gelfLogListener.enabled()) {
return;
}
try {
gelfLogListener.ensureStarted();
} catch (IllegalStateException e) {
LOG.warnv("{0}: a container that sends its log there will not start: {1}", e.getMessage(),
e.getCause() == null ? "" : e.getCause().getMessage());
}
}
/** Pause between creation checks; tests advance the monotonic clock instead of sleeping. */
@FunctionalInterface
interface CreateWait {
@@ -712,6 +749,7 @@ public class ContainerLifecycleManager {
* rather than a raw {@code dockerClient.startContainerCmd(...)} call.
*/
void startContainer(String containerId) {
startLogListener();
try {
dockerClient.startContainerCmd(containerId).exec();
} catch (NotModifiedException alreadyRunning) {
@@ -2,8 +2,11 @@ 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.InspectContainerResponse;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.LogConfig;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
@@ -32,6 +35,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -57,6 +61,8 @@ public class ContainerLogStreamer {
private final CloudWatchLogsService cloudWatchLogsService;
private final Duration pollInterval;
private final GelfLogListener gelfLogListener;
// Log-follow attaches hold their connection open for the whole container lifetime, so
// this class is the primary consumer of the streaming pool: sharing the control-plane
// pool is what starved short create/start/stop calls during an LZA Logging fan-out
@@ -64,9 +70,11 @@ public class ContainerLogStreamer {
// control-plane calls instead, and holds no connection between reads.
@Inject
public ContainerLogStreamer(@StreamingDocker DockerClient dockerClient, DockerClient pollingDockerClient,
CloudWatchLogsService cloudWatchLogsService, EmulatorConfig config) {
CloudWatchLogsService cloudWatchLogsService, EmulatorConfig config,
GelfLogListener gelfLogListener) {
this(dockerClient, pollingDockerClient, cloudWatchLogsService,
Duration.ofMillis(validateLogPollIntervalMillis(config.docker().logPollIntervalMillis())));
Duration.ofMillis(validateLogPollIntervalMillis(config.docker().logPollIntervalMillis())),
gelfLogListener);
}
public ContainerLogStreamer(DockerClient dockerClient, CloudWatchLogsService cloudWatchLogsService) {
@@ -75,6 +83,13 @@ public class ContainerLogStreamer {
ContainerLogStreamer(DockerClient dockerClient, DockerClient pollingDockerClient,
CloudWatchLogsService cloudWatchLogsService, Duration pollInterval) {
this(dockerClient, pollingDockerClient, cloudWatchLogsService, pollInterval, GelfLogListener.disabled());
}
ContainerLogStreamer(DockerClient dockerClient, DockerClient pollingDockerClient,
CloudWatchLogsService cloudWatchLogsService, Duration pollInterval,
GelfLogListener gelfLogListener) {
this.gelfLogListener = gelfLogListener;
this.dockerClient = dockerClient;
this.pollingDockerClient = pollingDockerClient;
this.cloudWatchLogsService = cloudWatchLogsService;
@@ -182,12 +197,58 @@ public class ContainerLogStreamer {
Closeable attachPolledForAccount(String accountId, String containerId, String logGroup, String logStream,
String region, String logPrefix, Instant since) {
ensureLogGroupAndStreamForAccount(accountId, logGroup, logStream, region);
return new PolledLogHandle(pollingDockerClient, containerId, since, (stream, line) -> {
BiConsumer<StreamType, String> sink = (stream, line) -> {
String logged = logToConsole(logPrefix, line);
if (logged != null) {
forwardToCloudWatchLogs(accountId, logGroup, logStream, region, logged);
}
}).start(pollInterval);
};
Closeable pushed = attachPushed(containerId, sink);
if (pushed != null) {
return pushed;
}
return new PolledLogHandle(pollingDockerClient, containerId, since, sink).start(pollInterval);
}
/**
* In the log-driver mode, a container created with Floci's {@code gelf} log configuration pushes its
* log, so it is claimed by its tag instead of read; null when the mode is off or the container was not
* created for it (one started before the mode was turned on). A container that still sends to the
* address of a listener this Floci no longer has is read on a timer instead, from the daemon's local copy.
*/
private Closeable attachPushed(String containerId, BiConsumer<StreamType, String> sink) {
if (!gelfLogListener.enabled()) {
return null;
}
GelfLogListener listener = gelfLogListener;
InspectContainerResponse inspect;
try {
inspect = pollingDockerClient.inspectContainerCmd(containerId).exec();
} catch (NotFoundException e) {
LOG.debugv("Container {0} is gone before its log was attached: {1}", containerId, e.getMessage());
return null;
} catch (RuntimeException e) {
LOG.warnv("Could not read the log tag of container {0}; reading its log on a timer instead, which "
+ "needs the daemon's local copy of a pushed log: {1}", containerId, e.getMessage());
return null;
}
Map<String, String> labels = inspect.getConfig() == null ? null : inspect.getConfig().getLabels();
String token = labels == null ? null : labels.get(GelfLogListener.LOG_TOKEN_LABEL);
if (token == null) {
return null;
}
LogConfig logConfig = inspect.getHostConfig() == null ? null : inspect.getHostConfig().getLogConfig();
String gelfAddress = logConfig == null || logConfig.getConfig() == null
? null : logConfig.getConfig().get("gelf-address");
if (!listener.listensAt(gelfAddress)) {
LOG.warnv("Container {0} sends its log to {1}, where this Floci does not listen; reading its log on a "
+ "timer instead, from the daemon's local copy", containerId, gelfAddress);
return null;
}
listener.register(token, sink);
// The daemon may still be sending the last lines when the container's owner closes the handle.
return () -> CompletableFuture.delayedExecutor(LogReassemblyCallback.DEFAULT_CLOSE_GRACE_MILLIS,
TimeUnit.MILLISECONDS).execute(() -> listener.unregister(token, sink));
}
/**
@@ -0,0 +1,350 @@
package io.floci.aws.core.common.docker;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.function.BiConsumer;
/**
* The opt-in log-driver mode ({@code floci.docker.log-driver-mode}): long-lived service containers are
* started with Docker's {@code gelf} log driver pointed at this listener, so the daemon pushes each log
* line over TCP and the container holds no follow stream and needs no read on a timer. Docker opens the
* connection itself, from wherever the daemon runs, so the mode needs a daemon that can reach Floci:
* Docker Desktop (through {@code host.docker.internal}) or a daemon on Floci's own host, not
* Docker-in-Docker or a remote daemon.
*
* <p>Each container gets a random tag, sent with every message as {@code _tag}, and a message whose tag
* no container registered is dropped, so another container cannot write into a service's logs. A
* message is one null-terminated GELF JSON document; its {@code level} tells standard error (3) from
* standard output (6).
*/
@ApplicationScoped
public class GelfLogListener {
private static final Logger LOG = Logger.getLogger(GelfLogListener.class);
private static final ObjectMapper JSON = new ObjectMapper();
private static final int MAX_MESSAGE_BYTES = 1024 * 1024;
private static final int STDERR_LEVEL = 3;
private static final int MAX_PENDING_LINES = 1000;
private static final Duration UNCLAIMED_EXPIRY = Duration.ofMinutes(10);
// The daemon holds one connection per container; this bounds what any other local process can open.
private static final int MAX_CONNECTIONS = 1024;
/** Label carrying a container's tag, so its log can be claimed when it is attached. */
static final String LOG_TOKEN_LABEL = "io.floci.log-token";
private final DockerClient dockerClient;
private final boolean enabled;
private final String configuredHost;
private final int port;
private final Map<String, BiConsumer<StreamType, String>> sinks = new ConcurrentHashMap<>();
/** Lines of containers that started but are not attached yet, by the tag this listener issued them. */
private final Map<String, Pending> pending = new ConcurrentHashMap<>();
private final int maxConnections;
private final Semaphore connections;
private final Object startLock = new Object();
private ServerSocket server;
private volatile String address;
@Inject
public GelfLogListener(DockerClient dockerClient, EmulatorConfig config) {
this(dockerClient, config.docker().logDriverMode(), config.docker().logDriverHost().orElse(null),
config.docker().logDriverPort(), MAX_CONNECTIONS);
}
/** A listener on an ephemeral port, for tests. */
GelfLogListener(DockerClient dockerClient, boolean enabled, String configuredHost) {
this(dockerClient, enabled, configuredHost, 0, MAX_CONNECTIONS);
}
GelfLogListener(DockerClient dockerClient, boolean enabled, String configuredHost, int port,
int maxConnections) {
this.dockerClient = dockerClient;
this.enabled = enabled;
this.configuredHost = configuredHost;
this.port = port;
this.maxConnections = maxConnections;
this.connections = new Semaphore(maxConnections);
}
/** A listener for the mode switched off, for the builder and streamer constructed outside CDI. */
static GelfLogListener disabled() {
return new GelfLogListener(null, false, null);
}
public boolean enabled() {
return enabled;
}
/** A fresh tag for a container about to be created. */
static String newToken() {
return UUID.randomUUID().toString();
}
/**
* The {@code gelf} log configuration that sends a container's log here under {@code token}. The daemon
* sends from the moment the container starts, before its owner attaches, so the lines that arrive
* first are held (up to {@value #MAX_PENDING_LINES}) until it does. The json-file rotation the container
* would have had ({@code max-size}, {@code max-file}) bounds the daemon's local copy of the log instead.
*/
LogConfig logConfigFor(String token, Map<String, String> jsonFileOptions) {
expireUnclaimed();
pending.put(token, new Pending(System.nanoTime(), new ArrayDeque<>()));
Map<String, String> options = new HashMap<>();
options.put("gelf-address", "tcp://" + ensureStarted());
options.put("tag", token);
if (jsonFileOptions != null) {
copyOption(jsonFileOptions, "max-size", options, "cache-max-size");
copyOption(jsonFileOptions, "max-file", options, "cache-max-file");
}
return new LogConfig(LogConfig.LoggingType.GELF, options);
}
private static void copyOption(Map<String, String> from, String key, Map<String, String> to, String as) {
String value = from.get(key);
if (value != null && !value.isBlank()) {
to.put(as, value);
}
}
private void expireUnclaimed() {
long now = System.nanoTime();
pending.values().removeIf(waiting -> now - waiting.issuedAt() > UNCLAIMED_EXPIRY.toNanos());
}
/**
* Whether a container created with {@code gelfAddress} reaches this listener, starting it if needed. A
* container created before {@code log-driver-port} or {@code log-driver-host} changed dials elsewhere.
*/
boolean listensAt(String gelfAddress) {
if (gelfAddress == null || !gelfAddress.startsWith("tcp://")) {
return false;
}
try {
return gelfAddress.equals("tcp://" + ensureStarted());
} catch (IllegalStateException e) {
LOG.warnv("Docker log-driver listener is not up, so {0} is not reached: {1}", gelfAddress,
e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
return false;
}
}
boolean started() {
return address != null;
}
void register(String token, BiConsumer<StreamType, String> sink) {
expireUnclaimed();
Pending waiting = pending.get(token);
if (waiting == null) {
sinks.put(token, sink);
return;
}
synchronized (waiting) {
for (String[] line : waiting.lines()) {
sink.accept(StreamType.valueOf(line[0]), line[1]);
}
sinks.put(token, sink);
pending.remove(token);
}
}
/** Removes {@code sink}, unless a later attach of the same container has replaced it. */
void unregister(String token, BiConsumer<StreamType, String> sink) {
if (sinks.remove(token, sink)) {
pending.remove(token);
}
}
/** Starts listening on first use and returns the {@code host:port} the daemon dials. */
String ensureStarted() {
synchronized (startLock) {
if (address == null) {
start();
}
return address;
}
}
// Called holding startLock.
private void start() {
String host = configuredHost != null ? configuredHost : daemonFacingHost();
try {
ServerSocket socket = new ServerSocket();
socket.bind(new InetSocketAddress(bindAddress(), port));
server = socket;
} catch (IOException e) {
throw new IllegalStateException("Could not open the Docker log-driver listener on port " + port
+ " (floci.docker.log-driver-port)", e);
}
address = host + ":" + server.getLocalPort();
Thread.ofVirtual().name("floci-gelf-accept").start(this::acceptLoop);
LOG.infov("Long-lived service containers send their logs to Floci over GELF at {0}", address);
}
/**
* Loopback, unless {@code log-driver-host} names an address of this host (Floci's address on a Docker
* network, say), which the listener then binds so the daemon's connection reaches it.
*/
private InetAddress bindAddress() {
InetAddress loopback = InetAddress.getLoopbackAddress();
if (configuredHost == null) {
return loopback;
}
try {
InetAddress configured = InetAddress.getByName(configuredHost);
if (configured.isLoopbackAddress() || NetworkInterface.getByInetAddress(configured) != null) {
return configured;
}
} catch (IOException e) {
LOG.debugv("Could not resolve log-driver-host {0}: {1}", configuredHost, e.getMessage());
}
LOG.warnv("log-driver-host {0} is not an address of this host, so the log-driver listener stays on "
+ "loopback; the daemon reaches it only if {0} forwards to this host's loopback", configuredHost);
return loopback;
}
// Docker Desktop's daemon runs in a VM and reaches the host through host.docker.internal; a daemon on
// this host reaches its loopback directly.
private String daemonFacingHost() {
boolean desktop = DockerDaemon.operatingSystem(dockerClient).map(DockerDaemon::isDockerDesktop).orElse(false);
return desktop ? "host.docker.internal" : "127.0.0.1";
}
private void acceptLoop() {
ServerSocket socket = server;
while (!socket.isClosed()) {
try {
Socket connection = socket.accept();
if (!connections.tryAcquire()) {
LOG.warnv("Docker log-driver listener refused a connection from {0}: {1} are already open",
connection.getRemoteSocketAddress(), maxConnections);
connection.close();
continue;
}
Thread.ofVirtual().name("floci-gelf-connection").start(() -> {
try {
read(connection);
} finally {
connections.release();
}
});
} catch (IOException e) {
if (!socket.isClosed()) {
LOG.debugv("Docker log-driver listener could not accept a connection: {0}", e.getMessage());
}
}
}
}
private void read(Socket connection) {
try (connection; InputStream in = connection.getInputStream()) {
readMessages(in);
} catch (IOException e) {
LOG.debugv("Docker log-driver connection ended: {0}", e.getMessage());
}
}
/** Reads null-terminated GELF messages until the stream ends, handing each to its container's sink. */
void readMessages(InputStream in) throws IOException {
ByteArrayOutputStream message = new ByteArrayOutputStream();
boolean oversized = false;
int b;
while ((b = in.read()) != -1) {
if (b != 0) {
if (message.size() < MAX_MESSAGE_BYTES) {
message.write(b);
} else {
oversized = true;
}
continue;
}
if (oversized) {
LOG.debugv("Dropped a GELF message over {0} bytes", MAX_MESSAGE_BYTES);
} else if (message.size() > 0) {
deliver(message.toByteArray());
}
message.reset();
oversized = false;
}
}
private void deliver(byte[] document) {
JsonNode gelf;
try {
gelf = JSON.readTree(document);
} catch (IOException e) {
LOG.debugv("Dropped a GELF message that is not JSON: {0}", e.getMessage());
return;
}
String token = gelf.path("_tag").asText("");
StreamType stream = gelf.path("level").asInt(6) == STDERR_LEVEL ? StreamType.STDERR : StreamType.STDOUT;
String line = gelf.path("short_message").asText("");
BiConsumer<StreamType, String> sink = sinks.get(token);
if (sink == null) {
Pending waiting = pending.get(token);
if (waiting == null) {
// register may have moved the pending lines to the sink between the two reads.
sink = sinks.get(token);
if (sink != null) {
sink.accept(stream, line);
}
return;
}
synchronized (waiting) {
sink = sinks.get(token);
if (sink == null) {
if (waiting.lines().size() < MAX_PENDING_LINES) {
waiting.lines().add(new String[] {stream.name(), line});
}
return;
}
}
}
sink.accept(stream, line);
}
private record Pending(long issuedAt, Deque<String[]> lines) {
}
void onShutdown(@Observes ShutdownEvent event) {
close();
}
void close() {
synchronized (startLock) {
if (server != null) {
try {
server.close();
} catch (IOException e) {
LOG.debugv("Could not close the Docker log-driver listener: {0}", e.getMessage());
}
}
}
}
}
@@ -99,6 +99,7 @@ public class RabbitMqManager {
.withName(containerName)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"amazonmq", broker.getBrokerId(), regionResolver.getAccountId(),
brokerRegion(broker)));
@@ -116,6 +116,7 @@ public class DocDbContainerManager {
.withName(containerName)
.withDockerNetwork(config.services().docdb().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withEnv(envVars)
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"docdb", clusterId, accountId, region));
@@ -572,6 +572,7 @@ public class EcrRegistryManager {
.withLoopbackPortBinding(CONTAINER_INTERNAL_PORT, port)
.withDockerNetwork(resolveRegistryDockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecr", null, regionResolver.getAccountId(), regionResolver.getDefaultRegion()));
addPersistenceMounts(specBuilder, env);
@@ -176,6 +176,7 @@ public class ElastiCacheContainerManager {
.withName(containerName)
.withDockerNetwork(config.services().elasticache().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"elasticache", groupId, regionResolver.getAccountId(), region));
if (shellLess) {
@@ -121,6 +121,7 @@ public class ElastiCacheMemcachedContainerManager {
.withName(containerName)
.withDockerNetwork(config.services().elasticache().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"elasticache", clusterId, regionResolver.getAccountId(), effectiveRegion));
@@ -167,6 +167,7 @@ public class FlinkContainerManager {
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation()
.withPushedLogs()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"kinesisanalytics", app.getApplicationName(),
@@ -152,6 +152,7 @@ public class MemoryDbContainerManager {
.withName(containerName)
.withDockerNetwork(config.services().memorydb().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"memorydb", clusterName, accountId, region));
@@ -238,6 +238,7 @@ public class RedpandaManager {
.withName(containerName)
.withDockerNetwork(config.services().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"msk", cluster.getClusterName(),
AwsArnUtils.accountOrDefault(cluster.getClusterArn(), regionResolver.getAccountId()),
@@ -115,6 +115,7 @@ public class NeptuneContainerManager {
.withEnv(backendEnv(dbType))
.withDockerNetwork(config.services().neptune().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"neptune", clusterId, accountId, region));
@@ -389,6 +389,10 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
.withLogRotation()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"rds", instanceId, runtimeIdentity.accountId(), runtimeIdentity.region()));
if (!ephemeral) {
// Only a container whose log is attached below gets it pushed; an ephemeral one is never read.
specBuilder.withPushedLogs();
}
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
@@ -102,6 +102,7 @@ public class RedshiftContainerManager {
.withCmd(List.of("postgres", "-c", "allow_system_table_mods=on", "-c", "max_connections=" + maxConnections))
.withDockerNetwork(config.services().redshift().dockerNetwork())
.withLogRotation()
.withPushedLogs()
.withLabels(ContainerStorageHelper.resourceIdentityLabels("redshift", clusterIdentifier, accountId, null));
int enginePort = 5432; // Default postgres port