Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): honor capacity-reservations-only launches (#6354)
Andre Kurait81d399a1ed37
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 8115bd2592..dc9d985c8e 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -739,8 +739,12 @@ through `payment-pending`/`assessing`. `DescribeCapacityReservations` supports tOn-demand launches consume matching open reservation capacity unless their preference is`none`. RunInstances also honors an explicit reservation target, including one supplied by-its launch template. A matching targeted reservation with too few available slots returns-`ReservationCapacityExceeded` on launch or restart. CreateFleet and AutoScaling retain the template's preference and target;+its launch template. `capacity-reservations-only` requires matching reservation capacity and+never falls back to On-Demand capacity when launching or restarting. It can accompany an+explicit reservation target; without one, only matching open reservations are eligible.+A matching targeted reservation with too few available slots returns+`ReservationCapacityExceeded` on launch or restart.+CreateFleet and AutoScaling retain the template's preference and target;CloudFormation launch templates preserve the same declaration. Creating an open reservationadopts matching, unassociated running instances with an `open` preference. DescribeInstancesreports the acquired reservation. Stop, termination,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 acd06080e7..f143ef80cf 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@@ -3678,13 +3678,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, ResettabLaunchTemplateData.CapacityReservationTarget capacityTarget = capacitySpecification == null ? null: capacitySpecification.getCapacityReservationTarget();String capacityTargetId = capacityTarget == null ? null : capacityTarget.getCapacityReservationId();- if (!Set.of("open", "none").contains(capacityPreference)) {+ if (!Set.of("open", "none", "capacity-reservations-only").contains(capacityPreference)) {throw new AwsException("InvalidParameterValue", "Invalid Capacity Reservation preference.", 400);}if (capacityTarget != null && capacityTarget.getCapacityReservationResourceGroupArn() != null) {throw new AwsException("Unsupported", "Capacity Reservation resource group targeting is not supported.", 400);}- if (capacityTargetId != null && ("none".equals(capacityPreference) || spot)) {+ if ((capacityTargetId != null && "none".equals(capacityPreference))+ || (spot && (capacityTargetId != null || "capacity-reservations-only".equals(capacityPreference)))) {throw new AwsException("InvalidParameterCombination", "Invalid Capacity Reservation target combination.", 400);}if (privateIpAddress != null && privateIpAddress.isBlank()) {@@ -3790,10 +3791,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, ResettabprivateIpAddress = validateRequestedPrivateIp(privateIpAddress, subnet, suppliedEni, maxCount);}int capacityMaxCount = maxCount;- if (capacityTargetId != null) {+ if (capacityTargetId != null || "capacity-reservations-only".equals(capacityPreference)) {synchronized (capacityReservationLock) {reconcileCapacityMembership(region);- CapacityReservation target = getRequiredCapacityReservation(region, capacityTargetId);+ CapacityReservation target = capacityTargetId == null ? null+ : getRequiredCapacityReservation(region, capacityTargetId);Instance requested = new Instance();requested.setOwnerId(callerAccountId());requested.setRegion(region);@@ -3804,15 +3806,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, ResettabrequestedPlacement.setTenancy(tenancy);}requested.setPlacement(requestedPlacement);- if (!matchesCapacityReservation(requested, target)) {+ if (target != null && !matchesCapacityReservation(requested, target)) {throw new AwsException("InsufficientInstanceCapacity","The targeted Capacity Reservation has no matching available capacity.", 400);}- if (target.getAvailableInstanceCount() < minCount) {- throw new AwsException("ReservationCapacityExceeded",- "The targeted Capacity Reservation has insufficient available capacity.", 400);+ long available = target == null+ ? capacityReservations.scan(k -> k.startsWith(region + "::")).stream()+ .filter(candidate -> "open".equals(candidate.getInstanceMatchCriteria()))+ .filter(candidate -> matchesCapacityReservation(requested, candidate))+ .mapToLong(CapacityReservation::getAvailableInstanceCount).sum()+ : target.getAvailableInstanceCount();+ if (available < Math.max(minCount, 1)) {+ throw new AwsException(target == null ? "InsufficientInstanceCapacity" : "ReservationCapacityExceeded",+ target == null ? "No matching Capacity Reservation has sufficient available capacity."+ : "The targeted Capacity Reservation has insufficient available capacity.", 400);}- capacityMaxCount = Math.min(maxCount, target.getAvailableInstanceCount());+ capacityMaxCount = (int) Math.min(maxCount, available);count = capacityMaxCount;}}@@ -10070,6 +10079,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettabthrow new AwsException("InsufficientInstanceCapacity","The targeted Capacity Reservation has no matching available capacity.", 400);}+ if ("capacity-reservations-only".equals(instance.getCapacityReservationPreference())) {+ throw new AwsException("InsufficientInstanceCapacity",+ "No matching Capacity Reservation has available capacity.", 400);+ }continue;}selected.getInstanceIds().add(instance.getInstanceId());diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReservationOnlyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReservationOnlyIntegrationTest.javanew file mode 100644index 0000000000..269ae4f3af--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReservationOnlyIntegrationTest.java@@ -0,0 +1,88 @@+package io.github.hectorvent.floci.services.autoscaling;++import io.github.hectorvent.floci.core.common.RequestScopes;+import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;+import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;++@QuarkusTest+class AutoScalingReservationOnlyIntegrationTest {+ private static final String ACCOUNT = "753190420009";+ private static final String REGION = "us-east-1";++ @Inject+ Ec2Service ec2;++ @Inject+ AutoScalingService service;++ @Inject+ AutoScalingReconciler reconciler;++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void templateReservationOnlyDoesNotFallBack(boolean available) {+ RequestScopes.runAs(ACCOUNT, REGION, () -> {+ CapacityReservation capacity = ec2.createCapacityReservation(REGION, "t3.small", "Linux/UNIX",+ REGION + "a", null, 1, null, null, null, null, null, null, null, null);+ String groupName = "reservation-only-" + UUID.randomUUID();+ LaunchTemplate template = null;+ boolean groupCreated = false;+ try {+ if (!available) {+ ec2.cancelCapacityReservation(REGION, capacity.getCapacityReservationId());+ }+ LaunchTemplateData data = new LaunchTemplateData();+ data.setImageId("ami-test");+ data.setInstanceType("t3.small");+ LaunchTemplateData.CapacityReservationSpecification specification =+ new LaunchTemplateData.CapacityReservationSpecification();+ specification.setCapacityReservationPreference("capacity-reservations-only");+ data.setCapacityReservationSpecification(specification);+ template = ec2.createLaunchTemplate(REGION, groupName, data, List.of());+ String subnet = ec2.describeSubnets(REGION, List.of(), Map.of()).stream()+ .filter(value -> (REGION + "a").equals(value.getAvailabilityZone()))+ .findFirst().orElseThrow().getSubnetId();+ AutoScalingGroup group = service.createAutoScalingGroup(REGION, groupName, null,+ template.getLaunchTemplateId(), null, "1", null, 0, 1, 1, 300,+ List.of(REGION + "a"), List.of(subnet), List.of(), List.of(), "EC2", 0,+ List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());+ groupCreated = true;+ reconciler.reconcile(group);+ AutoScalingGroup current = service.describeAutoScalingGroups(REGION, List.of(groupName)).getFirst();+ assertEquals(available ? 1 : 0, current.getInstances().size());+ assertEquals(available ? 1 : 0, ec2.describeInstances(REGION, List.of(), Map.of()).stream()+ .flatMap(value -> value.getInstances().stream())+ .filter(value -> !"terminated".equals(value.getState().getName())).count());+ if (available) {+ assertEquals(List.of(current.getInstances().getFirst().getInstanceId()),+ ec2.describeCapacityReservations(REGION, List.of(capacity.getCapacityReservationId()),+ Map.of()).getFirst().getInstanceIds());+ }+ } finally {+ if (groupCreated) {+ service.deleteAutoScalingGroup(REGION, groupName, true);+ }+ if (template != null) {+ ec2.deleteLaunchTemplate(REGION, template.getLaunchTemplateId(), null);+ }+ if (available) {+ ec2.cancelCapacityReservation(REGION, capacity.getCapacityReservationId());+ }+ }+ });+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationAssociationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationAssociationServiceTest.javaindex c9cfedeac9..54a0201955 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationAssociationServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationAssociationServiceTest.java@@ -293,6 +293,7 @@ class Ec2CapacityReservationAssociationServiceTest {AwsException failure = assertThrows(AwsException.class,() -> fixture.launch(capacity.getCapacityReservationId()));assertEquals("ReservationCapacityExceeded", failure.getErrorCode());+ assertEquals("The targeted Capacity Reservation has insufficient available capacity.", failure.getMessage());assertEquals(List.of(admitted.getInstanceId()), fixture.describe(capacity).getInstanceIds());assertEquals(1, fixture.service.describeVolumes(REGION, List.of(), Map.of()).size());}@@ -311,6 +312,7 @@ class Ec2CapacityReservationAssociationServiceTest {AwsException failure = assertThrows(AwsException.class,() -> fixture.launch(capacity.getCapacityReservationId()));assertEquals("ReservationCapacityExceeded", failure.getErrorCode());+ assertEquals("The targeted Capacity Reservation has insufficient available capacity.", failure.getMessage());assertEquals(List.of(winner.get().getInstanceId()), fixture.describe(capacity).getInstanceIds());assertEquals(1, fixture.service.describeVolumes(REGION, List.of(), Map.of()).size());assertEquals(1, fixture.service.describeInstances(REGION, List.of(), Map.of()).stream()@@ -329,12 +331,128 @@ class Ec2CapacityReservationAssociationServiceTest {AwsException failure = assertThrows(AwsException.class,() -> fixture.service.startInstances(REGION, List.of(stopped.getInstanceId())));assertEquals("ReservationCapacityExceeded", failure.getErrorCode());+ assertEquals("The targeted Capacity Reservation has insufficient available capacity.", failure.getMessage());assertEquals(List.of(occupant.getInstanceId()), fixture.describe(capacity).getInstanceIds());assertEquals("stopped", fixture.service.describeInstances(REGION,List.of(stopped.getInstanceId()), Map.of()).getFirst().getInstances().getFirst().getState().getName());}}+ @Test+ void reservationOnlyLaunchDoesNotFallBackToOnDemand() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ AwsException failure = assertThrows(AwsException.class,+ () -> fixture.launchWithPreference("capacity-reservations-only"));+ assertEquals("InsufficientInstanceCapacity", failure.getErrorCode());+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).isEmpty());+ assertTrue(fixture.service.describeVolumes(REGION, List.of(), Map.of()).isEmpty());+ }+ }++ @Test+ void reservationOnlyLaunchConsumesAndReleasesOpenCapacity() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ CapacityReservation capacity = fixture.create(1);+ Instance instance = fixture.launchWithPreference("capacity-reservations-only");+ assertEquals(capacity.getCapacityReservationId(),+ fixture.service.instanceCapacityReservationId(instance));+ assertEquals(0, fixture.describe(capacity).getAvailableInstanceCount());+ fixture.service.stopInstances(REGION, List.of(instance.getInstanceId()));+ assertEquals(1, fixture.describe(capacity).getAvailableInstanceCount());+ fixture.service.startInstances(REGION, List.of(instance.getInstanceId()));+ assertEquals(0, fixture.describe(capacity).getAvailableInstanceCount());+ fixture.service.terminateInstances(REGION, List.of(instance.getInstanceId()));+ assertEquals(1, fixture.describe(capacity).getAvailableInstanceCount());+ }+ }++ @Test+ void reservationOnlyRestartCannotFallBackAfterCapacityIsCancelled() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ CapacityReservation capacity = fixture.create(1);+ Instance instance = fixture.launchWithPreference("capacity-reservations-only");+ fixture.service.stopInstances(REGION, List.of(instance.getInstanceId()));+ fixture.service.cancelCapacityReservation(REGION, capacity.getCapacityReservationId());+ AwsException failure = assertThrows(AwsException.class,+ () -> fixture.service.startInstances(REGION, List.of(instance.getInstanceId())));+ assertEquals("InsufficientInstanceCapacity", failure.getErrorCode());+ assertEquals("stopped", fixture.service.describeInstances(REGION,+ List.of(instance.getInstanceId()), Map.of()).getFirst().getInstances().getFirst()+ .getState().getName());+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void reservationOnlyAdmissionCapsAtMatchingOpenCapacity(boolean enforceQuotas) {+ try (Fixture fixture = new Fixture("memory", directory)) {+ when(fixture.config.services().ec2().enforceVcpuQuotas()).thenReturn(enforceQuotas);+ when(fixture.config.services().servicequotas().standardOnDemandVcpus()).thenReturn(20);+ CapacityReservation first = fixture.create(1);+ CapacityReservation second = fixture.create(1);+ fixture.service.createCapacityReservation(REGION, "t3.small", "Linux/UNIX", REGION + "a",+ null, 5, null, null, null, null, null, null, null, null);+ LaunchTemplateData.CapacityReservationSpecification specification =+ new LaunchTemplateData.CapacityReservationSpecification();+ specification.setCapacityReservationPreference("capacity-reservations-only");+ List<Instance> instances = fixture.service.runInstances(REGION, "ami-test", "t3.micro", 1, 3,+ null, List.of(), null, null, List.of(), null, null, null, null, 0, null, null, null,+ null, false, null, null, null, false, null, specification).getInstances();+ assertEquals(2, instances.size());+ assertEquals(0, fixture.describe(first).getAvailableInstanceCount());+ assertEquals(0, fixture.describe(second).getAvailableInstanceCount());+ }+ }++ @Test+ void reservationOnlyRechecksCapacityAtAdmission() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ CapacityReservation capacity = fixture.create(1);+ doAnswer(invocation -> {+ fixture.service.cancelCapacityReservation(REGION, capacity.getCapacityReservationId());+ return invocation.callRealMethod();+ }).when(fixture.service).acquireCapacity(eq(REGION), any());+ AwsException failure = assertThrows(AwsException.class,+ () -> fixture.launchWithPreference("capacity-reservations-only"));+ assertEquals("InsufficientInstanceCapacity", failure.getErrorCode());+ assertTrue(fixture.service.describeVolumes(REGION, List.of(), Map.of()).isEmpty());+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).stream()+ .flatMap(reservation -> reservation.getInstances().stream())+ .allMatch(instance -> "terminated".equals(instance.getState().getName())));+ }+ }++ @Test+ void reservationOnlySpotLaunchIsRejectedBeforeMutation() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ fixture.create(1);+ LaunchTemplateData.CapacityReservationSpecification specification =+ new LaunchTemplateData.CapacityReservationSpecification();+ specification.setCapacityReservationPreference("capacity-reservations-only");+ AwsException failure = assertThrows(AwsException.class, () -> fixture.service.runInstances(+ REGION, "ami-test", "t3.micro", 1, 1, null, List.of(), null, null, List.of(), null,+ null, null, null, 0, null, null, null, null, false, null, null, null, true, null, specification));+ assertEquals("InvalidParameterCombination", failure.getErrorCode());+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).isEmpty());+ }+ }++ @Test+ void reservationOnlyInsufficientMinimumDoesNotConsumeCapacity() {+ try (Fixture fixture = new Fixture("memory", directory)) {+ CapacityReservation capacity = fixture.create(1);+ LaunchTemplateData.CapacityReservationSpecification specification =+ new LaunchTemplateData.CapacityReservationSpecification();+ specification.setCapacityReservationPreference("capacity-reservations-only");+ AwsException failure = assertThrows(AwsException.class, () -> fixture.service.runInstances(+ REGION, "ami-test", "t3.micro", 2, 3, null, List.of(), null, null, List.of(), null,+ null, null, null, 0, null, null, null, null, false, null, null, null, false, null, specification));+ assertEquals("InsufficientInstanceCapacity", failure.getErrorCode());+ assertEquals(1, fixture.describe(capacity).getAvailableInstanceCount());+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).isEmpty());+ }+ }+private static final class Fixture implements AutoCloseable {private final EmulatorConfig config;private final StorageFactory factory;diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationOnlyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationOnlyIntegrationTest.javanew file mode 100644index 0000000000..ea062b7e7c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationOnlyIntegrationTest.java@@ -0,0 +1,110 @@+package io.github.hectorvent.floci.services.ec2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.RestAssured;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.ec2.Ec2Client;+import software.amazon.awssdk.services.ec2.model.CapacityReservationSpecification;+import software.amazon.awssdk.services.ec2.model.CapacityReservationTarget;+import software.amazon.awssdk.services.ec2.model.Ec2Exception;+import software.amazon.awssdk.services.ec2.model.FleetLaunchTemplateConfigRequest;+import software.amazon.awssdk.services.ec2.model.FleetLaunchTemplateSpecificationRequest;+import software.amazon.awssdk.services.ec2.model.Instance;+import software.amazon.awssdk.services.ec2.model.LaunchTemplateCapacityReservationSpecificationRequest;+import software.amazon.awssdk.services.ec2.model.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest;+import software.amazon.awssdk.services.ec2.model.RequestLaunchTemplateData;+import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;++import java.net.URI;+import java.util.ArrayList;+import java.util.List;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class Ec2CapacityReservationOnlyIntegrationTest {+ @ParameterizedTest+ @CsvSource({"direct,false", "direct,true", "template,false", "template,true", "fleet,false", "fleet,true"})+ void reservationOnlyLaunchUsesCapacityWithoutFallback(String path, boolean targeted) {+ try (Ec2Client client = Ec2Client.builder()+ .endpointOverride(URI.create("http://localhost:" + RestAssured.port))+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create("753190420008", "test")))+ .httpClientBuilder(UrlConnectionHttpClient.builder()).build()) {+ String capacityId = client.createCapacityReservation(request -> request.instanceType("t3.small")+ .instancePlatform("Linux/UNIX").availabilityZone("us-east-1a").instanceCount(1)+ .instanceMatchCriteria(targeted ? "targeted" : "open"))+ .capacityReservation().capacityReservationId();+ String templateId = null;+ List<String> instances = new ArrayList<>();+ try {+ String subnet = client.describeSubnets().subnets().stream()+ .filter(value -> "us-east-1a".equals(value.availabilityZone())).findFirst().orElseThrow().subnetId();+ RequestLaunchTemplateData data = RequestLaunchTemplateData.builder().imageId("ami-test")+ .instanceType("t3.small").networkInterfaces(LaunchTemplateInstanceNetworkInterfaceSpecificationRequest.builder()+ .deviceIndex(0).subnetId(subnet).build())+ .capacityReservationSpecification(LaunchTemplateCapacityReservationSpecificationRequest.builder()+ .capacityReservationPreference("capacity-reservations-only")+ .capacityReservationTarget(targeted ? CapacityReservationTarget.builder()+ .capacityReservationId(capacityId).build() : null).build()).build();+ templateId = client.createLaunchTemplate(request -> request+ .launchTemplateName("capacity-only-" + UUID.randomUUID()).launchTemplateData(data))+ .launchTemplate().launchTemplateId();+ String selectedTemplate = templateId;+ RunInstancesRequest request = "direct".equals(path)+ ? RunInstancesRequest.builder().imageId("ami-test").instanceType("t3.small").subnetId(subnet)+ .minCount(1).maxCount(1).capacityReservationSpecification(+ CapacityReservationSpecification.builder()+ .capacityReservationPreference("capacity-reservations-only")+ .capacityReservationTarget(targeted ? CapacityReservationTarget.builder()+ .capacityReservationId(capacityId).build() : null).build()).build()+ : RunInstancesRequest.builder().minCount(1).maxCount(1)+ .launchTemplate(value -> value.launchTemplateId(selectedTemplate)).build();+ if ("fleet".equals(path)) {+ instances.addAll(client.createFleet(value -> value.type("instant")+ .launchTemplateConfigs(FleetLaunchTemplateConfigRequest.builder()+ .launchTemplateSpecification(FleetLaunchTemplateSpecificationRequest.builder()+ .launchTemplateId(selectedTemplate).build()).build())+ .targetCapacitySpecification(value2 -> value2.totalTargetCapacity(1)+ .defaultTargetCapacityType("on-demand")))+ .instances().stream().flatMap(value -> value.instanceIds().stream()).toList());+ } else {+ instances.addAll(client.runInstances(request).instances().stream().map(Instance::instanceId).toList());+ }+ assertEquals(1, instances.size());+ assertEquals(capacityId, client.describeInstances(value -> value.instanceIds(instances))+ .reservations().getFirst().instances().getFirst().capacityReservationId());+ assertEquals(0, client.describeCapacityReservations(value -> value.capacityReservationIds(capacityId))+ .capacityReservations().getFirst().availableInstanceCount());+ assertThrows(Ec2Exception.class, () -> {+ List<Instance> unexpected = client.runInstances(request.toBuilder()+ .clientToken(UUID.randomUUID().toString()).build()).instances();+ instances.addAll(unexpected.stream().map(Instance::instanceId).toList());+ });+ assertEquals(1, client.describeInstances().reservations().stream()+ .flatMap(value -> value.instances().stream())+ .filter(value -> !"terminated".equals(value.state().nameAsString())).count());+ } finally {+ if (!instances.isEmpty()) {+ client.terminateInstances(value -> value.instanceIds(instances));+ }+ if (templateId != null) {+ String ownedTemplate = templateId;+ client.deleteLaunchTemplate(value -> value.launchTemplateId(ownedTemplate));+ }+ client.cancelCapacityReservation(value -> value.capacityReservationId(capacityId));+ assertTrue(client.describeCapacityReservations(value -> value.capacityReservationIds(capacityId))+ .capacityReservations().getFirst().stateAsString().equals("cancelled"));+ }+ }+ }+}