diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index cd4524910d..adf1b35354 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -1471,7 +1471,7 @@ public class Ec2QueryHandler { private Response handleTerminateInstances(MultivaluedMap p, String region) { List ids = getList(p, "InstanceId"); - List> changes = service.terminateInstances(region, ids); + List> changes = service.terminateInstances(region, ids, dryRun(p)); return xmlResponse(buildInstanceStateChangeXml("TerminateInstancesResponse", changes)); } @@ -1531,13 +1531,13 @@ public class Ec2QueryHandler { private Response handleStartInstances(MultivaluedMap p, String region) { List ids = getList(p, "InstanceId"); - List> changes = service.startInstances(region, ids); + List> changes = service.startInstances(region, ids, dryRun(p)); return xmlResponse(buildInstanceStateChangeXml("StartInstancesResponse", changes)); } private Response handleStopInstances(MultivaluedMap p, String region) { List ids = getList(p, "InstanceId"); - List> changes = service.stopInstances(region, ids); + List> changes = service.stopInstances(region, ids, dryRun(p)); return xmlResponse(buildInstanceStateChangeXml("StopInstancesResponse", changes)); } @@ -1563,7 +1563,7 @@ public class Ec2QueryHandler { private Response handleRebootInstances(MultivaluedMap p, String region) { List ids = getList(p, "InstanceId"); - service.rebootInstances(region, ids); + service.rebootInstances(region, ids, dryRun(p)); return booleanResponse("RebootInstances"); } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 6db94422ac..25baacc699 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -5207,7 +5207,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public List> terminateInstances(String region, List instanceIds) { + return terminateInstances(region, instanceIds, false); + } + + /** + * As above; with {@code dryRun} every instance must be one TerminateInstances could end, and the + * request is then answered with DryRunOperation, nothing terminated. + */ + public List> terminateInstances(String region, List instanceIds, boolean dryRun) { ensureDefaultResources(region); + if (dryRun) { + instanceIds.forEach(id -> requireEc2ManagedInstance(region, id, "terminated")); + throw dryRunOperation(); + } List> result = new ArrayList<>(); // Every instance named here is going away, so none of them counts as a live dependant of // a capture -- not the ones already processed, which linger as shutting-down while their @@ -5218,11 +5230,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // would silently fall back to the default account. String owner = callerAccountId(); for (String id : instanceIds) { - Instance inst = getRequiredInstance(region, id); - if (isExternalInstance(region, id)) { - throw new AwsException("OperationNotPermitted", - "The instance '" + id + "' is a cluster node and cannot be terminated through EC2", 400); - } + Instance inst = requireEc2ManagedInstance(region, id, "terminated"); if (config.services().ec2().mock() && "pending".equals(inst.getState().getName())) { inst.setState(InstanceState.running()); @@ -5326,14 +5334,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public List> stopInstances(String region, List instanceIds) { + return stopInstances(region, instanceIds, false); + } + + /** + * As above; with {@code dryRun} every instance must be one StopInstances could stop, and the + * request is then answered with DryRunOperation, nothing stopped. + */ + public List> stopInstances(String region, List instanceIds, boolean dryRun) { ensureDefaultResources(region); + if (dryRun) { + instanceIds.forEach(id -> requireEc2ManagedInstance(region, id, "stopped")); + throw dryRunOperation(); + } List> result = new ArrayList<>(); for (String id : instanceIds) { - Instance inst = getRequiredInstance(region, id); - if (isExternalInstance(region, id)) { - throw new AwsException("OperationNotPermitted", - "The instance '" + id + "' is a cluster node and cannot be stopped through EC2", 400); - } + Instance inst = requireEc2ManagedInstance(region, id, "stopped"); if (config.services().ec2().mock() && "pending".equals(inst.getState().getName())) { inst.setState(InstanceState.running()); @@ -5376,6 +5392,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public List> startInstances(String region, List instanceIds) { + return startInstances(region, instanceIds, false); + } + + /** + * As above; with {@code dryRun} every instance must be one StartInstances could start, the vCPU + * quota and Capacity Reservation admission included, and the request is then answered with + * DryRunOperation, nothing started or reserved. + */ + public List> startInstances(String region, List instanceIds, boolean dryRun) { ensureDefaultResources(region); if (config.services().ec2().enforceVcpuQuotas()) { synchronized (privateIpAllocationLock) { @@ -5383,16 +5408,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab Set legacySpot = spotInstanceIds(region); List targets = new ArrayList<>(); for (String id : new LinkedHashSet<>(instanceIds)) { - Instance instance = getRequiredInstance(region, id); - if (isExternalInstance(region, id)) { - throw new AwsException("OperationNotPermitted", - "The instance '" + id + "' is a cluster node and cannot be started through EC2", 400); - } - if ("terminated".equals(instance.getState().getName())) { - throw new AwsException("IncorrectInstanceState", - "The instance '" + id + "' is not in a state from which it can be started.", 400); - } - targets.add(instance); + targets.add(requireStartableInstance(region, id)); } for (Instance instance : targets) { String state = instance.getState().getName(); @@ -5404,18 +5420,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab enforceStandardOnDemandQuota(region, additional); } } + if (dryRun) { + List starting = new ArrayList<>(); + for (String id : instanceIds) { + Instance instance = requireStartableInstance(region, id); + String state = instance.getState().getName(); + if ("stopped".equals(state) || "stopping".equals(state)) { + starting.add(instance); + } + } + // The real start sets each of these pending and admits it into its Capacity Reservation. + acquireCapacity(region, starting, true); + throw dryRunOperation(); + } List> result = new ArrayList<>(); for (String id : instanceIds) { - Instance inst = getRequiredInstance(region, id); - if (isExternalInstance(region, id)) { - throw new AwsException("OperationNotPermitted", - "The instance '" + id + "' is a cluster node and cannot be started through EC2", 400); - } - - if ("terminated".equals(inst.getState().getName())) { - throw new AwsException("IncorrectInstanceState", - "The instance '" + id + "' is not in a state from which it can be started.", 400); - } + Instance inst = requireStartableInstance(region, id); InstanceState prev = inst.getState(); synchronized (capacityReservationLock) { if ("stopped".equals(prev.getName()) || "stopping".equals(prev.getName())) { @@ -5522,13 +5542,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void rebootInstances(String region, List instanceIds) { + rebootInstances(region, instanceIds, false); + } + + /** + * As above; with {@code dryRun} every instance must be one RebootInstances could reboot, and the + * request is then answered with DryRunOperation, nothing rebooted. + */ + public void rebootInstances(String region, List instanceIds, boolean dryRun) { ensureDefaultResources(region); + if (dryRun) { + instanceIds.forEach(id -> requireEc2ManagedInstance(region, id, "rebooted")); + throw dryRunOperation(); + } for (String id : instanceIds) { - Instance inst = getRequiredInstance(region, id); - if (isExternalInstance(region, id)) { - throw new AwsException("OperationNotPermitted", - "The instance '" + id + "' is a cluster node and cannot be rebooted through EC2", 400); - } + Instance inst = requireEc2ManagedInstance(region, id, "rebooted"); if (!config.services().ec2().mock()) { containerManager.reboot(inst); @@ -6109,6 +6137,29 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return findExternalInstance(callerAccountId(), region, instanceId).isPresent(); } + /** + * The instance {@code instanceId} names, if EC2 itself runs it: a cluster node is refused with + * OperationNotPermitted, as its cluster runs it. {@code action} words the refusal ("stopped"). + */ + private Instance requireEc2ManagedInstance(String region, String instanceId, String action) { + Instance inst = getRequiredInstance(region, instanceId); + if (isExternalInstance(region, instanceId)) { + throw new AwsException("OperationNotPermitted", + "The instance '" + instanceId + "' is a cluster node and cannot be " + action + " through EC2", 400); + } + return inst; + } + + /** As above, for StartInstances, which also refuses an instance that is terminated. */ + private Instance requireStartableInstance(String region, String instanceId) { + Instance inst = requireEc2ManagedInstance(region, instanceId, "started"); + if ("terminated".equals(inst.getState().getName())) { + throw new AwsException("IncorrectInstanceState", + "The instance '" + instanceId + "' is not in a state from which it can be started.", 400); + } + return inst; + } + private Instance getRequiredInstance(String region, String instanceId) { Instance inst = instances.get(key(region, instanceId)).orElse(null); if (inst == null) { @@ -11341,9 +11392,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } void acquireCapacity(String region, List admitted) { + acquireCapacity(region, admitted, false); + } + + /** + * As above; with {@code dryRun}, {@code admitted} are the stopped instances a StartInstances dry + * run names. Each is admitted as the real start admits it once it is pending, the batch counted + * against copies of the reservations, and the same refusals are thrown, but nothing is recorded. + */ + private void acquireCapacity(String region, List admitted, boolean dryRun) { synchronized (capacityReservationLock) { Set groupInstances = capacityGroupInstanceIds.get(callerAccountId() + "::" + region); - if (groupInstances != null) { + if (groupInstances != null && !dryRun) { for (Instance instance : admitted) { if (instance.getCapacityReservationGroupArn() != null) { groupInstances.add(instance.getInstanceId()); @@ -11355,7 +11415,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .stream().map(CapacityReservation::new).toList(); Map changed = new LinkedHashMap<>(); for (Instance instance : admitted) { - if (!holdsCapacity(instance) || instance.isSpot() + if ((!dryRun && !holdsCapacity(instance)) || instance.isSpot() || "none".equals(instance.getCapacityReservationPreference())) { continue; } @@ -11374,7 +11434,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .filter(r -> r.getAvailableInstanceCount() > 0).findFirst().orElse(null); if (selected == null) { if (target != null) { - CapacityReservation reservation = getRequiredCapacityReservation(region, target); + // A dry run counts its batch on the copies, as the real start's save after each + // instance counts it in the store. + CapacityReservation reservation = dryRun + ? candidates.stream().filter(r -> target.equals(r.getCapacityReservationId())) + .findFirst().orElseGet(() -> getRequiredCapacityReservation(region, target)) + : getRequiredCapacityReservation(region, target); if (matchesCapacityReservation(instance, reservation) && reservation.getAvailableInstanceCount() <= 0) { throw new AwsException("ReservationCapacityExceeded", @@ -11393,7 +11458,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab selected.setAvailableInstanceCount(selected.getAvailableInstanceCount() - 1); changed.put(key(region, selected.getCapacityReservationId()), selected); } - if (!changed.isEmpty()) { + if (!changed.isEmpty() && !dryRun) { persistCapacityMembership(changed); } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2CapacityReservationAssociationServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2CapacityReservationAssociationServiceTest.java index 69eca44835..e745297884 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2CapacityReservationAssociationServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2CapacityReservationAssociationServiceTest.java @@ -654,6 +654,35 @@ class Ec2CapacityReservationAssociationServiceTest { } } + /** + * A dry-run start admits its stopped instances into their reservation as the real start does, + * the whole batch counted, and records nothing: one of two fits the free slot, both do not. + */ + @Test + void aDryRunRestartIsAdmittedAsTheRealOneAndRecordsNothing() { + try (Fixture fixture = new Fixture("memory", directory)) { + CapacityReservation capacity = fixture.create(1); + Instance first = fixture.launch(capacity.getCapacityReservationId()); + fixture.service.stopInstances(REGION, List.of(first.getInstanceId())); + Instance second = fixture.launch(capacity.getCapacityReservationId()); + fixture.service.stopInstances(REGION, List.of(second.getInstanceId())); + + assertEquals("DryRunOperation", assertThrows(AwsException.class, () -> fixture.service + .startInstances(REGION, List.of(first.getInstanceId()), true)).getErrorCode()); + AwsException failure = assertThrows(AwsException.class, () -> fixture.service + .startInstances(REGION, List.of(first.getInstanceId(), second.getInstanceId()), true)); + assertEquals("ReservationCapacityExceeded", failure.getErrorCode()); + assertEquals("The targeted Capacity Reservation has insufficient available capacity.", failure.getMessage()); + + assertEquals(List.of(), fixture.describe(capacity).getInstanceIds()); + assertEquals(1, fixture.describe(capacity).getAvailableInstanceCount()); + assertEquals(List.of("stopped", "stopped"), fixture.service.describeInstances(REGION, + List.of(first.getInstanceId(), second.getInstanceId()), Map.of()).stream() + .flatMap(reservation -> reservation.getInstances().stream()) + .map(instance -> instance.getState().getName()).toList()); + } + } + @Test void reservationOnlyLaunchDoesNotFallBackToOnDemand() { try (Fixture fixture = new Fixture("memory", directory)) { diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java index 29281ddcf0..9db7642a30 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java @@ -9,19 +9,22 @@ import io.quarkus.test.junit.TestProfile; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.InstanceType; import software.amazon.awssdk.services.ec2.model.Volume; import java.net.URI; +import java.time.Duration; import java.util.List; import java.util.Map; import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; /** * A dry run checks the caller's permission and changes nothing else: under IAM enforcement a caller the * policy does not allow gets UnauthorizedOperation for a dry run, as for the real call, and one it allows - * gets DryRunOperation, with nothing created or deleted either way. + * gets DryRunOperation, with nothing created, deleted or terminated either way. */ @QuarkusTest @TestProfile(SignedIamEnforcementProfile.class) @@ -84,4 +87,41 @@ class Ec2DryRunIamIntegrationTest { } } } + + @Test + void aTerminateDryRunNeedsTheCallersCurrentPermission() throws Exception { + String policy = """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*" + }]} + """; + try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint); + SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "instance-dryrun-allowed-", "instances", + policy); + Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), + user.secretAccessKey(), Region.US_EAST_1, endpoint)) { + String instanceId = admin.runInstances(r -> r.imageId("ami-1234567890abcdef0") + .instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)).instances().get(0).instanceId(); + try { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)) + .untilAsserted(() -> assertEquals("running", state(admin, instanceId))); + + assertAwsError("DryRunOperation", 412, + () -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true))); + SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "instances")) + .then().statusCode(200); + assertAwsError("UnauthorizedOperation", 403, + () -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true))); + + assertEquals("running", state(admin, instanceId)); + } finally { + admin.terminateInstances(r -> r.instanceIds(instanceId)); + } + } + } + + private static String state(Ec2Client client, String instanceId) { + return client.describeInstances(r -> r.instanceIds(instanceId)).reservations().get(0).instances().get(0) + .state().nameAsString(); + } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java new file mode 100644 index 0000000000..e47fe5afc1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.atomic.AtomicLong; + +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * DryRun on StartInstances, StopInstances, RebootInstances and TerminateInstances is answered with + * DryRunOperation and HTTP 412 once every instance it names has passed the checks the real call makes, and + * it changes no instance's state. A dry run naming an instance the real call would refuse keeps that call's + * error, even when it also names one it would accept. + */ +@QuarkusTest +class Ec2InstanceDryRunIntegrationTest { + + /** Each test works in an account of its own, so DescribeInstances lists only the fixture's instances. */ + private static final AtomicLong ACCOUNTS = new AtomicLong(726200000000L); + private static final String MISSING_INSTANCE = "i-0123456789abcdef0"; + private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item"; + + private String account; + private String runningId; + private String stoppedId; + + @BeforeEach + void launchARunningAndAStoppedInstance() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + runningId = launch(); + stoppedId = launch(); + ec2("StopInstances", "InstanceId.1", stoppedId); + awaitState(stoppedId, "stopped"); + } + + @AfterEach + void terminateTheInstances() { + ec2("TerminateInstances", "InstanceId.1", runningId, "InstanceId.2", stoppedId); + } + + @ParameterizedTest + @ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"}) + void aDryRunIsAnsweredWithDryRunOperationAndChangesNothing(String action) { + Map before = states(); + + request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId) + .formParam("DryRun", "true").post("/").then() + .statusCode(412) + .body("Response.Errors.Error.Code", equalTo("DryRunOperation")) + .body("Response.Errors.Error.Message", + equalTo("Request would have succeeded, but DryRun flag is set.")); + + assertEquals(before, states()); + } + + /** Every instance is checked before the dry run is answered, so one the call would refuse refuses it. */ + @ParameterizedTest + @ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"}) + void aDryRunNamingAMissingInstanceKeepsTheRealCallsError(String action) { + Map before = states(); + + request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId, + "InstanceId.2", MISSING_INSTANCE).formParam("DryRun", "true").post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + + assertEquals(before, states()); + } + + @Test + void aDryRunStartOfATerminatedInstanceKeepsTheRealCallsError() { + ec2("TerminateInstances", "InstanceId.1", runningId); + awaitState(runningId, "terminated"); + Map before = states(); + + for (String dryRun : List.of("true", "false")) { + request("StartInstances", "InstanceId.1", runningId).formParam("DryRun", dryRun).post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState")); + } + + assertEquals(before, states()); + } + + /** A DryRun value that is not a boolean is refused as one, and no instance changes. */ + @ParameterizedTest + @CsvSource({ + "StartInstances, maybe", "StartInstances, ''", + "StopInstances, maybe", "StopInstances, ''", + "RebootInstances, maybe", "RebootInstances, ''", + "TerminateInstances, maybe", "TerminateInstances, ''" + }) + void aDryRunValueThatIsNotABooleanIsRefused(String action, String value) { + Map before = states(); + + request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId) + .formParam("DryRun", value).post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", equalTo("DryRun is not a valid boolean.")); + + assertEquals(before, states()); + } + + private String launch() { + String instanceId = ec2("RunInstances", "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro", + "MinCount", "1", "MaxCount", "1").getString("RunInstancesResponse.instancesSet.item.instanceId"); + awaitState(instanceId, "running"); + return instanceId; + } + + private void awaitState(String instanceId, String state) { + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> + assertEquals(state, states().get(instanceId))); + } + + /** Every instance of the account with its state, ordered by instance id. */ + private Map states() { + XmlPath described = ec2("DescribeInstances"); + List ids = described.getList(INSTANCE + ".instanceId", String.class); + List states = described.getList(INSTANCE + ".instanceState.name", String.class); + Map byId = new TreeMap<>(); + for (int i = 0; i < ids.size(); i++) { + byId.put(ids.get(i), states.get(i)); + } + return byId; + } + + private XmlPath ec2(String action, String... params) { + return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); + } + + private RequestSpecification request(String action, String... params) { + return QueryRequests.request(account, "ec2", action, params); + } +}