mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(ssm): separate shell execution and delivery timeouts (#5865)
* fix(ssm): separate shell execution and delivery timeouts * fix(ssm): require a command list for public shell requests * test(ssm): share command request and cleanup fixtures
This commit is contained in:
1 parent
043b919e85
commit
23edd58992
9 files changed
+646
-65
No files matched your search
+110
@@ -0,0 +1,110 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.Command;
|
||||
import software.amazon.awssdk.services.ssm.model.SsmException;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("SSM shell execution budgets")
|
||||
class SsmShellExecutionBudgetTest {
|
||||
@ParameterizedTest
|
||||
@CsvSource({"0,3600", "1,1", "5,5", "172800,172800"})
|
||||
void publicCommandReportsDeliveryAndTotalBudgets(int supplied, int execution) {
|
||||
Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed-node fixture");
|
||||
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
|
||||
Map<String, List<String>> parameters = new LinkedHashMap<>();
|
||||
parameters.put("commands", List.of("echo budget"));
|
||||
if (supplied != 0) {
|
||||
parameters.put("executionTimeout", List.of(Integer.toString(supplied)));
|
||||
}
|
||||
try (SsmClient ssm = TestFixtures.ssmClient()) {
|
||||
try {
|
||||
Command command = ssm.sendCommand(r -> r.documentName("AWS-RunShellScript")
|
||||
.instanceIds(instance).parameters(parameters).timeoutSeconds(30)).command();
|
||||
assertThat(command.timeoutSeconds()).isEqualTo(30);
|
||||
assertThat(Duration.between(command.requestedDateTime(), command.expiresAfter()).toMillis())
|
||||
.isCloseTo((30L + execution) * 1000, within(1L));
|
||||
assertThat(command.parameters()).isEqualTo(parameters);
|
||||
Command stored = ssm.listCommands(r -> r.commandId(command.commandId())).commands().get(0);
|
||||
assertThat(stored.timeoutSeconds()).isEqualTo(30);
|
||||
assertThat(stored.expiresAfter()).isEqualTo(command.expiresAfter());
|
||||
assertThat(ssm.getCommandInvocation(r -> r.commandId(command.commandId()).instanceId(instance))
|
||||
.statusAsString()).isEqualTo("Pending");
|
||||
} finally {
|
||||
cancelFixture(ssm, instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"0", "172801", "not-a-number", "+5", "01"})
|
||||
void malformedExecutionBudgetDoesNotCreateACommand(String value) {
|
||||
Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed-node fixture");
|
||||
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
|
||||
try (SsmClient ssm = TestFixtures.ssmClient()) {
|
||||
try {
|
||||
assertThat(ssm.listCommands(r -> r.instanceId(instance)).commands()).isEmpty();
|
||||
assertThatThrownBy(() -> ssm.sendCommand(r -> r.documentName("AWS-RunShellScript")
|
||||
.instanceIds(instance).timeoutSeconds(30).parameters(Map.of(
|
||||
"commands", List.of("echo budget"), "executionTimeout", List.of(value)))))
|
||||
.isInstanceOfSatisfying(SsmException.class, error -> {
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidParameters");
|
||||
});
|
||||
assertThat(ssm.listCommands(r -> r.instanceId(instance)).commands()).isEmpty();
|
||||
} finally {
|
||||
cancelFixture(ssm, instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"missing", "empty", "only-timeout"})
|
||||
void requiredScriptIsCheckedBeforeCreatingACommand(String shape) {
|
||||
Assumptions.assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed-node fixture");
|
||||
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
|
||||
try (SsmClient ssm = TestFixtures.ssmClient()) {
|
||||
try {
|
||||
assertThatThrownBy(() -> ssm.sendCommand(request -> {
|
||||
request.documentName("AWS-RunShellScript").instanceIds(instance).timeoutSeconds(30);
|
||||
if ("empty".equals(shape)) {
|
||||
request.parameters(Map.of("commands", List.of()));
|
||||
}
|
||||
if ("only-timeout".equals(shape)) {
|
||||
request.parameters(Map.of("executionTimeout", List.of("5")));
|
||||
}
|
||||
})).isInstanceOfSatisfying(SsmException.class, error -> {
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidParameters");
|
||||
});
|
||||
assertThat(ssm.listCommands(request -> request.instanceId(instance)).commands()).isEmpty();
|
||||
Command retry = ssm.sendCommand(request -> request.documentName("AWS-RunShellScript")
|
||||
.instanceIds(instance).timeoutSeconds(30)
|
||||
.parameters(Map.of("commands", List.of("echo retry")))).command();
|
||||
assertThat(retry.commandId()).isNotBlank();
|
||||
assertThat(retry.timeoutSeconds()).isEqualTo(30);
|
||||
} finally {
|
||||
cancelFixture(ssm, instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void cancelFixture(SsmClient ssm, String instance) {
|
||||
// SendCommand has no deletion API: cancel its queued work, retaining normal command history.
|
||||
for (Command command : ssm.listCommands(r -> r.instanceId(instance)).commands()) {
|
||||
ssm.cancelCommand(r -> r.commandId(command.commandId()).instanceIds(instance));
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -61,7 +61,25 @@ on restart.
|
||||
|
||||
To get a container that both answers IMDS and runs `SendCommand` directly, launch it with EC2 `RunInstances` first and then register that same container's SSM agent. Floci logs a warning when an agent registers from a container that is not backed by a Floci EC2 instance.
|
||||
|
||||
Direct command output follows the AWS inline output limits: first 24,000 characters of stdout and first 8,000 characters of stderr. Commands that exceed `TimeoutSeconds` are constrained inside the target container when the container has the `timeout` command available, and terminal timeout results are marked `TimedOut` with `StatusDetails` set to `Execution Timed Out`; commands with nonzero exit codes are marked `Failed`.
|
||||
Direct command output follows the AWS inline output limits: first 24,000 characters of stdout and first 8,000 characters of stderr. Commands that exceed their execution budget are constrained inside the target container when the container has the `timeout` command available, and terminal timeout results are marked `TimedOut` with `StatusDetails` set to `Execution Timed Out`; commands with nonzero exit codes are marked `Failed`.
|
||||
|
||||
### Shell command timeout budgets
|
||||
|
||||
For public `SendCommand` requests using the exact `AWS-RunShellScript` document name,
|
||||
`TimeoutSeconds` is the delivery/start allowance. `Parameters.executionTimeout` is a separate
|
||||
execution allowance, defaulting to 3600 seconds and accepting one decimal string from 1 to
|
||||
172800. The direct worker uses this execution allowance; agent payloads retain the public
|
||||
document's 3600-second default and carry an explicit parameter unchanged.
|
||||
|
||||
`Command.TimeoutSeconds` still reports the delivery allowance. `ExpiresAfter` includes both
|
||||
allowances for these shell requests. This corrects metadata and execution budgets; it does not
|
||||
add automatic delivery expiration, restart recovery, cleanup retries or late-start fencing.
|
||||
Internal CodeDeploy hook budgets and non-shell document handling keep their existing behavior.
|
||||
Missing or empty `commands`, malformed shell parameter wire shapes and invalid execution limits
|
||||
are refused before command creation
|
||||
with `InvalidParameters`/HTTP400. This is Floci's chosen mapping; exact AWS error wording and
|
||||
empty-list normalization were not observed live. Other document parameters and delivery-timeout
|
||||
coercion/upper-bound handling are not a complete document-schema implementation.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -47,6 +48,8 @@ public class SsmCommandService implements Resettable {
|
||||
private static final Logger LOG = Logger.getLogger(SsmCommandService.class);
|
||||
private static final int MIN_TIMEOUT_SECONDS = 30;
|
||||
private static final int MAX_INSTANCE_IDS = 50;
|
||||
private static final int DEFAULT_SHELL_EXECUTION_TIMEOUT_SECONDS = 3600;
|
||||
private static final int MAX_SHELL_EXECUTION_TIMEOUT_SECONDS = 172800;
|
||||
static final int MAX_STDOUT_CHARS = 24000;
|
||||
static final int MAX_STDERR_CHARS = 8000;
|
||||
|
||||
@@ -75,7 +78,7 @@ public class SsmCommandService implements Resettable {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.directCommandExecutor = directCommandExecutor;
|
||||
// Each direct execution blocks for the whole container exec, up to TimeoutSeconds, so every
|
||||
// Each direct execution blocks for the whole container exec, up to its execution budget, so every
|
||||
// target gets its own virtual thread instead of a platform thread.
|
||||
this.directExecutionExecutor = Executors.newThreadPerTaskExecutor(
|
||||
Thread.ofVirtual().name("floci-ssm-direct-execution").factory());
|
||||
@@ -159,10 +162,14 @@ public class SsmCommandService implements Resettable {
|
||||
400);
|
||||
}
|
||||
|
||||
Map<String, List<String>> parameters = parseParameters(request.path("Parameters"));
|
||||
boolean publicShell = "AWS-RunShellScript".equals(documentName);
|
||||
Map<String, List<String>> parameters = publicShell
|
||||
? parseShellParameters(request.path("Parameters")) : parseParameters(request.path("Parameters"));
|
||||
String comment = request.path("Comment").asText("");
|
||||
int timeoutSeconds = request.path("TimeoutSeconds").asInt(3600);
|
||||
validateTimeoutSeconds(timeoutSeconds);
|
||||
int executionTimeoutSeconds = publicShell ? shellExecutionTimeout(parameters) : timeoutSeconds;
|
||||
int documentTimeoutDefault = publicShell ? DEFAULT_SHELL_EXECUTION_TIMEOUT_SECONDS : timeoutSeconds;
|
||||
String documentVersion = request.path("DocumentVersion").asText("$DEFAULT");
|
||||
String outputS3Bucket = request.path("OutputS3BucketName").asText("");
|
||||
String outputS3Prefix = request.path("OutputS3KeyPrefix").asText("");
|
||||
@@ -187,7 +194,8 @@ public class SsmCommandService implements Resettable {
|
||||
command.setOutputS3KeyPrefix(outputS3Prefix.isEmpty() ? null : outputS3Prefix);
|
||||
command.setOutputS3Region(region);
|
||||
command.setRegion(region);
|
||||
command.setExpiresAfter(now.plusSeconds(timeoutSeconds));
|
||||
command.setExpiresAfter(now.plusSeconds((long) timeoutSeconds
|
||||
+ (publicShell ? executionTimeoutSeconds : 0)));
|
||||
|
||||
command.setStatus("InProgress");
|
||||
command.setStatusDetails(statusDetails("InProgress"));
|
||||
@@ -215,7 +223,7 @@ public class SsmCommandService implements Resettable {
|
||||
}
|
||||
else {
|
||||
invocationStore.put(invocationKey(region, commandId, instanceId), inv);
|
||||
queueMessage(commandId, instanceId, documentName, parameters, timeoutSeconds, region);
|
||||
queueMessage(commandId, instanceId, documentName, parameters, documentTimeoutDefault, region);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,12 +236,62 @@ public class SsmCommandService implements Resettable {
|
||||
directExecutionRequest.instanceId(),
|
||||
directExecutionRequest.documentName(),
|
||||
directExecutionRequest.parameters(),
|
||||
timeoutSeconds,
|
||||
executionTimeoutSeconds,
|
||||
documentTimeoutDefault,
|
||||
region);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private static int shellExecutionTimeout(Map<String, List<String>> parameters) {
|
||||
if (!parameters.containsKey("executionTimeout")) {
|
||||
return DEFAULT_SHELL_EXECUTION_TIMEOUT_SECONDS;
|
||||
}
|
||||
List<String> values = parameters.get("executionTimeout");
|
||||
if (values.size() != 1 || !values.getFirst().matches("[1-9][0-9]{0,5}")) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
int seconds = Integer.parseInt(values.getFirst());
|
||||
if (seconds > MAX_SHELL_EXECUTION_TIMEOUT_SECONDS) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
return seconds;
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> parseShellParameters(JsonNode node) {
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
Map<String, List<String>> parameters = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> field : node.properties()) {
|
||||
if (!field.getValue().isArray()) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode value : field.getValue()) {
|
||||
if (!value.isTextual()) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
values.add(value.textValue());
|
||||
}
|
||||
parameters.put(field.getKey(), values);
|
||||
}
|
||||
List<String> commands = parameters.get("commands");
|
||||
if (commands == null || commands.isEmpty()) {
|
||||
throw invalidShellParameters();
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private static AwsException invalidShellParameters() {
|
||||
return new AwsException("InvalidParameters",
|
||||
"AWS-RunShellScript requires at least one command and string-list parameters; "
|
||||
+ "executionTimeout must contain one integer from 1 to 172800.", 400);
|
||||
}
|
||||
|
||||
private static void validateTimeoutSeconds(int timeoutSeconds) {
|
||||
if (timeoutSeconds < MIN_TIMEOUT_SECONDS) {
|
||||
throw new AwsException(
|
||||
@@ -573,6 +631,7 @@ public class SsmCommandService implements Resettable {
|
||||
String documentName,
|
||||
Map<String, List<String>> parameters,
|
||||
int timeoutSeconds,
|
||||
int documentTimeoutDefault,
|
||||
String region) {
|
||||
CompletableFuture.runAsync(() -> RequestScopes.runAs(accountId, region, () -> {
|
||||
String invKey = invocationKey(region, commandId, instanceId);
|
||||
@@ -593,7 +652,7 @@ public class SsmCommandService implements Resettable {
|
||||
invocation.setStatusDetails(statusDetails("Pending"));
|
||||
invocationStore.put(invKey, invocation);
|
||||
}
|
||||
queueMessage(commandId, instanceId, documentName, parameters, timeoutSeconds, region);
|
||||
queueMessage(commandId, instanceId, documentName, parameters, documentTimeoutDefault, region);
|
||||
updateCommandStatus(commandId, region);
|
||||
return;
|
||||
}
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
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 io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.reset;
|
||||
|
||||
abstract class SsmCommandIntegrationFixture {
|
||||
@Inject protected StorageFactory storageFactory;
|
||||
@Inject protected SsmCommandService commandService;
|
||||
@InjectMock protected SsmDirectCommandExecutor executor;
|
||||
@TestHTTPResource protected URI endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void setupSsmFixture() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
reset(executor);
|
||||
}
|
||||
|
||||
protected Response call(String account, String region, String target, Object body) {
|
||||
return given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EnforcementFixtures.auth(account, region, "ssm"))
|
||||
.header("X-Amz-Target", target).body(body).post("/");
|
||||
}
|
||||
|
||||
protected void cleanupCommands(String account, String region, String instance) {
|
||||
RequestScopes.runAs(account, region, () -> {
|
||||
List<Command> owned = commandService.listCommands(null, instance, region);
|
||||
assertAll("remove queued and polled correlations and every owned record",
|
||||
() -> commandService.failActiveInvocationsForInstance(region, instance, "fixture cleanup"),
|
||||
() -> assertAll(owned.stream().map(command -> (Executable) () ->
|
||||
deleteCommandRecords(account, region, command.getCommandId(), instance))));
|
||||
});
|
||||
}
|
||||
|
||||
protected void deleteCommand(String account, String region, String command, String instance) {
|
||||
assertAll("remove owned queue, command and invocation",
|
||||
() -> RequestScopes.runAs(account, region, () ->
|
||||
commandService.failActiveInvocationsForInstance(region, instance, "fixture cleanup")),
|
||||
() -> deleteCommandRecords(account, region, command, instance));
|
||||
}
|
||||
|
||||
private void deleteCommandRecords(String account, String region, String command, String instance) {
|
||||
AccountAwareStorageBackend<Command> commands = storageFactory.create(
|
||||
"ssm", "ssm-commands.json", new TypeReference<>() {});
|
||||
AccountAwareStorageBackend<CommandInvocation> invocations = storageFactory.create(
|
||||
"ssm", "ssm-invocations.json", new TypeReference<>() {});
|
||||
String key = region + "::" + command;
|
||||
assertAll("remove both owned records",
|
||||
() -> {
|
||||
commands.deleteForAccount(account, key);
|
||||
assertTrue(commands.getForAccount(account, key).isEmpty());
|
||||
},
|
||||
() -> {
|
||||
invocations.deleteForAccount(account, key + "::" + instance);
|
||||
assertTrue(invocations.getForAccount(account, key + "::" + instance).isEmpty());
|
||||
});
|
||||
}
|
||||
}
|
||||
+13
-12
@@ -83,7 +83,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "hello\n", "", 0, start, end)));
|
||||
|
||||
@@ -233,7 +233,8 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
"InstanceIds": ["i-timeout"],
|
||||
"DocumentName": "AWS-RunShellScript",
|
||||
"Parameters": {
|
||||
"commands": ["sleep 100"]
|
||||
"commands": ["sleep 100"],
|
||||
"executionTimeout": ["30"]
|
||||
},
|
||||
"TimeoutSeconds": 30
|
||||
}
|
||||
@@ -270,7 +271,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "done\n", "", 0, start, end)));
|
||||
|
||||
@@ -346,7 +347,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-race"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-race"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "done\n", "", 0, start, end)));
|
||||
|
||||
@@ -437,7 +438,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
String instanceId = "i-" + i;
|
||||
instanceIds.add(instanceId);
|
||||
when(executor.supports(any(), eq(instanceId), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq(instanceId), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq(instanceId), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
barrier.await(5, TimeUnit.SECONDS);
|
||||
return Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
@@ -472,7 +473,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.supports(any(), eq("i-agent"), eq("AWS-RunShellScript"))).thenReturn(false);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "done\n", "", 0, start, end)));
|
||||
|
||||
@@ -514,7 +515,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
started.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
@@ -554,7 +555,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
void directExecutionThatBecomesUnsupportedFallsBackToAgentQueue() throws Exception {
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
SsmCommandService service = new SsmCommandService(
|
||||
@@ -587,7 +588,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
String stdout = "o".repeat(24_010) + "tail";
|
||||
String stderr = "e".repeat(8_010) + "tail";
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Failed", stdout, stderr, 1, Instant.parse("2026-06-07T00:00:00Z"), Instant.parse("2026-06-07T00:00:01Z"))));
|
||||
|
||||
@@ -626,7 +627,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicBoolean ranOnPlatformThread = new AtomicBoolean();
|
||||
when(executor.supports(any(), any(), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), any(), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), any(), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
if (!Thread.currentThread().isVirtual()) {
|
||||
ranOnPlatformThread.set(true);
|
||||
@@ -673,7 +674,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Thread> executionThread = new AtomicReference<>();
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
executionThread.set(Thread.currentThread());
|
||||
executing.countDown();
|
||||
@@ -714,7 +715,7 @@ class SsmCommandServiceDirectExecutionTest {
|
||||
Instant start = Instant.parse("2026-06-07T00:00:00Z");
|
||||
Instant end = Instant.parse("2026-06-07T00:00:01Z");
|
||||
when(executor.supports(any(), eq("i-container"), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(any(), eq("i-container"), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
executionThread.set(Thread.currentThread());
|
||||
executing.countDown();
|
||||
|
||||
+5
-45
@@ -6,21 +6,14 @@ import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
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 io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
@@ -32,24 +25,13 @@ import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class SsmDirectCommandAccountIntegrationTest {
|
||||
@Inject StorageFactory storageFactory;
|
||||
class SsmDirectCommandAccountIntegrationTest extends SsmCommandIntegrationFixture {
|
||||
@Inject RegionResolver regionResolver;
|
||||
@InjectMock SsmDirectCommandExecutor executor;
|
||||
@Inject SsmCommandService commandService;
|
||||
@TestHTTPResource URI endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
reset(executor);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
@@ -67,7 +49,7 @@ class SsmDirectCommandAccountIntegrationTest {
|
||||
AtomicReference<String> workerRegion = new AtomicReference<>();
|
||||
AtomicReference<String> workerPartition = new AtomicReference<>();
|
||||
when(executor.supports(account, instance, "AWS-RunShellScript")).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq(account), eq(instance), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(eq(account), eq(instance), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
worker.set(Thread.currentThread());
|
||||
workerAccount.set(regionResolver.getAccountId());
|
||||
@@ -141,7 +123,7 @@ class SsmDirectCommandAccountIntegrationTest {
|
||||
AtomicReference<Thread> blockedWorker = new AtomicReference<>();
|
||||
AtomicReference<Thread> otherWorker = new AtomicReference<>();
|
||||
when(executor.supports(anyString(), eq(instance), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(anyString(), eq(instance), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(anyString(), eq(instance), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
assertEquals(invocation.getArgument(0), regionResolver.getAccountId());
|
||||
if (account.equals(regionResolver.getAccountId()) && region.equals(regionResolver.getRegion())) {
|
||||
@@ -320,7 +302,7 @@ class SsmDirectCommandAccountIntegrationTest {
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
AtomicReference<Thread> worker = new AtomicReference<>();
|
||||
when(executor.supports(account, instance, "AWS-RunShellScript")).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq(account), eq(instance), eq("AWS-RunShellScript"), any(), eq(60)))
|
||||
when(executor.executeIfSupported(eq(account), eq(instance), eq("AWS-RunShellScript"), any(), eq(3600)))
|
||||
.thenAnswer(invocation -> {
|
||||
worker.set(Thread.currentThread());
|
||||
entered.countDown();
|
||||
@@ -360,25 +342,6 @@ class SsmDirectCommandAccountIntegrationTest {
|
||||
assertTrue(invocations.getForAccount(account, key + "::" + instance).isPresent());
|
||||
}
|
||||
|
||||
private void deleteCommand(String account, String region, String commandId, String instance) {
|
||||
AccountAwareStorageBackend<Command> commands = storageFactory.create(
|
||||
"ssm", "ssm-commands.json", new TypeReference<>() {});
|
||||
AccountAwareStorageBackend<CommandInvocation> invocations = storageFactory.create(
|
||||
"ssm", "ssm-invocations.json", new TypeReference<>() {});
|
||||
String key = region + "::" + commandId;
|
||||
assertAll("remove owned queue, command and invocation",
|
||||
() -> RequestScopes.runAs(account, region, () ->
|
||||
commandService.failActiveInvocationsForInstance(region, instance, "fixture cleanup")),
|
||||
() -> {
|
||||
commands.deleteForAccount(account, key);
|
||||
assertTrue(commands.getForAccount(account, key).isEmpty());
|
||||
},
|
||||
() -> {
|
||||
invocations.deleteForAccount(account, key + "::" + instance);
|
||||
assertTrue(invocations.getForAccount(account, key + "::" + instance).isEmpty());
|
||||
});
|
||||
}
|
||||
|
||||
private void joinWorker(AtomicReference<Thread> worker) throws InterruptedException {
|
||||
if (worker.get() != null) {
|
||||
worker.get().join(5000);
|
||||
@@ -387,9 +350,6 @@ class SsmDirectCommandAccountIntegrationTest {
|
||||
}
|
||||
|
||||
private Response call(String account, String region, String action, Map<String, Object> body) {
|
||||
return given().port(endpoint.getPort()).contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EnforcementFixtures.auth(account, region, "ssm"))
|
||||
.header("X-Amz-Target", action).body(body).post("/")
|
||||
.then().statusCode(200).extract().response();
|
||||
return super.call(account, region, action, body).then().statusCode(200).extract().response();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -419,7 +419,7 @@ class SsmSendCommandIntegrationTest {
|
||||
eq("i-direct-container"),
|
||||
eq("AWS-RunShellScript"),
|
||||
any(),
|
||||
eq(60)))
|
||||
eq(3600)))
|
||||
.thenReturn(Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "direct-output\n", "", 0, start, end)));
|
||||
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Command;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class SsmShellExecutionBudgetIntegrationTest extends SsmCommandIntegrationFixture {
|
||||
private static final String ACCOUNT = "222222222222";
|
||||
private static final String REGION = "us-west-2";
|
||||
@Inject ObjectMapper mapper;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"0,3600", "5,5", "172800,172800"})
|
||||
void publicResponseAndActualAgentPayloadKeepSeparateBudgets(int supplied, int execution) throws Exception {
|
||||
String instance = "i-budget-" + UUID.randomUUID();
|
||||
ObjectNode request = request(instance);
|
||||
if (supplied != 0) {
|
||||
request.withObject("Parameters").putArray("executionTimeout").add(Integer.toString(supplied));
|
||||
}
|
||||
try {
|
||||
Response response = call("AmazonSSM.SendCommand", request);
|
||||
assertEquals(200, response.statusCode());
|
||||
String id = response.jsonPath().getString("Command.CommandId");
|
||||
assertNotNull(id);
|
||||
Response poll = call("AmazonSSMMessageDeliveryService.GetMessages", mapper.valueToTree(
|
||||
Map.of("Destination", instance, "MessagesRequestId", "budget")));
|
||||
assertEquals(200, poll.statusCode());
|
||||
assertEquals(1, poll.jsonPath().getList("Messages").size());
|
||||
JsonNode payload = mapper.readTree(Base64.getDecoder().decode(
|
||||
poll.jsonPath().getString("Messages[0].Payload")));
|
||||
JsonNode command = mapper.readTree(response.asByteArray()).path("Command");
|
||||
assertAll("public metadata and delivered document",
|
||||
() -> assertEquals(30, command.path("TimeoutSeconds").asInt()),
|
||||
() -> assertEquals(30 + execution,
|
||||
command.path("ExpiresAfter").asDouble() - command.path("RequestedDateTime").asDouble(),
|
||||
0.001),
|
||||
() -> assertEquals("3600", payload.at("/DocumentContent/parameters/executionTimeout/default")
|
||||
.asText()),
|
||||
() -> {
|
||||
if (supplied != 0) {
|
||||
assertEquals(Integer.toString(supplied),
|
||||
payload.at("/Parameters/executionTimeout/0").asText());
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
cleanup(instance);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"[]", "[\"0\"]", "[\"-1\"]", "[\"172801\"]", "[\"999999999999999999999\"]",
|
||||
"[\"01\"]", "[\"+5\"]", "[\" 5\"]", "[\"5.0\"]", "[\"5\",\"6\"]",
|
||||
"null", "\"5\"", "[5]", "[null]", "{}"
|
||||
})
|
||||
void malformedExplicitBudgetCannotTurnIntoTheDefault(String json) throws Exception {
|
||||
String instance = "i-budget-" + UUID.randomUUID();
|
||||
ObjectNode request = request(instance);
|
||||
request.withObject("Parameters").set("executionTimeout", mapper.readTree(json));
|
||||
try {
|
||||
Response response = call("AmazonSSM.SendCommand", request);
|
||||
List<Command> commands = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> commandService.listCommands(null, instance, REGION));
|
||||
assertAll("refuse before any allocation or dispatch",
|
||||
() -> assertEquals(400, response.statusCode()),
|
||||
() -> assertEquals("InvalidParameters", response.jsonPath().getString("__type")),
|
||||
() -> assertTrue(commands.isEmpty()),
|
||||
() -> verifyNoInteractions(executor));
|
||||
request.withObject("Parameters").putArray("executionTimeout").add("5");
|
||||
Response retry = call("AmazonSSM.SendCommand", request);
|
||||
assertEquals(200, retry.statusCode());
|
||||
JsonNode command = mapper.readTree(retry.asByteArray()).path("Command");
|
||||
assertEquals(35, command.path("ExpiresAfter").asDouble()
|
||||
- command.path("RequestedDateTime").asDouble(), 0.001);
|
||||
} finally {
|
||||
cleanup(instance);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{\"bad\":\"shape\"}", "5", "null"})
|
||||
void malformedSiblingCannotEraseAValidExplicitBudget(String commands) throws Exception {
|
||||
String instance = "i-budget-" + UUID.randomUUID();
|
||||
ObjectNode request = request(instance);
|
||||
request.withObject("Parameters").putArray("executionTimeout").add("5");
|
||||
request.withObject("Parameters").set("commands", mapper.readTree(commands));
|
||||
try {
|
||||
Response response = call("AmazonSSM.SendCommand", request);
|
||||
assertAll("parameters conversion must not discard the explicit limit",
|
||||
() -> assertEquals(400, response.statusCode()),
|
||||
() -> assertEquals("InvalidParameters", response.jsonPath().getString("__type")),
|
||||
() -> assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> commandService.listCommands(null, instance, REGION)).isEmpty()),
|
||||
() -> verifyNoInteractions(executor));
|
||||
} finally {
|
||||
cleanup(instance);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"missing", "null", "{}", "{\"commands\":[]}"})
|
||||
void shellRequiresAtLeastOneCommandBeforeAllocation(String parameters) throws Exception {
|
||||
String instance = "i-budget-" + UUID.randomUUID();
|
||||
ObjectNode request = request(instance);
|
||||
if ("missing".equals(parameters)) {
|
||||
request.remove("Parameters");
|
||||
} else {
|
||||
request.set("Parameters", mapper.readTree(parameters));
|
||||
}
|
||||
try {
|
||||
Response response = call("AmazonSSM.SendCommand", request);
|
||||
assertAll("required script is checked before allocation or dispatch",
|
||||
() -> assertEquals(400, response.statusCode()),
|
||||
() -> assertEquals("InvalidParameters", response.jsonPath().getString("__type")),
|
||||
() -> assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> commandService.listCommands(null, instance, REGION)).isEmpty()),
|
||||
() -> verifyNoInteractions(executor));
|
||||
Response retry = call("AmazonSSM.SendCommand", request(instance));
|
||||
assertEquals(200, retry.statusCode());
|
||||
} finally {
|
||||
cleanup(instance);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode request(String instance) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("DocumentName", "AWS-RunShellScript");
|
||||
request.putArray("InstanceIds").add(instance);
|
||||
request.put("TimeoutSeconds", 30);
|
||||
request.putObject("Parameters").putArray("commands").add("echo budget");
|
||||
return request;
|
||||
}
|
||||
|
||||
private Response call(String target, JsonNode request) {
|
||||
return super.call(ACCOUNT, REGION, target, request.toString());
|
||||
}
|
||||
|
||||
private void cleanup(String instance) {
|
||||
cleanupCommands(ACCOUNT, REGION, instance);
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package io.github.hectorvent.floci.services.ssm;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Command;
|
||||
import io.github.hectorvent.floci.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class SsmShellExecutionBudgetTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"0,3600", "5,5", "1,1", "172800,172800"})
|
||||
void directWorkerUsesDocumentExecutionBudget(int supplied, int expected) throws Exception {
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn("000000000000");
|
||||
when(resolver.getRegion()).thenReturn("us-east-1");
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
AtomicInteger captured = new AtomicInteger();
|
||||
AtomicReference<Thread> worker = new AtomicReference<>();
|
||||
when(executor.supports(any(), anyString(), eq("AWS-RunShellScript"))).thenReturn(true);
|
||||
when(executor.executeIfSupported(any(), anyString(), eq("AWS-RunShellScript"), any(), anyInt()))
|
||||
.thenAnswer(call -> {
|
||||
worker.set(Thread.currentThread());
|
||||
captured.set(call.getArgument(4));
|
||||
return Optional.of(new SsmDirectCommandExecutor.ExecutionResult(
|
||||
"Success", "ok", "", 0, Instant.now(), Instant.now()));
|
||||
});
|
||||
SsmCommandService service = new SsmCommandService(new InMemoryStorageFactory("000000000000"),
|
||||
mapper, resolver, executor);
|
||||
try {
|
||||
Command command = service.sendCommand(request(supplied), "us-east-1");
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> worker.get() != null);
|
||||
worker.get().join(5000);
|
||||
assertFalse(worker.get().isAlive());
|
||||
assertAll("delivery and execution are separate",
|
||||
() -> assertEquals(expected, captured.get()),
|
||||
() -> assertEquals(30, command.getTimeoutSeconds()),
|
||||
() -> assertEquals(30L + expected, Duration.between(
|
||||
command.getRequestedDateTime(), command.getExpiresAfter()).toSeconds()),
|
||||
() -> assertEquals("Success", service.getCommandInvocation(
|
||||
command.getCommandId(), "i-budget", "us-east-1").getStatus()));
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false,0,3600", "false,5,5", "true,0,3600", "true,5,5"})
|
||||
void queuedAndDirectFallbackKeepThePublicDocumentDefault(boolean fallback, int supplied, int expected)
|
||||
throws Exception {
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn("000000000000");
|
||||
when(resolver.getRegion()).thenReturn("us-east-1");
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
AtomicReference<Thread> worker = new AtomicReference<>();
|
||||
AtomicInteger captured = new AtomicInteger();
|
||||
when(executor.supports(any(), anyString(), eq("AWS-RunShellScript"))).thenReturn(fallback);
|
||||
when(executor.executeIfSupported(any(), anyString(), eq("AWS-RunShellScript"), any(), anyInt()))
|
||||
.thenAnswer(call -> {
|
||||
worker.set(Thread.currentThread());
|
||||
captured.set(call.getArgument(4));
|
||||
return Optional.empty();
|
||||
});
|
||||
SsmCommandService service = new SsmCommandService(new InMemoryStorageFactory("000000000000"),
|
||||
mapper, resolver, executor);
|
||||
try {
|
||||
Command command = service.sendCommand(request(supplied), "us-east-1");
|
||||
if (fallback) {
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> worker.get() != null);
|
||||
worker.get().join(5000);
|
||||
assertFalse(worker.get().isAlive());
|
||||
}
|
||||
List<Map<String, Object>> messages = service.getMessages("i-budget", "budget", 30);
|
||||
assertEquals(1, messages.size());
|
||||
JsonNode payload = mapper.readTree(new String(Base64.getDecoder().decode(
|
||||
(String) messages.getFirst().get("Payload")), StandardCharsets.UTF_8));
|
||||
assertAll("fallback retains the effective budget without changing the document default",
|
||||
() -> assertEquals("3600", payload.at("/DocumentContent/parameters/executionTimeout/default")
|
||||
.asText()),
|
||||
() -> assertEquals(30L + expected, Duration.between(
|
||||
command.getRequestedDateTime(), command.getExpiresAfter()).toSeconds()),
|
||||
() -> {
|
||||
if (fallback) {
|
||||
assertEquals(expected, captured.get());
|
||||
}
|
||||
},
|
||||
() -> {
|
||||
if (supplied != 0) {
|
||||
assertEquals(Integer.toString(supplied),
|
||||
payload.at("/Parameters/executionTimeout/0").asText());
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {1, 30})
|
||||
void internalHookKeepsItsSuppliedExecutionBudget(int timeout) throws Exception {
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn("000000000000");
|
||||
when(resolver.getRegion()).thenReturn("us-east-1");
|
||||
SsmDirectCommandExecutor executor = mock(SsmDirectCommandExecutor.class);
|
||||
SsmCommandService service = new SsmCommandService(new InMemoryStorageFactory("000000000000"),
|
||||
mapper, resolver, executor);
|
||||
try {
|
||||
String id = service.sendCommandToInstance("i-budget", "AWS-RunShellScript",
|
||||
Map.of("commands", List.of("echo hook")), timeout, "us-east-1");
|
||||
Command command = service.listCommands(id, null, "us-east-1").getFirst();
|
||||
JsonNode payload = mapper.readTree(Base64.getDecoder().decode((String)
|
||||
service.getMessages("i-budget", "hook", 30).getFirst().get("Payload")));
|
||||
assertEquals(timeout, command.getTimeoutSeconds());
|
||||
assertEquals(timeout, Duration.between(command.getRequestedDateTime(), command.getExpiresAfter())
|
||||
.toSeconds());
|
||||
assertEquals(Integer.toString(timeout),
|
||||
payload.at("/DocumentContent/parameters/executionTimeout/default").asText());
|
||||
verifyNoInteractions(executor);
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"AWS-RunPowerShellScript", "CustomDocument"})
|
||||
void nonShellBudgetHandlingRemainsUnchanged(String document) throws Exception {
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn("000000000000");
|
||||
when(resolver.getRegion()).thenReturn("us-east-1");
|
||||
SsmCommandService service = new SsmCommandService(new InMemoryStorageFactory("000000000000"),
|
||||
mapper, resolver, mock(SsmDirectCommandExecutor.class));
|
||||
try {
|
||||
ObjectNode request = request(5);
|
||||
request.put("DocumentName", document);
|
||||
Command command = service.sendCommand(request, "us-east-1");
|
||||
JsonNode payload = mapper.readTree(Base64.getDecoder().decode((String)
|
||||
service.getMessages("i-budget", "other", 30).getFirst().get("Payload")));
|
||||
assertEquals(30, Duration.between(command.getRequestedDateTime(), command.getExpiresAfter())
|
||||
.toSeconds());
|
||||
assertEquals("30", payload.at("/DocumentContent/parameters/executionTimeout/default").asText());
|
||||
assertEquals("5", payload.at("/Parameters/executionTimeout/0").asText());
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedDeliveryAndExecutionProduceTheDefaultTotal() {
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenReturn("000000000000");
|
||||
SsmCommandService service = new SsmCommandService(new InMemoryStorageFactory("000000000000"),
|
||||
mapper, resolver, mock(SsmDirectCommandExecutor.class));
|
||||
try {
|
||||
ObjectNode request = request(0);
|
||||
request.remove("TimeoutSeconds");
|
||||
Command command = service.sendCommand(request, "us-east-1");
|
||||
assertEquals(3600, command.getTimeoutSeconds());
|
||||
assertEquals(7200, Duration.between(command.getRequestedDateTime(), command.getExpiresAfter())
|
||||
.toSeconds());
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode request(int supplied) {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.put("DocumentName", "AWS-RunShellScript");
|
||||
request.putArray("InstanceIds").add("i-budget");
|
||||
request.put("TimeoutSeconds", 30);
|
||||
ObjectNode parameters = request.putObject("Parameters");
|
||||
parameters.putArray("commands").add("echo budget");
|
||||
if (supplied != 0) {
|
||||
parameters.putArray("executionTimeout").add(Integer.toString(supplied));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user