From 585bad28c2bb50951b4e36099d520eae746eff20 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:24:38 -0400 Subject: [PATCH] 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. --- .../core/common/docker/ContainerExec.java | 121 +++++++++++ .../services/ec2/Ec2ContainerManager.java | 57 ++--- .../ec2/Ec2VolumeBlockDeviceManager.java | 52 +---- .../ecs/container/EcsCredentialsProxy.java | 22 +- .../floci/services/eks/EksClusterManager.java | 56 +---- .../container/FlinkContainerManager.java | 38 +--- .../services/mwaa/MwaaEnvironmentManager.java | 42 +--- .../services/mwaa/proxy/MwaaWebProxy.java | 6 +- .../rds/container/RdsContainerManager.java | 73 +------ .../container/RedshiftContainerManager.java | 84 +------ .../TimestreamInfluxDbContainerManager.java | 72 +----- .../common/docker/ContainerExecStubs.java | 69 ++++++ .../core/common/docker/ContainerExecTest.java | 205 ++++++++++++++++++ .../services/ec2/Ec2ContainerManagerTest.java | 63 ++++++ ...olumeBlockDeviceDockerIntegrationTest.java | 85 +++----- .../ec2/Ec2VolumeBlockDeviceManagerTest.java | 63 ++++++ .../container/EcsCredentialsProxyTest.java | 21 +- .../eks/EksImdsDockerIntegrationTest.java | 44 +--- .../eks/EksIrsaDockerIntegrationTest.java | 52 +---- .../EksPodIdentityDockerIntegrationTest.java | 24 +- .../EksRoute53DnsDockerIntegrationTest.java | 37 +--- ...RouteProgrammingDockerIntegrationTest.java | 26 +-- .../container/FlinkContainerManagerTest.java | 17 ++ .../mwaa/MwaaEnvironmentManagerTest.java | 17 ++ .../proxy/MwaaWebProxyCliOffloadTest.java | 8 +- .../RdsContainerManagerPostgresTest.java | 72 +----- ...imestreamInfluxDbContainerManagerTest.java | 17 ++ 27 files changed, 718 insertions(+), 725 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerExec.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerExecStubs.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerExecTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManagerTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerExec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerExec.java new file mode 100644 index 0000000000..fb2378b21e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerExec.java @@ -0,0 +1,121 @@ +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.model.Frame; +import com.github.dockerjava.api.model.StreamType; +import org.jboss.logging.Logger; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +/** + * Runs a command in a running container and waits for its exit code, shared by every container + * manager that drives its container through {@code docker exec}: each of them had its own copy of + * this before it moved here. + * + *
A command that outlives its timeout is left running in the container, with its attach
+ * stream closed, and reported with {@link Result#timedOut()} set and an exit code of {@code -1}.
+ * An error on the attach stream propagates as the {@link RuntimeException} docker-java raises for
+ * it.
+ */
+public final class ContainerExec {
+
+ private static final Logger LOG = Logger.getLogger(ContainerExec.class);
+
+ private ContainerExec() {
+ }
+
+ /**
+ * The outcome of one command. On a timeout, {@code stderr} ends with a note naming the timeout,
+ * so a caller that logs the output says why the command stopped.
+ */
+ public record Result(long exitCode, String stdout, String stderr, boolean timedOut) {
+
+ /** Both streams, trimmed, or {@code "(no output)"} when the command printed nothing. */
+ public String summary() {
+ String output = joinLines(stdout, stderr).trim();
+ return output.isEmpty() ? "(no output)" : output;
+ }
+
+ /** This result, or a {@link RuntimeException} naming {@code containerId} when it timed out. */
+ public Result throwIfTimedOut(String containerId) {
+ if (timedOut) {
+ throw new RuntimeException("exec timed out in container " + containerId);
+ }
+ return this;
+ }
+ }
+
+ /** Runs {@code cmd}, keeping its stdout and stderr apart. */
+ public static Result run(DockerClient dockerClient, String containerId, String[] cmd, int timeoutSeconds) {
+ ByteArrayOutputStream stdout = new ByteArrayOutputStream();
+ ByteArrayOutputStream stderr = new ByteArrayOutputStream();
+ Result result = run(dockerClient, containerId, cmd, timeoutSeconds, stdout, stderr);
+ return new Result(result.exitCode(), stdout.toString(StandardCharsets.UTF_8),
+ joinLines(stderr.toString(StandardCharsets.UTF_8), result.stderr()), result.timedOut());
+ }
+
+ /** Runs {@code cmd}, interleaving stderr into stdout in the order the container wrote them. */
+ public static Result runMerged(DockerClient dockerClient, String containerId, String[] cmd, int timeoutSeconds) {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ Result result = run(dockerClient, containerId, cmd, timeoutSeconds, output, output);
+ return new Result(result.exitCode(), output.toString(StandardCharsets.UTF_8), result.stderr(),
+ result.timedOut());
+ }
+
+ /**
+ * Runs {@code cmd}, writing its stdout and stderr to the given streams, which may be the same
+ * one. The returned {@code stdout} is empty and its {@code stderr} holds only the timeout note.
+ */
+ public static Result run(DockerClient dockerClient, String containerId, String[] cmd, int timeoutSeconds,
+ OutputStream stdout, OutputStream stderr) {
+ String execId = dockerClient.execCreateCmd(containerId)
+ .withCmd(cmd)
+ .withAttachStdout(true)
+ .withAttachStderr(true)
+ .exec()
+ .getId();
+
+ ResultCallback.Adapter callback = new ResultCallback.Adapter<>() {
+ @Override
+ public void onNext(Frame frame) {
+ byte[] payload = frame.getPayload();
+ if (payload == null) {
+ return;
+ }
+ try {
+ if (frame.getStreamType() == StreamType.STDERR) {
+ stderr.write(payload);
+ } else {
+ stdout.write(payload);
+ }
+ } catch (IOException e) {
+ LOG.warnv(e, "Failed to capture output of container exec {0}", execId);
+ }
+ }
+ };
+ dockerClient.execStartCmd(execId).exec(callback);
+
+ try {
+ if (!callback.awaitCompletion(timeoutSeconds, TimeUnit.SECONDS)) {
+ return new Result(-1, "", "Timed out after " + timeoutSeconds + "s", true);
+ }
+ Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
+ return new Result(exitCode != null ? exitCode : -1, "", "", false);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted running a command in container " + containerId, e);
+ }
+ }
+
+ private static String joinLines(String first, String second) {
+ if (first.isEmpty() || second.isEmpty()) {
+ return first + second;
+ }
+ return first.endsWith("\n") ? first + second : first + "\n" + second;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
index 92ef4fb613..6e12d7ffa1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
@@ -4,6 +4,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.ContainerExec;
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.ContainerReachableEndpoint;
@@ -54,7 +55,6 @@ import java.util.Set;
import java.util.function.Consumer;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
@@ -1511,7 +1511,7 @@ public class Ec2ContainerManager {
// Exit 1 means sshd is absent and there is nothing to start; exit 2 means sshd is
// there but the client package did not land. Only the first is fatal - see
// sshdInstallProbeCommand() for why the probe distinguishes them.
- ContainerExecResult install = execInContainerForResult(containerId, sshdInstallProbeCommand(), 120);
+ ContainerExec.Result install = execInContainerForResult(containerId, sshdInstallProbeCommand(), 120);
if (install.exitCode() == SSH_CLIENT_MISSING_EXIT_CODE) {
LOG.warnv("sshd is available on EC2 instance {0} but the OpenSSH client package is not:"
+ " scp is missing, so provisioners that upload files over scp will fail: {1}",
@@ -1522,7 +1522,7 @@ public class Ec2ContainerManager {
return;
}
// Generate host keys
- ContainerExecResult keygen = execInContainerForResult(containerId, new String[]{"ssh-keygen", "-A"}, 10);
+ ContainerExec.Result keygen = execInContainerForResult(containerId, new String[]{"ssh-keygen", "-A"}, 10);
if (keygen.exitCode() != 0) {
LOG.warnv("Could not generate SSH host keys for EC2 instance {0}: {1}",
instanceId, keygen.summary());
@@ -1530,7 +1530,7 @@ public class Ec2ContainerManager {
}
// Modern OpenSSH refuses to start without its privilege-separation directory, and /run
// is a fresh tmpfs in most container images, so /run/sshd genuinely isn't there yet.
- ContainerExecResult mkdir = execInContainerForResult(containerId,
+ ContainerExec.Result mkdir = execInContainerForResult(containerId,
new String[]{"mkdir", "-p", "/run/sshd"}, 5);
if (mkdir.exitCode() != 0) {
LOG.warnv("Could not create /run/sshd for EC2 instance {0}: {1}",
@@ -1540,7 +1540,7 @@ public class Ec2ContainerManager {
// Start sshd without -D so it daemonizes itself and survives this exec session. Since sshd
// requires execution with an absolute path, several paths are tried until it starts
for (String sshdPath : ALLOWED_SSHD_PATHS) {
- ContainerExecResult start = execInContainerForResult(containerId, new String[]{sshdPath}, 5);
+ ContainerExec.Result start = execInContainerForResult(containerId, new String[]{sshdPath}, 5);
if (start.exitCode() != 0) {
LOG.warnv("Could not start sshd using path {0} for EC2 instance {1}: {2}", sshdPath, instanceId, start.summary());
continue;
@@ -1677,14 +1677,14 @@ public class Ec2ContainerManager {
private void configureLinkLocalMetadataEndpoint(String containerId, String instanceId, String flociHost, int imdsPort) {
try {
- ContainerExecResult install = execInContainerForResult(containerId, metadataProxyInstallCommand(), 180);
+ ContainerExec.Result install = execInContainerForResult(containerId, metadataProxyInstallCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install IMDS proxy dependencies for EC2 instance {0}: {1}",
instanceId, install.summary());
return;
}
- ContainerExecResult start = execInContainerForResult(containerId, metadataProxyStartCommand(flociHost, imdsPort), 30);
+ ContainerExec.Result start = execInContainerForResult(containerId, metadataProxyStartCommand(flociHost, imdsPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local IMDS proxy for EC2 instance {0}: {1}",
instanceId, start.summary());
@@ -1697,44 +1697,25 @@ public class Ec2ContainerManager {
}
}
- private void execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
+ private void execInContainer(String containerId, String[] cmd, int timeoutSeconds) {
execInContainerForResult(containerId, cmd, timeoutSeconds);
}
- private ContainerExecResult execInContainerForResult(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);
+ private ContainerExec.Result execInContainerForResult(String containerId, String[] cmd, int timeoutSeconds) {
BoundedOutput output = new BoundedOutput(UserDataPipeline.MAX_EXEC_OUTPUT_BYTES);
- dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter() {
- @Override
- public void onNext(Frame frame) {
- if (frame.getPayload() != null) {
- try { output.write(frame.getPayload()); } catch (IOException ignored) {}
- }
+ ContainerExec.Result result;
+ try {
+ result = ContainerExec.run(dockerClient, containerId, cmd, timeoutSeconds, output, output);
+ } catch (RuntimeException e) {
+ if (Thread.currentThread().isInterrupted()) {
+ throw e;
}
- @Override
- public void onComplete() { latch.countDown(); }
- @Override
- public void onError(Throwable t) { latch.countDown(); }
- });
- boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
- if (!completed) {
- return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");
+ return new ContainerExec.Result(-1, "", Objects.requireNonNullElse(e.getMessage(), e.toString()), false);
}
- Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
- return new ContainerExecResult(exitCode != null ? exitCode : -1, summarizeUserDataOutput(output));
- }
-
- record ContainerExecResult(long exitCode, String output) {
- String summary() {
- return output == null || output.isBlank() ? "(no output)" : output;
+ if (result.timedOut()) {
+ return result;
}
+ return new ContainerExec.Result(result.exitCode(), summarizeUserDataOutput(output), "", false);
}
private String getContainerBridgeIp(String containerId) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java
index 59f7595743..1e9eee1a87 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeBlockDeviceManager.java
@@ -1,14 +1,12 @@
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.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
-import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
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;
@@ -19,14 +17,13 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Pattern;
@@ -108,7 +105,7 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
int effectiveSize = sizeGib > 0 ? sizeGib : 8;
String rawFile = "/volumes/" + volumeId + ".raw";
String cmd = "truncate -s " + effectiveSize + "G " + rawFile;
- ContainerExecResult result = execInContainer(helperId, new String[]{"sh", "-c", cmd}, DEFAULT_TIMEOUT_SECONDS);
+ ContainerExec.Result result = execInContainer(helperId, new String[]{"sh", "-c", cmd}, DEFAULT_TIMEOUT_SECONDS);
if (result.exitCode() != 0) {
LOG.warnv("Failed to create backing file for volume {0}: {1}", volumeId, result.summary());
}
@@ -156,7 +153,7 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
+ " losetup -d \"$loop\" 2>/dev/null || break\n"
+ "done\n"
+ "rm -f \"$raw\"";
- ContainerExecResult result = execInContainer(helperId,
+ ContainerExec.Result result = execInContainer(helperId,
new String[]{"sh", "-c", script, "delete", rawFile}, DEFAULT_TIMEOUT_SECONDS);
activeLoopDevices.remove(volumeId);
return result.exitCode() == 0;
@@ -222,7 +219,7 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
+ "fi\n"
+ "echo \"$loop\"";
- ContainerExecResult helperResult;
+ ContainerExec.Result helperResult;
synchronized (loopAllocationLock) {
helperResult = execInContainer(helperId,
new String[]{"sh", "-c", helperScript, "helper", rawFile, String.valueOf(effectiveSize)},
@@ -258,7 +255,7 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
+ "fi\n"
+ "[ -b \"$dev\" ] || [ -L \"$dev\" ]";
- ContainerExecResult targetResult = execInContainer(targetContainerId,
+ ContainerExec.Result targetResult = execInContainer(targetContainerId,
new String[]{"sh", "-c", targetScript, "target", normalizedDevice, loopDev, minorStr},
DEFAULT_TIMEOUT_SECONDS);
if (targetResult.exitCode() != 0) {
@@ -364,34 +361,11 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
}
}
- private ContainerExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) {
+ private ContainerExec.Result execInContainer(String containerId, String[] cmd, int timeoutSeconds) {
try {
- ExecCreateCmdResponse exec = dockerClient
- .execCreateCmd(containerId)
- .withCmd(cmd)
- .withAttachStdout(true)
- .withAttachStderr(true)
- .exec();
-
- StringBuilder output = new StringBuilder();
- boolean completed = dockerClient.execStartCmd(exec.getId())
- .exec(new ResultCallback.Adapter() {
- @Override
- public void onNext(Frame frame) {
- if (frame != null && frame.getPayload() != null) {
- output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
- }
- }
- })
- .awaitCompletion(timeoutSeconds, TimeUnit.SECONDS);
-
- if (!completed) {
- return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");
- }
- Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
- return new ContainerExecResult(exitCode != null ? exitCode : -1, output.toString());
- } catch (Exception e) {
- return new ContainerExecResult(-1, e.getMessage());
+ return ContainerExec.runMerged(dockerClient, containerId, cmd, timeoutSeconds);
+ } catch (RuntimeException e) {
+ return new ContainerExec.Result(-1, "", Objects.requireNonNullElse(e.getMessage(), e.toString()), false);
}
}
@@ -417,10 +391,4 @@ public class Ec2VolumeBlockDeviceManager implements Resettable {
}
activeLoopDevices.clear();
}
-
- public record ContainerExecResult(long exitCode, String output) {
- public String summary() {
- return output == null || output.isBlank() ? "(no output)" : output.trim();
- }
- }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
index ec5acbdc47..3e6b8ed01a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java
@@ -1,12 +1,11 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
-import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Container;
-import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
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;
@@ -17,7 +16,6 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -45,6 +43,7 @@ public class EcsCredentialsProxy implements ContainerTeardown {
private static final String OWNS_NETWORK_LABEL = "floci.ecs-task-role-credentials-proxy";
private static final int VERIFY_ATTEMPTS = 30;
private static final long VERIFY_INTERVAL_MILLIS = 200;
+ private static final int EXEC_TIMEOUT_SECONDS = 10;
private final DockerClient dockerClient;
private final ContainerBuilder containerBuilder;
@@ -250,19 +249,10 @@ public class EcsCredentialsProxy implements ContainerTeardown {
private String execCapture(String containerId, String... cmd) {
try {
- String execId = dockerClient.execCreateCmd(containerId)
- .withAttachStdout(true).withAttachStderr(true).withCmd(cmd).exec().getId();
- StringBuilder output = new StringBuilder();
- try (ResultCallback.Adapter callback = new ResultCallback.Adapter<>() {
- @Override
- public void onNext(Frame frame) {
- output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
- }
- }) {
- dockerClient.execStartCmd(execId).exec(callback).awaitCompletion();
- }
- return output.toString();
- } catch (Exception e) {
+ ContainerExec.Result result = ContainerExec.runMerged(dockerClient, containerId, cmd, EXEC_TIMEOUT_SECONDS);
+ return result.timedOut() ? null : result.stdout();
+ } catch (RuntimeException e) {
+ LOG.debugv("Probe command in credentials proxy {0} failed: {1}", containerId, e.getMessage());
return null;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
index 85c0622bbe..6b01dd352c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java
@@ -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.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerNetwork;
-import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsRegions;
@@ -14,6 +12,7 @@ import io.github.hectorvent.floci.core.common.dns.DnsClientVpcSource;
import io.github.hectorvent.floci.core.common.dns.DnsClientVpcSource.ClientVpc;
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
@@ -73,7 +72,6 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@@ -1787,7 +1785,7 @@ public class EksClusterManager
metadataServer.reconcileContainerAddresses(containerIps.allIps(), nodeInstance);
}
- ContainerExecResult install = execInContainerForResult(containerId,
+ ContainerExec.Result install = execInContainerForResult(containerId,
Ec2MetadataProxy.installCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install IMDS proxy dependencies for EKS cluster {0}: {1}",
@@ -1798,7 +1796,7 @@ public class EksClusterManager
String flociHost = dockerHostResolver.resolve();
int imdsPort = config.services().ec2().imdsPort();
- ContainerExecResult start = execInContainerForResult(containerId,
+ ContainerExec.Result start = execInContainerForResult(containerId,
Ec2MetadataProxy.startCommand(flociHost, imdsPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local IMDS proxy for EKS cluster {0}: {1}",
@@ -1822,7 +1820,7 @@ public class EksClusterManager
return;
}
try {
- ContainerExecResult install = execInContainerForResult(containerId,
+ ContainerExec.Result install = execInContainerForResult(containerId,
Ec2MetadataProxy.installCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install Pod Identity relay dependencies for EKS cluster {0}: {1}",
@@ -1833,7 +1831,7 @@ public class EksClusterManager
String flociHost = dockerHostResolver.resolve();
int flociPort = config.port();
- ContainerExecResult start = execInContainerForResult(containerId,
+ ContainerExec.Result start = execInContainerForResult(containerId,
Ec2MetadataProxy.podIdentityStartCommand(flociHost, flociPort), 30);
if (start.exitCode() != 0) {
LOG.warnv("Could not start link-local Pod Identity relay for EKS cluster {0}: {1}",
@@ -1859,7 +1857,7 @@ public class EksClusterManager
String[] routingCmd = EksPodNetworkRouting.buildRoutingCommand(
EksPodNetworkRouting.DEFAULT_POD_CIDR,
endpoints);
- ContainerExecResult routing = execInContainerForResult(containerId, routingCmd, 15);
+ ContainerExec.Result routing = execInContainerForResult(containerId, routingCmd, 15);
if (routing.exitCode() != 0) {
LOG.warnv("Could not configure link-local pod network routing for EKS cluster {0}: {1}",
cluster.getName(), routing.summary());
@@ -1918,7 +1916,7 @@ public class EksClusterManager
programmedClusterRoutes.put(clusterKey, desiredDests);
return;
}
- ContainerExecResult result = execInContainerForResult(containerId, cmd.get(), 30);
+ ContainerExec.Result result = execInContainerForResult(containerId, cmd.get(), 30);
if (result.exitCode() != 0) {
LOG.warnv("Could not program VPC routes for EKS cluster {0}: {1}",
cluster.getName(), result.summary());
@@ -2164,38 +2162,8 @@ public class EksClusterManager
return record != null ? record.instance() : null;
}
- ContainerExecResult execInContainerForResult(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
- DockerClient dockerClient = lifecycleManager.getDockerClient();
- ExecCreateCmdResponse exec = dockerClient
- .execCreateCmd(containerId)
- .withCmd(cmd)
- .withAttachStdout(true)
- .withAttachStderr(true)
- .exec();
-
- StringBuilder output = new StringBuilder();
- boolean completed = dockerClient.execStartCmd(exec.getId())
- .exec(new ResultCallback.Adapter() {
- @Override
- public void onNext(Frame frame) {
- if (frame != null && frame.getPayload() != null) {
- output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
- }
- }
- })
- .awaitCompletion(timeoutSeconds, TimeUnit.SECONDS);
-
- if (!completed) {
- return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s");
- }
- Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
- return new ContainerExecResult(exitCode != null ? exitCode : -1, output.toString());
- }
-
- record ContainerExecResult(long exitCode, String output) {
- String summary() {
- return output == null || output.isBlank() ? "(no output)" : output.trim();
- }
+ ContainerExec.Result execInContainerForResult(String containerId, String[] cmd, int timeoutSeconds) {
+ return ContainerExec.runMerged(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds);
}
/**
@@ -2231,11 +2199,7 @@ public class EksClusterManager
private String execInContainer(String containerId, String[] cmd) throws Exception {
- ContainerExecResult result = execInContainerForResult(containerId, cmd, 10);
- if (result.exitCode() == -1 && result.output().startsWith("Timed out")) {
- throw new RuntimeException("exec timed out in container " + containerId);
- }
- return result.output();
+ return execInContainerForResult(containerId, cmd, 10).throwIfTimedOut(containerId).stdout();
}
private String extractYamlField(String yaml, String fieldName) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java
index e1d4fb0115..b6a7c07c85 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
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.ContainerExec;
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;
@@ -24,9 +25,6 @@ import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import com.github.dockerjava.api.async.ResultCallback;
-import com.github.dockerjava.api.model.Frame;
-import com.github.dockerjava.api.model.StreamType;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
@@ -43,7 +41,6 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
/**
* Manages the backing Apache Flink cluster for a Managed Service for Apache Flink application.
@@ -654,36 +651,7 @@ public class FlinkContainerManager {
}
}
- private ExecResult execInContainer(String containerId, String[] cmd) throws Exception {
- var dockerClient = lifecycleManager.getDockerClient();
- var exec = dockerClient.execCreateCmd(containerId)
- .withCmd(cmd)
- .withAttachStdout(true)
- .withAttachStderr(true)
- .exec();
-
- ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- ByteArrayOutputStream stderr = new ByteArrayOutputStream();
- boolean completed = dockerClient.execStartCmd(exec.getId())
- .exec(new ResultCallback.Adapter() {
- @Override
- public void onNext(Frame frame) {
- if (frame.getStreamType() == StreamType.STDERR) {
- stderr.writeBytes(frame.getPayload());
- } else {
- stdout.writeBytes(frame.getPayload());
- }
- }
- })
- .awaitCompletion(15, 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 : -1,
- stdout.toString(StandardCharsets.UTF_8), stderr.toString(StandardCharsets.UTF_8));
+ private ContainerExec.Result execInContainer(String containerId, String[] cmd) throws Exception {
+ return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 15).throwIfTimedOut(containerId);
}
-
- private record ExecResult(long exitCode, String stdout, String stderr) {}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
index 9c98f81d08..f9979cf731 100644
--- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java
@@ -4,18 +4,16 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
-import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
-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.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -356,7 +354,7 @@ public class MwaaEnvironmentManager {
}
copyFileIntoContainer(containerId, "/tmp", "mwaa-requirements.txt", requirementsContent);
try {
- ExecResult result = execInContainer(containerId,
+ ContainerExec.Result result = execInContainer(containerId,
new String[]{"pip", "install", "--no-cache-dir", "-r", "/tmp/mwaa-requirements.txt"});
if (result.exitCode() != 0) {
LOG.warnv("pip install -r requirements.txt exited {0} for environment {1}: {2}",
@@ -370,7 +368,7 @@ public class MwaaEnvironmentManager {
}
/** Runs {@code airflow > completeEveryExec(DockerClient dockerClient, String containerId, long exitCode,
+ String stdout, String stderr) {
+ String execId = "exec-" + containerId;
+ List
> 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 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;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerExecTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerExecTest.java
new file mode 100644
index 0000000000..88c316dbb5
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerExecTest.java
@@ -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 frames) {
+ startWith(callback -> {
+ frames.forEach(callback::onNext);
+ callback.onComplete();
+ });
+ }
+
+ private void startWith(Consumer
> 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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
index 3bc7cc96f6..712e12838c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
@@ -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
> 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,
diff --git a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java
index 68ace876b4..e135cb78d6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java
@@ -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
> 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());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/mwaa/proxy/MwaaWebProxyCliOffloadTest.java b/src/test/java/io/github/hectorvent/floci/services/mwaa/proxy/MwaaWebProxyCliOffloadTest.java
index e92851b3f8..271586f8d0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/mwaa/proxy/MwaaWebProxyCliOffloadTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/mwaa/proxy/MwaaWebProxyCliOffloadTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerPostgresTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerPostgresTest.java
index 3554225793..d98a895042 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerPostgresTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerPostgresTest.java
@@ -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() {
- @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) {}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java
index d2fadf9828..17d0f83d31 100644
--- a/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/timestreaminfluxdb/container/TimestreamInfluxDbContainerManagerTest.java
@@ -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
> 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);
+ }
}