diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index 8b736eb57c..c0655bd2c6 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -137,6 +137,7 @@ floci:
breaker-failure-threshold: 3 # Consecutive Docker call attempts (each retry counts) failing at the transport before Floci pings the daemon and fails calls fast if it is gone; 0 = off
breaker-probe-interval-seconds: 5 # Seconds between pings while the daemon is unreachable
max-concurrent-launches: 0 # Most container creates and starts at once; 0 = twice the CPUs, at least 4
+ log-poll-interval-millis: 1000 # How often a long-lived service container's log is read (it is not followed)
docker-config-path: "" # Path to dir containing Docker's config.json (e.g. /root/.docker)
registry-credentials: [] # Per-registry explicit credentials for private registries
diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md
index 786a24e6af..de8709ddfe 100644
--- a/docs/configuration/docker.md
+++ b/docs/configuration/docker.md
@@ -64,7 +64,7 @@ floci:
Environment variable: `FLOCI_DOCKER_MAX_CONNECTIONS`
-Streams that stay open for as long as a container or a command runs use a second, separate pool, so they can never starve create, start, stop and remove calls. Each Lambda container holds two of these (its log stream and the watcher that notices its runtime exiting) plus one per Lambda extension; other containers' log streams use it too, and so does the output of each long-running command: CodeBuild build phases, SSM run commands, ECS Exec sessions, EKS audit log followers, ECR garbage collection, EC2 and EKS user data and EMR bootstrap actions. The default of 3072 covers the 500 concurrent Lambda containers the default [Runtime API port range](../services/lambda.md#configuration) allows, with two extensions each (2000 connections), and leaves about 1000 for every other stream. Raise it if you widen that range, or run many builds, sessions or other containers at the same time. It follows the same rule (at least 1):
+Streams that stay open for as long as a container or a command runs use a second, separate pool, so they can never starve create, start, stop and remove calls. Each Lambda container holds two of these (its log stream and the watcher that notices its runtime exiting) plus one per Lambda extension; short-lived containers' log streams use it too (a long-lived service container's log is read on a timer instead, see [Container Log Settings](#container-log-settings)), and so does the output of each long-running command: CodeBuild build phases, SSM run commands, ECS Exec sessions, EKS audit log followers, ECR garbage collection, EC2 and EKS user data and EMR bootstrap actions. The default of 3072 covers the 500 concurrent Lambda containers the default [Runtime API port range](../services/lambda.md#configuration) allows, with two extensions each (2000 connections), and leaves about 1000 for every other stream. Raise it if you widen that range, or run many builds, sessions or other containers at the same time. It follows the same rule (at least 1):
```yaml
floci:
@@ -216,6 +216,17 @@ Explicit credentials take precedence for registries they cover. For everything e
## Container Log Settings
+Floci forwards each container's output to the console and to CloudWatch Logs. A container that runs for one job or invocation (a Lambda function, a build, an ECS task) has its log followed as it is written. A long-lived service container (a database, cache or broker, the ECR registry, the EKS API server) instead has its log read every `log-poll-interval-millis` (1000 by default) with one short call, so it holds no Docker connection between reads. Its lines reach the console and CloudWatch Logs up to one interval later, and its last lines are read between its stop and its removal:
+
+```yaml
+floci:
+ docker:
+ log-poll-interval-millis: 1000
+```
+
+Environment variable: `FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS` (at least 100)
+
+
Configure log rotation for all containers spawned by Floci:
```yaml
@@ -402,6 +413,7 @@ caller keeps its existing failure handling after retries are exhausted.
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__SERVER` | _(unset)_ | Registry hostname for credential entry 0 |
| `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_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) |
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 1d3861750f..b513f5e926 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -152,6 +152,7 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
| `FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD` | `3` | Docker call attempts in a row (each retry counts) that fail before the daemon answers, after which a failed ping makes every Docker call fail at once until the daemon answers again; `0` turns this off. See [Docker Configuration](docker.md#unreachable-daemon) |
| `FLOCI_DOCKER_BREAKER_PROBE_INTERVAL_SECONDS` | `5` | Seconds between the pings that check whether an unreachable Docker daemon is back |
| `FLOCI_DOCKER_MAX_CONCURRENT_LAUNCHES` | `0` | Most container creates and starts sent to the Docker daemon at once; `0` means twice the CPUs Floci sees, at least 4. See [Docker Configuration](docker.md#concurrent-container-launches) |
+| `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_IMAGE_REGISTRY_BASE` | _(none)_ | Optional registry/repository base for every Docker image Floci launches. When set, `postgres:16-alpine` resolves as `/postgres:16-alpine` and `public.ecr.aws/docker/library/ubuntu:24.04` resolves as `/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 |
diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java
index ff54ebb0ed..643dd0263b 100644
--- a/src/main/java/io/floci/aws/config/EmulatorConfig.java
+++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java
@@ -4537,6 +4537,15 @@ public interface EmulatorConfig {
@WithDefault("0")
int maxConcurrentLaunches();
+ /**
+ * Milliseconds between the reads of a long-lived service container's log (a database, a broker, a
+ * registry), which Floci reads on a timer instead of holding a follow stream open for the
+ * container's life. A line reaches the console and CloudWatch Logs up to this long after the
+ * container writes it. At least 100.
+ */
+ @WithDefault("1000")
+ int logPollIntervalMillis();
+
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java
index 7af2547460..c18e616ce1 100644
--- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java
@@ -717,6 +717,7 @@ public class ContainerLifecycleManager {
*/
public void stopAndRemove(String containerId, Closeable logStream, int stopTimeoutSeconds) {
boolean stoppedOrMissing = stop(containerId, stopTimeoutSeconds);
+ readLastLogLines(logStream);
// Force removal is the recovery path when Docker could not stop the container cleanly. It also
// terminates the follow-log transport, allowing its terminal callback to drain the final tail.
@@ -737,6 +738,25 @@ public class ContainerLifecycleManager {
}
}
+ /**
+ * A log read on a timer ({@link ContainerLogStreamer#attachPolled}) has not seen what the container
+ * wrote since its last read, and cannot once the container is removed, so read it between the stop
+ * and the removal. A follow stream needs nothing: the removal ends it and it drains its own tail.
+ */
+ private static void readLastLogLines(Closeable logStream) {
+ if (logStream instanceof PolledLogHandle polled) {
+ polled.drainBeforeRemove();
+ }
+ }
+
+ /**
+ * Reads what a polled log has not seen yet, for a caller that force-removes its container itself
+ * instead of going through {@link #stopAndRemove}: once the container is gone its log cannot be read.
+ */
+ public void readLogBeforeRemoval(Closeable logStream) {
+ readLastLogLines(logStream);
+ }
+
/**
* Stops a container and leaves it in place, for its output to be read before it is removed: one that
* had already exited, or is gone, counts as stopped.
@@ -829,6 +849,7 @@ public class ContainerLifecycleManager {
stopFailure = e;
LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage());
}
+ readLastLogLines(logStream);
try {
RemoveContainerCmd remove = dockerClient.removeContainerCmd(containerId).withForce(true);
diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java
index 945d9ef1a7..d466ee24c9 100644
--- a/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java
+++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLogStreamer.java
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
+import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
import jakarta.enterprise.context.ApplicationScoped;
@@ -16,6 +17,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@@ -47,17 +49,43 @@ public class ContainerLogStreamer {
private static final Logger LOG = Logger.getLogger(ContainerLogStreamer.class);
private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd");
+ private static final Duration DEFAULT_POLL_INTERVAL = Duration.ofMillis(1000);
+
private final DockerClient dockerClient;
+ private final DockerClient pollingDockerClient;
private final CloudWatchLogsService cloudWatchLogsService;
+ private final Duration pollInterval;
// 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
- // (see DockerClientProducer / StreamingDocker).
+ // (see DockerClientProducer / StreamingDocker). A polled attach reads with short
+ // control-plane calls instead, and holds no connection between reads.
@Inject
- public ContainerLogStreamer(@StreamingDocker DockerClient dockerClient, CloudWatchLogsService cloudWatchLogsService) {
+ public ContainerLogStreamer(@StreamingDocker DockerClient dockerClient, DockerClient pollingDockerClient,
+ CloudWatchLogsService cloudWatchLogsService, EmulatorConfig config) {
+ this(dockerClient, pollingDockerClient, cloudWatchLogsService,
+ Duration.ofMillis(validateLogPollIntervalMillis(config.docker().logPollIntervalMillis())));
+ }
+
+ public ContainerLogStreamer(DockerClient dockerClient, CloudWatchLogsService cloudWatchLogsService) {
+ this(dockerClient, dockerClient, cloudWatchLogsService, DEFAULT_POLL_INTERVAL);
+ }
+
+ ContainerLogStreamer(DockerClient dockerClient, DockerClient pollingDockerClient,
+ CloudWatchLogsService cloudWatchLogsService, Duration pollInterval) {
this.dockerClient = dockerClient;
+ this.pollingDockerClient = pollingDockerClient;
this.cloudWatchLogsService = cloudWatchLogsService;
+ this.pollInterval = pollInterval;
+ }
+
+ static int validateLogPollIntervalMillis(int millis) {
+ if (millis < 100) {
+ throw new IllegalArgumentException("floci.docker.log-poll-interval-millis "
+ + "(FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS) must be at least 100, got: " + millis);
+ }
+ return millis;
}
/**
@@ -120,6 +148,47 @@ public class ContainerLogStreamer {
return follow(containerId, since, emitter);
}
+ /**
+ * Like {@link #attach}, but for a long-lived service container (a database, a broker, a registry):
+ * the log is read every {@code floci.docker.log-poll-interval-millis} with a short call, so the container
+ * holds no streaming connection and no stream thread for its life. Lines arrive up to one interval
+ * later. Hand the handle to {@code ContainerLifecycleManager.stopAndRemove}, which reads the last
+ * lines between the container's stop and its removal.
+ */
+ public Closeable attachPolled(String containerId, String logGroup, String logStream,
+ String region, String logPrefix) {
+ return attachPolledForAccount(null, containerId, logGroup, logStream, region, logPrefix);
+ }
+
+ /** Like {@link #attachFromNow}, read on a timer as {@link #attachPolled} is. */
+ public Closeable attachPolledFromNow(String containerId, String logGroup, String logStream,
+ String region, String logPrefix) {
+ return attachPolledFromNowForAccount(null, containerId, logGroup, logStream, region, logPrefix);
+ }
+
+ /** Like {@link #attachForAccount}, read on a timer as {@link #attachPolled} is. */
+ public Closeable attachPolledForAccount(String accountId, String containerId, String logGroup,
+ String logStream, String region, String logPrefix) {
+ return attachPolledForAccount(accountId, containerId, logGroup, logStream, region, logPrefix, null);
+ }
+
+ /** Like {@link #attachFromNowForAccount}, read on a timer as {@link #attachPolled} is. */
+ public Closeable attachPolledFromNowForAccount(String accountId, String containerId, String logGroup,
+ String logStream, String region, String logPrefix) {
+ return attachPolledForAccount(accountId, containerId, logGroup, logStream, region, logPrefix, Instant.now());
+ }
+
+ 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) -> {
+ String logged = logToConsole(logPrefix, line);
+ if (logged != null) {
+ forwardToCloudWatchLogs(accountId, logGroup, logStream, region, logged);
+ }
+ }).start(pollInterval);
+ }
+
/**
* Like {@link #attachForAccount}, but forwards the container's standard output and standard error to
* log streams of their own in {@code logGroup}, {@code stdoutStream} and {@code stderrStream}, either
diff --git a/src/main/java/io/floci/aws/core/common/docker/PolledLogHandle.java b/src/main/java/io/floci/aws/core/common/docker/PolledLogHandle.java
new file mode 100644
index 0000000000..d81ecbc83c
--- /dev/null
+++ b/src/main/java/io/floci/aws/core/common/docker/PolledLogHandle.java
@@ -0,0 +1,419 @@
+package io.floci.aws.core.common.docker;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.async.ResultCallback;
+import com.github.dockerjava.api.command.LogContainerCmd;
+import com.github.dockerjava.api.exception.NotFoundException;
+import com.github.dockerjava.api.model.Frame;
+import com.github.dockerjava.api.model.StreamType;
+import io.floci.aws.core.common.docker.ContainerLogStreamer.LogLineBuffer;
+import org.jboss.logging.Logger;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.format.DateTimeParseException;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+
+/**
+ * Reads a long-lived container's log on a timer instead of holding a follow stream for its whole life:
+ * every {@code interval} one short {@code logs?since=} request returns what the container wrote since the
+ * last read, and the connection goes back to the pool. Lines reach {@code sink} in the order the container
+ * wrote them, each once.
+ *
+ *
Docker's {@code since} is whole seconds, so each read starts at the second of the last record seen
+ * and gets some records again. The cursor is that record's timestamp and how many records carried it,
+ * so a repeated record is skipped and a new one with the same timestamp is not, which a "last timestamp
+ * plus a nanosecond" cursor would drop. A line split across reads is held per stream until its newline.
+ *
+ *
Docker applies {@code since} by reading the log from its start, so once a record has been seen each
+ * read also asks for only the last {@link #TAIL_LINES} records. That read still begins with a record
+ * already seen unless more than that many arrived since the last one; when its first record is new
+ * instead, the read is dropped and made again without the bound, so no record is skipped.
+ *
+ *
{@link #drainBeforeRemove} reads once more on the caller's thread, for the container's last lines
+ * between its stop and its removal; {@link #close} reads a last time without blocking and then flushes
+ * any unterminated line.
+ */
+final class PolledLogHandle implements Closeable {
+
+ private static final Logger LOG = Logger.getLogger(PolledLogHandle.class);
+ private static final Duration READ_TIMEOUT = Duration.ofSeconds(2);
+ private static final int TIMESTAMP_MAX_BYTES = 40;
+ static final int TAIL_LINES = 1000;
+
+ // Idle threads time out, as the close-drain scheduler's do, so the poller pins no classloader.
+ private static final ScheduledThreadPoolExecutor POLLER = poller();
+
+ private static ScheduledThreadPoolExecutor poller() {
+ ScheduledThreadPoolExecutor poller = new ScheduledThreadPoolExecutor(2, runnable -> {
+ Thread thread = new Thread(runnable, "floci-container-log-poll");
+ thread.setDaemon(true);
+ return thread;
+ });
+ poller.setKeepAliveTime(5, TimeUnit.SECONDS);
+ poller.allowCoreThreadTimeOut(true);
+ poller.setRemoveOnCancelPolicy(true);
+ return poller;
+ }
+
+ private final DockerClient docker;
+ private final String containerId;
+ private final BiConsumer sink;
+ private final Object readLock = new Object();
+ private final Object stateLock = new Object();
+ private final Map buffers = new EnumMap<>(StreamType.class);
+ private final Map includeContinuation = new EnumMap<>(StreamType.class);
+ private final Map atRecordStart = new EnumMap<>(StreamType.class);
+ private final Map pendingRecordStart = new EnumMap<>(StreamType.class);
+ // How long the stamp of the record each stream is in was: one further into that record must match it.
+ private final Map stampLength = new EnumMap<>(StreamType.class);
+ private Instant cursor;
+ private int recordsAtCursor;
+ private int seenAtCursor;
+ private boolean finished;
+ private boolean boundedRead;
+ private boolean awaitingFirstRecord;
+ private boolean overflowed;
+ private volatile boolean stopped;
+ private ScheduledFuture> schedule;
+
+ /** {@code since} of null reads the container's whole log; otherwise only what it writes from then on. */
+ PolledLogHandle(DockerClient docker, String containerId, Instant since, BiConsumer sink) {
+ this.docker = docker;
+ this.containerId = containerId;
+ this.sink = sink;
+ this.cursor = since == null ? Instant.EPOCH : since;
+ }
+
+ /** Starts reading every {@code interval}, the first read at once. */
+ PolledLogHandle start(Duration interval) {
+ schedule = POLLER.scheduleWithFixedDelay(this::readSafely, 0, interval.toMillis(), TimeUnit.MILLISECONDS);
+ return this;
+ }
+
+ /** Reads what the container wrote since the last read, on the caller's thread; for between its stop and its removal. */
+ void drainBeforeRemove() {
+ readSafely();
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (stopped) {
+ return;
+ }
+ stopped = true;
+ if (schedule != null) {
+ schedule.cancel(false);
+ }
+ POLLER.execute(() -> {
+ try {
+ readSafely();
+ } finally {
+ finish();
+ }
+ });
+ }
+
+ private void readSafely() {
+ try {
+ read();
+ } catch (RuntimeException e) {
+ LOG.debugv("Could not read the log of container {0}: {1}", containerId, e.getMessage());
+ }
+ }
+
+ /** One {@code logs?since=} read; returns quietly when the container is gone, and stops reading it. */
+ void read() {
+ synchronized (readLock) {
+ if (readOnce(true)) {
+ readOnce(false);
+ }
+ }
+ }
+
+ /** True when a bounded read began past the cursor, so records may lie between them and it must be made again. */
+ private boolean readOnce(boolean allowTail) {
+ if (!beginRead(allowTail)) {
+ return false;
+ }
+ ResultCallback.Adapter callback = new ResultCallback.Adapter<>() {
+ @Override
+ public void onNext(Frame frame) {
+ if (frame != null && frame.getPayload() != null) {
+ accept(frame.getStreamType(), frame.getPayload());
+ }
+ }
+ };
+ try (LogContainerCmd command = docker.logContainerCmd(containerId)
+ .withStdOut(true)
+ .withStdErr(true)
+ .withFollowStream(false)
+ .withTimestamps(true)
+ .withSince(sinceSeconds())) {
+ if (isBoundedRead()) {
+ command.withTail(TAIL_LINES);
+ }
+ if (command.exec(callback).awaitCompletion(READ_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) {
+ endRead();
+ } else {
+ LOG.debugv("Reading the log of container {0} took over {1} s; the next read resumes it",
+ containerId, READ_TIMEOUT.toSeconds());
+ }
+ } catch (NotFoundException e) {
+ stopReading();
+ finish();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ closeQuietly(callback);
+ }
+ return hasOverflowed();
+ }
+
+ /**
+ * Starts counting the records at the cursor afresh for a new read; false once finished. The read asks for
+ * only the last {@link #TAIL_LINES} records when {@code allowTail} is set and a record has been seen.
+ */
+ boolean beginRead(boolean allowTail) {
+ synchronized (stateLock) {
+ seenAtCursor = 0;
+ atRecordStart.clear();
+ pendingRecordStart.clear();
+ boundedRead = allowTail && recordsAtCursor > 0;
+ awaitingFirstRecord = true;
+ overflowed = false;
+ return !finished;
+ }
+ }
+
+ private boolean isBoundedRead() {
+ synchronized (stateLock) {
+ return boundedRead;
+ }
+ }
+
+ boolean hasOverflowed() {
+ synchronized (stateLock) {
+ return overflowed;
+ }
+ }
+
+ private int sinceSeconds() {
+ synchronized (stateLock) {
+ return (int) Math.min(Integer.MAX_VALUE, Math.max(0, cursor.getEpochSecond()));
+ }
+ }
+
+ /**
+ * One payload of a timestamped read: records of {@code }, each up to its
+ * newline. Docker writes each record as one frame, and docker-java hands a frame on in reads of up to
+ * 1024 bytes, so a payload can begin or end anywhere inside a record.
+ *
+ * A read begins with a record, and a frame holds no newline but its last byte, so the start of a read
+ * and what follows a newline open a record, whose stamp is read in any RFC 3339 form the runtime writes:
+ * Docker's nine fractional digits, or the whole seconds Podman wrote before 5.8. A payload that continues
+ * a line is either more of that record, cut by the transport, or the next record of one Docker split at
+ * 16 KB, which has no newline. Only a stamp exactly as long as the record's own opens a record there, so
+ * a line's text that starts with a shorter instant, as MySQL's six-digit one, stays text.
+ *
+ *
A payload that ends while its start could still be a stamp is held and read again with that
+ * stream's next payload.
+ */
+ void accept(StreamType stream, byte[] payload) {
+ synchronized (stateLock) {
+ if (finished || overflowed) {
+ return;
+ }
+ byte[] data = payload;
+ boolean atStart = atRecordStart.getOrDefault(stream, true);
+ byte[] pending = pendingRecordStart.remove(stream);
+ if (pending != null) {
+ data = new byte[pending.length + payload.length];
+ System.arraycopy(pending, 0, data, 0, pending.length);
+ System.arraycopy(payload, 0, data, pending.length, payload.length);
+ }
+ int offset = 0;
+ while (offset < data.length) {
+ int end = offset;
+ while (end < data.length && data[end] != '\n') {
+ end++;
+ }
+ boolean terminated = end < data.length;
+ if (terminated) {
+ end++;
+ }
+ Stamp stamp = stampAt(stream, atStart, data, offset, end);
+ if (stamp == Stamp.UNDECIDED) {
+ pendingRecordStart.put(stream, Arrays.copyOfRange(data, offset, end));
+ atRecordStart.put(stream, atStart);
+ return;
+ }
+ if (stamp == Stamp.NONE) {
+ acceptContinuation(stream, data, offset, end);
+ } else {
+ acceptRecord(stream, stamp, data, offset, end);
+ }
+ if (overflowed) {
+ return;
+ }
+ atStart = terminated;
+ offset = end;
+ }
+ atRecordStart.put(stream, atStart);
+ }
+ }
+
+ /** A record's stamp: its instant and where the space after it is. */
+ private record Stamp(Instant instant, int space) {
+ static final Stamp NONE = new Stamp(null, -1);
+ // The bytes so far could still be a stamp cut before its space.
+ static final Stamp UNDECIDED = new Stamp(null, -2);
+ }
+
+ /** The stamp opening {@code data[start, end)}, at a record start or, when {@code atStart} is false, further into one. */
+ private Stamp stampAt(StreamType stream, boolean atStart, byte[] data, int start, int end) {
+ int required = atStart ? -1 : stampLength.getOrDefault(stream, 0);
+ if (required == 0) {
+ return Stamp.NONE;
+ }
+ int limit = atStart ? TIMESTAMP_MAX_BYTES : required;
+ int space = start;
+ while (space < end && space - start <= limit && isTimestampChar(data[space])) {
+ space++;
+ }
+ if (space - start > limit) {
+ return Stamp.NONE;
+ }
+ if (space == end) {
+ return Stamp.UNDECIDED;
+ }
+ if (data[space] != ' ' || space == start || (!atStart && space - start != required)) {
+ return Stamp.NONE;
+ }
+ try {
+ return new Stamp(Instant.parse(new String(data, start, space - start, StandardCharsets.US_ASCII)), space);
+ } catch (DateTimeParseException notAStamp) {
+ return Stamp.NONE;
+ }
+ }
+
+ private static boolean isTimestampChar(byte b) {
+ return (b >= '0' && b <= '9') || b == '-' || b == ':' || b == '.' || b == 'T' || b == 'Z' || b == '+';
+ }
+
+ /** Text of the record a stream is in, without a stamp of its own; it shares that record's fate. */
+ private void acceptContinuation(StreamType stream, byte[] data, int start, int end) {
+ if (includeContinuation.getOrDefault(stream, false)) {
+ emit(stream, data, start, end);
+ }
+ }
+
+ /**
+ * Ends a read that completed. It ended on a frame, so bytes held further into a record were that record's
+ * text and not the start of a stamp.
+ */
+ void endRead() {
+ synchronized (stateLock) {
+ if (!finished) {
+ flushHeldText();
+ }
+ }
+ }
+
+ private void flushHeldText() {
+ pendingRecordStart.forEach((stream, held) -> {
+ if (!atRecordStart.getOrDefault(stream, true)) {
+ acceptContinuation(stream, held, 0, held.length);
+ }
+ });
+ pendingRecordStart.clear();
+ }
+
+ private void acceptRecord(StreamType stream, Stamp stamp, byte[] data, int start, int end) {
+ stampLength.put(stream, stamp.space() - start);
+ Instant timestamp = stamp.instant();
+ if (awaitingFirstRecord) {
+ awaitingFirstRecord = false;
+ if (boundedRead && timestamp.isAfter(cursor)) {
+ overflowed = true;
+ return;
+ }
+ }
+ boolean include = isNew(timestamp);
+ includeContinuation.put(stream, include);
+ if (include) {
+ emit(stream, data, stamp.space() + 1, end);
+ }
+ }
+
+ /** Whether a record with this timestamp is past the cursor, moving the cursor when it is. */
+ private boolean isNew(Instant timestamp) {
+ int order = timestamp.compareTo(cursor);
+ if (order < 0) {
+ return false;
+ }
+ if (order == 0) {
+ seenAtCursor++;
+ if (seenAtCursor <= recordsAtCursor) {
+ return false;
+ }
+ recordsAtCursor++;
+ return true;
+ }
+ cursor = timestamp;
+ recordsAtCursor = 1;
+ seenAtCursor = 1;
+ return true;
+ }
+
+ private void emit(StreamType stream, byte[] payload, int start, int end) {
+ if (end <= start) {
+ return;
+ }
+ byte[] content = new byte[end - start];
+ System.arraycopy(payload, start, content, 0, content.length);
+ for (String line : buffers.computeIfAbsent(stream, ignored -> new LogLineBuffer()).append(content)) {
+ sink.accept(stream, line);
+ }
+ }
+
+ private void stopReading() {
+ stopped = true;
+ if (schedule != null) {
+ schedule.cancel(false);
+ }
+ }
+
+ /** Hands on each stream's unterminated last line and ignores anything read after. */
+ void finish() {
+ synchronized (stateLock) {
+ if (finished) {
+ return;
+ }
+ flushHeldText();
+ finished = true;
+ buffers.forEach((stream, buffer) -> buffer.flush().ifPresent(line -> sink.accept(stream, line)));
+ }
+ }
+
+ boolean isReading() {
+ return !stopped;
+ }
+
+ private static void closeQuietly(Closeable closeable) {
+ try {
+ closeable.close();
+ } catch (IOException e) {
+ LOG.debugv("Could not close a container log read: {0}", e.getMessage());
+ }
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java b/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java
index d80d4636f6..3bd1e2d797 100644
--- a/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java
+++ b/src/main/java/io/floci/aws/services/amazonmq/container/RabbitMqManager.java
@@ -176,7 +176,7 @@ public class RabbitMqManager {
String logGroup = broker.generalLogGroup();
String logStream = logStreamer.generateLogStreamName(shortId);
String region = brokerRegion(broker);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "amazonmq:" + broker.getBrokerId());
if (logHandle != null) {
logStreams.put(broker.getBrokerId(), logHandle);
diff --git a/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java b/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
index 2e7dd2b475..36100411aa 100644
--- a/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
+++ b/src/main/java/io/floci/aws/services/appsync/graphql/js/NodeAppSyncJsRuntime.java
@@ -372,7 +372,7 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown
private void attachLogStream() {
try {
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
- this.logStream = logStreamer.attach(containerId, "/floci/appsync-js",
+ this.logStream = logStreamer.attachPolled(containerId, "/floci/appsync-js",
logStreamer.generateLogStreamName(shortId),
regionResolver.getDefaultRegion(), "appsync:js");
} catch (RuntimeException e) {
diff --git a/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java b/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java
index c0b9b9ec53..0d94070838 100644
--- a/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java
+++ b/src/main/java/io/floci/aws/services/docdb/container/DocDbContainerManager.java
@@ -144,7 +144,7 @@ public class DocDbContainerManager {
String logGroup = "/aws/docdb/cluster/" + clusterId + "/audit";
String logStream = logStreamer.generateLogStreamName(shortId);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "docdb:" + clusterId);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java
index 789bf74aea..65a0635ae9 100644
--- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java
+++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java
@@ -597,8 +597,8 @@ public class EcrRegistryManager {
String region = regionResolver.getDefaultRegion();
this.logStream = adopted
- ? logStreamer.attachFromNow(containerId, logGroup, logStreamName, region, "ecr:registry")
- : logStreamer.attach(containerId, logGroup, logStreamName, region, "ecr:registry");
+ ? logStreamer.attachPolledFromNow(containerId, logGroup, logStreamName, region, "ecr:registry")
+ : logStreamer.attachPolled(containerId, logGroup, logStreamName, region, "ecr:registry");
}
private void closeLogStream() {
diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java
index 4b32e91343..ed03e22030 100644
--- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java
+++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java
@@ -1752,9 +1752,9 @@ public class EksClusterManager
try {
String logStream = "kube-apiserver-" + hash;
Closeable handle = fromNow
- ? logStreamer.attachFromNowForAccount(
+ ? logStreamer.attachPolledFromNowForAccount(
accountId, containerId, logGroup, logStream, region, "eks:" + cluster.getName())
- : logStreamer.attachForAccount(
+ : logStreamer.attachPolledForAccount(
accountId, containerId, logGroup, logStream, region, "eks:" + cluster.getName());
if (handle != null) {
handles.add(handle);
diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java
index 1e1073bcde..7689a1ef0b 100644
--- a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java
+++ b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManager.java
@@ -237,7 +237,7 @@ public class ElastiCacheContainerManager {
String logGroup = "/aws/elasticache/cluster/" + groupId + "/engine-log";
String logStream = logStreamer.generateLogStreamName(shortId);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "elasticache:" + groupId);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManager.java b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManager.java
index db2c46b528..96a2f20e83 100644
--- a/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManager.java
+++ b/src/main/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManager.java
@@ -146,7 +146,7 @@ public class ElastiCacheMemcachedContainerManager {
String logGroup = "/aws/elasticache/cluster/" + clusterId + "/engine-log";
String logStream = logStreamer.generateLogStreamName(shortId);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, effectiveRegion, "elasticache-memcached:" + clusterId);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/floci/ui/FlociUiManager.java b/src/main/java/io/floci/aws/services/floci/ui/FlociUiManager.java
index ccee9dae6b..69491e9d44 100644
--- a/src/main/java/io/floci/aws/services/floci/ui/FlociUiManager.java
+++ b/src/main/java/io/floci/aws/services/floci/ui/FlociUiManager.java
@@ -812,8 +812,8 @@ public class FlociUiManager {
String logStreamName = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
this.logStream = adopted
- ? logStreamer.attachFromNow(containerId, logGroup, logStreamName, region, "floci:ui")
- : logStreamer.attach(containerId, logGroup, logStreamName, region, "floci:ui");
+ ? logStreamer.attachPolledFromNow(containerId, logGroup, logStreamName, region, "floci:ui")
+ : logStreamer.attachPolled(containerId, logGroup, logStreamName, region, "floci:ui");
}
/** Releases the previous follower, so a restarted sidecar does not leave one behind. */
diff --git a/src/main/java/io/floci/aws/services/kinesisanalytics/container/FlinkContainerManager.java b/src/main/java/io/floci/aws/services/kinesisanalytics/container/FlinkContainerManager.java
index bec81a1ff6..32b6ace073 100644
--- a/src/main/java/io/floci/aws/services/kinesisanalytics/container/FlinkContainerManager.java
+++ b/src/main/java/io/floci/aws/services/kinesisanalytics/container/FlinkContainerManager.java
@@ -628,7 +628,7 @@ public class FlinkContainerManager {
String logGroup = "/aws/kinesis-analytics/" + app.getApplicationName();
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionOf(app);
- Closeable logHandle = logStreamer.attach(containerId, logGroup, logStream, region,
+ Closeable logHandle = logStreamer.attachPolled(containerId, logGroup, logStream, region,
"kinesisanalytics:" + runtimeKey(app));
if (logHandle != null) {
logStreams.put(runtimeKey(app), logHandle);
diff --git a/src/main/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManager.java b/src/main/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManager.java
index 648e1130ad..f9c32d622e 100644
--- a/src/main/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManager.java
+++ b/src/main/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManager.java
@@ -190,7 +190,7 @@ public class MemoryDbContainerManager {
String logName = isDefaultScope(accountId, region) ? logicalName : clusterName;
String logGroup = "/aws/memorydb/cluster/" + logName + "/engine-log";
String logStream = logStreamer.generateLogStreamName(shortId);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "memorydb:" + clusterName);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/msk/RedpandaManager.java b/src/main/java/io/floci/aws/services/msk/RedpandaManager.java
index 840ceec0db..21551261b1 100644
--- a/src/main/java/io/floci/aws/services/msk/RedpandaManager.java
+++ b/src/main/java/io/floci/aws/services/msk/RedpandaManager.java
@@ -201,7 +201,7 @@ public class RedpandaManager {
String region = regionResolver.regionOf(cluster.getClusterArn());
String account = AwsArnUtils.accountOrDefault(cluster.getClusterArn(), regionResolver.getDefaultAccountId());
- Closeable logHandle = logStreamer.attachForAccount(
+ Closeable logHandle = logStreamer.attachPolledForAccount(
account, info.containerId(), logGroup, logStream, region, "msk:" + cluster.getClusterName());
if (logHandle != null) {
logStreams.put(clusterIdentityKey(cluster), logHandle);
diff --git a/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java b/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java
index 85a254c2b2..49540626fc 100644
--- a/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java
+++ b/src/main/java/io/floci/aws/services/neptune/container/NeptuneContainerManager.java
@@ -140,7 +140,7 @@ public class NeptuneContainerManager {
String logGroup = "/aws/neptune/cluster/" + identity + "/" + dbType.name().toLowerCase() + "-log";
String logStream = logStreamer.generateLogStreamName(shortId);
- Closeable logHandle = logStreamer.attach(
+ Closeable logHandle = logStreamer.attachPolled(
info.containerId(), logGroup, logStream, region, "neptune:" + identity);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java
index c096d3f472..685d80ba58 100644
--- a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java
+++ b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java
@@ -450,10 +450,10 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
String logStream = logStreamer.generateLogStreamName(shortId);
Closeable logHandle = runtimeIdentity.arnAccountId() != null
- ? logStreamer.attachForAccount(
+ ? logStreamer.attachPolledForAccount(
runtimeIdentity.arnAccountId(), info.containerId(), logGroup,
logStream, runtimeIdentity.region(), "rds:" + effectiveRuntimeId)
- : logStreamer.attach(
+ : logStreamer.attachPolled(
info.containerId(), logGroup, logStream, runtimeIdentity.region(),
"rds:" + effectiveRuntimeId);
handle.setLogStream(logHandle);
diff --git a/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java b/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java
index a91fc0048b..73d5a80c73 100644
--- a/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java
+++ b/src/main/java/io/floci/aws/services/redshift/container/RedshiftContainerManager.java
@@ -220,7 +220,7 @@ public class RedshiftContainerManager {
info.containerId(), clusterIdentifier, endpoint.host(), endpoint.port());
try {
- Closeable stream = logStreamer.attach(
+ Closeable stream = logStreamer.attachPolled(
info.containerId(),
"/floci/redshift",
clusterIdentifier,
@@ -250,6 +250,9 @@ public class RedshiftContainerManager {
String adoptedId = adoptedContainers.get(key);
String containerId = handle == null
? adoptedContainers.getOrDefault(key, containerName(accountId, clusterIdentifier)) : handle.getContainerId();
+ if (handle != null) {
+ lifecycleManager.readLogBeforeRemoval(handle.getLogStream());
+ }
lifecycleManager.removeIfExistsStrict(containerId, true);
releaseHandle(key, handle);
if (containerId.equals(adoptedId)) {
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 56b008416f..ec01e54ac4 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -445,6 +445,11 @@ floci:
# Floci sees, at least 4. Keep in step with the @WithDefault on
# EmulatorConfig.DockerConfig.maxConcurrentLaunches: a value set here WINS over the annotation.
max-concurrent-launches: 0
+ # FLOCI_DOCKER_LOG_POLL_INTERVAL_MILLIS: milliseconds between the reads of a long-lived service
+ # container's log (databases, brokers, registries), read on a timer instead of a follow stream held
+ # 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
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
diff --git a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java
index 174ec93727..e7e7079ff5 100644
--- a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java
+++ b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java
@@ -247,6 +247,18 @@ class ApplicationDefaultsTest {
.getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
}
+ // Catches: log-poll-interval-millis missing from the shipped application.yml, or a yml value that
+ // silently disagrees with its @WithDefault fallback.
+ @Test
+ void productionConfigDeclaresTheContainerLogPollIntervalAtItsDefault() throws IOException, NoSuchMethodException {
+ JsonNode interval = productionConfig().path("floci").path("docker").path("log-poll-interval-millis");
+
+ assertFalse(interval.isMissingNode(), "log-poll-interval-millis should be declared in application.yml");
+ assertEquals(1000, interval.asInt());
+ assertEquals("1000", EmulatorConfig.DockerConfig.class.getMethod("logPollIntervalMillis")
+ .getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml");
+ }
+
// Catches: warm-pool-max-total shipped unbounded again, so a stack of many functions keeps one
// warm container per function touched, or a yml value that disagrees with the @WithDefault.
@Test
diff --git a/src/test/java/io/floci/aws/core/common/docker/PolledLogHandleTest.java b/src/test/java/io/floci/aws/core/common/docker/PolledLogHandleTest.java
new file mode 100644
index 0000000000..2937649e3c
--- /dev/null
+++ b/src/test/java/io/floci/aws/core/common/docker/PolledLogHandleTest.java
@@ -0,0 +1,261 @@
+package io.floci.aws.core.common.docker;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.async.ResultCallback;
+import com.github.dockerjava.api.command.LogContainerCmd;
+import com.github.dockerjava.api.command.RemoveContainerCmd;
+import com.github.dockerjava.api.command.StopContainerCmd;
+import com.github.dockerjava.api.model.Frame;
+import com.github.dockerjava.api.model.StreamType;
+import org.junit.jupiter.api.Test;
+import org.mockito.Answers;
+import org.mockito.InOrder;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class PolledLogHandleTest {
+
+ private final List lines = Collections.synchronizedList(new ArrayList<>());
+
+ private PolledLogHandle handle(Instant since) {
+ return new PolledLogHandle(mock(DockerClient.class), "c1", since,
+ (stream, line) -> lines.add(stream + ":" + line));
+ }
+
+ private static byte[] record(String timestamp, String content) {
+ return (timestamp + " " + content).getBytes(StandardCharsets.UTF_8);
+ }
+
+ private static void read(PolledLogHandle handle, StreamType stream, byte[]... frames) {
+ handle.beginRead(true);
+ for (byte[] frame : frames) {
+ handle.accept(stream, frame);
+ }
+ }
+
+ // Catches: a whole-second since re-reading the records of the last second into CloudWatch Logs
+ // again, or a "last timestamp plus a nanosecond" cursor dropping a later record that shares a timestamp.
+ @Test
+ void recordsAreForwardedOnceAcrossOverlappingReadsEvenWhenTheyShareATimestamp() {
+ PolledLogHandle handle = handle(null);
+ String t1 = "2026-11-19T10:00:00.100000000Z";
+ String t2 = "2026-11-19T10:00:00.200000000Z";
+ String t3 = "2026-11-19T10:00:01.000000000Z";
+
+ read(handle, StreamType.STDOUT, record(t1, "a\n"), record(t2, "b\n"), record(t2, "c\n"));
+ read(handle, StreamType.STDOUT, record(t1, "a\n"), record(t2, "b\n"), record(t2, "c\n"),
+ record(t2, "d\n"), record(t3, "e\n"));
+
+ assertEquals(List.of("STDOUT:a", "STDOUT:b", "STDOUT:c", "STDOUT:d", "STDOUT:e"), lines);
+ }
+
+ // Catches: docker-java handing a Docker frame on in reads of up to 1024 bytes, one of which ends inside
+ // a record's timestamp, so that neither piece parses as a record and the line is dropped or forwarded
+ // with Docker's timestamp in front of it; or one that ends right after the stamp, so that a line whose
+ // text starts with an instant, as MySQL's error log does, is taken for an older record and dropped.
+ @Test
+ void aRecordCutAnywhereByTheTransportIsForwardedOnceWithoutItsTimestamp() {
+ assertForwardedOnceWhereverCut("2026-11-19T10:00:00.100000000Z", "2026-11-19T10:00:00.200000000Z",
+ "2026-11-19T10:00:01.000000000Z", "2026-11-19T10:00:01.500000000Z");
+ }
+
+ // Catches: the stamp Podman wrote before 5.8 (Go's time.RFC3339: whole seconds, in the daemon's offset)
+ // not being read as one, so that no line of a service container under that Podman is forwarded.
+ @Test
+ void aWholeSecondStampAsPodmanWroteBefore58IsReadWhereverTheRecordIsCut() {
+ assertForwardedOnceWhereverCut("2026-11-19T04:00:00-06:00", "2026-11-19T04:00:00-06:00",
+ "2026-11-19T04:00:01-06:00", "2026-11-19T04:00:02-06:00");
+ }
+
+ /** Four records, the last one's text opening with MySQL's instant, cut by the transport at every byte. */
+ private void assertForwardedOnceWhereverCut(String t1, String t2, String t3, String t4) {
+ byte[] stream = String.join("", t1 + " first\n", t2 + " second line\n", t3 + " third\n",
+ t4 + " 2026-11-19T10:00:00.099999Z 0 [System] ready\n").getBytes(StandardCharsets.UTF_8);
+ List expected = List.of("STDOUT:first", "STDOUT:second line", "STDOUT:third",
+ "STDOUT:2026-11-19T10:00:00.099999Z 0 [System] ready");
+
+ for (int cut = 1; cut < stream.length; cut++) {
+ lines.clear();
+ read(handle(null), StreamType.STDOUT, Arrays.copyOfRange(stream, 0, cut),
+ Arrays.copyOfRange(stream, cut, stream.length));
+ assertEquals(expected, lines, "cut at byte " + cut);
+ }
+
+ lines.clear();
+ PolledLogHandle byteAtATime = handle(null);
+ byteAtATime.beginRead(true);
+ for (byte b : stream) {
+ byteAtATime.accept(StreamType.STDOUT, new byte[] {b});
+ }
+ assertEquals(expected, lines);
+ }
+
+ // Catches: a line over 16 KB, which Docker writes as several records with a newline only on the last,
+ // forwarded with a later record's stamp in its text, or that record dropped when the transport cuts it.
+ @Test
+ void aLineDockerSplitIntoRecordsIsForwardedWholeWhereverItsLaterRecordIsCut() {
+ byte[] first = record("2026-11-19T10:00:00.100000000Z", "partial-");
+ byte[] last = record("2026-11-19T10:00:00.200000000Z", "end\n");
+
+ for (int cut = 1; cut < last.length; cut++) {
+ lines.clear();
+ read(handle(null), StreamType.STDOUT, first, Arrays.copyOfRange(last, 0, cut),
+ Arrays.copyOfRange(last, cut, last.length));
+ assertEquals(List.of("STDOUT:partial-end"), lines, "cut at byte " + cut);
+ }
+ }
+
+ // Catches: digits ending a payload inside a record, held in case they open a stamp, lost when the read
+ // ends there and the rest of the line comes only in a later read.
+ @Test
+ void textHeldAtTheEndOfAReadIsForwardedWithItsLine() {
+ String t1 = "2026-11-19T10:00:00.100000000Z";
+ String t2 = "2026-11-19T10:00:00.200000000Z";
+ LogContainerCmd first = logRead(record(t1, "closing at "), "12:30".getBytes(StandardCharsets.UTF_8));
+ LogContainerCmd second = logRead(record(t1, "closing at 12:30"), record(t2, " done\n"));
+ DockerClient docker = mock(DockerClient.class);
+ when(docker.logContainerCmd("c1")).thenReturn(first, second);
+ PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
+
+ handle.read();
+ handle.read();
+
+ assertEquals(List.of("closing at 12:30 done"), lines);
+ }
+
+ // Catches: a line the container had not finished writing at one read being split in two, or its
+ // first half being forwarded twice.
+ @Test
+ void aLineSplitAcrossReadsIsForwardedWhole() {
+ PolledLogHandle handle = handle(null);
+ String t1 = "2026-11-19T10:00:00.100000000Z";
+ String t2 = "2026-11-19T10:00:00.900000000Z";
+
+ read(handle, StreamType.STDERR, record(t1, "hel"));
+ read(handle, StreamType.STDERR, record(t1, "hel"), record(t2, "lo\n"));
+
+ assertEquals(List.of("STDERR:hello"), lines);
+ }
+
+ // Catches: an attach from now replaying the history of a container that ran before Floci started.
+ @Test
+ void anAttachFromNowSkipsWhatTheContainerWroteBefore() {
+ PolledLogHandle handle = handle(Instant.parse("2026-11-19T10:00:00.500000000Z"));
+
+ read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "old\n"),
+ record("2026-11-19T10:00:00.600000000Z", "new\n"));
+
+ assertEquals(List.of("STDOUT:new"), lines);
+ }
+
+ // Catches: an unterminated last line lost at close, or a read landing after the close duplicating it.
+ @Test
+ void finishFlushesTheUnterminatedTailAndIgnoresLaterReads() {
+ PolledLogHandle handle = handle(null);
+ read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "shutting down"));
+
+ handle.finish();
+ read(handle, StreamType.STDOUT, record("2026-11-19T10:00:02.000000000Z", "late\n"));
+
+ assertEquals(List.of("STDOUT:shutting down"), lines);
+ }
+
+ private static LogContainerCmd logRead(byte[]... records) {
+ LogContainerCmd command = mock(LogContainerCmd.class, Answers.RETURNS_SELF);
+ when(command.exec(any())).thenAnswer(invocation -> {
+ ResultCallback.Adapter callback = invocation.getArgument(0);
+ for (byte[] record : records) {
+ callback.onNext(new Frame(StreamType.STDOUT, record));
+ }
+ callback.onComplete();
+ return callback;
+ });
+ return command;
+ }
+
+ // Catches: every read after the first decoding the container's whole log again (no tail bound), or a
+ // bounded read that more records than the bound arrived for skipping the ones before its first.
+ @Test
+ void aBoundedReadThatBeginsPastTheCursorIsMadeAgainWithoutTheBound() {
+ String t1 = "2026-11-19T10:00:00.100000000Z";
+ String t2 = "2026-11-19T10:00:00.200000000Z";
+ String t3 = "2026-11-19T10:00:00.300000000Z";
+ LogContainerCmd first = logRead(record(t1, "a\n"));
+ LogContainerCmd bounded = logRead(record(t3, "c\n"));
+ LogContainerCmd unbounded = logRead(record(t1, "a\n"), record(t2, "b\n"), record(t3, "c\n"));
+ DockerClient docker = mock(DockerClient.class);
+ when(docker.logContainerCmd("c1")).thenReturn(first, bounded, unbounded);
+ PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
+
+ handle.read();
+ handle.read();
+
+ assertEquals(List.of("a", "b", "c"), lines);
+ verify(first, never()).withTail(anyInt());
+ verify(bounded).withTail(PolledLogHandle.TAIL_LINES);
+ verify(unbounded, never()).withTail(anyInt());
+ }
+
+ // Catches: a final read that fails at close skipping the flush of the unterminated last line.
+ @Test
+ void closeFlushesTheUnterminatedLineWhenTheLastReadFails() throws Exception {
+ DockerClient docker = mock(DockerClient.class);
+ when(docker.logContainerCmd("c1")).thenThrow(new IllegalStateException("daemon gone"));
+ PolledLogHandle handle = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
+ read(handle, StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "shutting down"));
+
+ handle.close();
+
+ await().atMost(Duration.ofSeconds(5)).until(() -> lines.equals(List.of("shutting down")));
+ }
+
+ // Catches: a polled container's last lines lost, since a removed container's log can no longer be read.
+ @Test
+ void stopAndRemoveReadsAPolledLogBetweenTheStopAndTheRemoval() throws Exception {
+ DockerClient docker = mock(DockerClient.class);
+ StopContainerCmd stop = mock(StopContainerCmd.class, Answers.RETURNS_SELF);
+ when(docker.stopContainerCmd("c1")).thenReturn(stop);
+ RemoveContainerCmd remove = mock(RemoveContainerCmd.class, Answers.RETURNS_SELF);
+ when(docker.removeContainerCmd("c1")).thenReturn(remove);
+ LogContainerCmd logs = mock(LogContainerCmd.class);
+ when(docker.logContainerCmd("c1")).thenReturn(logs);
+ when(logs.withStdOut(anyBoolean())).thenReturn(logs);
+ when(logs.withStdErr(anyBoolean())).thenReturn(logs);
+ when(logs.withFollowStream(anyBoolean())).thenReturn(logs);
+ when(logs.withTimestamps(anyBoolean())).thenReturn(logs);
+ when(logs.withSince(anyInt())).thenReturn(logs);
+ when(logs.exec(any())).thenAnswer(invocation -> {
+ ResultCallback.Adapter callback = invocation.getArgument(0);
+ callback.onNext(new Frame(StreamType.STDOUT, record("2026-11-19T10:00:00.100000000Z", "bye\n")));
+ callback.onComplete();
+ return callback;
+ });
+ PolledLogHandle polled = new PolledLogHandle(docker, "c1", null, (stream, line) -> lines.add(line));
+ ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
+
+ manager.stopAndRemove("c1", polled);
+
+ InOrder order = inOrder(stop, logs, remove);
+ order.verify(stop).exec();
+ order.verify(logs).exec(any());
+ order.verify(remove).exec();
+ assertEquals(List.of("bye"), lines);
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java b/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java
index afb4afce58..e870edb518 100644
--- a/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java
+++ b/src/test/java/io/floci/aws/services/amazonmq/container/RabbitMqManagerTest.java
@@ -187,7 +187,7 @@ class RabbitMqManagerTest {
manager.startContainer(broker);
assertEquals("/aws/amazonmq/broker/b-1/general", broker.generalLogGroup());
- verify(logStreamer).attach(eq("container-id"), eq(broker.generalLogGroup()),
+ verify(logStreamer).attachPolled(eq("container-id"), eq(broker.generalLogGroup()),
any(), any(), eq("amazonmq:b-1"));
}
diff --git a/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java b/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java
index 0971f80de3..9db7b1ea12 100644
--- a/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/docdb/container/DocDbContainerManagerTest.java
@@ -199,7 +199,7 @@ class DocDbContainerManagerTest {
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
- lenient().when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString()))
+ lenient().when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenAnswer(call -> mock(Closeable.class));
EmulatorConfig config = mock(EmulatorConfig.class);
diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java
index 74c45ece5f..78bb2cb5a4 100644
--- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java
+++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java
@@ -385,7 +385,7 @@ class EcrRegistryManagerTest {
.thenReturn(new ContainerLifecycleManager.ContainerInfo("second-container", Map.of()));
Closeable firstLogStream = Mockito.mock(Closeable.class);
Closeable secondLogStream = Mockito.mock(Closeable.class);
- when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString()))
+ when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(firstLogStream, secondLogStream);
assertTrue(manager.tryEnsureStarted());
@@ -495,8 +495,8 @@ class EcrRegistryManagerTest {
manager.ensureStarted();
- verify(logStreamer).attach(eq("container-id"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
- verify(logStreamer, never()).attachFromNow(any(), any(), any(), any(), any());
+ verify(logStreamer).attachPolled(eq("container-id"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
+ verify(logStreamer, never()).attachPolledFromNow(any(), any(), any(), any(), any());
}
@Test
@@ -514,8 +514,8 @@ class EcrRegistryManagerTest {
manager.ensureStarted();
- verify(logStreamer).attachFromNow(eq("0123456789abcdef"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
- verify(logStreamer, never()).attach(any(), any(), any(), any(), any());
+ verify(logStreamer).attachPolledFromNow(eq("0123456789abcdef"), eq("/aws/ecr/registry"), any(), eq("us-east-1"), eq("ecr:registry"));
+ verify(logStreamer, never()).attachPolled(any(), any(), any(), any(), any());
}
@Test
diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java
index c58939556f..6fb97236d7 100644
--- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java
+++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java
@@ -4246,9 +4246,9 @@ class EksClusterManagerTest {
logStreamer = Mockito.mock(ContainerLogStreamer.class);
mockHandle = Mockito.mock(Closeable.class);
- when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
+ when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(mockHandle);
- when(logStreamer.attachFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
+ when(logStreamer.attachPolledFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(mockHandle);
manager = new EksClusterManager(containerBuilder, lifecycleManager,
@@ -4267,7 +4267,7 @@ class EksClusterManagerTest {
manager.setUpGuest(cluster);
- verify(logStreamer).attachForAccount(
+ verify(logStreamer).attachPolledForAccount(
eq("000000000000"),
eq("container-id-123456789012345678901234567890"),
eq("/aws/eks/prod-cluster/cluster"),
@@ -4316,7 +4316,7 @@ class EksClusterManagerTest {
@Test
void attachmentFailureLogsWarningAndContinuesWithoutAborting() {
- when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
+ when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenThrow(new RuntimeException("Docker attach connection failed"));
Cluster cluster = new Cluster();
@@ -4352,7 +4352,7 @@ class EksClusterManagerTest {
manager.startCluster(stale);
manager.setUpGuest(stale);
Closeable freshHandle = Mockito.mock(Closeable.class);
- when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
+ when(logStreamer.attachPolledForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(freshHandle);
Cluster recreated = new Cluster();
recreated.setName("prod-cluster");
@@ -4475,7 +4475,7 @@ class EksClusterManagerTest {
manager.setUpGuest(cluster);
- verify(logStreamer).attachFromNowForAccount(
+ verify(logStreamer).attachPolledFromNowForAccount(
eq("000000000000"),
eq("adopted-container-id-12345678901234567890"),
eq("/aws/eks/prod-cluster/cluster"),
diff --git a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManagerTest.java b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManagerTest.java
index 4507282ecd..acdf7cfcd6 100644
--- a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheContainerManagerTest.java
@@ -94,7 +94,7 @@ class ElastiCacheContainerManagerTest {
"io.floci.resource-id", "my-group",
"io.floci.account", "000000000000",
"io.floci.region", "eu-west-1"));
- verify(logStreamer).attach(eq("container-id"), anyString(), any(), eq("eu-west-1"), anyString());
+ verify(logStreamer).attachPolled(eq("container-id"), anyString(), any(), eq("eu-west-1"), anyString());
}
}
@@ -106,7 +106,7 @@ class ElastiCacheContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 6379))));
when(lifecycleManager.isDockerReachable()).thenReturn(false);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
- when(logStreamer.attach(any(), any(), any(), any(), any()))
+ when(logStreamer.attachPolled(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
diff --git a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java
index 9dc55d476d..357280b191 100644
--- a/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/elasticache/container/ElastiCacheMemcachedContainerManagerTest.java
@@ -90,7 +90,7 @@ class ElastiCacheMemcachedContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 11211))));
when(lifecycleManager.isDockerReachable()).thenReturn(false);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
- when(logStreamer.attach(any(), any(), any(), any(), any()))
+ when(logStreamer.attachPolled(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
diff --git a/src/test/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManagerTest.java b/src/test/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManagerTest.java
index 1c09471b74..7fa290145f 100644
--- a/src/test/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/memorydb/container/MemoryDbContainerManagerTest.java
@@ -262,12 +262,12 @@ class MemoryDbContainerManagerTest {
assertEquals(List.of("floci-aws-memorydb-cache",
"floci-aws-memorydb-111111111111-eu-west-1-same",
"floci-aws-memorydb-111111111111_eu-west-1_same"), names.getAllValues());
- verify(logs).attach("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
+ verify(logs).attachPolled("default-cid", "/aws/memorydb/cluster/cache/engine-log", "engine",
"us-east-1", "memorydb:" + defaultIdentity);
- verify(logs).attach("collision-cid",
+ verify(logs).attachPolled("collision-cid",
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
"us-east-1", "memorydb:" + collisionIdentity);
- verify(logs).attach("foreign-cid",
+ verify(logs).attachPolled("foreign-cid",
"/aws/memorydb/cluster/111111111111-eu-west-1-same/engine-log", "engine",
"eu-west-1", "memorydb:" + foreignIdentity);
responder.get(5, TimeUnit.SECONDS);
diff --git a/src/test/java/io/floci/aws/services/msk/RedpandaManagerTest.java b/src/test/java/io/floci/aws/services/msk/RedpandaManagerTest.java
index 5978b51874..2ffb757063 100644
--- a/src/test/java/io/floci/aws/services/msk/RedpandaManagerTest.java
+++ b/src/test/java/io/floci/aws/services/msk/RedpandaManagerTest.java
@@ -638,7 +638,7 @@ class RedpandaManagerTest {
ArgumentCaptor specCaptor = ArgumentCaptor.forClass(ContainerSpec.class);
manager.startContainer(newCluster());
- verify(logStreamer).attachForAccount(eq("000000000000"), eq("container-789"),
+ verify(logStreamer).attachPolledForAccount(eq("000000000000"), eq("container-789"),
eq("/aws/msk/cluster/test-cluster"), eq("log-stream"), eq("us-east-1"),
eq("msk:test-cluster"));
verify(lifecycleManager).createAndStart(specCaptor.capture());
diff --git a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java
index 4c3628ae8a..93eaf49e34 100644
--- a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java
@@ -638,7 +638,7 @@ class RdsContainerManagerTest {
verify(lifecycleManager).create(spec.capture());
assertEquals(dbPath.toString(), spec.getValue().binds().getFirst().getPath());
assertEquals("floci-aws-rds-db1", spec.getValue().name());
- verify(logStreamer).attachForAccount(
+ verify(logStreamer).attachPolledForAccount(
"222222222222", "container-id", "/aws/rds/instance/db1/error",
"log-stream", "us-west-2", "rds:" + runtimeId);
}
@@ -1185,7 +1185,7 @@ class RdsContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
- when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
+ when(logStreamer.attachPolledForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"))
.thenReturn(null);
RdsContainerManager manager = new RdsContainerManager(
@@ -1221,7 +1221,7 @@ class RdsContainerManagerTest {
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
- when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
+ when(logStreamer.attachPolledForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"));
doThrow(new IllegalStateException("Docker cleanup failed"))
.doNothing()
diff --git a/src/test/java/io/floci/aws/services/redshift/container/RedshiftContainerManagerTest.java b/src/test/java/io/floci/aws/services/redshift/container/RedshiftContainerManagerTest.java
index c42a1eb1a7..85e296cd01 100644
--- a/src/test/java/io/floci/aws/services/redshift/container/RedshiftContainerManagerTest.java
+++ b/src/test/java/io/floci/aws/services/redshift/container/RedshiftContainerManagerTest.java
@@ -124,7 +124,7 @@ class RedshiftContainerManagerTest {
} else {
when(lifecycleManager.adopt(eq("cont-survivor"), any(), any())).thenReturn(
new ContainerInfo("cont-survivor", Map.of(5432, new EndpointInfo("localhost", 5432))));
- when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
+ when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
if ("readiness".equals(failureStage)) {
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
@@ -683,17 +683,17 @@ class RedshiftContainerManagerTest {
ContainerInfo info = new ContainerInfo("cont-stream", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
Closeable stream = mock(Closeable.class);
- when(logStreamer.attach("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
+ when(logStreamer.attachPolled("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
.thenReturn(stream);
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
assertEquals(stream, handle.getLogStream());
- verify(logStreamer).attach("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
+ verify(logStreamer).attachPolled("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
// When logStreamer throws, start still completes successfully
doThrow(new RuntimeException("stream error"))
- .when(logStreamer).attach(anyString(), anyString(), anyString(), anyString(), anyString());
+ .when(logStreamer).attachPolled(anyString(), anyString(), anyString(), anyString(), anyString());
RedshiftContainerHandle handleTolerated = manager.start(ACCOUNT_ID, "test-cluster-2", "admin", "pass");
assertNotNull(handleTolerated);
assertNull(handleTolerated.getLogStream());
@@ -708,17 +708,17 @@ class RedshiftContainerManagerTest {
ContainerInfo adopted = new ContainerInfo("cont-adopt-stream", Map.of(5432, new EndpointInfo("localhost", 6000)));
when(lifecycleManager.adopt(eq("cont-adopt-stream"), any(), eq(Optional.empty()))).thenReturn(adopted);
Closeable stream = mock(Closeable.class);
- when(logStreamer.attach("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
+ when(logStreamer.attachPolled("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
.thenReturn(stream);
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
assertEquals(stream, handle.getLogStream());
- verify(logStreamer).attach("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
+ verify(logStreamer).attachPolled("cont-adopt-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster");
// When logStreamer throws, adoptOrStart still completes successfully
doThrow(new RuntimeException("stream error"))
- .when(logStreamer).attach(anyString(), anyString(), anyString(), anyString(), anyString());
+ .when(logStreamer).attachPolled(anyString(), anyString(), anyString(), anyString(), anyString());
RedshiftContainerHandle handleTolerated = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handleTolerated);
assertNull(handleTolerated.getLogStream());
@@ -787,6 +787,24 @@ class RedshiftContainerManagerTest {
verify(stream).close();
}
+ // Catches: the cluster's last log lines lost, since the forced removal leaves its polled log nothing to read.
+ @Test
+ void stopReadsThePolledLogBeforeTheRemoval() {
+ ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
+ when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
+ when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
+ new ContainerInfo("cont-owned", Map.of(5432, new EndpointInfo("localhost", 5432))));
+ RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "owned", "admin", "pass");
+ Closeable stream = mock(Closeable.class);
+ handle.setLogStream(stream);
+
+ manager.stop(ACCOUNT_ID, "owned");
+
+ InOrder order = inOrder(lifecycleManager);
+ order.verify(lifecycleManager).readLogBeforeRemoval(stream);
+ order.verify(lifecycleManager).removeIfExistsStrict("cont-owned", true);
+ }
+
@Test
void staleRemovalFailurePreventsReplacementCreation() {
doThrow(new IllegalStateException("Docker unavailable")).when(lifecycleManager)
@@ -802,7 +820,7 @@ class RedshiftContainerManagerTest {
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-unready", Map.of(5432, new EndpointInfo("localhost", 5432))));
Closeable stream = mock(Closeable.class);
- when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
+ when(logStreamer.attachPolled(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
try {