mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ssm): execute run commands in EC2 containers (#1387)
This commit is contained in:
1 parent
717769857b
commit
660a8bceb3
11 files changed
+1203
-28
No files matched your search
+332
@@ -0,0 +1,332 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Command;
|
||||
import io.github.hectorvent.floci.services.ssm.model.CommandInvocation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SsmCommandServiceDirectExecutionTest {
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final RegionResolver regionResolver = mock(RegionResolver.class);
|
||||
|
||||
@Test
|
||||
void directExecutionCompletesCommandWithoutQueuedAgentMessage() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "hello\n", "", 0, start, end)));
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-container"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["echo hello"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("InProgress", command.getStatus());
|
||||
assertEquals("In Progress", command.getStatusDetails());
|
||||
assertEquals(0, command.getCompletedCount());
|
||||
assertEquals("Success", waitForCommandStatus(service, command.getCommandId(), "us-west-2"));
|
||||
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-container", "us-west-2");
|
||||
assertEquals("Success", invocation.getStatus());
|
||||
assertEquals(0, invocation.getResponseCode());
|
||||
assertEquals("hello\n", invocation.getStandardOutputContent());
|
||||
assertEquals(start, invocation.getExecutionStartDateTime());
|
||||
assertEquals(end, invocation.getExecutionEndDateTime());
|
||||
assertTrue(service.getMessages("i-container", "request-id", 30).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedDirectExecutionFallsBackToAgentQueue() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
when(executor.supports(eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-agent"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["echo hello"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("InProgress", command.getStatus());
|
||||
assertEquals("In Progress", command.getStatusDetails());
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-agent", "us-west-2");
|
||||
assertEquals("Pending", invocation.getStatus());
|
||||
assertEquals(1, service.getMessages("i-agent", "request-id", 30).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void directTimeoutMarksCommandTimedOut() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:05Z");
|
||||
when(executor.supports(eq("i-timeout"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq("i-timeout"), eq("AWS-RunShellScript"), any(), eq(5)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"TimedOut", "", "Timed out after 5s", -1, start, end)));
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-timeout"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["sleep 100"]
|
||||
},
|
||||
"TimeoutSeconds": 5
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("TimedOut", waitForCommandStatus(service, command.getCommandId(), "us-west-2"));
|
||||
Command updatedCommand = service.listCommands(command.getCommandId(), null, "us-west-2").getFirst();
|
||||
assertEquals("Execution Timed Out", updatedCommand.getStatusDetails());
|
||||
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-timeout", "us-west-2");
|
||||
assertEquals("TimedOut", invocation.getStatus());
|
||||
assertEquals("Execution Timed Out", invocation.getStatusDetails());
|
||||
assertEquals(-1, invocation.getResponseCode());
|
||||
assertEquals("Timed out after 5s", invocation.getStandardErrorContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixedDirectAndQueuedTargetsRemainInProgress() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.supports(eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
|
||||
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "done\n", "", 0, start, end)));
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-container", "i-agent"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["echo done"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("InProgress", command.getStatus());
|
||||
assertEquals("In Progress", command.getStatusDetails());
|
||||
waitForInvocationStatus(service, command.getCommandId(), "i-container", "us-west-2", "Success");
|
||||
Command updatedCommand = service.listCommands(command.getCommandId(), null, "us-west-2").getFirst();
|
||||
assertEquals(1, updatedCommand.getCompletedCount());
|
||||
assertEquals(0, command.getErrorCount());
|
||||
assertEquals("Success",
|
||||
service.getCommandInvocation(command.getCommandId(), "i-container", "us-west-2").getStatus());
|
||||
assertEquals("Pending",
|
||||
service.getCommandInvocation(command.getCommandId(), "i-agent", "us-west-2").getStatus());
|
||||
assertEquals(1, service.getMessages("i-agent", "request-id", 30).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void directExecutionReturnsBeforeContainerCommandCompletes() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
.thenAnswer(invocation -> {
|
||||
started.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
return Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "done\n", "", 0, start, end));
|
||||
});
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-container"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["sleep 1 && echo done"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("InProgress", command.getStatus());
|
||||
assertEquals("In Progress", command.getStatusDetails());
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-container", "us-west-2");
|
||||
assertEquals("InProgress", invocation.getStatus());
|
||||
assertEquals("In Progress", invocation.getStatusDetails());
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
|
||||
release.countDown();
|
||||
assertEquals("Success", waitForCommandStatus(service, command.getCommandId(), "us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directExecutionThatBecomesUnsupportedFallsBackToAgentQueue() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-container"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["echo hello"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("InProgress", command.getStatus());
|
||||
assertEquals(1, waitForMessageCount(service, "i-container"));
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-container", "us-west-2");
|
||||
assertEquals("Pending", invocation.getStatus());
|
||||
assertEquals("Pending", invocation.getStatusDetails());
|
||||
}
|
||||
|
||||
@Test
|
||||
void directExecutionUsesAwsOutputLimitsFromBeginning() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
String stdout = "o".repeat(24_010) + "tail";
|
||||
String stderr = "e".repeat(8_010) + "tail";
|
||||
when(executor.supports(eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Failed", stdout, stderr, 1, Instant.parse("2026-06-07T00:00:00Z"), Instant.parse("2026-06-07T00:00:01Z"))));
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
new InMemoryStorageFactory(),
|
||||
objectMapper,
|
||||
regionResolver,
|
||||
executor);
|
||||
|
||||
Command command = service.sendCommand(objectMapper.readTree("""
|
||||
{
|
||||
"InstanceIds": ["i-container"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["printf output"]
|
||||
},
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
"""), "us-west-2");
|
||||
|
||||
assertEquals("Failed", waitForCommandStatus(service, command.getCommandId(), "us-west-2"));
|
||||
CommandInvocation invocation = service.getCommandInvocation(command.getCommandId(), "i-container", "us-west-2");
|
||||
assertEquals(24_000, invocation.getStandardOutputContent().length());
|
||||
assertEquals(8_000, invocation.getStandardErrorContent().length());
|
||||
assertEquals("o".repeat(24_000), invocation.getStandardOutputContent());
|
||||
assertEquals("e".repeat(8_000), invocation.getStandardErrorContent());
|
||||
}
|
||||
|
||||
private static String waitForCommandStatus(SsmCommandService service, String commandId, String region) throws InterruptedException {
|
||||
for (int i = 0; i < 50; i++) {
|
||||
Command command = service.listCommands(commandId, null, region).getFirst();
|
||||
if (!"InProgress".equals(command.getStatus())) {
|
||||
return command.getStatus();
|
||||
}
|
||||
TimeUnit.MILLISECONDS.sleep(20);
|
||||
}
|
||||
return service.listCommands(commandId, null, region).getFirst().getStatus();
|
||||
}
|
||||
|
||||
private static void waitForInvocationStatus(SsmCommandService service, String commandId, String instanceId, String region, String status) throws InterruptedException {
|
||||
for (int i = 0; i < 50; i++) {
|
||||
if (status.equals(service.getCommandInvocation(commandId, instanceId, region).getStatus())) {
|
||||
return;
|
||||
}
|
||||
TimeUnit.MILLISECONDS.sleep(20);
|
||||
}
|
||||
}
|
||||
|
||||
private static int waitForMessageCount(SsmCommandService service, String instanceId) throws InterruptedException {
|
||||
for (int i = 0; i < 50; i++) {
|
||||
int messageCount = service.getMessages(instanceId, "request-id", 30).size();
|
||||
if (messageCount > 0) {
|
||||
return messageCount;
|
||||
}
|
||||
TimeUnit.MILLISECONDS.sleep(20);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static final class InMemoryStorageFactory extends StorageFactory {
|
||||
private InMemoryStorageFactory() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return new InMemoryStorage<>();
|
||||
}
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
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.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import com.github.dockerjava.api.command.InspectExecResponse;
|
||||
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 java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
class SsmDirectCommandExecutorTest {
|
||||
|
||||
@Test
|
||||
void executesRunShellScriptInsideEc2Container() throws Exception {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
|
||||
ExecCreateCmdResponse execCreateResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(execCreateResponse.getId()).thenReturn("exec-1");
|
||||
when(execCreate.exec()).thenReturn(execCreateResponse);
|
||||
when(dockerClient.execCreateCmd("container-1")).thenReturn(execCreate);
|
||||
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
AtomicReference<ResultCallback<Frame>> callback = new AtomicReference<>();
|
||||
when(execStart.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback<Frame> resultCallback = invocation.getArgument(0);
|
||||
callback.set(resultCallback);
|
||||
resultCallback.onNext(new Frame(StreamType.STDOUT, "stdout\n".getBytes()));
|
||||
resultCallback.onNext(new Frame(StreamType.STDERR, "stderr\n".getBytes()));
|
||||
resultCallback.onComplete();
|
||||
return resultCallback;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
when(inspectExecResponse.getExitCodeLong()).thenReturn(0L);
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("echo stdout"), "workingDirectory", List.of("/tmp")),
|
||||
30);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("Success", result.get().status());
|
||||
assertEquals("stdout\n", result.get().standardOutput());
|
||||
assertEquals("stderr\n", result.get().standardError());
|
||||
assertEquals(0, result.get().responseCode());
|
||||
assertTrue(callback.get() != null);
|
||||
verify(execCreate).withCmd(
|
||||
eq("sh"),
|
||||
eq("-c"),
|
||||
argThat(command -> command.contains("timeout --kill-after=1s '30s' sh -c")
|
||||
&& command.contains("'echo stdout'")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyWhenInstanceIsNotContainerBacked() {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
when(ec2Service.findInstanceById("i-agent")).thenReturn(null);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-agent",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("echo agent")),
|
||||
30);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyForUnsupportedDocument() {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunPowerShellScript",
|
||||
Map.of("commands", List.of("Write-Host nope")),
|
||||
30);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankRunShellScriptCompletesWithoutDockerExec() {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("")),
|
||||
30);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("Success", result.get().status());
|
||||
assertEquals("", result.get().standardOutput());
|
||||
assertEquals(0, result.get().responseCode());
|
||||
verifyNoInteractions(dockerClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonZeroExitCodeMapsToFailedResult() {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
|
||||
ExecCreateCmdResponse execCreateResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(execCreateResponse.getId()).thenReturn("exec-1");
|
||||
when(execCreate.exec()).thenReturn(execCreateResponse);
|
||||
when(dockerClient.execCreateCmd("container-1")).thenReturn(execCreate);
|
||||
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
when(execStart.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback<Frame> resultCallback = invocation.getArgument(0);
|
||||
resultCallback.onNext(new Frame(StreamType.STDERR, "nope\n".getBytes()));
|
||||
resultCallback.onComplete();
|
||||
return resultCallback;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
when(inspectExecResponse.getExitCodeLong()).thenReturn(7L);
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("exit 7")),
|
||||
30);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("Failed", result.get().status());
|
||||
assertEquals("nope\n", result.get().standardError());
|
||||
assertEquals(7, result.get().responseCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutClosesDockerExecCallback() throws Exception {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
|
||||
ExecCreateCmdResponse execCreateResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(execCreateResponse.getId()).thenReturn("exec-1");
|
||||
when(execCreate.exec()).thenReturn(execCreateResponse);
|
||||
when(dockerClient.execCreateCmd("container-1")).thenReturn(execCreate);
|
||||
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback<Frame> callback = mock(ResultCallback.class);
|
||||
when(execStart.exec(any())).thenReturn(callback);
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("sleep 100")),
|
||||
0);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("TimedOut", result.get().status());
|
||||
assertEquals(-1, result.get().responseCode());
|
||||
verify(callback).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutExitCodeMapsToTimedOutResult() throws Exception {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
|
||||
ExecCreateCmdResponse execCreateResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(execCreateResponse.getId()).thenReturn("exec-1");
|
||||
when(execCreate.exec()).thenReturn(execCreateResponse);
|
||||
when(dockerClient.execCreateCmd("container-1")).thenReturn(execCreate);
|
||||
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
when(execStart.exec(any())).thenAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback<Frame> resultCallback = invocation.getArgument(0);
|
||||
resultCallback.onNext(new Frame(StreamType.STDERR, "terminated\n".getBytes()));
|
||||
resultCallback.onComplete();
|
||||
return resultCallback;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
when(inspectExecResponse.getExitCodeLong()).thenReturn(124L);
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
Map.of("commands", List.of("sleep 100")),
|
||||
1);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals("TimedOut", result.get().status());
|
||||
assertEquals(-1, result.get().responseCode());
|
||||
assertEquals("terminated\n", result.get().standardError());
|
||||
}
|
||||
|
||||
private static Instance instance(String instanceId, String containerId) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(instanceId);
|
||||
instance.setDockerContainerId(containerId);
|
||||
instance.setState(InstanceState.running());
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
+93
@@ -1,18 +1,29 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
@@ -21,10 +32,19 @@ class SsmSendCommandIntegrationTest {
|
||||
private static final String SSM_CT = "application/x-amz-json-1.1";
|
||||
private static final String INSTANCE_ID = "i-0abc1234def56789a";
|
||||
private static String commandId;
|
||||
private static final SsmDirectCommandExecutor directCommandExecutor = mock(SsmDirectCommandExecutor.class);
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
QuarkusMock.installMockForType(directCommandExecutor, SsmDirectCommandExecutor.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void resetDirectExecution() {
|
||||
reset(directCommandExecutor);
|
||||
when(directCommandExecutor.executeIfSupported(anyString(), anyString(), any(), anyInt()))
|
||||
.thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
// ── Agent registration ─────────────────────────────────────────────────
|
||||
@@ -358,6 +378,79 @@ class SsmSendCommandIntegrationTest {
|
||||
.body("Commands[0].Status", equalTo("Cancelled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void sendCommandDirectlyExecutesForContainerBackedInstance() {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(directCommandExecutor.supports(eq("i-direct-container"), eq("AWS-RunShellScript")))
|
||||
.thenReturn(true);
|
||||
when(directCommandExecutor.executeIfSupported(
|
||||
eq("i-direct-container"),
|
||||
eq("AWS-RunShellScript"),
|
||||
any(),
|
||||
eq(60)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "direct-output\n", "", 0, start, end)));
|
||||
|
||||
String response = given()
|
||||
.header("X-Amz-Target", "AmazonSSM.SendCommand")
|
||||
.contentType(SSM_CT)
|
||||
.body("""
|
||||
{
|
||||
"InstanceIds": ["i-direct-container"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": { "commands": ["echo direct-output"] },
|
||||
"TimeoutSeconds": 60
|
||||
}
|
||||
""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Command.Status", equalTo("InProgress"))
|
||||
.body("Command.StatusDetails", equalTo("In Progress"))
|
||||
.body("Command.CompletedCount", equalTo(0))
|
||||
.body("Command.ErrorCount", equalTo(0))
|
||||
.extract().body().asString();
|
||||
|
||||
String cid = io.restassured.path.json.JsonPath.from(response).getString("Command.CommandId");
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSM.GetCommandInvocation")
|
||||
.contentType(SSM_CT)
|
||||
.body("""
|
||||
{
|
||||
"CommandId": "%s",
|
||||
"InstanceId": "i-direct-container"
|
||||
}
|
||||
""".formatted(cid))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Status", equalTo("Success"))
|
||||
.body("StatusDetails", equalTo("Success"))
|
||||
.body("ResponseCode", equalTo(0))
|
||||
.body("StandardOutputContent", equalTo("direct-output\n"));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
|
||||
.contentType(SSM_CT)
|
||||
.body("""
|
||||
{
|
||||
"Destination": "i-direct-container",
|
||||
"MessagesRequestId": "%s",
|
||||
"VisibilityTimeoutInSeconds": 30
|
||||
}
|
||||
""".formatted(UUID.randomUUID()))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Messages", empty());
|
||||
}
|
||||
|
||||
private static String buildReplyPayload(String stdout, String status, int returnCode) {
|
||||
String json = """
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user