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

@@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.InspectVolumeCmd;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.command.WaitContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.NotFoundException;
@@ -18,6 +19,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
@@ -46,6 +49,49 @@ class ContainerLifecycleManagerVolumeTest {
manager = new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, portAllocator);
}
@Test
void stopAndRemoveStopsContainerBeforeClosingItsLogStream() {
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
List<String> operations = new ArrayList<>();
doAnswer(invocation -> {
operations.add("stop");
return null;
}).when(stop).exec();
doAnswer(invocation -> {
operations.add("remove");
return null;
}).when(remove).exec();
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
manager.stopAndRemove("container-id", () -> operations.add("logs"));
assertEquals(List.of("stop", "remove", "logs"), operations);
}
@Test
void stopAndRemoveForceRemovesAndFinalizesLogStreamWhenContainerStopFails() {
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
List<String> operations = new ArrayList<>();
doThrow(new RuntimeException("Docker daemon unavailable")).when(stop).exec();
doAnswer(invocation -> {
operations.add("remove");
return null;
}).when(remove).exec();
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
manager.stopAndRemove("container-id", () -> operations.add("logs"));
assertEquals(List.of("remove", "logs"), operations);
}
@Test
void volumeExists_returnsTrue_whenVolumeExists() {
InspectVolumeCmd cmd = mock(InspectVolumeCmd.class);
@@ -218,4 +264,3 @@ class ContainerLifecycleManagerVolumeTest {
verify(dockerClient, times(2)).createContainerCmd("busybox:stable");
}
}
@@ -0,0 +1,328 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ContainerLogStreamerTest {
private static byte[] utf8(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
@Test
void reassemblesSingleLineSplitAcrossFrames() {
// A ~1.5 KB stdout line that Docker delivers as multiple frames must arrive
// as ONE CloudWatch event, not several (regression for the >1024-byte split).
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
String longLine = "x".repeat(1500);
assertEquals(List.of(), buffer.append(utf8(longLine.substring(0, 1024))));
assertEquals(List.of(), buffer.append(utf8(longLine.substring(1024))));
List<String> lines = buffer.append(utf8("\n"));
assertEquals(1, lines.size());
assertEquals(1500, lines.get(0).length());
assertEquals(longLine, lines.get(0));
}
@Test
void splitsMultipleLinesPackedIntoOneFrame() {
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
assertEquals(List.of("first", "second", "third"), buffer.append(utf8("first\nsecond\nthird\n")));
}
@Test
void flushReturnsTrailingUnterminatedContent() {
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
assertEquals(List.of("complete"), buffer.append(utf8("complete\npartial")));
assertEquals("partial", buffer.flush().orElseThrow());
assertTrue(buffer.flush().isEmpty(), "buffer should be cleared after flush");
}
@Test
void doesNotCorruptMultibyteCharacterSplitAcrossFrames() {
// "€" is E2 82 AC in UTF-8; decoding per-frame would corrupt it, decoding the
// reassembled line does not.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
byte[] euro = utf8("€");
assertEquals(List.of(), buffer.append(new byte[]{euro[0], euro[1]}));
assertEquals(List.of("€"), buffer.append(new byte[]{euro[2], '\n'}));
}
@Test
void preservesEmptyLinesInSplitOutput() {
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
// append() splits faithfully; the emit layer is what skips blanks.
assertEquals(List.of("a", "", "b"), buffer.append(utf8("a\n\nb\n")));
}
@Test
void boundsBufferBySplittingOverlongUnterminatedRuns() {
// A 256 KB run with no newline must be force-emitted (bounded), not buffered until the
// heap is exhausted — regression guard for the unbounded-growth review finding.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
byte[] overlong = new byte[256 * 1024];
java.util.Arrays.fill(overlong, (byte) 'a');
List<String> lines = buffer.append(overlong);
assertEquals(1, lines.size());
assertEquals(256 * 1024, lines.get(0).length());
assertTrue(buffer.flush().isEmpty(), "buffer is drained after the forced split");
}
@Test
void forcedSplitKeepsEventWithinCapAndDefersStraddlingMultibyteChar() {
// Regression for the oversized-event finding: with the buffer one byte below the cap, a 3-byte
// '€' would inflate the event to cap+2. The split must instead emit the buffered run WITHIN the
// cap and defer the whole '€' to the next event — never cutting the character.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
int cap = 256 * 1024;
byte[] fill = new byte[cap - 1];
java.util.Arrays.fill(fill, (byte) 'a');
assertEquals(List.of(), buffer.append(fill));
List<String> lines = buffer.append(utf8("€"));
assertEquals(1, lines.size());
String event = lines.get(0);
assertTrue(event.getBytes(StandardCharsets.UTF_8).length <= cap, "event must not exceed the cap");
assertFalse(event.contains("�"), "no half-decoded character in the emitted event");
assertTrue(event.chars().allMatch(c -> c == 'a'), "the straddling '€' was deferred, not included");
// '€' is buffered whole and emitted intact on the next newline.
assertEquals("€", buffer.append(utf8("\n")).get(0));
}
@Test
void keepsCharacterIntactWhenItsFinalBytesArriveAtTheCapInAnotherFrame() {
// A four-byte character that exactly fills the remaining capacity must not be decoded after its
// first frame. The terminal continuation bytes complete the same capped event intact.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
int cap = 256 * 1024;
byte[] fill = new byte[cap - 4];
java.util.Arrays.fill(fill, (byte) 'a');
byte[] rocket = utf8("🚀");
assertEquals(List.of(), buffer.append(fill));
assertEquals(List.of(), buffer.append(new byte[]{rocket[0], rocket[1]}));
List<String> lines = buffer.append(new byte[]{rocket[2], rocket[3]});
assertEquals(1, lines.size());
assertTrue(lines.get(0).endsWith("🚀"));
assertFalse(lines.get(0).contains("�"));
}
@Test
void boundsBufferOnRepeatedLeadingBytesThatNeverCompleteACharacter() {
// Invalid UTF-8 that never reaches a character boundary (a run of lead bytes) must still be
// force-split at the hard ceiling, not buffered without bound.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
byte[] leads = new byte[256 * 1024 + 64];
java.util.Arrays.fill(leads, (byte) 0xE2); // 1110xxxx lead byte, never followed by continuations
List<String> lines = buffer.append(leads);
assertFalse(lines.isEmpty(), "a boundary-less lead-byte run must be force-split, not buffered unbounded");
}
@Test
void boundsBufferOnStrayContinuationBytes() {
// A run of stray continuation bytes (invalid UTF-8, no lead byte) must be force-split at the
// cap rather than growing unbounded.
ContainerLogStreamer.LogLineBuffer buffer = new ContainerLogStreamer.LogLineBuffer();
byte[] continuations = new byte[256 * 1024 + 64];
java.util.Arrays.fill(continuations, (byte) 0x80); // 10xxxxxx continuation
List<String> lines = buffer.append(continuations);
assertFalse(lines.isEmpty(), "a continuation-only run must be force-split, not buffered unbounded");
}
@Test
void keepsLateUnterminatedFragmentsTogetherUntilTerminal() throws Exception {
// A cancelled transport can still deliver an in-flight continuation. It must not flush the first
// fragment then let that continuation become a second event. The terminal callback, not elapsed
// time, is the boundary that flushes the complete logical line.
List<String> emitted = new ArrayList<>();
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDOUT, utf8("partial")));
cb.close();
cb.onNext(new Frame(StreamType.STDOUT, utf8("-late")));
assertEquals(List.of(), emitted, "the partial line stays intact until the reader terminates");
cb.onComplete();
assertEquals(List.of("partial-late"), emitted);
}
@Test
void lifecycleHandleCloseRetainsDelayedFramesUntilTerminal() throws Exception {
// Container shutdown has completed, but the Docker reader can still deliver bytes it already read.
// Closing the lifecycle handle must keep the reader attached through its drain period so a delayed
// continuation reaches the terminal flush rather than being truncated immediately.
List<String> emitted = Collections.synchronizedList(new ArrayList<>());
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
Closeable handle = new ContainerLogStreamer.ContainerLogHandle(cb);
cb.onNext(new Frame(StreamType.STDOUT, utf8("before")));
handle.close();
cb.onNext(new Frame(StreamType.STDOUT, utf8("-after")));
cb.onComplete();
assertEquals(List.of("before-after"), emitted);
}
@Test
void emitsCompletedLinesBeforeTheFinalTailDuringConcurrentLifecycleClose() throws Exception {
// The reader begins emitting a complete line, then a lifecycle-confirmed container stop drains a
// trailing partial line. The final tail must queue behind the already-complete line, even though
// the consumer for that line is still running on a different thread.
List<String> emitted = Collections.synchronizedList(new ArrayList<>());
CountDownLatch firstEmissionStarted = new CountDownLatch(1);
CountDownLatch releaseFirstEmission = new CountDownLatch(1);
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(line -> {
if ("complete".equals(line)) {
firstEmissionStarted.countDown();
try {
releaseFirstEmission.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
emitted.add(line);
});
Thread reader = new Thread(() -> cb.onNext(new Frame(StreamType.STDOUT, utf8("complete\npartial"))));
reader.start();
assertTrue(firstEmissionStarted.await(1, TimeUnit.SECONDS), "the first line should begin emitting");
Thread closer = new Thread(() -> {
cb.closeAfterContainerStopped();
});
closer.start();
Thread terminal = new Thread(cb::onComplete);
terminal.start();
closer.join();
releaseFirstEmission.countDown();
reader.join();
terminal.join();
assertEquals(List.of("complete", "partial"), emitted);
}
@Test
void framesDeliveredAfterTransportCloseAreStillEmitted() throws Exception {
// Cancelling the transport must not permanently stop buffering. A frame the reader delivers after
// cancellation is still emitted; the eventual terminal drains the rest.
List<String> emitted = new ArrayList<>();
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDOUT, utf8("before-grace")));
cb.close();
cb.onNext(new Frame(StreamType.STDOUT, utf8("-after-close")));
cb.onComplete(); // the reader's real terminal drains the reassembled tail
assertEquals(List.of("before-grace-after-close"), emitted);
}
@Test
void onNextAfterTerminalIsIgnored() throws Exception {
// A straggler frame arriving after the reader's TERMINAL (the true end of the stream) must not be
// appended into a buffer that will never be flushed — the terminated flag, checked under the
// lock, drops it deterministically.
List<String> emitted = new ArrayList<>();
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDOUT, utf8("kept\n")));
cb.onComplete(); // true terminal: drains and marks terminated
cb.onNext(new Frame(StreamType.STDOUT, utf8("straggler-after-terminal")));
assertEquals(List.of("kept"), emitted);
}
@Test
void reassemblesInFlightFramesDeliveredDuringClose() throws Exception {
// Fragments of ONE newline-free write are delivered by the transport reader AFTER close() is
// called; the terminal callback then flushes their reassembled line. A separate thread supplies
// the reader callbacks, mirroring the transport.
List<String> emitted = java.util.Collections.synchronizedList(new ArrayList<>());
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDOUT, utf8("frag1")));
Thread reader = new Thread(() -> {
cb.onNext(new Frame(StreamType.STDOUT, utf8("frag2")));
cb.onNext(new Frame(StreamType.STDOUT, utf8("frag3\n")));
cb.onComplete(); // terminal: drains and unblocks close()
});
reader.start();
cb.close();
reader.join();
assertEquals(List.of("frag1frag2frag3"), emitted);
}
@Test
void flushesTrailingContentOnComplete() throws Exception {
// A clean end (onComplete) flushes any trailing unterminated line.
List<String> emitted = new ArrayList<>();
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDOUT, utf8("no-newline-tail")));
cb.onComplete();
assertEquals(List.of("no-newline-tail"), emitted);
}
@Test
void flushesStreamTailsInTheirLastFrameArrivalOrder() {
List<String> emitted = new ArrayList<>();
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add);
cb.onNext(new Frame(StreamType.STDERR, utf8("stderr-tail")));
cb.onNext(new Frame(StreamType.STDOUT, utf8("stdout-tail")));
cb.onComplete();
assertEquals(List.of("stderr-tail", "stdout-tail"), emitted);
}
@Test
void lifecycleHandleFlushesTailWhenDockerNeverSignalsTerminal() throws Exception {
List<String> emitted = Collections.synchronizedList(new ArrayList<>());
ContainerLogStreamer.LogReassemblyCallback cb =
new ContainerLogStreamer.LogReassemblyCallback(emitted::add, 10);
Closeable handle = new ContainerLogStreamer.ContainerLogHandle(cb);
cb.onNext(new Frame(StreamType.STDOUT, utf8("unterminated-tail")));
handle.close();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
while (emitted.isEmpty() && System.nanoTime() < deadline) {
Thread.sleep(5);
}
assertEquals(List.of("unterminated-tail"), emitted);
}
}
@@ -0,0 +1,51 @@
package io.github.hectorvent.floci.services.codebuild;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.codebuild.model.Build;
import io.github.hectorvent.floci.services.codebuild.model.Project;
import io.github.hectorvent.floci.services.codebuild.model.ProjectArtifacts;
import io.github.hectorvent.floci.services.codebuild.model.ProjectEnvironment;
import io.github.hectorvent.floci.services.codebuild.model.ProjectSource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class CodeBuildServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
@Test
void retryBuildRetainsOriginalBuildspecOverride() {
CodeBuildRunner runner = mock(CodeBuildRunner.class);
CodeBuildService service = new CodeBuildService(runner, mock(EmulatorConfig.class), null);
ProjectSource source = new ProjectSource();
source.setType("NO_SOURCE");
ProjectArtifacts artifacts = new ProjectArtifacts();
artifacts.setType("NO_ARTIFACTS");
service.createProject(REGION, ACCOUNT, "retry-project", null, source, null, null,
artifacts, null, new ProjectEnvironment(), "arn:aws:iam::000000000000:role/codebuild",
null, null, null, null, null, null, null);
String buildspec = "version: 0.2\nphases:\n build:\n commands:\n - echo retry\n";
Build original = service.startBuild(REGION, ACCOUNT, "retry-project", buildspec,
null, null, null, null, null, null);
Build retried = service.retryBuild(REGION, ACCOUNT, original.getId());
assertNotEquals(original.getId(), retried.getId());
ArgumentCaptor<String> buildspecOverrides = ArgumentCaptor.forClass(String.class);
verify(runner, times(2)).startBuild(eq(REGION), any(Build.class), any(Project.class),
buildspecOverrides.capture());
assertEquals(List.of(buildspec, buildspec), buildspecOverrides.getAllValues());
}
}
@@ -12,9 +12,11 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -72,6 +74,50 @@ class EcsServiceTeardownTest {
verify(containerManager, times(1)).stopTask(handle);
}
@Test
void stoppedTaskRetriesTeardownUntilItsRemainingLogStreamIsReleased() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(false); // docker mode
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsContainerManager containerManager = mock(EcsContainerManager.class);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"),
Map.of("docker-id", mock(Closeable.class)));
when(containerManager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
AtomicInteger teardownAttempts = new AtomicInteger();
when(containerManager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> {
if (teardownAttempts.incrementAndGet() == 2) {
handle.removeLogStream("docker-id");
}
return Map.of();
});
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"),
containerManager,
config,
mock(EcsLoadBalancerRegistrar.class),
new SingleUseStorageFactory());
service.initializeStorage();
ContainerDefinition cd = new ContainerDefinition();
cd.setName("app");
cd.setImage("nginx:alpine");
service.registerTaskDefinition("retry-fam", List.of(cd), null, null, null,
null, null, List.of(), REGION);
String taskArn = service.runTask(null, "retry-fam", 1, LaunchType.FARGATE, null, null,
List.of(), null, REGION).getFirst().getTaskArn();
service.stopTask(null, taskArn, null, REGION);
verify(containerManager, times(1)).stopTaskAndCollectExitCodes(handle);
service.reconcile();
verify(containerManager, times(2)).stopTaskAndCollectExitCodes(handle);
service.reconcile();
verify(containerManager, times(2)).stopTaskAndCollectExitCodes(handle);
}
private static final class SingleUseStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doThrow;
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 EcsContainerManagerLifecycleTest {
@Test
void finalizesTaskLogStreamsAfterForceRemovingAContainerWhoseStopFails() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
Closeable logStream = mock(Closeable.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("docker-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
doThrow(new RuntimeException("Docker daemon unavailable")).when(stop).exec();
EcsContainerManager manager = manager(lifecycleManager);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"),
Map.of("docker-id", logStream));
manager.stopTaskAndCollectExitCodes(handle);
verify(remove).exec();
verify(lifecycleManager).closeLogStreamAfterContainerStop(logStream);
}
@Test
void finalizesTaskLogStreamsAfterEveryContainerStops() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd stop = mock(StopContainerCmd.class);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class);
Closeable logStream = mock(Closeable.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("docker-id")).thenReturn(stop);
when(stop.withTimeout(5)).thenReturn(stop);
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
when(remove.withForce(true)).thenReturn(remove);
EcsContainerManager manager = manager(lifecycleManager);
EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"),
Map.of("docker-id", logStream));
manager.stopTaskAndCollectExitCodes(handle);
verify(lifecycleManager).closeLogStreamAfterContainerStop(logStream);
}
@Test
void preservesOnlyTheLogStreamForAContainerThatCouldNotStopOrBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class);
StopContainerCmd failedStop = mock(StopContainerCmd.class);
StopContainerCmd successfulStop = mock(StopContainerCmd.class);
RemoveContainerCmd failedRemove = mock(RemoveContainerCmd.class);
RemoveContainerCmd successfulRemove = mock(RemoveContainerCmd.class);
Closeable retainedLogStream = mock(Closeable.class);
Closeable finalizedLogStream = mock(Closeable.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.stopContainerCmd("running-id")).thenReturn(failedStop);
when(failedStop.withTimeout(5)).thenReturn(failedStop);
doThrow(new RuntimeException("stop failed")).when(failedStop).exec();
when(dockerClient.stopContainerCmd("stopped-id")).thenReturn(successfulStop);
when(successfulStop.withTimeout(5)).thenReturn(successfulStop);
when(dockerClient.removeContainerCmd("running-id")).thenReturn(failedRemove);
when(failedRemove.withForce(true)).thenReturn(failedRemove);
doThrow(new RuntimeException("remove failed")).when(failedRemove).exec();
when(dockerClient.removeContainerCmd("stopped-id")).thenReturn(successfulRemove);
when(successfulRemove.withForce(true)).thenReturn(successfulRemove);
Map<String, String> containerIds = new LinkedHashMap<>();
containerIds.put("running", "running-id");
containerIds.put("stopped", "stopped-id");
EcsTaskHandle handle = new EcsTaskHandle("task-arn", containerIds,
Map.of("running-id", retainedLogStream, "stopped-id", finalizedLogStream));
manager(lifecycleManager).stopTaskAndCollectExitCodes(handle);
verify(lifecycleManager, never()).closeLogStreamAfterContainerStop(retainedLogStream);
verify(lifecycleManager).closeLogStreamAfterContainerStop(finalizedLogStream);
assertTrue(handle.hasOpenLogStreams());
assertSame(retainedLogStream, handle.getLogStreamsByContainerId().get("running-id"));
assertFalse(handle.getLogStreamsByContainerId().containsKey("stopped-id"));
}
private static EcsContainerManager manager(ContainerLifecycleManager lifecycleManager) {
return new EcsContainerManager(
mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), mock(EmulatorConfig.class), mock(RegionResolver.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class), mock(SecretsManagerService.class));
}
}