fix(lambda): reassemble container log lines split across Docker frames (#1953)

* fix(lambda): reassemble Docker log frames into complete lines

Buffer stdout and stderr independently, emit complete UTF-8 lines, and finalize trailing tails only after Docker has stopped or its reader reaches a terminal state.

* fix(codebuild): retain buildspec overrides when retrying builds

Keep request-scoped buildspec overrides alongside transient build state so RetryBuild executes the same source-less build definition as the original request.

* fix(ecs): finalize logs after force-removing tasks

Keep Docker force removal available after stop failures and release task log handles once removal has terminated their transports.

* fix(ecs): retain logs for containers that survive teardown

Track ECS log handles by Docker ID so teardown finalizes only containers that have stopped, disappeared, or been force-removed.

* fix(ecs): retry unresolved log stream teardown
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-08-11 06:50:07 -04:00
1 parent 40e8aad55a
commit 6344852540
12 files changed
+1046 -48

No files matched your search

@@ -164,34 +164,46 @@ public class ContainerLifecycleManager {
public void stopAndRemove(String containerId, Closeable logStream) {
LOG.infov("Stopping container {0}", containerId);
// Close log stream first
if (logStream != null) {
try {
logStream.close();
} catch (Exception e) {
LOG.debugv("Error closing log stream: {0}", e.getMessage());
}
}
// Stop container
boolean stoppedOrMissing = false;
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
stoppedOrMissing = true;
} catch (NotFoundException e) {
LOG.debugv("Container {0} not found (already removed)", containerId);
return;
stoppedOrMissing = true;
} catch (Exception e) {
LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage());
}
// Remove container
// 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.
boolean removedOrMissing = false;
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
removedOrMissing = true;
LOG.debugv("Removed container {0}", containerId);
} catch (NotFoundException e) {
// Already gone
removedOrMissing = true;
} catch (Exception e) {
LOG.warnv("Error removing container {0}: {1}", containerId, e.getMessage());
}
if (logStream != null && (stoppedOrMissing || removedOrMissing)) {
closeLogStreamAfterContainerStop(logStream);
}
}
/**
* Releases lifecycle ownership of a log stream after its container has stopped. Docker's terminal
* callback normally flushes the final tail; a bounded fallback handles a broken transport.
*/
public void closeLogStreamAfterContainerStop(Closeable logStream) {
try {
logStream.close();
} catch (Exception e) {
LOG.debugv("Error closing log stream: {0}", e.getMessage());
}
}
/**
@@ -5,17 +5,32 @@ import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
/**
* Streams Docker container logs to both the Floci console logger and CloudWatch Logs.
@@ -38,26 +53,39 @@ public class ContainerLogStreamer {
/**
* Attaches a log stream to a container and forwards logs to CloudWatch Logs.
* Returns a Closeable handle that should be closed when the container is stopped.
* Returns a lifecycle handle that should be closed after the container stops. Closing the handle
* allows Docker's reader a bounded drain period before a non-blocking fallback flushes the tail.
*
* @param containerId Docker container ID
* @param logGroup CloudWatch log group name (e.g., "/aws/lambda/myFunction")
* @param logStream CloudWatch log stream name (e.g., "2024/01/15/[$LATEST]abc123")
* @param region AWS region for CloudWatch Logs
* @param logPrefix prefix for console logging (e.g., "lambda:myFunction")
* @return Closeable handle to stop the log stream
* @return Closeable lifecycle handle for the log stream
*/
public Closeable attach(String containerId, String logGroup, String logStream,
String region, String logPrefix) {
ensureLogGroupAndStream(logGroup, logStream, region);
// Trim trailing whitespace and drop blank lines, then fan each reassembled line out to the
// console logger and CloudWatch Logs.
Consumer<String> emitter = line -> {
String trimmed = line.stripTrailing();
if (!trimmed.isEmpty()) {
LOG.infov("[{0}] {1}", logPrefix, trimmed);
forwardToCloudWatchLogs(logGroup, logStream, region, trimmed);
}
};
try {
return dockerClient.logContainerCmd(containerId)
LogReassemblyCallback callback = new LogReassemblyCallback(emitter);
dockerClient.logContainerCmd(containerId)
.withStdOut(true)
.withStdErr(true)
.withFollowStream(true)
.withTimestamps(false)
.exec(frameCallback(logGroup, logStream, region, logPrefix));
.exec(callback);
return new ContainerLogHandle(callback);
} catch (Exception e) {
LOG.warnv("Could not attach log stream for container {0}: {1}", containerId, e.getMessage());
return null;
@@ -149,4 +177,312 @@ public class ContainerLogStreamer {
LOG.debugv("Could not forward log line to CloudWatch Logs: {0}", e.getMessage());
}
}
/**
* Docker frame callback that reassembles multiplexed stdout/stderr frames into newline-delimited
* lines and forwards each to {@code lineConsumer}. One logical line can span several frames and one
* frame can carry several lines, so bytes are buffered per stream and emitted one line at a time
* (matching real AWS Lambda).
*/
static final class LogReassemblyCallback extends ResultCallback.Adapter<Frame> {
private static final ScheduledExecutorService CLOSE_DRAIN_SCHEDULER =
Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "floci-container-log-close");
thread.setDaemon(true);
return thread;
});
private static final long DEFAULT_CLOSE_GRACE_MILLIS = 2_000;
private final Map<StreamType, LogLineBuffer> buffers = new EnumMap<>(StreamType.class);
private final Map<StreamType, Long> tailSequences = new EnumMap<>(StreamType.class);
private final Deque<String> pendingLines = new ArrayDeque<>();
private final Object emissionLock = new Object();
// A fair write lock makes fallback finalization wait for callbacks already in progress, then blocks
// any later callback until the transport has been closed and the final tail has been flushed.
private final ReentrantReadWriteLock callbackGate = new ReentrantReadWriteLock(true);
private final Consumer<String> lineConsumer;
private final long closeGraceMillis;
// Guarded by 'buffers'. Set only by the Docker transport terminal callback; afterwards onNext
// refuses to append, so nothing is ever buffered past the final flush.
private boolean terminated;
// Guarded by 'buffers'. The most recent callback with an unfinished tail gets the largest value.
private long nextTailSequence;
// Guarded by 'buffers'. Cancels when Docker supplies its terminal callback before the fallback.
private ScheduledFuture<?> fallbackFinalization;
// Guarded by 'emissionLock'. Exactly one caller drains pendingLines at a time, preserving Docker
// callback order even when a terminal callback and onNext run on different threads.
private boolean emitting;
LogReassemblyCallback(Consumer<String> lineConsumer) {
this(lineConsumer, DEFAULT_CLOSE_GRACE_MILLIS);
}
LogReassemblyCallback(Consumer<String> lineConsumer, long closeGraceMillis) {
this.lineConsumer = lineConsumer;
this.closeGraceMillis = closeGraceMillis;
}
@Override
public void onNext(Frame frame) {
callbackGate.readLock().lock();
try {
boolean emit;
synchronized (emissionLock) {
synchronized (buffers) {
if (terminated) {
return; // the final drain has run; never append into a buffer that won't be flushed
}
LogLineBuffer buffer = buffers.computeIfAbsent(frame.getStreamType(), t -> new LogLineBuffer());
pendingLines.addAll(buffer.append(frame.getPayload()));
if (buffer.hasPendingBytes()) {
tailSequences.put(frame.getStreamType(), nextTailSequence++);
} else {
tailSequences.remove(frame.getStreamType());
}
}
emit = startEmissionIfNeeded();
}
if (emit) {
emitPendingLines();
}
} finally {
callbackGate.readLock().unlock();
}
}
@Override
public void onComplete() {
callbackGate.readLock().lock();
try {
flush();
super.onComplete();
} finally {
callbackGate.readLock().unlock();
}
}
@Override
public void onError(Throwable throwable) {
callbackGate.readLock().lock();
try {
flush();
super.onError(throwable);
} finally {
callbackGate.readLock().unlock();
}
}
// Called only once ContainerLifecycleManager has stopped (or confirmed the absence of) the Docker
// container. Give its follow-log reader a bounded chance to deliver any queued frames and terminal
// callback without blocking lifecycle teardown. If no terminal arrives, close that reader before
// flushing so frames cannot continue after the fallback finalization boundary.
void closeAfterContainerStopped() {
synchronized (emissionLock) {
synchronized (buffers) {
if (terminated || fallbackFinalization != null) {
return;
}
fallbackFinalization = CLOSE_DRAIN_SCHEDULER.schedule(
this::closeTransportAndFlush, closeGraceMillis, TimeUnit.MILLISECONDS);
}
}
}
// Flush trailing content never terminated by a newline once Docker has signalled the definitive
// end of its transport input.
private void flush() {
boolean emit;
synchronized (emissionLock) {
synchronized (buffers) {
if (terminated) {
return;
}
terminated = true;
cancelFallbackFinalization();
buffers.entrySet().stream()
.sorted(Comparator.comparingLong(entry -> tailSequences.getOrDefault(
entry.getKey(), Long.MAX_VALUE)))
.forEach(entry -> entry.getValue().flush().ifPresent(pendingLines::addLast));
tailSequences.clear();
}
emit = startEmissionIfNeeded();
}
if (emit) {
emitPendingLines();
}
}
private void closeTransportAndFlush() {
callbackGate.writeLock().lock();
try {
try {
super.close();
} catch (IOException e) {
LOG.debugv("Could not close container log transport: {0}", e.getMessage());
} finally {
flush();
}
} finally {
callbackGate.writeLock().unlock();
}
}
private void cancelFallbackFinalization() {
if (fallbackFinalization != null) {
fallbackFinalization.cancel(false);
fallbackFinalization = null;
}
}
private boolean startEmissionIfNeeded() {
if (emitting) {
return false;
}
synchronized (buffers) {
if (pendingLines.isEmpty()) {
return false;
}
}
emitting = true;
return true;
}
private void emitPendingLines() {
while (true) {
String line;
synchronized (emissionLock) {
synchronized (buffers) {
line = pendingLines.pollFirst();
if (line == null) {
emitting = false;
return;
}
}
}
lineConsumer.accept(line);
}
}
}
/**
* The lifecycle-facing log handle. Closing it is valid only after the owning container has stopped;
* it gives Docker a bounded chance to deliver its terminal callback before a non-blocking fallback
* closes the reader and finalizes any tail.
*/
static final class ContainerLogHandle implements Closeable {
private final LogReassemblyCallback callback;
ContainerLogHandle(LogReassemblyCallback callback) {
this.callback = callback;
}
@Override
public void close() throws IOException {
callback.closeAfterContainerStopped();
}
}
/**
* Reassembles newline-delimited log lines from Docker multiplexed frame payloads.
* A single logical line can be split across several frames (Docker chunks large
* writes) and a single frame can carry several lines, so buffering bytes and
* emitting exactly one line per {@code '\n'} avoids both splitting long lines and
* merging short ones. Bytes are buffered and each complete line decoded as UTF-8,
* so a multibyte character straddling a frame boundary is not corrupted.
*/
static final class LogLineBuffer {
/**
* Cap on a single reconstructed line, matching CloudWatch Logs' maximum event size
* (256 KB). A longer run with no newline is force-split at the cap, so a container
* emitting unbounded output without a newline cannot grow the buffer until the heap
* is exhausted. A valid UTF-8 event is split at the limit without cutting a character.
*/
private static final int MAX_LINE_BYTES = 256 * 1024;
private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
/** Continuation bytes still needed to complete the character at the buffer's tail; 0 means the
* buffer currently ends on a UTF-8 character boundary. */
private int pendingContinuation;
/** Appends a frame payload and returns the complete lines it produced (possibly none). */
List<String> append(byte[] payload) {
List<String> lines = new ArrayList<>();
for (byte b : payload) {
if (b == '\n') {
lines.add(takeLine());
continue;
}
// Force-split BEFORE a character that would push the buffer past the cap, so the emitted
// event never exceeds MAX_LINE_BYTES and a multibyte character straddling the limit starts
// the next event whole instead of inflating this one. Only at a character boundary, and
// only for a real character start (not a continuation byte).
if (pendingContinuation == 0 && (b & 0xC0) != 0x80
&& buffer.size() > 0
&& buffer.size() + utf8CharLength(b) > MAX_LINE_BYTES) {
lines.add(takeLine());
}
buffer.write(b);
trackUtf8(b);
if ((buffer.size() >= MAX_LINE_BYTES && pendingContinuation == 0)
|| buffer.size() >= MAX_LINE_BYTES + 3) {
// Do not split a valid character whose continuation bytes arrive in a later frame.
// Malformed input may never reach a boundary, so allow at most the three continuation
// bytes a valid UTF-8 character could need before forcing the buffer to drain.
lines.add(takeLine());
}
}
return lines;
}
/** Byte length of the UTF-8 character starting with {@code b} (1 for ASCII or an invalid lead byte). */
private static int utf8CharLength(byte b) {
int v = b & 0xFF;
if ((v & 0x80) == 0x00) return 1; // 0xxxxxxx — ASCII
if ((v & 0xE0) == 0xC0) return 2; // 110xxxxx
if ((v & 0xF0) == 0xE0) return 3; // 1110xxxx
if ((v & 0xF8) == 0xF0) return 4; // 11110xxx
return 1; // invalid lead byte
}
/** Returns any buffered content not yet terminated by a newline, clearing the buffer. */
Optional<String> flush() {
return buffer.size() == 0 ? Optional.empty() : Optional.of(takeLine());
}
boolean hasPendingBytes() {
return buffer.size() > 0;
}
/** Updates how many UTF-8 continuation bytes are still expected after appending byte {@code b}. */
private void trackUtf8(byte b) {
int v = b & 0xFF;
if ((v & 0x80) == 0x00) { // 0xxxxxxx — ASCII, self-contained
pendingContinuation = 0;
} else if ((v & 0xC0) == 0x80) { // 10xxxxxx — continuation byte
if (pendingContinuation > 0) {
pendingContinuation--;
}
// a stray continuation (no preceding lead) leaves the tail on a boundary
} else if ((v & 0xE0) == 0xC0) { // 110xxxxx — 2-byte lead
pendingContinuation = 1;
} else if ((v & 0xF0) == 0xE0) { // 1110xxxx — 3-byte lead
pendingContinuation = 2;
} else if ((v & 0xF8) == 0xF0) { // 11110xxx — 4-byte lead
pendingContinuation = 3;
} else { // 0xF8-0xFF — invalid lead byte
pendingContinuation = 0;
}
}
private String takeLine() {
String line = buffer.toString(StandardCharsets.UTF_8);
buffer.reset();
pendingContinuation = 0;
return line;
}
}
}
@@ -369,11 +369,10 @@ public class CodeBuildRunner implements ContainerTeardown {
}
} finally {
stopFlags.remove(buildId);
if (logHandle != null) {
try { logHandle.close(); } catch (Exception ignored) {}
}
if (containerId != null && runningContainers.remove(buildId, containerId)) {
lifecycleManager.stopAndRemove(containerId, null);
lifecycleManager.stopAndRemove(containerId, logHandle);
} else if (logHandle != null) {
try { logHandle.close(); } catch (Exception ignored) {}
}
if (workspace != null) {
deleteDirectory(workspace);
@@ -39,6 +39,8 @@ public class CodeBuildService {
private Map<String, Map<String, SourceCredential>> sourceCredentials = new ConcurrentHashMap<>();
// key: region -> buildId -> build (transient: builds are runtime state)
private final ConcurrentHashMap<String, ConcurrentHashMap<String, Build>> builds = new ConcurrentHashMap<>();
// key: region -> buildId -> request buildspec override (transient: builds are runtime state)
private final ConcurrentHashMap<String, ConcurrentHashMap<String, String>> buildspecOverrides = new ConcurrentHashMap<>();
// key: region:projectName -> build counter (transient)
private final ConcurrentHashMap<String, AtomicLong> buildCounters = new ConcurrentHashMap<>();
@@ -108,6 +110,10 @@ public class CodeBuildService {
return builds.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
private Map<String, String> buildspecOverridesFor(String region) {
return buildspecOverrides.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
}
// ---- Projects ----
public Project createProject(String region, String account,
@@ -448,6 +454,9 @@ public class CodeBuildService {
build.setPhases(new CopyOnWriteArrayList<>());
buildsFor(region).put(buildId, build);
if (buildspecOverride != null && !buildspecOverride.isBlank()) {
buildspecOverridesFor(region).put(buildId, buildspecOverride);
}
Build responseBuild = copyBuild(build);
runner.startBuild(region, build, project, buildspecOverride);
@@ -500,8 +509,9 @@ public class CodeBuildService {
public Build retryBuild(String region, String account, String buildId) {
Build original = getBuild(region, buildId);
String buildspecOverride = buildspecOverridesFor(region).get(original.getId());
return startBuild(region, account, original.getProjectName(),
null, original.getEnvironment(), original.getArtifacts(),
buildspecOverride, original.getEnvironment(), original.getArtifacts(),
null, original.getTimeoutInMinutes(), null, null);
}
@@ -74,7 +74,7 @@ public class EcsService implements ContainerTeardown {
private Map<String, Integer> latestRevisions = new ConcurrentHashMap<>();
// taskArn → EcsTask
private final Map<String, EcsTask> tasks = new ConcurrentHashMap<>();
// taskArn → EcsTaskHandle (running containers)
// taskArn → EcsTaskHandle (running containers or unresolved log readers)
private final Map<String, EcsTaskHandle> taskHandles = new ConcurrentHashMap<>();
// region::clusterName/serviceName → EcsServiceModel
private Map<String, EcsServiceModel> services = new ConcurrentHashMap<>();
@@ -554,7 +554,11 @@ public class EcsService implements ContainerTeardown {
Map<String, Integer> exitCodes = Map.of();
if (dockerMode) {
EcsTaskHandle handle = taskHandles.remove(task.getTaskArn());
exitCodes = containerManager.stopTaskAndCollectExitCodes(handle);
try {
exitCodes = containerManager.stopTaskAndCollectExitCodes(handle);
} finally {
retainUnresolvedLogHandle(task.getTaskArn(), handle);
}
}
task.setLastStatus(TaskStatus.STOPPED.name());
@@ -1411,7 +1415,16 @@ public class EcsService implements ContainerTeardown {
private void reconcileTask(String taskArn) {
EcsTask task = tasks.get(taskArn);
if (task == null || !TaskStatus.RUNNING.name().equals(task.getLastStatus())) {
if (task == null) {
return;
}
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
reconcileStoppedTask(taskArn);
return;
}
if (!TaskStatus.RUNNING.name().equals(task.getLastStatus())) {
return;
}
@@ -1463,6 +1476,27 @@ public class EcsService implements ContainerTeardown {
LOG.infov("ECS task {0} reconciled to STOPPED (all containers exited)", taskArn);
}
private void reconcileStoppedTask(String taskArn) {
EcsTaskHandle claimed = taskHandles.remove(taskArn);
if (claimed == null) {
return;
}
try {
containerManager.stopTaskAndCollectExitCodes(claimed);
} finally {
// A task can be reported STOPPED even if Docker rejected both teardown attempts.
// Keep only the affected log readers and retry their teardown on later reconciliation ticks.
retainUnresolvedLogHandle(taskArn, claimed);
}
}
private void retainUnresolvedLogHandle(String taskArn, EcsTaskHandle handle) {
if (handle != null && handle.hasOpenLogStreams()) {
taskHandles.put(taskArn, handle);
}
}
void reconcileServices() {
for (Map.Entry<String, EcsServiceModel> entry : services.entrySet()) {
try {
@@ -35,10 +35,12 @@ import org.jboss.logging.Logger;
import java.io.Closeable;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Manages Docker container lifecycle for ECS tasks.
@@ -89,7 +91,7 @@ public class EcsContainerManager {
String taskId = extractTaskId(task.getTaskArn());
Map<String, String> containerIds = new LinkedHashMap<>();
List<Closeable> logStreams = new ArrayList<>();
Map<String, Closeable> logStreamsByContainerId = new LinkedHashMap<>();
List<Container> runtimeContainers = new ArrayList<>();
// Task-level volumes consumed by per-container mountPoints: host volumes map their
@@ -249,7 +251,7 @@ public class EcsContainerManager {
dockerId, logGroup, logStream, region,
"ecs:" + taskDef.getFamily() + ":" + def.getName());
if (logHandle != null) {
logStreams.add(logHandle);
logStreamsByContainerId.put(dockerId, logHandle);
}
}
@@ -258,7 +260,7 @@ public class EcsContainerManager {
task.setDesiredStatus(TaskStatus.RUNNING.name());
task.setStartedAt(Instant.now());
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreams);
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId);
}
/**
@@ -276,15 +278,11 @@ public class EcsContainerManager {
if (handle == null) {
return;
}
for (Closeable logStream : handle.getLogStreams()) {
try {
logStream.close();
} catch (Exception ignored) {
}
}
for (String dockerId : handle.getContainerIds().values()) {
lifecycleManager.stopAndRemove(dockerId, null);
}
new ArrayList<>(handle.getLogStreamsByContainerId().keySet())
.forEach(dockerId -> finalizeLogStream(handle, dockerId));
}
/**
@@ -298,18 +296,14 @@ public class EcsContainerManager {
return exitCodes;
}
for (Closeable logStream : handle.getLogStreams()) {
try {
logStream.close();
} catch (Exception ignored) {
}
}
// Phase 1: stop all containers (no-op for those already exited).
Set<String> terminatedContainerIds = new HashSet<>();
for (String dockerId : handle.getContainerIds().values()) {
try {
lifecycleManager.getDockerClient().stopContainerCmd(dockerId).withTimeout(5).exec();
terminatedContainerIds.add(dockerId);
} catch (NotFoundException ignored) {
terminatedContainerIds.add(dockerId);
} catch (Exception e) {
LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage());
}
@@ -322,14 +316,26 @@ public class EcsContainerManager {
exitCodes.put(name, getExitCodeIfStopped(dockerId));
try {
lifecycleManager.getDockerClient().removeContainerCmd(dockerId).withForce(true).exec();
terminatedContainerIds.add(dockerId);
} catch (NotFoundException ignored) {
terminatedContainerIds.add(dockerId);
} catch (Exception e) {
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
}
}
// A force removal terminates Docker's follow-log transport even when the preceding stop failed.
// Preserve handles for any container that still may be running after both operations failed.
terminatedContainerIds.forEach(dockerId -> finalizeLogStream(handle, dockerId));
return exitCodes;
}
private void finalizeLogStream(EcsTaskHandle handle, String dockerId) {
Closeable logStream = handle.removeLogStream(dockerId);
if (logStream != null) {
lifecycleManager.closeLogStreamAfterContainerStop(logStream);
}
}
/**
* Returns the exit code of a container that has already stopped, or {@code null}
* if the container is still running or its state cannot be determined.
@@ -1,26 +1,36 @@
package io.github.hectorvent.floci.services.ecs.container;
import java.io.Closeable;
import java.util.List;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Holds the runtime Docker container IDs for a running ECS task.
* Maps container name → Docker container ID and log stream handle.
* Maps container names to Docker IDs and Docker IDs to their log stream handles.
*/
public class EcsTaskHandle {
private final String taskArn;
private final Map<String, String> containerIds; // containerName → dockerId
private final List<Closeable> logStreams;
private final Map<String, Closeable> logStreamsByContainerId;
public EcsTaskHandle(String taskArn, Map<String, String> containerIds, List<Closeable> logStreams) {
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId) {
this.taskArn = taskArn;
this.containerIds = containerIds;
this.logStreams = logStreams;
this.containerIds = new LinkedHashMap<>(containerIds);
this.logStreamsByContainerId = new LinkedHashMap<>(logStreamsByContainerId);
}
public String getTaskArn() { return taskArn; }
public Map<String, String> getContainerIds() { return containerIds; }
public List<Closeable> getLogStreams() { return logStreams; }
public Map<String, Closeable> getLogStreamsByContainerId() { return logStreamsByContainerId; }
/** Removes and returns the log stream that no longer needs task-level ownership. */
public Closeable removeLogStream(String containerId) {
return logStreamsByContainerId.remove(containerId);
}
public boolean hasOpenLogStreams() {
return !logStreamsByContainerId.isEmpty();
}
}