refactor(docker): share one helper for running a command in a container (#4505)

Ten container managers each carried their own copy of the docker exec
round trip: create the exec, attach a frame callback, wait for it, then
read the exit code. The copies disagreed on what a timeout returns, on
whether an attach-stream error throws, and on how output frames are
decoded.

ContainerExec now owns that round trip. MWAA, Flink, Timestream,
Redshift, RDS, EKS, both EC2 managers and the ECS credentials proxy call
it, and the four identical ExecResult records and three
ContainerExecResult variants give way to ContainerExec.Result. The seven
Docker integration tests that hand-rolled the same exec (EKS IMDS, IRSA,
pod identity, Route 53 and VPC route programming, EC2 volumes, RDS
Postgres) use it as well.

A timeout now returns exit code -1 with the output captured so far and a
"Timed out after Ns" note in stderr. MWAA, Flink and EKS still throw on a
timeout, through Result.throwIfTimedOut. Output is decoded once from the
collected bytes, so a multi-byte character split across frames survives,
and an interrupt keeps the thread's interrupt flag. The two EC2 managers
keep reporting a Docker error as a failed result, so an attach error on
one sshd path still falls through to the next. An interrupt is the
exception in Ec2ContainerManager: it still ends the setup step it hits,
as it did before, instead of being retried on the next sshd path.

The ECS credentials proxy's reachability probe waited on its exec with no
timeout at all. It now gives up after 10 seconds and treats that like any
other failed probe, retrying until its verify budget runs out.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-28 17:24:38 -05:00
1 parent 93ec5967fe
commit 585bad28c2
27 files changed
+718 -725

No files matched your search

@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InspectExecCmd;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Stubs a mocked {@link DockerClient} so every {@link ContainerExec} run in one container completes
* at once with a fixed output and exit code, for tests of the managers that call it.
*/
public final class ContainerExecStubs {
private ContainerExecStubs() {
}
/** Returns the commands run in {@code containerId}, in order, as the stubbed execs see them. */
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId, long exitCode,
String stdout, String stderr) {
String execId = "exec-" + containerId;
List<List<String>> commands = new ArrayList<>();
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF);
when(createCmd.withCmd(any(String[].class))).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
String[] cmd = args.length == 1 && args[0] instanceof String[] array
? array
: Arrays.copyOf(args, args.length, String[].class);
commands.add(List.of(cmd));
return createCmd;
});
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn(execId);
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd(containerId)).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
ResultCallback.Adapter<Frame> callback = invocation.getArgument(0);
callback.onNext(new Frame(StreamType.STDOUT, stdout.getBytes(StandardCharsets.UTF_8)));
callback.onNext(new Frame(StreamType.STDERR, stderr.getBytes(StandardCharsets.UTF_8)));
callback.onComplete();
return callback;
});
when(dockerClient.execStartCmd(execId)).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(exitCode);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(execId)).thenReturn(inspectCmd);
return commands;
}
}
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InspectExecCmd;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Pins the contract every container manager now shares: how frames are routed, what a timeout and
* a missing exit code turn into, and that an attach-stream error or an interrupt is not mistaken
* for a finished command. None of it needs a daemon, so the docker-java calls are mocked.
*/
class ContainerExecTest {
private static final String CONTAINER_ID = "container-1";
private static final String EXEC_ID = "exec-1";
private static final String[] CMD = {"sh", "-c", "true"};
private DockerClient dockerClient;
private ExecStartCmd execStartCmd;
private InspectExecResponse inspectResponse;
@BeforeEach
void setUp() {
dockerClient = mock(DockerClient.class);
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn(EXEC_ID);
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd(CONTAINER_ID)).thenReturn(createCmd);
execStartCmd = mock(ExecStartCmd.class);
when(dockerClient.execStartCmd(EXEC_ID)).thenReturn(execStartCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(EXEC_ID)).thenReturn(inspectCmd);
}
@Test
void runKeepsStdoutAndStderrApart() {
completeWith(List.of(frame(StreamType.STDOUT, "out-1 "), frame(StreamType.STDERR, "err"),
frame(StreamType.STDOUT, "out-2")));
when(inspectResponse.getExitCodeLong()).thenReturn(3L);
ContainerExec.Result result = ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5);
assertEquals(3L, result.exitCode());
assertEquals("out-1 out-2", result.stdout());
assertEquals("err", result.stderr());
assertFalse(result.timedOut());
}
@Test
void runMergedInterleavesBothStreamsInArrivalOrder() {
completeWith(List.of(frame(StreamType.STDOUT, "a\n"), frame(StreamType.STDERR, "b\n"),
frame(StreamType.STDOUT, "c\n")));
ContainerExec.Result result = ContainerExec.runMerged(dockerClient, CONTAINER_ID, CMD, 5);
assertEquals("a\nb\nc\n", result.stdout());
assertEquals("", result.stderr());
assertEquals("a\nb\nc", result.summary());
}
@Test
void aMultiByteCharacterSplitAcrossFramesSurvives() {
byte[] euro = "€".getBytes(StandardCharsets.UTF_8);
completeWith(List.of(new Frame(StreamType.STDOUT, new byte[]{euro[0]}),
new Frame(StreamType.STDOUT, new byte[]{euro[1], euro[2]})));
assertEquals("€", ContainerExec.runMerged(dockerClient, CONTAINER_ID, CMD, 5).stdout());
}
@Test
void aMissingExitCodeIsReportedAsMinusOne() {
completeWith(List.of());
when(inspectResponse.getExitCodeLong()).thenReturn(null);
assertEquals(-1L, ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5).exitCode());
}
@Test
void aCommandThatOutlivesItsTimeoutIsReportedWithWhatItPrintedSoFar() {
startWith(callback -> {
callback.onNext(frame(StreamType.STDOUT, "partial"));
callback.onNext(frame(StreamType.STDERR, "warning"));
});
ContainerExec.Result result = ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 0);
assertTrue(result.timedOut());
assertEquals(-1L, result.exitCode());
assertEquals("partial", result.stdout());
assertEquals("warning\nTimed out after 0s", result.stderr());
verify(dockerClient, never()).inspectExecCmd(EXEC_ID);
}
@Test
void aTimedOutMergedRunSummarisesAsTheTimeout() {
startWith(callback -> {
});
ContainerExec.Result result = ContainerExec.runMerged(dockerClient, CONTAINER_ID, CMD, 0);
assertTrue(result.timedOut());
assertEquals("Timed out after 0s", result.summary());
}
@Test
void throwIfTimedOutNamesTheContainer() {
startWith(callback -> {
});
ContainerExec.Result result = ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 0);
RuntimeException error = assertThrows(RuntimeException.class, () -> result.throwIfTimedOut(CONTAINER_ID));
assertEquals("exec timed out in container " + CONTAINER_ID, error.getMessage());
}
@Test
void throwIfTimedOutPassesAFinishedResultThrough() {
completeWith(List.of());
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
ContainerExec.Result result = ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5);
assertSame(result, result.throwIfTimedOut(CONTAINER_ID));
}
@Test
void anEmptyRunSummarisesAsNoOutput() {
completeWith(List.of());
assertEquals("(no output)", ContainerExec.runMerged(dockerClient, CONTAINER_ID, CMD, 5).summary());
}
@Test
void anAttachStreamErrorPropagatesInsteadOfReadingAnExitCode() {
startWith(callback -> callback.onError(new IllegalStateException("attach stream broke")));
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5));
assertEquals("attach stream broke", error.getMessage());
verify(dockerClient, never()).inspectExecCmd(EXEC_ID);
}
@Test
void anInterruptIsRaisedAndTheInterruptFlagKept() {
startWith(callback -> {
});
Thread.currentThread().interrupt();
try {
assertThrows(IllegalStateException.class, () -> ContainerExec.run(dockerClient, CONTAINER_ID, CMD, 5));
assertTrue(Thread.currentThread().isInterrupted());
} finally {
Thread.interrupted();
}
}
private void completeWith(List<Frame> frames) {
startWith(callback -> {
frames.forEach(callback::onNext);
callback.onComplete();
});
}
private void startWith(Consumer<ResultCallback.Adapter<Frame>> behaviour) {
when(execStartCmd.exec(any())).thenAnswer(invocation -> {
ResultCallback.Adapter<Frame> callback = invocation.getArgument(0);
behaviour.accept(callback);
return callback;
});
}
private static Frame frame(StreamType type, String payload) {
return new Frame(type, payload.getBytes(StandardCharsets.UTF_8));
}
}
@@ -76,6 +76,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Answers.RETURNS_SELF;
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.atLeastOnce;
@@ -1331,6 +1332,68 @@ class Ec2ContainerManagerTest {
+ "\"Missing privilege separation directory\"");
}
@Test
void anAttachStreamErrorOnOneSshdPathStillTriesTheNext() throws Exception {
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.21");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
doAnswer(invocation -> {
ExecStartCmd execStart = mock(ExecStartCmd.class);
when(execStart.exec(any())).thenAnswer(startInvocation -> {
ResultCallback<Frame> callback = startInvocation.getArgument(0);
String[] command = harness.executedCommands.get(harness.executedCommands.size() - 1);
if (Arrays.equals(command, new String[]{"/usr/sbin/sshd"})) {
callback.onError(new IllegalStateException("attach stream broke"));
} else {
callback.onComplete();
}
return callback;
});
return execStart;
}).when(harness.dockerClient).execStartCmd(anyString());
harness.manager.launch(instance("i-sshd-retry"), "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> commandIndex(harness.executedCommands, "/usr/local/sbin/sshd") >= 0, Duration.ofSeconds(2));
assertTrue(commandIndex(harness.executedCommands, "/usr/sbin/sshd")
< commandIndex(harness.executedCommands, "/usr/local/sbin/sshd"));
}
@Test
void anInterruptWhileStartingSshdStopsTryingFurtherSshdPaths() throws Exception {
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.22");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
doAnswer(invocation -> {
ExecStartCmd execStart = mock(ExecStartCmd.class);
when(execStart.exec(any())).thenAnswer(startInvocation -> {
ResultCallback<Frame> callback = startInvocation.getArgument(0);
String[] command = harness.executedCommands.get(harness.executedCommands.size() - 1);
if (Arrays.equals(command, new String[]{"/usr/sbin/sshd"})) {
Thread.currentThread().interrupt();
} else {
callback.onComplete();
}
return callback;
});
return execStart;
}).when(harness.dockerClient).execStartCmd(anyString());
Instance instance = instance("i-sshd-interrupted");
instance.setUserData("#!/bin/sh\necho ready\n");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
// UserData is the next step after sshd, so its exec marks sshd startup as finished.
awaitUntil(() -> commandIndex(harness.executedCommands, "/var/lib/user-data.sh") >= 0, Duration.ofSeconds(2));
assertEquals(-1, commandIndex(harness.executedCommands, "/usr/local/sbin/sshd"));
}
@Test
void launchWithoutKeyPairStillStartsSshd() throws Exception {
// Regression for #2184: sshd previously only started when a key pair was supplied, so
@@ -1,12 +1,10 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
@@ -25,13 +23,12 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -177,22 +174,22 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
String targetContainerId = instance.getDockerContainerId();
// 1. Device node exists in container
ExecResult checkDev = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, checkDev.exitCode(), "Device /dev/xvdf should exist as block or symlink: " + checkDev.output());
ContainerExec.Result checkDev = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, checkDev.exitCode(), "Device /dev/xvdf should exist as block or symlink: " + checkDev.summary());
// 2. Size matches 1 GiB (1073741824 bytes)
ExecResult checkSize = execIn(targetContainerId, "blockdev --getsize64 /dev/xvdf");
assertEquals(0, checkSize.exitCode(), "blockdev query should succeed: " + checkSize.output());
assertEquals("1073741824", checkSize.output().trim());
ContainerExec.Result checkSize = execIn(targetContainerId, "blockdev --getsize64 /dev/xvdf");
assertEquals(0, checkSize.exitCode(), "blockdev query should succeed: " + checkSize.summary());
assertEquals("1073741824", checkSize.stdout().trim());
// 3. Format filesystem, mount, write data, unmount
ExecResult mkfs = execIn(targetContainerId, "mkfs.ext4 -F /dev/xvdf");
assertEquals(0, mkfs.exitCode(), "mkfs.ext4 should succeed: " + mkfs.output());
ContainerExec.Result mkfs = execIn(targetContainerId, "mkfs.ext4 -F /dev/xvdf");
assertEquals(0, mkfs.exitCode(), "mkfs.ext4 should succeed: " + mkfs.summary());
ExecResult mountAndWrite = execIn(targetContainerId,
ContainerExec.Result mountAndWrite = execIn(targetContainerId,
"mkdir -p /mnt/vol && mount /dev/xvdf /mnt/vol && echo 'floci-ebs-test-data' > /mnt/vol/test.txt && cat /mnt/vol/test.txt && umount /mnt/vol");
assertEquals(0, mountAndWrite.exitCode(), "Mount, write, read and umount should succeed: " + mountAndWrite.output());
assertTrue(mountAndWrite.output().contains("floci-ebs-test-data"));
assertEquals(0, mountAndWrite.exitCode(), "Mount, write, read and umount should succeed: " + mountAndWrite.summary());
assertTrue(mountAndWrite.stdout().contains("floci-ebs-test-data"));
}
@Test
@@ -206,7 +203,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance.getInstanceId(), "/dev/xvdf");
String targetContainerId = instance.getDockerContainerId();
ExecResult existsBefore = execIn(targetContainerId, "test -e /dev/xvdf");
ContainerExec.Result existsBefore = execIn(targetContainerId, "test -e /dev/xvdf");
assertEquals(0, existsBefore.exitCode());
// Detach volume
@@ -214,7 +211,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
assertEquals("detached", detached.getState());
// Device node should be removed from container
ExecResult existsAfter = execIn(targetContainerId, "test ! -e /dev/xvdf");
ContainerExec.Result existsAfter = execIn(targetContainerId, "test ! -e /dev/xvdf");
assertEquals(0, existsAfter.exitCode(), "Device /dev/xvdf should no longer exist in container");
// Delete volume
@@ -223,7 +220,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
// Verify helper container removed backing file
String helperName = ContainerStorageHelper.resourceName(config, "ec2", null, "volume-helper");
ExecResult checkFile = execIn(helperName, "test ! -f /volumes/" + volume.getVolumeId() + ".raw");
ContainerExec.Result checkFile = execIn(helperName, "test ! -f /volumes/" + volume.getVolumeId() + ".raw");
assertEquals(0, checkFile.exitCode(), "Backing file should be removed on volume deletion");
}
@@ -246,9 +243,9 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
assertEquals("VolumeInUse", ex.getErrorCode());
// Format and write data on instance1
ExecResult formatAndWrite = execIn(instance1.getDockerContainerId(),
ContainerExec.Result formatAndWrite = execIn(instance1.getDockerContainerId(),
"mkfs.ext4 -F /dev/xvdf && mkdir -p /mnt/vol1 && mount /dev/xvdf /mnt/vol1 && echo 'persisted-payload' > /mnt/vol1/hello.txt && umount /mnt/vol1");
assertEquals(0, formatAndWrite.exitCode(), formatAndWrite.output());
assertEquals(0, formatAndWrite.exitCode(), formatAndWrite.summary());
// Detach from instance1
ec2Service.detachVolume("us-east-1", volume.getVolumeId(), instance1.getInstanceId(), "/dev/xvdf", false);
@@ -257,10 +254,10 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instance2.getInstanceId(), "/dev/xvdg");
// Verify device exists on instance2 and data is preserved
ExecResult verifyData = execIn(instance2.getDockerContainerId(),
ContainerExec.Result verifyData = execIn(instance2.getDockerContainerId(),
"mkdir -p /mnt/vol2 && mount /dev/xvdg /mnt/vol2 && cat /mnt/vol2/hello.txt && umount /mnt/vol2");
assertEquals(0, verifyData.exitCode(), "Data should be preserved across detach and re-attach: " + verifyData.output());
assertTrue(verifyData.output().contains("persisted-payload"));
assertEquals(0, verifyData.exitCode(), "Data should be preserved across detach and re-attach: " + verifyData.summary());
assertTrue(verifyData.stdout().contains("persisted-payload"));
}
@Test
@@ -276,7 +273,7 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
// Simulate device node loss (e.g. container reboot or tmpfs recreation)
execIn(targetContainerId, "rm -f /dev/xvdf");
ExecResult deleted = execIn(targetContainerId, "test ! -e /dev/xvdf");
ContainerExec.Result deleted = execIn(targetContainerId, "test ! -e /dev/xvdf");
assertEquals(0, deleted.exitCode());
// Call restoreInstanceVolumeDevices
@@ -284,8 +281,8 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
volId -> Optional.of(volume));
// Verify device node is restored
ExecResult restored = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, restored.exitCode(), "Device /dev/xvdf should be restored: " + restored.output());
ContainerExec.Result restored = execIn(targetContainerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, restored.exitCode(), "Device /dev/xvdf should be restored: " + restored.summary());
}
@Test
@@ -333,8 +330,8 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
VolumeAttachment attachment = ec2Service.attachVolume("us-east-1", volume.getVolumeId(), instanceId, "/dev/xvdf");
assertNotNull(attachment);
ExecResult checkDev = execIn(containerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, checkDev.exitCode(), "Block device should exist inside cluster node container: " + checkDev.output());
ContainerExec.Result checkDev = execIn(containerId, "test -b /dev/xvdf || test -L /dev/xvdf");
assertEquals(0, checkDev.exitCode(), "Block device should exist inside cluster node container: " + checkDev.summary());
ec2Service.setClusterNodeInstanceProvider(null);
}
@@ -396,35 +393,11 @@ class Ec2VolumeBlockDeviceDockerIntegrationTest {
assertTrue(ex.getMessage().contains("already in use by volume"));
}
private ExecResult execIn(String containerIdOrName, String command) {
private ContainerExec.Result execIn(String containerIdOrName, String command) {
try {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerIdOrName)
.withCmd("sh", "-c", command)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder sb = new StringBuilder();
boolean done = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
sb.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}
})
.awaitCompletion(30, TimeUnit.SECONDS);
if (!done) {
return new ExecResult(-1, "Timed out: " + sb);
}
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
return new ExecResult(exitCode != null ? exitCode : -1, sb.toString());
} catch (Exception e) {
return new ExecResult(-1, e.getMessage());
return ContainerExec.runMerged(dockerClient, containerIdOrName, new String[]{"sh", "-c", command}, 30);
} catch (RuntimeException e) {
return new ContainerExec.Result(-1, "", Objects.requireNonNullElse(e.getMessage(), e.toString()), false);
}
}
private record ExecResult(long exitCode, String output) {}
}
@@ -0,0 +1,63 @@
package io.github.hectorvent.floci.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Covers how the volume manager drives its helper container without a Docker daemon: the command
* it runs there, and that a Docker failure while running it is reported rather than thrown.
*/
class Ec2VolumeBlockDeviceManagerTest {
private static final String HELPER_ID = "helper-container-id";
private DockerClient dockerClient;
private Ec2VolumeBlockDeviceManager manager;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ec2().volumeBlockDevices()).thenReturn(true);
when(config.services().ec2().mock()).thenReturn(false);
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
InspectContainerResponse helper = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
when(helper.getState().getRunning()).thenReturn(true);
when(helper.getId()).thenReturn(HELPER_ID);
when(dockerClient.inspectContainerCmd(anyString()).exec()).thenReturn(helper);
manager = new Ec2VolumeBlockDeviceManager(dockerClient, mock(ContainerBuilder.class),
mock(ContainerLifecycleManager.class), config);
}
@Test
void createVolumeSizesTheBackingFileInsideTheHelperContainer() {
List<List<String>> commands = ContainerExecStubs.completeEveryExec(dockerClient, HELPER_ID, 0, "", "");
manager.createVolume("vol-1", 0);
assertEquals(List.of(List.of("sh", "-c", "truncate -s 8G /volumes/vol-1.raw")), commands);
}
@Test
void aDockerFailureWhileRunningTheCommandIsNotThrown() {
when(dockerClient.execCreateCmd(HELPER_ID)).thenThrow(new IllegalStateException("daemon went away"));
assertDoesNotThrow(() -> manager.createVolume("vol-1", 8));
}
}
@@ -8,6 +8,7 @@ import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
@@ -218,25 +219,7 @@ class EcsCredentialsProxyTest {
when(inspectResponse.getState()).thenReturn(running);
when(running.getRunning()).thenReturn(true);
com.github.dockerjava.api.command.ExecCreateCmd execCreate =
mock(com.github.dockerjava.api.command.ExecCreateCmd.class, RETURNS_SELF);
com.github.dockerjava.api.command.ExecCreateCmdResponse execResponse =
mock(com.github.dockerjava.api.command.ExecCreateCmdResponse.class);
when(dockerClient.execCreateCmd(containerId)).thenReturn(execCreate);
when(execCreate.exec()).thenReturn(execResponse);
when(execResponse.getId()).thenReturn("exec-" + containerId);
com.github.dockerjava.api.command.ExecStartCmd execStart =
mock(com.github.dockerjava.api.command.ExecStartCmd.class);
when(dockerClient.execStartCmd("exec-" + containerId)).thenReturn(execStart);
when(execStart.exec(any())).thenAnswer(invocation -> {
com.github.dockerjava.api.async.ResultCallback<com.github.dockerjava.api.model.Frame> callback =
invocation.getArgument(0);
callback.onNext(new com.github.dockerjava.api.model.Frame(
com.github.dockerjava.api.model.StreamType.STDOUT,
"404".getBytes()));
callback.onComplete();
return callback;
});
ContainerExecStubs.completeEveryExec(dockerClient, containerId, 0, "404", "");
}
@Test
@@ -1,11 +1,9 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
@@ -21,11 +19,9 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -185,7 +181,7 @@ class EksImdsDockerIntegrationTest {
// and fails because port 80 is redirected to 9999.
execInContainer(containerId, new String[]{"sh", "-c",
"iptables -t nat -D PREROUTING -j FLOCI-LINK-LOCAL"});
ExecResult intercepted = execInContainerWithExitCode(containerId, new String[]{"sh", "-c",
ContainerExec.Result intercepted = execInContainerWithExitCode(containerId, new String[]{"sh", "-c",
"ip netns exec pod-test wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id"});
assertNotEquals(0, intercepted.exitCode(),
"Without FLOCI-LINK-LOCAL chain, pod request should be intercepted by CNI-HOSTPORT-DNAT and fail");
@@ -217,42 +213,12 @@ class EksImdsDockerIntegrationTest {
}
}
record ExecResult(long exitCode, String stdout, String stderr) {}
private ExecResult execInContainerWithExitCode(String containerId, String[] cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
boolean completed = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
String text = new String(frame.getPayload(), StandardCharsets.UTF_8);
if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {
stderr.append(text);
} else {
stdout.append(text);
}
}
}
})
.awaitCompletion(30, TimeUnit.SECONDS);
if (!completed) {
throw new RuntimeException("exec timed out in container " + containerId);
}
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
return new ExecResult(exitCode != null ? exitCode : -1L, stdout.toString(), stderr.toString());
private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) {
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ExecResult result = execInContainerWithExitCode(containerId, cmd);
ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd);
if (result.exitCode() != 0) {
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
}
@@ -1,9 +1,7 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.services.eks.model.Cluster;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
@@ -15,11 +13,9 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -152,7 +148,7 @@ class EksIrsaDockerIntegrationTest {
long saDeadline = System.currentTimeMillis() + 30000;
boolean saReady = false;
while (System.currentTimeMillis() < saDeadline) {
ExecResult saResult = execInContainerWithExitCode(containerId,
ContainerExec.Result saResult = execInContainerWithExitCode(containerId,
new String[]{"kubectl", "get", "serviceaccount", "default"});
if (saResult.exitCode() == 0) {
saReady = true;
@@ -195,7 +191,7 @@ class EksIrsaDockerIntegrationTest {
long podDeadline = System.currentTimeMillis() + 45000;
boolean podRunning = false;
while (System.currentTimeMillis() < podDeadline) {
ExecResult statusResult = execInContainerWithExitCode(containerId,
ContainerExec.Result statusResult = execInContainerWithExitCode(containerId,
new String[]{"kubectl", "get", "pod", "irsa-workload-pod", "-o", "jsonpath={.status.phase}"});
if ("Running".equalsIgnoreCase(statusResult.stdout().trim())) {
podRunning = true;
@@ -207,20 +203,20 @@ class EksIrsaDockerIntegrationTest {
// The pod is Running, so it was scheduled onto the node, which the kubelet
// registered with its provider ID: the node is guaranteed to exist here.
ExecResult nodeResult = execInContainerWithExitCode(containerId,
ContainerExec.Result nodeResult = execInContainerWithExitCode(containerId,
new String[]{"kubectl", "get", "nodes", "-o", "jsonpath={.items[0].spec.providerID}"});
assertEquals(0, nodeResult.exitCode(), "kubectl get nodes failed");
assertEquals(eksClusterManager.deriveClusterNodeProviderId(cluster), nodeResult.stdout().trim(),
"Node providerID must match the derived AWS provider ID");
ExecResult zoneResult = execInContainerWithExitCode(containerId,
ContainerExec.Result zoneResult = execInContainerWithExitCode(containerId,
new String[]{"kubectl", "get", "nodes", "-o",
"jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/zone}"});
assertEquals(0, zoneResult.exitCode(), "kubectl get nodes failed");
assertEquals(eksClusterManager.deriveClusterNodeAvailabilityZone(cluster), zoneResult.stdout().trim(),
"Node topology zone label must match the derived availability zone");
ExecResult regionResult = execInContainerWithExitCode(containerId,
ContainerExec.Result regionResult = execInContainerWithExitCode(containerId,
new String[]{"kubectl", "get", "nodes", "-o",
"jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/region}"});
assertEquals(0, regionResult.exitCode(), "kubectl get nodes failed");
@@ -362,42 +358,12 @@ class EksIrsaDockerIntegrationTest {
}
}
record ExecResult(long exitCode, String stdout, String stderr) {}
private ExecResult execInContainerWithExitCode(String containerId, String[] cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
boolean completed = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
String text = new String(frame.getPayload(), StandardCharsets.UTF_8);
if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {
stderr.append(text);
} else {
stdout.append(text);
}
}
}
})
.awaitCompletion(30, TimeUnit.SECONDS);
if (!completed) {
throw new RuntimeException("exec timed out in container " + containerId);
}
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
return new ExecResult(exitCode != null ? exitCode : -1L, stdout.toString(), stderr.toString());
private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) {
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ExecResult result = execInContainerWithExitCode(containerId, cmd);
ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd);
if (result.exitCode() != 0) {
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
}
@@ -1,11 +1,9 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
@@ -26,12 +24,10 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -189,21 +185,7 @@ class EksPodIdentityDockerIntegrationTest {
}
}
private String execInContainer(String containerId, String cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd("sh", "-c", cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder stdout = new StringBuilder();
dockerClient.execStartCmd(exec.getId()).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
stdout.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}
}).awaitCompletion(30, TimeUnit.SECONDS);
return stdout.toString();
private String execInContainer(String containerId, String cmd) {
return ContainerExec.runMerged(dockerClient, containerId, new String[]{"sh", "-c", cmd}, 30).stdout();
}
}
@@ -1,12 +1,9 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.services.route53.Route53Service;
@@ -23,13 +20,11 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -156,31 +151,11 @@ class EksRoute53DnsDockerIntegrationTest {
}
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd(cmd).withAttachStdout(true).withAttachStderr(true).exec();
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
boolean completed = dockerClient.execStartCmd(exec.getId())
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame != null && frame.getPayload() != null) {
String text = new String(frame.getPayload(), StandardCharsets.UTF_8);
(frame.getStreamType() == StreamType.STDERR ? stderr : stdout).append(text);
}
}
})
.awaitCompletion(30, TimeUnit.SECONDS);
if (!completed) {
throw new RuntimeException("exec timed out in container " + containerId);
private String execInContainer(String containerId, String[] cmd) {
ContainerExec.Result result = ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
if (result.exitCode() != 0) {
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
}
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
if (exitCode == null || exitCode != 0) {
throw new RuntimeException("exec failed with code " + exitCode + ": " + stderr);
}
return stdout.toString();
return result.stdout();
}
}
@@ -1,10 +1,8 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.quarkus.test.junit.QuarkusTest;
@@ -15,12 +13,10 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -119,23 +115,7 @@ class EksVpcRouteProgrammingDockerIntegrationTest {
}
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec();
StringBuilder output = new StringBuilder();
dockerClient.execStartCmd(exec.getId()).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame item) {
if (item != null && item.getPayload() != null) {
output.append(new String(item.getPayload(), StandardCharsets.UTF_8));
}
}
}).awaitCompletion(30, TimeUnit.SECONDS);
return output.toString();
private String execInContainer(String containerId, String[] cmd) {
return ContainerExec.runMerged(dockerClient, containerId, cmd, 30).stdout();
}
}
@@ -8,6 +8,7 @@ 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.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
@@ -17,6 +18,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.services.kinesisanalytics.model.FlinkApplication;
import io.github.hectorvent.floci.services.kinesisanalytics.model.Snapshot;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
@@ -138,6 +140,21 @@ class FlinkContainerManagerTest {
return storage;
}
@Test
void deleteSnapshotFilesRemovesTheSavepointInsideTheJobManager() {
DockerClient dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(dockerClient, "jm-container-id", 0, "", "");
FlinkApplication app = application("my-app");
app.setContainerId("jm-container-id");
Snapshot snapshot = new Snapshot();
snapshot.setFlinkLocation("/savepoints/savepoint-1");
manager.deleteSnapshotFiles(app, snapshot);
assertEquals(List.of(List.of("rm", "-rf", "/savepoints/savepoint-1")), commands);
}
private FlinkApplication application(String name) {
return new FlinkApplication(name,
"arn:aws:kinesisanalytics:us-west-2:000000000000:application/" + name,
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.mwaa;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
@@ -524,4 +526,19 @@ class MwaaEnvironmentManagerTest {
Mockito.verify(lifecycleManager).stopAndRemove("airflow-container-id", null);
Mockito.verify(lifecycleManager).stopAndRemove("db-container-id", null);
}
@Test
void runAirflowCliRunsTheCommandThroughAShellInTheAirflowContainer() throws Exception {
DockerClient dockerClient = Mockito.mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(dockerClient, "airflow-container-id", 2,
"dag1\n", "warning\n");
ContainerExec.Result result = manager.runAirflowCli("airflow-container-id", "dags list");
assertEquals(List.of(List.of("sh", "-c", "airflow dags list")), commands);
assertEquals(2, result.exitCode());
assertEquals("dag1\n", result.stdout());
assertEquals("warning\n", result.stderr());
}
}
@@ -1,6 +1,6 @@
package io.github.hectorvent.floci.services.mwaa.proxy;
import io.github.hectorvent.floci.services.mwaa.MwaaEnvironmentManager;
import io.github.hectorvent.floci.core.common.docker.ContainerExec;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
@@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Confirms {@code POST /aws_mwaa/cli} runs its Docker exec off the Vert.x event loop.
* {@code MwaaEnvironmentManager#execInContainer} can block for up to 30 seconds
* ({@code awaitCompletion(30, TimeUnit.SECONDS)}), so running it synchronously on the event
* (its exec timeout), so running it synchronously on the event
* loop that also serves the rest of this environment's proxied Airflow traffic would stall
* every other request for the duration of one CLI call.
*
@@ -62,7 +62,7 @@ class MwaaWebProxyCliOffloadTest {
if (!releaseCli.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("test did not release the CLI exec in time");
}
return new MwaaEnvironmentManager.ExecResult(0, "dag1\ndag2\n", "");
return new ContainerExec.Result(0, "dag1\ndag2\n", "", false);
};
MwaaWebProxy proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", backend.actualPort(),
@@ -138,7 +138,7 @@ class MwaaWebProxyCliOffloadTest {
if (!releaseCli.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("test did not release the CLI exec in time");
}
return new MwaaEnvironmentManager.ExecResult(0, "", "");
return new ContainerExec.Result(0, "", "", false);
};
MwaaWebProxy proxy = new MwaaWebProxy("env1", vertx, "127.0.0.1", 1,
(environmentName, token) -> true, slowExecutor);
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
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.ContainerExec;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import org.junit.jupiter.api.AfterAll;
@@ -22,18 +23,11 @@ import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -157,7 +151,7 @@ class RdsContainerManagerPostgresTest {
String[] cmd = {"psql", "-h", "127.0.0.1", "-U", user, "-d", dbName, "-c", "SELECT 1"};
for (int i = 0; i < maxSeconds; i++) {
try {
ExecResult result = exec(containerId, cmd, 5);
ContainerExec.Result result = exec(containerId, cmd, 5);
if (result.exitCode() == 0) {
return;
}
@@ -176,7 +170,7 @@ class RdsContainerManagerPostgresTest {
private void execPsql(String containerId, String user, String db, String sql) throws Exception {
String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db, "-c", sql};
ExecResult result = exec(containerId, cmd, 30);
ContainerExec.Result result = exec(containerId, cmd, 30);
if (result.exitCode() != 0) {
throw new RuntimeException("psql exec failed (exit " + result.exitCode() + "): "
+ result.stderr() + " | " + result.stdout());
@@ -185,7 +179,7 @@ class RdsContainerManagerPostgresTest {
private String queryPsql(String containerId, String user, String db, String sql) throws Exception {
String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db, "-tAc", sql};
ExecResult result = exec(containerId, cmd, 30);
ContainerExec.Result result = exec(containerId, cmd, 30);
if (result.exitCode() != 0) {
throw new RuntimeException("psql query failed (exit " + result.exitCode() + "): "
+ result.stderr() + " | " + result.stdout());
@@ -193,60 +187,8 @@ class RdsContainerManagerPostgresTest {
return result.stdout();
}
private ExecResult exec(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
String execId = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec()
.getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
Closeable callback = dockerClient.execStartCmd(execId)
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame.getPayload() != null) {
try {
if (frame.getStreamType() == StreamType.STDOUT) {
stdout.write(frame.getPayload());
} else if (frame.getStreamType() == StreamType.STDERR) {
stderr.write(frame.getPayload());
}
} catch (IOException ignored) {
// best effort
}
}
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
});
try {
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
if (!completed) {
return new ExecResult(-1, stdout.toString(StandardCharsets.UTF_8),
"Timed out after " + timeoutSeconds + "s");
}
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
return new ExecResult(
exitCode != null ? exitCode : -1,
stdout.toString(StandardCharsets.UTF_8),
stderr.toString(StandardCharsets.UTF_8));
} finally {
callback.close();
}
private ContainerExec.Result exec(String containerId, String[] cmd, int timeoutSeconds) {
return ContainerExec.run(dockerClient, containerId, cmd, timeoutSeconds);
}
private RdsContainerManager createManager() {
@@ -293,6 +235,4 @@ class RdsContainerManagerPostgresTest {
// best effort
}
}
record ExecResult(long exitCode, String stdout, String stderr) {}
}
@@ -1,9 +1,11 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb.container;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.ContainerExecStubs;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
@@ -15,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -164,4 +167,18 @@ class TimestreamInfluxDbContainerManagerTest {
"INFLUXD_STORAGE_CACHE_SNAPSHOT_WRITE_COLD_DURATION", "48h",
"INFLUXD_HTTP_WRITE_TIMEOUT", "250ms"), environment);
}
@Test
void aFailedInfluxBackupReportsTheExitCodeAndTheCommandsOutput() {
DockerClient dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
List<List<String>> commands = ContainerExecStubs.completeEveryExec(dockerClient, "influx-container-id", 1, "",
"Error: failed to connect");
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> manager.backup("influx-container-id", "backup-1"));
assertEquals("influx backup failed with exit code 1: Error: failed to connect", error.getMessage());
assertEquals(List.of(List.of("influx", "backup", "/tmp/floci-backup-backup-1")), commands);
}
}