fix(ssm): preserve command exits and terminate timed-out process groups (#7093)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-31 14:08:37 -04:00
1 parent b7e96c4be8
commit b4cd98fb61
6 files changed
+469 -35

No files matched your search

@@ -0,0 +1,123 @@
package io.github.hectorvent.floci.services.ssm;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;
/** Separates the supervisor's deadline signal from an arbitrary user exit status. */
final class SsmCommandTimeout {
private final String marker = "\036floci-ssm-timeout-" + UUID.randomUUID() + "\037";
private final byte[] markerBytes = marker.getBytes(StandardCharsets.UTF_8);
private final BoundedOutputCollector stderr;
private int matched;
private boolean timedOut;
SsmCommandTimeout(int limit) {
stderr = new BoundedOutputCollector(limit);
}
String wrap(String script, int seconds) {
String command = "sh -c " + quote(script);
if (seconds < 1) {
return command;
}
// Keep GNU timeout's monitored shell alive until -k kills the entire group, even if its child exits first.
String completedCommand = "trap 'while :; do sleep 1; done' TERM; " + command
+ " & child=$!; wait \"$child\" 2>/dev/null; result=$?; printf '%s\\n' \"$result\" > \"$1/completed\"; exit \"$result\"";
return """
if ! command -v mktemp >/dev/null 2>&1; then
exec %s
fi
state=$(mktemp -d 2>/dev/null) || exec %s
if ! command -v setsid >/dev/null 2>&1; then
case "$(timeout --version 2>/dev/null)" in
*"GNU coreutils"*)
timeout -k 1s %s sh -c %s sh "$state"
result=$?
if [ -f "$state/completed" ] && read -r completed_result < "$state/completed"; then
result=$completed_result
else
case "$result" in 124|137|143) printf '%%s' %s >&2 ;; esac
fi
rm -rf "$state"
exit "$result"
;;
*) rmdir "$state"; exec %s ;;
esac
fi
setsid %s &
child=$!
(
timer=
trap 'if [ -n "$timer" ]; then kill "$timer" 2>/dev/null; wait "$timer" 2>/dev/null; fi; exit 0' TERM
sleep %s &
timer=$!
wait "$timer"
if mkdir "$state/finished" 2>/dev/null; then
: > "$state/timed-out"
kill -TERM "-$child" 2>/dev/null
sleep 1
kill -KILL "-$child" 2>/dev/null
fi
) &
watchdog=$!
wait "$child" 2>/dev/null
result=$?
if mkdir "$state/finished" 2>/dev/null; then
kill "$watchdog" 2>/dev/null
fi
wait "$watchdog" 2>/dev/null
if [ -f "$state/timed-out" ]; then
printf '%%s' %s >&2
fi
rm -rf "$state"
exit "$result"
""".formatted(command, command, seconds, quote(completedCommand), quote(marker), command,
command, seconds, quote(marker));
}
synchronized void writeError(byte[] payload) {
int start = 0;
for (int i = 0; i < payload.length; i++) {
byte value = payload[i];
if (value == markerBytes[matched]) {
if (matched == 0 && i > start) {
stderr.write(Arrays.copyOfRange(payload, start, i));
}
matched++;
start = i + 1;
if (matched == markerBytes.length) {
timedOut = true;
matched = 0;
}
} else if (matched > 0) {
stderr.write(Arrays.copyOf(markerBytes, matched));
matched = 0;
start = i;
if (value == markerBytes[0]) {
matched = 1;
start = i + 1;
}
}
}
if (payload.length > start) {
stderr.write(Arrays.copyOfRange(payload, start, payload.length));
}
}
synchronized String standardError() {
if (matched > 0) {
stderr.write(Arrays.copyOf(markerBytes, matched));
matched = 0;
}
return stderr.content();
}
synchronized boolean timedOut() {
return timedOut;
}
static String quote(String value) {
return "'" + value.replace("'", "'\"'\"'") + "'";
}
}
@@ -110,7 +110,8 @@ public class SsmDirectCommandExecutor {
private ExecutionResult executeInContainer(String containerId, String script, String workingDirectory, int timeoutSeconds)
throws InterruptedException {
String[] cmd = {"sh", "-c", timeoutWrappedScript(script, timeoutSeconds)};
SsmCommandTimeout timeout = new SsmCommandTimeout(SsmCommandService.MAX_STDERR_CHARS);
String[] cmd = {"sh", "-c", timeout.wrap(script, timeoutSeconds)};
ExecCreateCmd create = dockerClient.execCreateCmd(containerId)
.withCmd(cmd)
.withAttachStdout(true)
@@ -122,7 +123,6 @@ public class SsmDirectCommandExecutor {
String execId = create.exec().getId();
CountDownLatch latch = new CountDownLatch(1);
BoundedOutputCollector stdout = new BoundedOutputCollector(SsmCommandService.MAX_STDOUT_CHARS);
BoundedOutputCollector stderr = new BoundedOutputCollector(SsmCommandService.MAX_STDERR_CHARS);
Instant start = Instant.now();
ResultCallback<Frame> callback = dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@@ -132,8 +132,11 @@ public class SsmDirectCommandExecutor {
if (payload == null) {
return;
}
BoundedOutputCollector target = frame.getStreamType() == StreamType.STDERR ? stderr : stdout;
target.write(payload);
if (frame.getStreamType() == StreamType.STDERR) {
timeout.writeError(payload);
} else {
stdout.write(payload);
}
}
@Override
@@ -143,7 +146,7 @@ public class SsmDirectCommandExecutor {
@Override
public void onError(Throwable throwable) {
stderr.write((throwable.getMessage() != null ? throwable.getMessage() : throwable.toString())
timeout.writeError((throwable.getMessage() != null ? throwable.getMessage() : throwable.toString())
.getBytes(StandardCharsets.UTF_8));
latch.countDown();
}
@@ -161,8 +164,8 @@ public class SsmDirectCommandExecutor {
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
int responseCode = exitCode != null ? exitCode.intValue() : 1;
String standardOutput = stdout.content();
String standardError = stderr.content();
if (isTimeoutExitCode(responseCode)) {
String standardError = timeout.standardError();
if (timeout.timedOut()) {
logFailureDiagnostics(containerId);
return ExecutionResult.timedOut(standardOutput, standardError, start);
}
@@ -174,22 +177,11 @@ public class SsmDirectCommandExecutor {
}
static String timeoutWrappedScript(String script, int timeoutSeconds) {
return userScriptCommand(script, timeoutSeconds);
}
private static String userScriptCommand(String script, int timeoutSeconds) {
String command = "sh -c " + shellSingleQuote(script);
if (timeoutSeconds < 1) {
return command;
}
String timeout = timeoutSeconds + "s";
return "if command -v timeout >/dev/null 2>&1; then "
+ "timeout --kill-after=1s " + shellSingleQuote(timeout) + " " + command + "; "
+ "else " + command + "; fi";
return new SsmCommandTimeout(SsmCommandService.MAX_STDERR_CHARS).wrap(script, timeoutSeconds);
}
static String diagnosticWrappedScript(String script) {
return "sh -c " + shellSingleQuote(script);
return "sh -c " + SsmCommandTimeout.quote(script);
}
private void logFailureDiagnostics(String containerId) {
@@ -268,14 +260,6 @@ public class SsmDirectCommandExecutor {
return timeoutSeconds + 2L;
}
private static boolean isTimeoutExitCode(int responseCode) {
return responseCode == 124 || responseCode == 137 || responseCode == 143;
}
private static String shellSingleQuote(String value) {
return "'" + value.replace("'", "'\"'\"'") + "'";
}
private static void closeQuietly(Closeable closeable) {
if (closeable == null) {
return;
@@ -0,0 +1,46 @@
package io.github.hectorvent.floci.services.ssm;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class SsmCommandTimeoutTest {
@Test
void markerIsRecognizedAcrossFramesAfterOutputLimit() {
SsmCommandTimeout timeout = new SsmCommandTimeout(3);
byte[] marker = marker(timeout).getBytes(StandardCharsets.UTF_8);
timeout.writeError("abcdef".getBytes(StandardCharsets.UTF_8));
for (byte value : marker) {
timeout.writeError(new byte[]{value});
}
assertTrue(timeout.timedOut());
assertEquals("abc", timeout.standardError());
}
@Test
void markerIsRemovedWithoutChangingSurroundingUnicodeOrPartialMatches() {
SsmCommandTimeout timeout = new SsmCommandTimeout(100);
String output = "é\036floci-x" + marker(timeout) + "後\036partial";
for (byte value : output.getBytes(StandardCharsets.UTF_8)) {
timeout.writeError(new byte[]{value});
}
assertTrue(timeout.timedOut());
assertEquals("é\036floci-x後\036partial", timeout.standardError());
}
@Test
void ordinaryTextAndDifferentMarkersAreNotTimeouts() {
SsmCommandTimeout timeout = new SsmCommandTimeout(100);
String text = marker(new SsmCommandTimeout(100)) + "natural exit 124";
timeout.writeError(text.getBytes(StandardCharsets.UTF_8));
assertFalse(timeout.timedOut());
assertEquals(text, timeout.standardError());
}
private static String marker(SsmCommandTimeout timeout) {
String script = timeout.wrap("true", 5);
return script.substring(script.indexOf('\036'), script.indexOf('\037') + 1);
}
}
@@ -13,6 +13,8 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
@@ -83,7 +85,7 @@ class SsmDirectCommandExecutorTest {
verify(execCreate).withCmd(
eq("sh"),
eq("-c"),
argThat(command -> command.contains("timeout --kill-after=1s '30s' sh -c")
argThat(command -> command.contains("setsid sh -c")
&& !command.contains("floci_ssm_redact")
&& command.contains("echo stdout")));
}
@@ -113,7 +115,7 @@ class SsmDirectCommandExecutorTest {
void timeoutAppliesOnlyToUserScriptBeforeDiagnosticsRun() {
String command = SsmDirectCommandExecutor.timeoutWrappedScript("sleep 100", 30);
assertTrue(command.contains("timeout --kill-after=1s '30s' sh -c 'sleep 100'"));
assertTrue(command.contains("setsid sh -c 'sleep 100'"));
assertFalse(command.contains("floci_ssm_redact"));
}
@@ -269,8 +271,9 @@ class SsmDirectCommandExecutorTest {
verify(callback).close();
}
@Test
void timeoutExitCodeMapsToTimedOutResult() throws Exception {
@ParameterizedTest
@ValueSource(longs = {124, 137, 143})
void ordinaryReservedExitCodeMapsToFailedResult(long exitCode) throws Exception {
DockerClient dockerClient = mock(DockerClient.class);
Ec2Service ec2Service = mock(Ec2Service.class);
Instance instance = instance("i-container", "container-1");
@@ -295,7 +298,7 @@ class SsmDirectCommandExecutorTest {
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
when(inspectExecResponse.getExitCodeLong()).thenReturn(124L);
when(inspectExecResponse.getExitCodeLong()).thenReturn(exitCode);
when(inspectExec.exec()).thenReturn(inspectExecResponse);
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
@@ -307,8 +310,8 @@ class SsmDirectCommandExecutorTest {
1);
assertTrue(result.isPresent());
assertEquals("TimedOut", result.get().status());
assertEquals(-1, result.get().responseCode());
assertEquals("Failed", result.get().status());
assertEquals(exitCode, result.get().responseCode());
assertEquals("terminated\n", result.get().standardError());
}
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.services.ssm;
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.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.ContainerStorageHelper;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@QuarkusTest
class SsmTimeoutDockerIntegrationTest {
@Inject
DockerClient docker;
@Inject
ContainerBuilder builder;
@Inject
ContainerLifecycleManager lifecycle;
@Inject
EmulatorConfig config;
@ParameterizedTest
@ValueSource(strings = {"busybox:stable", "public.ecr.aws/lambda/nodejs:20", "ubuntu:24.04"})
void timeoutPreservesOutputAndTerminatesScriptsOnBothGuestToolchains(String image) {
String name = ContainerStorageHelper.resourceName(config, "ssm-timeout", null, UUID.randomUUID().toString());
try {
ContainerInfo container = lifecycle.createAndStartEphemeral(builder.newContainer(image)
.withName(name).withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 600")).build());
ContainerExec.Result output = execute(container.containerId(),
"printf '%s' \"a 'quoted' line\"; printf '%s' stderr-marker >&2; exit 7", 5);
assertFalse(output.timedOut());
assertEquals(7, output.exitCode(), output.summary());
assertEquals("a 'quoted' line", output.stdout());
assertEquals("stderr-marker", output.stderr());
ContainerExec.Result tools = ContainerExec.run(docker, container.containerId(), new String[]{"sh", "-c",
"mkdir /tmp/ssm-minimal-tools && ln -s /bin/sh /tmp/ssm-minimal-tools/sh"}, 3);
assertEquals(0, tools.exitCode(), tools.summary());
ContainerExec.Result fallback = ContainerExec.run(docker, container.containerId(), new String[]{"sh", "-c",
"PATH=/tmp/ssm-minimal-tools; export PATH; " + SsmDirectCommandExecutor.timeoutWrappedScript(
"printf fallback; exit 143", 5)}, 3);
assertEquals(143, fallback.exitCode(), fallback.summary());
assertEquals("fallback", fallback.stdout());
ContainerExec.Result withoutSetsid = ContainerExec.run(docker, container.containerId(), new String[]{"sh", "-c",
"for tool in mktemp mkdir rmdir rm sleep timeout; do "
+ "ln -s \"$(command -v $tool)\" /tmp/ssm-minimal-tools/$tool || exit 1; done; "
+ "PATH=/tmp/ssm-minimal-tools; export PATH; "
+ SsmDirectCommandExecutor.timeoutWrappedScript("printf no-setsid; exit 137", 5)}, 3);
assertEquals(137, withoutSetsid.exitCode(), withoutSetsid.summary());
assertEquals("no-setsid", withoutSetsid.stdout());
ContainerExec.Result terminated = execute(container.containerId(), "exec sleep 20", 1);
assertFalse(terminated.timedOut(), "The guest timeout must finish before Docker attach's deadline");
assertTrue(Set.of(124L, 137L, 143L).contains(terminated.exitCode()), terminated.summary());
ContainerExec.Result killed = execute(container.containerId(), "trap '' TERM; exec sleep 20", 1);
assertFalse(killed.timedOut(), "Kill escalation must finish before Docker attach's deadline");
assertEquals(137, killed.exitCode(), killed.summary());
} finally {
lifecycle.removeIfExistsStrict(name, true);
}
}
@ParameterizedTest
@ValueSource(strings = {"busybox:stable", "public.ecr.aws/lambda/nodejs:20", "ubuntu:24.04"})
void executorPreservesNaturalReservedExits(String image) {
checkExecutor(image, false, false);
}
@ParameterizedTest
@ValueSource(strings = {"busybox:stable", "public.ecr.aws/lambda/nodejs:20", "ubuntu:24.04"})
void executorKillsBackgroundDescendants(String image) {
checkExecutor(image, true, false);
}
@ParameterizedTest
@ValueSource(strings = {"busybox:stable", "public.ecr.aws/lambda/nodejs:20", "ubuntu:24.04"})
void executorDoesNotMisreportAnEarlyParentExitAsTimeout(String image) {
checkExecutor(image, true, true);
}
@ParameterizedTest
@ValueSource(strings = {"public.ecr.aws/lambda/nodejs:20", "ubuntu:24.04"})
void gnuFallbackKillsStartedDescendantAfterDeadline(String image) {
String name = ContainerStorageHelper.resourceName(config, "ssm-timeout", null, UUID.randomUUID().toString());
try {
ContainerInfo container = lifecycle.createAndStartEphemeral(builder.newContainer(image)
.withName(name).withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 600")).build());
ContainerExec.Result setup = ContainerExec.run(docker, container.containerId(), new String[]{"sh", "-c",
"mkdir /tmp/ssm-gnu-tools; for tool in sh mktemp mkdir rmdir rm sleep timeout mkfifo; do "
+ "ln -s \"$(command -v $tool)\" /tmp/ssm-gnu-tools/$tool || exit 1; done"}, 3);
assertEquals(0, setup.exitCode(), setup.summary());
SsmCommandTimeout timeout = new SsmCommandTimeout(4096);
String script = "mkfifo /tmp/started; sh -c 'trap \"\" TERM; echo $$ > /tmp/descendant; "
+ "echo ready > /tmp/started; exec sleep 600' & read ready < /tmp/started; wait";
ContainerExec.Result result = ContainerExec.run(docker, container.containerId(), new String[]{"sh", "-c",
"PATH=/tmp/ssm-gnu-tools; export PATH; " + timeout.wrap(script, 1)}, 8);
timeout.writeError(result.stderr().getBytes(StandardCharsets.UTF_8));
assertFalse(result.timedOut(), "Guest supervision must finish before the Docker attach deadline");
assertEquals(137, result.exitCode(), result.summary());
assertTrue(timeout.timedOut(), "GNU escalation must emit the guest deadline marker");
assertFalse(timeout.standardError().contains("floci-ssm-timeout-"));
ContainerExec.Result state = descendantState(container.containerId());
assertEquals(0, state.exitCode(), "The descendant must have started: " + state.summary());
assertTrue(Set.of("absent", "Z").contains(state.stdout()), "Descendant still running: " + state.summary());
} finally {
lifecycle.removeIfExistsStrict(name, true);
}
}
private void checkExecutor(String image, boolean descendantsOnly, boolean parentExits) {
String name = ContainerStorageHelper.resourceName(config, "ssm-timeout", null, UUID.randomUUID().toString());
try {
ContainerInfo container = lifecycle.createAndStartEphemeral(builder.newContainer(image)
.withName(name).withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 600")).build());
Ec2Service ec2 = mock(Ec2Service.class);
Instance instance = new Instance();
instance.setDockerContainerId(container.containerId());
when(ec2.findInstanceById("i-timeout")).thenReturn(instance);
when(ec2.isInstanceContainerRunning("i-timeout")).thenReturn(true);
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(docker, ec2);
if (!descendantsOnly) {
for (int code : List.of(124, 137, 143)) {
SsmDirectCommandExecutor.ExecutionResult result = executor.executeIfSupported("i-timeout",
"AWS-RunShellScript", Map.of("commands", List.of(
"printf 'quoted \"output\"'; printf 'natural-error' >&2; exit " + code)), 10).orElseThrow();
assertEquals("Failed", result.status());
assertEquals(code, result.responseCode());
assertEquals("quoted \"output\"", result.standardOutput());
assertEquals("natural-error", result.standardError());
}
return;
}
String script = parentExits
? "mkfifo /tmp/started; sh -c 'trap \"\" TERM; echo $$ > /tmp/descendant; "
+ "echo ready > /tmp/started; exec sleep 600' & read ready < /tmp/started; printf parent-done"
: "sh -c 'trap \"\" TERM; echo $$ > /tmp/descendant; exec sleep 600' & wait";
SsmDirectCommandExecutor.ExecutionResult result = executor.executeIfSupported("i-timeout",
"AWS-RunShellScript", Map.of("commands", List.of(script)), 1).orElseThrow();
ContainerExec.Result state = descendantState(container.containerId());
assertEquals(0, state.exitCode(), "The descendant must have started: " + state.summary());
if (parentExits) {
assertEquals("Success", result.status(), "Early parent exit must not become a host attach timeout");
assertEquals(0, result.responseCode());
assertEquals("parent-done", result.standardOutput());
assertTrue(Set.of("R", "S", "D").contains(state.stdout()), state.summary());
} else {
assertEquals("TimedOut", result.status());
assertEquals(-1, result.responseCode());
assertTrue(Set.of("absent", "Z").contains(state.stdout()), "Descendant still running: " + state.summary());
}
assertFalse(result.standardError().contains("floci-ssm-timeout-"));
} finally {
lifecycle.removeIfExistsStrict(name, true);
}
}
private ContainerExec.Result descendantState(String container) {
return ContainerExec.run(docker, container, new String[]{"sh", "-c",
"test -s /tmp/descendant || exit 1; pid=$(cat /tmp/descendant); if [ -f /proc/$pid/stat ]; then "
+ "read p name state rest < /proc/$pid/stat; printf '%s' \"$state\"; else printf absent; fi"}, 3);
}
private ContainerExec.Result execute(String container, String script, int seconds) {
return ContainerExec.run(docker, container,
new String[]{"sh", "-c", SsmDirectCommandExecutor.timeoutWrappedScript(script, seconds)}, 8);
}
}
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.ssm;
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.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetCommandInvocationResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@QuarkusTest
class SsmTimeoutSdkIntegrationTest extends SsmCommandIntegrationFixture {
@Inject DockerClient docker;
@Inject ContainerBuilder builder;
@Inject ContainerLifecycleManager lifecycle;
@Inject EmulatorConfig config;
@ParameterizedTest
@ValueSource(strings = {"busybox:stable", "public.ecr.aws/lambda/nodejs:20"})
void sdkDistinguishesReservedFailuresFromExecutionDeadline(String image) {
String instanceId = "i-timeout-" + UUID.randomUUID();
String name = ContainerStorageHelper.resourceName(config, "ssm-timeout", null, UUID.randomUUID().toString());
String account = "000000000000";
try (SsmClient ssm = AwsTestClients.create(SsmClient.builder(), account, Region.US_EAST_1)) {
ContainerInfo container = lifecycle.createAndStartEphemeral(builder.newContainer(image)
.withName(name).withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 600")).build());
Ec2Service ec2 = mock(Ec2Service.class);
Instance instance = new Instance();
instance.setDockerContainerId(container.containerId());
when(ec2.findInstanceById(account, instanceId)).thenReturn(instance);
when(ec2.isInstanceContainerRunning(account, instanceId)).thenReturn(true);
SsmDirectCommandExecutor actual = new SsmDirectCommandExecutor(docker, ec2);
when(executor.supports(account, instanceId, "AWS-RunShellScript")).thenReturn(true);
when(executor.executeIfSupported(eq(account), eq(instanceId), eq("AWS-RunShellScript"), any(), anyInt()))
.thenAnswer(call -> actual.executeIfSupported(call.getArgument(0), call.getArgument(1),
call.getArgument(2), call.getArgument(3), call.getArgument(4)));
for (int code : List.of(124, 137, 143)) {
GetCommandInvocationResponse result = invoke(ssm, instanceId,
"printf stdout; printf stderr >&2; exit " + code, 10);
assertEquals("Failed", result.statusAsString());
assertEquals(code, result.responseCode());
assertEquals("stdout", result.standardOutputContent());
assertEquals("stderr", result.standardErrorContent());
}
GetCommandInvocationResponse timed = invoke(ssm, instanceId,
"printf before; trap '' TERM; exec sleep 600", 1);
assertEquals("TimedOut", timed.statusAsString());
assertEquals(-1, timed.responseCode());
assertEquals("before", timed.standardOutputContent());
assertFalse(timed.standardErrorContent().contains("floci-ssm-timeout-"));
} finally {
assertAll("command and container cleanup",
() -> cleanupCommands(account, Region.US_EAST_1.id(), instanceId),
() -> lifecycle.removeIfExistsStrict(name, true));
}
}
private GetCommandInvocationResponse invoke(SsmClient ssm, String instance, String script, int seconds) {
String command = ssm.sendCommand(r -> r.documentName("AWS-RunShellScript").instanceIds(instance)
.parameters(Map.of("commands", List.of(script), "executionTimeout", List.of(Integer.toString(seconds)))))
.command().commandId();
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
GetCommandInvocationResponse result = ssm.getCommandInvocation(r -> r.commandId(command).instanceId(instance));
assertTrue(List.of("Failed", "TimedOut").contains(result.statusAsString()));
});
return ssm.getCommandInvocation(r -> r.commandId(command).instanceId(instance));
}
}