Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): answer MonitorInstances and UnmonitorInstances (#3319)
Allen Sanborn8921ca11182f
diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.batsindex 1785574c05..e98591d4b4 100644--- a/compatibility-tests/sdk-test-awscli/test/ec2.bats+++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats@@ -12,9 +12,13 @@ setup() {TGW_ATTACHMENT_ID=""TGW_VPC_ID=""TGW_ROUTE_TABLE_ID=""+ MONITOR_INSTANCE_ID=""}teardown() {+ if [ -n "$MONITOR_INSTANCE_ID" ]; then+ aws_cmd ec2 terminate-instances --instance-ids "$MONITOR_INSTANCE_ID" >/dev/null 2>&1 || true+ fiif [ -n "$PREFIX_LIST_ID" ]; thenaws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || truefi@@ -606,3 +610,52 @@ create_attachment_fixture() {count=$(json_get "$output" '.Routes | length')[ "$count" = "2" ]}++# Monitoring goes through the SDK, not just the raw Query wire, because that is the+# path aws_instance takes: `monitoring = true` calls MonitorInstances, and the SDK+# parses the response rather than reading the XML we happen to emit. AGENTS.md asks+# for management APIs to be validated with SDK clients and not only handcrafted HTTP.++launch_monitor_instance() {+ run aws_cmd ec2 run-instances \+ --image-id ami-0abcdef1234567890 --instance-type t3.micro \+ --count 1+ assert_success+ MONITOR_INSTANCE_ID=$(json_get "$output" '.Instances[0].InstanceId')+ [ -n "$MONITOR_INSTANCE_ID" ]+}++@test "EC2: monitor-instances reports enabled and the state survives to describe" {+ launch_monitor_instance++ run aws_cmd ec2 monitor-instances --instance-ids "$MONITOR_INSTANCE_ID"+ assert_success+ [ "$(json_get "$output" '.InstanceMonitorings[0].InstanceId')" = "$MONITOR_INSTANCE_ID" ]+ [ "$(json_get "$output" '.InstanceMonitorings[0].Monitoring.State')" = "enabled" ]++ # Read it back rather than trusting the mutating call's own response: the bug this+ # guards against was answering "enabled" while every later read still said disabled.+ run aws_cmd ec2 describe-instances --instance-ids "$MONITOR_INSTANCE_ID"+ assert_success+ [ "$(json_get "$output" '.Reservations[0].Instances[0].Monitoring.State')" = "enabled" ]+}++@test "EC2: unmonitor-instances reports disabled and the state survives to describe" {+ launch_monitor_instance+ run aws_cmd ec2 monitor-instances --instance-ids "$MONITOR_INSTANCE_ID"+ assert_success++ run aws_cmd ec2 unmonitor-instances --instance-ids "$MONITOR_INSTANCE_ID"+ assert_success+ [ "$(json_get "$output" '.InstanceMonitorings[0].Monitoring.State')" = "disabled" ]++ run aws_cmd ec2 describe-instances --instance-ids "$MONITOR_INSTANCE_ID"+ assert_success+ [ "$(json_get "$output" '.Reservations[0].Instances[0].Monitoring.State')" = "disabled" ]+}++@test "EC2: monitor-instances rejects an instance that does not exist" {+ run aws_cmd ec2 monitor-instances --instance-ids i-1234567890abcdef0+ assert_failure+ [[ "$output" == *"InvalidInstanceID.NotFound"* ]]+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 5cfdd2e5c3..793a3de2d7 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -67,6 +67,8 @@ public class Ec2QueryHandler {case "StartInstances" -> handleStartInstances(params, region);case "StopInstances" -> handleStopInstances(params, region);case "RebootInstances" -> handleRebootInstances(params, region);+ case "MonitorInstances" -> handleMonitoring(params, region, "MonitorInstances", true);+ case "UnmonitorInstances" -> handleMonitoring(params, region, "UnmonitorInstances", false);case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region);case "DescribeInstanceAttribute" -> handleDescribeInstanceAttribute(params, region);case "ModifyInstanceAttribute" -> handleModifyInstanceAttribute(params, region);@@ -1127,6 +1129,33 @@ public class Ec2QueryHandler {return xmlResponse(xml.build());}+ /**+ * Detailed monitoring is a CloudWatch billing switch with no emulated behaviour behind+ * it, so this acknowledges the requested state without storing it. Answering matters+ * because a single unsupported call fails an entire {@code terraform apply}: an+ * {@code aws_instance} with {@code monitoring = true} calls MonitorInstances right+ * after RunInstances, and rejecting it discards everything else the module built.+ */+ private Response handleMonitoring(MultivaluedMap<String, String> p, String region, String action,+ boolean enabled) {+ List<String> changed = service.setInstanceMonitoring(region, getList(p, "InstanceId"), enabled);+ String state = enabled ? "enabled" : "disabled";+ XmlBuilder xml = new XmlBuilder()+ .start(action + "Response", AwsNamespaces.EC2)+ .elem("requestId", UUID.randomUUID().toString())+ .start("instancesSet");+ for (String id : changed) {+ xml.start("item")+ .elem("instanceId", id)+ .start("monitoring")+ .elem("state", state)+ .end("monitoring")+ .end("item");+ }+ xml.end("instancesSet").end(action + "Response");+ return xmlResponse(xml.build());+ }+private Response handleStartInstances(MultivaluedMap<String, String> p, String region) {List<String> ids = getList(p, "InstanceId");List<Map<String, String>> changes = service.startInstances(region, ids);diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 4c20b5e0b1..e2c3bcf676 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -2881,6 +2881,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {}}+ /**+ * Set the monitoring state of each named instance, in the order given.+ *+ * <p>Every id is resolved through {@link #getRequiredInstance}, so naming an instance that+ * does not exist in this region raises {@code InvalidInstanceID.NotFound} exactly as the+ * other instance operations do. Echoing an unknown id back with a 200 would be worse than+ * not implementing the action at all: the caller is told its request took effect on an+ * instance that is not there.+ *+ * <p>The state is stored on the instance rather than only echoed, so a following+ * DescribeInstances reports it. Instance already carries a {@code monitoring} member and+ * DescribeInstances already emits it, so echoing without storing left MonitorInstances+ * saying "enabled" while every subsequent read still said "disabled".+ *+ * @return the ids that were changed, in request order+ */+ public List<String> setInstanceMonitoring(String region, List<String> instanceIds, boolean enabled) {+ ensureDefaultResources(region);+ List<String> changed = new ArrayList<>();+ for (String id : instanceIds) {+ Instance inst = getRequiredInstance(region, id);+ inst.setMonitoring(enabled ? "enabled" : "disabled");+ instances.put(key(region, id), inst);+ changed.add(id);+ }+ return changed;+ }+public List<Map<String, String>> stopInstances(String region, List<String> instanceIds) {ensureDefaultResources(region);List<Map<String, String>> result = new ArrayList<>();diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MonitorInstancesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MonitorInstancesIntegrationTest.javanew file mode 100644index 0000000000..b13d86d125--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MonitorInstancesIntegrationTest.java@@ -0,0 +1,138 @@+package io.github.hectorvent.floci.services.ec2;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++/**+ * MonitorInstances and UnmonitorInstances. Detailed monitoring is a CloudWatch billing+ * switch with no emulated behaviour behind it, but the calls have to be answered and+ * answered honestly: one unsupported action fails a whole deployment, and an action that+ * reports success for an instance that does not exist is worse than one that is missing.+ *+ * @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_MonitorInstances.html">MonitorInstances</a>+ */+@QuarkusTest+class Ec2MonitorInstancesIntegrationTest {++ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";+ private static final String INSTANCE = "RunInstancesResponse.instancesSet.item.";++ private String launchInstance() {+ return given()+ .formParam("Action", "RunInstances")+ .formParam("ImageId", "ami-0abcdef1234567890")+ .formParam("InstanceType", "t3.micro")+ .formParam("MinCount", "1")+ .formParam("MaxCount", "1")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().path(INSTANCE + "instanceId");+ }++ private String monitoringStateOf(String instanceId) {+ return given()+ .formParam("Action", "DescribeInstances")+ .formParam("InstanceId.1", instanceId)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("DescribeInstancesResponse.reservationSet.item.instancesSet.item.monitoring.state");+ }++ @Test+ void monitorInstancesReportsMonitoringEnabledForEachInstance() {+ String id = launchInstance();++ given()+ .formParam("Action", "MonitorInstances")+ .formParam("InstanceId.1", id)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("MonitorInstancesResponse.instancesSet.item.instanceId", equalTo(id))+ .body("MonitorInstancesResponse.instancesSet.item.monitoring.state", equalTo("enabled"));+ }++ @Test+ void unmonitorInstancesReportsMonitoringDisabledForEachInstance() {+ String id = launchInstance();++ given()+ .formParam("Action", "UnmonitorInstances")+ .formParam("InstanceId.1", id)+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("UnmonitorInstancesResponse.instancesSet.item.instanceId", equalTo(id))+ .body("UnmonitorInstancesResponse.instancesSet.item.monitoring.state", equalTo("disabled"));+ }++ /**+ * The state has to be stored, not just echoed. Instance already carries a monitoring+ * member and DescribeInstances already emits it, so answering "enabled" while every+ * later read still says "disabled" is the accepted-then-never-returned shape.+ */+ @Test+ void monitoringStateSurvivesToDescribeInstances() {+ String id = launchInstance();+ // A fresh instance reports the AWS default before anything asks for monitoring.+ org.junit.jupiter.api.Assertions.assertEquals("disabled", monitoringStateOf(id));++ given().formParam("Action", "MonitorInstances").formParam("InstanceId.1", id)+ .header("Authorization", AUTH_HEADER)+ .when().post("/").then().statusCode(200);++ org.junit.jupiter.api.Assertions.assertEquals("enabled", monitoringStateOf(id));++ given().formParam("Action", "UnmonitorInstances").formParam("InstanceId.1", id)+ .header("Authorization", AUTH_HEADER)+ .when().post("/").then().statusCode(200);++ org.junit.jupiter.api.Assertions.assertEquals("disabled", monitoringStateOf(id));+ }++ /**+ * Echoing an unknown id back with a 200 tells the caller its request took effect on an+ * instance that is not there. Every other instance operation raises this error.+ */+ @Test+ void monitoringAnInstanceThatDoesNotExistIsRejected() {+ given()+ .formParam("Action", "MonitorInstances")+ .formParam("InstanceId.1", "i-1234567890abcdef0")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("InvalidInstanceID.NotFound"));+ }++ @Test+ void unmonitoringAnInstanceThatDoesNotExistIsRejected() {+ given()+ .formParam("Action", "UnmonitorInstances")+ .formParam("InstanceId.1", "i-1234567890abcdef0")+ .header("Authorization", AUTH_HEADER)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("InvalidInstanceID.NotFound"));+ }+}