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

@@ -139,6 +139,8 @@ floci:
max-concurrent-launches: 0 # Most container creates and starts at once; 0 = twice the CPUs, at least 4
events-exit-detection: false # Watch Lambda exits through one Docker events stream instead of a wait per container
log-poll-interval-millis: 1000 # How often a long-lived service container's log is read (it is not followed)
log-driver-mode: false # Opt-in: service containers push their logs over GELF; needs a daemon that can reach Floci
log-driver-port: 12201 # Fixed port of the log-driver listener; Docker dials it on every container start
docker-config-path: "" # Path to dir containing Docker's config.json (e.g. /root/.docker)
registry-credentials: [] # Per-registry explicit credentials for private registries
+25
View File
@@ -252,6 +252,28 @@ floci:
Environment variable: `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` (at least 100)
### Log-driver mode (opt-in)
With `log-driver-mode` on, the long-lived service containers whose logs Floci forwards (RDS, DocumentDB, Neptune, ElastiCache, MemoryDB, MSK, Redshift, Amazon MQ, the Managed Flink JobManager and the ECR registry) are started with Docker's `gelf` log driver pointed at a listener in Floci, so the daemon pushes each line as it is written: no reads on a timer and no Docker connection held for the container's log. Containers whose log Floci never reads, such as Flink TaskManagers and ephemeral RDS instances, keep the `json-file` driver.
Docker opens that connection itself, from wherever the daemon runs, so the mode only works when the daemon can reach Floci: Docker Desktop, which dials `host.docker.internal`, or a daemon on Floci's own host, which dials `127.0.0.1`. It does not work with Podman (which has no `gelf` driver), Docker-in-Docker, a remote daemon, or Floci running in a container whose port the daemon cannot reach, and when the daemon cannot connect, the container fails to start.
The daemon's local copy of the log (dual logging, on by default since Docker Engine 20.10) is what `docker logs`, the RDS log-file APIs and the fallback below read, so keep it on; `log-max-size` and `log-max-file` bound it.
Docker keeps the listener's address in each container's log configuration and dials it every time the container starts, so the listener takes a fixed port, `log-driver-port` (12201, GELF's standard port), and Floci opens it before it starts any container. A stopped container that Floci adopts after a restart therefore starts again. The port must be free on Floci's host. A container created with another `log-driver-port` or `log-driver-host` keeps dialing the old address: Floci reads its log on a timer from the local copy and logs a warning, and once stopped it starts again only after the setting is restored or the resource is recreated.
`log-driver-host` overrides the host the daemon dials. When it names an address of Floci's own host (Floci's address on a Docker network, for example), the listener binds that address instead of loopback; the listener has no authentication beyond each container's random tag, so only point it at a network you trust:
```yaml
floci:
docker:
log-driver-mode: true
log-driver-host: host.docker.internal
log-driver-port: 12201
```
Environment variables: `FLOCI_DOCKER_LOG_DRIVER_MODE`, `FLOCI_DOCKER_LOG_DRIVER_HOST`, `FLOCI_DOCKER_LOG_DRIVER_PORT`
Configure log rotation for all containers spawned by Floci:
@@ -442,6 +464,9 @@ caller keeps its existing failure handling after retries are exhausted.
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__USERNAME` | _(unset)_ | Username for credential entry 0 |
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__PASSWORD` | _(unset)_ | Password for credential entry 0 |
| `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` | `1000` | Milliseconds between the reads of a long-lived service container's log (databases, caches, brokers, the ECR registry, the EKS API server), read on a timer instead of followed; at least 100 |
| `FLOCI_DOCKER_LOG_DRIVER_MODE` | `false` | Long-lived service containers push their logs to Floci through Docker's `gelf` driver; needs a daemon that can reach Floci |
| `FLOCI_DOCKER_LOG_DRIVER_HOST` | _(unset)_ | Host the daemon dials for the log-driver mode; `host.docker.internal` on Docker Desktop, `127.0.0.1` otherwise |
| `FLOCI_DOCKER_LOG_DRIVER_PORT` | `12201` | Fixed port of Floci's log listener in the log-driver mode; Docker dials it on every start of a container created in the mode |
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Max container log file size before rotation |
| `FLOCI_DOCKER_LOG_MAX_FILE` | `3` | Number of rotated log files to retain |
| `FLOCI_DOCKER_EXTRA_LABELS_0__KEY` | _(unset)_ | Label key for extra-label entry 0, applied to every Floci-created container and volume (increment the index for more) |
@@ -155,6 +155,9 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
| `FLOCI_DOCKER_EVENTS_EXIT_DETECTION` | `false` | Watch Lambda containers' exits through one Docker events subscription instead of a wait stream per container. See [Docker Configuration](docker.md#container-exits-through-docker-events) |
| `FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_<SERVICE>` | _(none)_ | Most containers one service runs at once, named by its `io.floci.service` label in upper case (`FLOCI_DOCKER_SERVICE_MAX_CONTAINERS_LAMBDA=50`); a create past it fails with that service's own capacity error. A service not set is not limited. See [Docker Configuration](docker.md#per-service-container-budgets) |
| `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` | `1000` | Milliseconds between the reads of a long-lived service container's log, read on a timer instead of followed; at least 100. See [Docker Configuration](docker.md#container-log-settings) |
| `FLOCI_DOCKER_LOG_DRIVER_MODE` | `false` | Opt-in: long-lived service containers push their logs to Floci through Docker's `gelf` driver; needs a daemon that can reach Floci. See [Docker Configuration](docker.md#log-driver-mode-opt-in) |
| `FLOCI_DOCKER_LOG_DRIVER_HOST` | _(unset)_ | Host the daemon dials in the log-driver mode; `host.docker.internal` on Docker Desktop, `127.0.0.1` otherwise |
| `FLOCI_DOCKER_LOG_DRIVER_PORT` | `12201` | Fixed port of Floci's log listener in the log-driver mode; Docker dials it on every start of a container created in the mode |
| `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` | _(none)_ | Optional registry/repository base for every Docker image Floci launches. When set, `postgres:16-alpine` resolves as `<base>/postgres:16-alpine` and `public.ecr.aws/docker/library/ubuntu:24.04` resolves as `<base>/public.ecr.aws/docker/library/ubuntu:24.04`. An image in a registry on `localhost` or a loopback address, Floci's own ECR among them, is launched as it is |
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Log rotation max size for spawned containers (e.g. `10m`, `1g`) |
| `FLOCI_DOCKER_LOG_MAX_FILE` | `3` | Number of rotated log files to keep for spawned containers |
@@ -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
+9
View File
@@ -454,6 +454,15 @@ floci:
# for the container's life; at least 100. Keep in step with the @WithDefault on
# EmulatorConfig.DockerConfig.logPollIntervalMillis: a value set here WINS over the annotation.
log-poll-interval-millis: 1000
# FLOCI_DOCKER_LOG_DRIVER_MODE: opt-in; long-lived service containers push their logs to Floci
# through Docker's gelf driver instead of being read on a timer. Needs a daemon that can reach
# Floci (Docker Desktop or the same host). FLOCI_DOCKER_LOG_DRIVER_HOST overrides the host the
# daemon dials. Keep in step with the @WithDefault on EmulatorConfig.DockerConfig.logDriverMode.
log-driver-mode: false
# FLOCI_DOCKER_LOG_DRIVER_PORT: the listener's port in the log-driver mode (GELF's standard port).
# Docker dials it on every start of a container created in the mode, so it stays fixed. Keep in
# step with the @WithDefault on EmulatorConfig.DockerConfig.logDriverPort.
log-driver-port: 12201
resource-namespace: "" # FLOCI_DOCKER_RESOURCE_NAMESPACE; scopes child container/volume names
docker-config-path: ""
# extra-labels: # Extra Docker labels applied to every Floci-created container and volume
@@ -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);
}
}