From 8921ca11182ffd1fb8ac4ddb13cb855a24a008a7 Mon Sep 17 00:00:00 2001 From: Allen Sanborn Date: Wed, 9 Sep 2026 21:36:02 -0500 Subject: [PATCH] feat(ec2): answer MonitorInstances and UnmonitorInstances (#3319) * feat(ec2): answer MonitorInstances and UnmonitorInstances Both actions returned UnsupportedOperation. Detailed monitoring is a CloudWatch billing switch with no behaviour an emulator can meaningfully model, which is presumably why it was left out -- but declining the call is more costly than answering it, because one unsupported action fails an entire deployment regardless of how much of the rest of it succeeded. An aws_instance declared with monitoring = true calls MonitorInstances immediately after RunInstances, so the whole configuration is discarded over a flag with no state behind it. Acknowledge the requested state and echo every instance the caller named. Nothing is stored: there is no monitoring data to serve, and DescribeInstances does not report a monitoring state today, so persisting one would only create a second place for it to be wrong. Reference: the MonitorInstances response shape -- instancesSet of InstanceMonitoring, each with instanceId and monitoring.state, plus requestId -- https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_MonitorInstances.html https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UnmonitorInstances.html One deliberate deviation: AWS reports state "pending" because the change is applied asynchronously, then settles on "enabled". The emulator has nothing to settle, so it reports the terminal state directly. Reporting "pending" for a transition that would never complete would be worse for any client that polls. * fix(ec2): reject monitoring for an instance that does not exist, and store the state Two problems, both of which made the action answer confidently about something it had not done. The handler echoed every InstanceId back with a 200 without resolving it, and did not even take a region to resolve it with. Naming an instance that does not exist got a success response saying its monitoring was enabled. Every other instance operation raises InvalidInstanceID.NotFound; this now does too, by delegating to the service and resolving each id through getRequiredInstance, which is the same shape stopInstances and the rest already use. The state was also never stored. Instance already carries a monitoring member and DescribeInstances already emits it, so MonitorInstances reported "enabled" while every subsequent read still said "disabled". The state now persists, so the round trip agrees with itself. The previous tests asserted the old behaviour: they passed a made-up instance id and expected 200. They are rewritten to launch a real instance, and two cases are added for the not-found path plus one that reads the state back through DescribeInstances. * test(ec2): name the monitoring suite for what it is, an integration test It is a @QuarkusTest driving the HTTP endpoint, and the repository's dominant convention for those is *IntegrationTest: 607 of the 736 @QuarkusTest classes on main follow it. Renaming rather than arguing, since the evidence here points at the convention. * test(ec2): cover monitoring through the SDK path, not only the Query wire AGENTS.md asks for management APIs to be validated with SDK clients and "not only handcrafted HTTP requests". The Java test drives the Query endpoint with RestAssured, which is right for pinning exact XML but does not exercise the path aws_instance actually takes: monitoring = true calls MonitorInstances through the SDK, which parses the response rather than reading whatever XML we happen to emit. Three cases in the awscli suite, which is where EC2 SDK coverage already lives: enable and read back through DescribeInstances, disable and read back, and reject an instance that does not exist. The read-backs are the point rather than padding: the bug this guards against was the handler answering "enabled" while every later read still said "disabled", which asserting on the mutating call's own response cannot see. Verified as far as this machine allows. run-instances, the teardown and the harness plumbing all work against a local emulator; the three assertions themselves cannot pass here because the released 2.0.1 image predates MonitorInstances, which is the gap this PR closes. They run against the branch build in CI. --- .../sdk-test-awscli/test/ec2.bats | 53 +++++++ .../floci/services/ec2/Ec2QueryHandler.java | 29 ++++ .../floci/services/ec2/Ec2Service.java | 28 ++++ .../Ec2MonitorInstancesIntegrationTest.java | 138 ++++++++++++++++++ 4 files changed, 248 insertions(+) create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MonitorInstancesIntegrationTest.java diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.bats index 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 + fi if [ -n "$PREFIX_LIST_ID" ]; then aws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || true fi @@ -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.java index 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 p, String region, String action, + boolean enabled) { + List 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 p, String region) { List ids = getList(p, "InstanceId"); List> 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.java index 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. + * + *

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. + * + *

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 setInstanceMonitoring(String region, List instanceIds, boolean enabled) { + ensureDefaultResources(region); + List 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> stopInstances(String region, List instanceIds) { ensureDefaultResources(region); List> 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.java new file mode 100644 index 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 MonitorInstances + */ +@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")); + } +}