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,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.
*
* <p>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<Frame> 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;
}
}
@@ -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<Frame>() {
@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) {
@@ -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<Frame>() {
@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();
}
}
}
@@ -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<Frame> 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;
}
}
@@ -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<Frame>() {
@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) {
@@ -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<Frame>() {
@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) {}
}
@@ -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 <cliCommand>} inside the Airflow container via {@code sh -c}. */
public ExecResult runAirflowCli(String airflowContainerId, String cliCommand) throws Exception {
public ContainerExec.Result runAirflowCli(String airflowContainerId, String cliCommand) throws Exception {
return execInContainer(airflowContainerId, new String[]{"sh", "-c", "airflow " + cliCommand});
}
@@ -531,7 +529,7 @@ public class MwaaEnvironmentManager {
Exception last = null;
for (int attempt = 1; attempt <= 60; attempt++) {
try {
ExecResult result = execInContainer(containerId,
ContainerExec.Result result = execInContainer(containerId,
new String[]{"pg_isready", "-h", "127.0.0.1", "-U", "airflow"});
if (result.exitCode() == 0) {
return;
@@ -608,35 +606,8 @@ public class MwaaEnvironmentManager {
}
}
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<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame.getStreamType() == StreamType.STDERR) {
stderr.writeBytes(frame.getPayload());
} else {
stdout.writeBytes(frame.getPayload());
}
}
})
.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 : -1,
stdout.toString(StandardCharsets.UTF_8), stderr.toString(StandardCharsets.UTF_8));
ContainerExec.Result execInContainer(String containerId, String[] cmd) throws Exception {
return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 30).throwIfTimedOut(containerId);
}
private static String generateSecret(int bytes) {
@@ -652,5 +623,4 @@ public class MwaaEnvironmentManager {
return Base64.getUrlEncoder().encodeToString(buf);
}
public record ExecResult(long exitCode, String stdout, String 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.WorkerExecutor;
import io.vertx.core.http.HttpClient;
@@ -121,7 +121,7 @@ public class MwaaWebProxy {
String command = body.toString(StandardCharsets.UTF_8).trim();
// The Docker exec can block for up to 30 seconds, so keep it off the event loop.
// Unordered: independent CLI calls should not queue behind each other.
cliWorkers.<MwaaEnvironmentManager.ExecResult>executeBlocking(() -> cliExecutor.execute(command), false)
cliWorkers.<ContainerExec.Result>executeBlocking(() -> cliExecutor.execute(command), false)
.onSuccess(result -> {
String stdoutB64 = Base64.getEncoder().encodeToString(result.stdout().getBytes(StandardCharsets.UTF_8));
String stderrB64 = Base64.getEncoder().encodeToString(result.stderr().getBytes(StandardCharsets.UTF_8));
@@ -199,6 +199,6 @@ public class MwaaWebProxy {
@FunctionalInterface
public interface CliExecutor {
MwaaEnvironmentManager.ExecResult execute(String cliCommand) throws Exception;
ContainerExec.Result execute(String cliCommand) throws Exception;
}
}
@@ -1,8 +1,6 @@
package io.github.hectorvent.floci.services.rds.container;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -10,6 +8,7 @@ import io.github.hectorvent.floci.core.common.Resettable;
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.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
@@ -28,8 +27,8 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
@@ -39,7 +38,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@@ -860,8 +858,8 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
String lastOutput = "";
for (int attempt = 1; attempt <= 60; attempt++) {
try {
ContainerExecResult result = execInContainer(containerId, cmd, 5);
lastOutput = result.output() + (result.stderr().isEmpty() ? "" : "\n" + result.stderr());
ContainerExec.Result result = execInContainer(containerId, cmd, 5);
lastOutput = result.stdout() + (result.stderr().isEmpty() ? "" : "\n" + result.stderr());
if (result.exitCode() == 0) {
LOG.infov("Initialized {0} in RDS container {1}", description, containerName);
return;
@@ -886,11 +884,11 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
"-U", effectiveUser
};
try (Lease _ = holdContainer(containerId)) {
ContainerExecResult result = execInContainer(containerId, cmd, 120);
ContainerExec.Result result = execInContainer(containerId, cmd, 120);
if (result.exitCode() != 0) {
throw new RuntimeException("pg_dumpall failed with exit code " + result.exitCode() + ": " + result.stderr());
}
return result.output();
return result.stdout();
} catch (Exception e) {
throw new RuntimeException("Failed to create postgres snapshot", e);
}
@@ -920,7 +918,7 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
String[] cmd = { "sh", "/tmp/restore.sh", effectiveUser };
ContainerExecResult result = null;
ContainerExec.Result result = null;
for (int i = 0; i < 60; i++) {
result = execInContainer(containerId, cmd, 120);
if (result.exitCode() == 0) {
@@ -938,7 +936,7 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
}
if (result == null || result.exitCode() != 0) {
String errMsg = result != null ? (result.stderr().isEmpty() ? result.output() : result.stderr()) : "";
String errMsg = result != null ? (result.stderr().isEmpty() ? result.stdout() : result.stderr()) : "";
throw new RuntimeException("psql restore failed with exit code "
+ (result != null ? result.exitCode() : -1) + ": " + errMsg);
}
@@ -993,61 +991,10 @@ public class RdsContainerManager implements RdsBackendGate, Resettable {
tar.closeArchiveEntry();
}
private ContainerExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
String execId = lifecycleManager.getDockerClient().execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec()
.getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
Closeable callback = lifecycleManager.getDockerClient().execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
if (frame.getPayload() != null) {
try {
if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDOUT) {
output.write(frame.getPayload());
} else if (frame.getStreamType() == com.github.dockerjava.api.model.StreamType.STDERR) {
stderr.write(frame.getPayload());
}
} catch (IOException e) {
LOG.warnv(e, "Failed to read output stream for container exec {0}", execId);
}
}
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public void onError(Throwable t) {
LOG.warnv(t, "Container exec {0} failed", execId);
latch.countDown();
}
});
try {
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
if (!completed) {
return new ContainerExecResult(-1, "Timed out after " + timeoutSeconds + "s", "");
}
Long exitCode = lifecycleManager.getDockerClient().inspectExecCmd(execId).exec().getExitCodeLong();
return new ContainerExecResult(
exitCode != null ? exitCode : -1,
output.toString(StandardCharsets.UTF_8),
stderr.toString(StandardCharsets.UTF_8));
} finally {
callback.close();
}
private ContainerExec.Result execInContainer(String containerId, String[] cmd, int timeoutSeconds) {
return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds);
}
record ContainerExecResult(long exitCode, String output, String stderr) {}
public void removeVolume(String instanceId, String volumeId) {
removeVolume(instanceId, instanceId,
ContainerStorageHelper.resourceName(config, "rds", volumeId, instanceId));
@@ -1,13 +1,11 @@
package io.github.hectorvent.floci.services.redshift.container;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
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.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;
@@ -27,8 +25,6 @@ import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@@ -36,7 +32,6 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
@@ -181,7 +176,7 @@ public class RedshiftContainerManager {
String[] cmd = new String[]{"pg_dump", "-U", effectiveUser, effectiveDb, "-f", "/tmp/dump.sql"};
try {
ExecResult result = execInContainer(handle.getContainerId(), cmd, 30);
ContainerExec.Result result = execInContainer(handle.getContainerId(), cmd, 30);
if (result.exitCode() != 0) {
LOG.warnv("pg_dump failed for cluster {0} (exit {1}): {2}", clusterIdentifier, result.exitCode(), result.stderr());
throw new AwsException("InternalFailure", "Failed to create snapshot for cluster " + clusterIdentifier + ": " + result.stderr(), 500);
@@ -241,7 +236,7 @@ public class RedshiftContainerManager {
String sql = "ALTER USER " + effectiveUser + " PASSWORD '" + newPassword + "'";
String[] cmd = new String[]{"psql", "-U", effectiveUser, "-d", "dev", "-c", sql};
try {
ExecResult result = execInContainer(handle.getContainerId(), cmd, 15);
ContainerExec.Result result = execInContainer(handle.getContainerId(), cmd, 15);
if (result.exitCode() != 0) {
// Deliberately omit result.stderr() from the log and the exception: psql echoes
// the failing ALTER USER statement, which contains the password literal.
@@ -285,7 +280,7 @@ public class RedshiftContainerManager {
.exec();
String[] cmd = new String[]{"psql", "-U", effectiveUser, "-d", effectiveDb, "-f", "/tmp/" + fileName};
ExecResult result = execInContainer(handle.getContainerId(), cmd, 60);
ContainerExec.Result result = execInContainer(handle.getContainerId(), cmd, 60);
if (result.exitCode() != 0) {
LOG.warnv("psql restore failed for cluster {0} (exit {1}): {2}", clusterIdentifier, result.exitCode(), result.stderr());
throw new AwsException("InternalFailure", "Failed to restore snapshot for cluster " + clusterIdentifier + ": " + result.stderr(), 500);
@@ -309,70 +304,8 @@ public class RedshiftContainerManager {
restoreSnapshot(accountId, cluster.getClusterIdentifier(), cluster.getMasterUsername(), "dev", sqlDumpFile);
}
private ExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds) throws Exception {
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ExecResult res = execInContainer(containerId, cmd, timeoutSeconds, stdout);
return new ExecResult(res.exitCode(), stdout.toString(StandardCharsets.UTF_8), res.stderr());
}
private ExecResult execInContainer(String containerId, String[] cmd, int timeoutSeconds, OutputStream out) throws Exception {
String execId = lifecycleManager.getDockerClient().execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
.withAttachStderr(true)
.exec()
.getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
Closeable callback = lifecycleManager.getDockerClient().execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
byte[] payload = frame.getPayload();
if (payload == null) {
return;
}
try {
if (frame.getStreamType() == StreamType.STDERR) {
stderr.write(payload);
} else {
out.write(payload);
}
} catch (IOException e) {
LOG.warnv(e, "Failed to capture output of container exec {0}", execId);
}
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public void onError(Throwable t) {
LOG.warnv(t, "Container exec {0} failed", execId);
latch.countDown();
}
});
try {
boolean completed = latch.await(timeoutSeconds, TimeUnit.SECONDS);
if (!completed) {
return new ExecResult(-1, "", "Timed out after " + timeoutSeconds + "s");
}
Long exitCode = lifecycleManager.getDockerClient().inspectExecCmd(execId).exec().getExitCodeLong();
return new ExecResult(
exitCode != null ? exitCode : -1,
"",
stderr.toString(StandardCharsets.UTF_8));
} finally {
try {
callback.close();
} catch (IOException ignored) {
// The exec result is already collected, so a failure to release the callback stream cannot change it.
}
}
private ContainerExec.Result execInContainer(String containerId, String[] cmd, int timeoutSeconds) {
return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, timeoutSeconds);
}
private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
@@ -405,7 +338,7 @@ public class RedshiftContainerManager {
String lastOutput = "";
for (int attempt = 1; attempt <= 60; attempt++) {
try {
ExecResult result = execInContainer(containerId, cmd, 5);
ContainerExec.Result result = execInContainer(containerId, cmd, 5);
lastOutput = result.stderr();
if (result.exitCode() == 0) {
LOG.infov("Initialized {0} in Redshift container {1}", description, containerName);
@@ -455,7 +388,7 @@ public class RedshiftContainerManager {
"-d", db,
"-f", "/tmp/bootstrap-catalog.sql"
};
ExecResult result = execInContainer(containerId, cmd, 30);
ContainerExec.Result result = execInContainer(containerId, cmd, 30);
if (result.exitCode() != 0) {
LOG.warnv("Redshift catalog bootstrap for {0} exited with code {1}: {2}", db, result.exitCode(), result.stderr());
} else {
@@ -467,5 +400,4 @@ public class RedshiftContainerManager {
}
}
public record ExecResult(long exitCode, String stdout, String stderr) {}
}
@@ -1,14 +1,11 @@
package io.github.hectorvent.floci.services.timestreaminfluxdb.container;
import com.fasterxml.jackson.databind.JsonNode;
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 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.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;
@@ -18,13 +15,10 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@@ -34,7 +28,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
@@ -358,7 +351,7 @@ public class TimestreamInfluxDbContainerManager implements ContainerTeardown {
}
private void execOrThrow(String containerId, String[] command, String description) {
ExecResult result = exec(containerId, command);
ContainerExec.Result result = exec(containerId, command);
if (result.exitCode() != 0) {
throw new IllegalStateException(description + " failed with exit code " + result.exitCode()
+ ": " + result.stderr() + result.stdout());
@@ -373,64 +366,7 @@ public class TimestreamInfluxDbContainerManager implements ContainerTeardown {
}
}
private ExecResult exec(String containerId, String[] command) {
DockerClient dockerClient = lifecycleManager.getDockerClient();
String execId = dockerClient.execCreateCmd(containerId)
.withCmd(command)
.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) {
return;
}
try {
if (frame.getStreamType() == StreamType.STDERR) {
stderr.write(frame.getPayload());
} else {
stdout.write(frame.getPayload());
}
} catch (IOException e) {
LOG.warnv(e, "Failed to read output of container exec {0}", execId);
}
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public void onError(Throwable throwable) {
LOG.warnv(throwable, "Container exec {0} failed", execId);
latch.countDown();
}
});
try {
if (!latch.await(EXEC_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
return new ExecResult(-1, stdout.toString(StandardCharsets.UTF_8), "timed out");
}
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
return new ExecResult(exitCode != null ? exitCode : -1,
stdout.toString(StandardCharsets.UTF_8), stderr.toString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted running command in container " + containerId, e);
} finally {
try {
callback.close();
} catch (IOException e) {
LOG.debugv("Failed to close exec callback {0}: {1}", execId, e.getMessage());
}
}
}
private record ExecResult(long exitCode, String stdout, String stderr) {
private ContainerExec.Result exec(String containerId, String[] command) {
return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, command, EXEC_TIMEOUT_SECONDS);
}
}