Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): associate instances with capacity reservations (#6336)

Andre Kuraitd05399feb1a7
diff --git a/compatibility-tests/sdk-test-python/tests/test_ec2_capacity_reservation_association.py b/compatibility-tests/sdk-test-python/tests/test_ec2_capacity_reservation_association.py
new file mode 100644
index 0000000000..4edc6b3540
--- /dev/null
+++ b/compatibility-tests/sdk-test-python/tests/test_ec2_capacity_reservation_association.py
@@ -0,0 +1,196 @@
+"""Exercise capacity associations through the EC2 SDK against an isolated Floci image."""
+import json
+import os
+import subprocess
+import time
+import urllib.request
+import uuid
+
+import boto3
+import pytest
+from botocore.config import Config
+from botocore.exceptions import ClientError
+
+IMAGE = os.environ.get("FLOCI_CAPACITY_ASSOCIATION_TEST_IMAGE")
+pytestmark = pytest.mark.skipif(not IMAGE, reason="Set FLOCI_CAPACITY_ASSOCIATION_TEST_IMAGE for Docker checks")
+
+
+def docker(*args):
+ result = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=60)
+ if result.returncode:
+ raise RuntimeError(f"docker {args[0]} failed: {result.stderr.strip()}")
+ return result.stdout.strip()
+
+
[email protected](scope="module")
+def endpoint():
+ name = "floci-capacity-association-" + uuid.uuid4().hex[:12]
+ container = docker(
+ "run", "-d", "--name", name, "--publish", "127.0.0.1::4566",
+ "--env", "FLOCI_SERVICES_EC2_MOCK=true",
+ "--env", "FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=false",
+ "--env", "FLOCI_STORAGE_MODE=memory", IMAGE,
+ )
+ try:
+ port = json.loads(docker("inspect", container))[0]["NetworkSettings"]["Ports"]["4566/tcp"][0]["HostPort"]
+ url = "http://127.0.0.1:" + port
+ deadline = time.monotonic() + 60
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ while True:
+ try:
+ with opener.open(url + "/_localstack/health", timeout=2) as response:
+ json.load(response)
+ break
+ except (OSError, ValueError):
+ if time.monotonic() >= deadline:
+ raise
+ time.sleep(0.2)
+ yield url
+ finally:
+ docker("rm", "-f", "-v", container)
+ assert not docker("ps", "-aq", "--filter", "id=" + container)
+
+
+def client(endpoint, account="111111111111", region="us-east-1"):
+ return boto3.client(
+ "ec2", endpoint_url=endpoint, region_name=region,
+ aws_access_key_id=account, aws_secret_access_key="test",
+ config=Config(proxies={}, connect_timeout=2, read_timeout=5,
+ retries={"total_max_attempts": 1}),
+ )
+
+
+def reservations(endpoint):
+ ec2 = client(endpoint)
+ created = []
+
+ def create(count, **overrides):
+ arguments = dict(InstanceType="t3.micro", InstancePlatform="Linux/UNIX",
+ AvailabilityZone="us-east-1a", InstanceCount=count)
+ arguments.update(overrides)
+ if "AvailabilityZoneId" in overrides:
+ arguments.pop("AvailabilityZone")
+ reservation = ec2.create_capacity_reservation(**arguments)["CapacityReservation"]
+ created.append(reservation["CapacityReservationId"])
+ for specification in arguments.get("TagSpecifications", []):
+ if specification["ResourceType"] == "capacity-reservation":
+ assert reservation["Tags"] == specification["Tags"]
+ return reservation["CapacityReservationId"]
+
+ try:
+ yield ec2, create
+ finally:
+ for reservation_id in created:
+ record = describe(ec2, reservation_id)
+ if record["State"] == "active":
+ ec2.cancel_capacity_reservation(CapacityReservationId=reservation_id)
+ assert describe(ec2, reservation_id)["State"] == "cancelled"
+
+
+def describe(ec2, reservation_id):
+ return ec2.describe_capacity_reservations(
+ CapacityReservationIds=[reservation_id])["CapacityReservations"][0]
+
+
+def test_targeted_launch_and_none_preference_preserve_eligibility(reservations):
+ ec2, create = reservations
+ target = create(1, InstanceMatchCriteria="targeted")
+ instance_ids = []
+ try:
+ for specification in [
+ {"CapacityReservationPreference": "none"},
+ {"CapacityReservationTarget": {"CapacityReservationId": target}}]:
+ instance = ec2.run_instances(
+ ImageId="ami-test", InstanceType="t3.micro", MinCount=1, MaxCount=1,
+ CapacityReservationSpecification=specification)["Instances"][0]
+ instance_ids.append(instance["InstanceId"])
+ if "CapacityReservationTarget" in specification:
+ assert instance["CapacityReservationId"] == target
+ assert instance["CapacityReservationSpecification"] == specification
+ else:
+ assert "CapacityReservationId" not in instance
+ assert describe(ec2, target)["AvailableInstanceCount"] == 0
+ with pytest.raises(ClientError):
+ ec2.run_instances(
+ ImageId="ami-test", InstanceType="t3.micro", MinCount=1, MaxCount=1,
+ CapacityReservationSpecification={"CapacityReservationTarget": {
+ "CapacityReservationId": target}})
+ ec2.stop_instances(InstanceIds=[instance_ids[1]])
+ assert describe(ec2, target)["AvailableInstanceCount"] == 1
+ ec2.start_instances(InstanceIds=[instance_ids[1]])
+ assert describe(ec2, target)["AvailableInstanceCount"] == 0
+ ec2.cancel_capacity_reservation(CapacityReservationId=target)
+ current = ec2.describe_instances(InstanceIds=[instance_ids[1]])["Reservations"][0]["Instances"][0]
+ assert "CapacityReservationId" not in current
+ assert current["State"]["Name"] == "running"
+ finally:
+ if instance_ids:
+ ec2.terminate_instances(InstanceIds=instance_ids)
+
+
+def test_new_open_reservation_adopts_running_open_but_not_none(reservations):
+ ec2, create = reservations
+ instances = []
+ try:
+ for preference in ("open", "none"):
+ instance = ec2.run_instances(
+ ImageId="ami-test", InstanceType="t3.micro", MinCount=1, MaxCount=1,
+ CapacityReservationSpecification={"CapacityReservationPreference": preference},
+ )["Instances"][0]
+ instances.append(instance["InstanceId"])
+ before = ec2.describe_instances(InstanceIds=instances)
+ assert all(i["State"]["Name"] == "running" for r in before["Reservations"] for i in r["Instances"])
+ capacity_id = create(2)
+ described = ec2.describe_instances(InstanceIds=instances)
+ by_id = {i["InstanceId"]: i for r in described["Reservations"] for i in r["Instances"]}
+ assert by_id[instances[0]]["CapacityReservationId"] == capacity_id
+ assert "CapacityReservationId" not in by_id[instances[1]]
+ assert describe(ec2, capacity_id)["AvailableInstanceCount"] == 1
+ finally:
+ if instances:
+ ec2.terminate_instances(InstanceIds=instances)
+
+
[email protected]("preference", ["none", "targeted"])
+def test_fleet_retains_template_capacity_specification(reservations, preference):
+ ec2, create = reservations
+ capacity_id = create(1, InstanceMatchCriteria="targeted" if preference == "targeted" else "open")
+ specification = ({"CapacityReservationPreference": "none"} if preference == "none" else
+ {"CapacityReservationTarget": {"CapacityReservationId": capacity_id}})
+ template_id = None
+ instances = []
+ try:
+ template_id = ec2.create_launch_template(
+ LaunchTemplateName="capacity-fleet-" + uuid.uuid4().hex,
+ LaunchTemplateData={"ImageId": "ami-test", "InstanceType": "t3.micro",
+ "Placement": {"AvailabilityZone": "us-east-1a"},
+ "CapacityReservationSpecification": specification},
+ )["LaunchTemplate"]["LaunchTemplateId"]
+ fleet = ec2.create_fleet(
+ Type="instant", LaunchTemplateConfigs=[{"LaunchTemplateSpecification": {
+ "LaunchTemplateId": template_id, "Version": "$Latest"}}],
+ TargetCapacitySpecification={"TotalTargetCapacity": 1, "DefaultTargetCapacityType": "on-demand"},
+ )
+ instances = [i for group in fleet["Instances"] for i in group["InstanceIds"]]
+ assert len(instances) == 1
+ instance = ec2.describe_instances(InstanceIds=instances)["Reservations"][0]["Instances"][0]
+ assert instance.get("CapacityReservationId") == (capacity_id if preference == "targeted" else None)
+ assert describe(ec2, capacity_id)["AvailableInstanceCount"] == (0 if preference == "targeted" else 1)
+ finally:
+ if instances:
+ ec2.terminate_instances(InstanceIds=instances)
+ if template_id:
+ ec2.delete_launch_template(LaunchTemplateId=template_id)
+
+
+def test_unknown_zone_id_rejected_without_reservation_publication(reservations):
+ ec2, create = reservations
+ before = ec2.describe_capacity_reservations()["CapacityReservations"]
+ with pytest.raises(ClientError) as rejected:
+ create(1, AvailabilityZoneId="use1-az99")
+ assert rejected.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert ec2.describe_capacity_reservations()["CapacityReservations"] == before
+ zone = ec2.describe_availability_zones()["AvailabilityZones"][0]
+ reservation_id = create(1, AvailabilityZoneId=zone["ZoneId"])
+ assert describe(ec2, reservation_id)["AvailabilityZoneId"] == zone["ZoneId"]
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 04c7732df7..38a47912d1 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -737,6 +737,21 @@ through `payment-pending`/`assessing`. `DescribeCapacityReservations` supports t
`instance-type`, `state` and `tenancy` filters alongside the shared `tag:`, `tag-key` and
`tag-value` filters.
+On-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. CreateFleet and AutoScaling retain the template's preference and target;
+CloudFormation launch templates preserve the same declaration. Creating an open reservation
+adopts matching, unassociated running instances with an `open` preference. DescribeInstances
+reports the acquired reservation. Stop, termination,
+cancellation and expiration release membership; a restart acquires capacity using the
+instance's retained launch preference and target. A failed membership write reports an error;
+subsequent access reconciles released membership from persisted instance state.
+
+Membership and available counts publish in one atomic storage batch. Older snapshots without
+membership remain readable. Capacity reservation resource-group targeting is unsupported.
+
+Capacity reservation zone IDs must be among those returned by `DescribeAvailabilityZones`.
+
### Dedicated Hosts
| Action | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
index a735cca773..ff35cafeae 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
@@ -555,7 +555,8 @@ public class AutoScalingReconciler {
launchSource.associatePublicIpAddress(), null, 0, null, launchSource.metadataOptions(), null,
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
: encodeLegacyUserData(launchSource.userData()),
- false, null, null, launchSource.blockDeviceMappings());
+ false, null, null, launchSource.blockDeviceMappings(), false, null,
+ launchSource.capacityReservationSpecification());
} catch (RuntimeException launchFailure) {
if (!refreshLaunch) {
throw launchFailure;
@@ -851,7 +852,7 @@ public class AutoScalingReconciler {
// subnet's MapPublicIpOnLaunch, and only null means
// "fall back to the subnet default".
lc.getAssociatePublicIpAddress(),
- null, lc.getMetadataOptions());
+ null, lc.getMetadataOptions(), null);
}
LaunchTemplate launchTemplate = resolveLaunchTemplate(asg);
@@ -880,7 +881,8 @@ public class AutoScalingReconciler {
asg.getLaunchTemplateName(),
resolvedVersion,
version.getData().effectiveAssociatePublicIpAddress(),
- version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
+ version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions(),
+ version.getData().getCapacityReservationSpecification());
}
MixedInstancesPolicy.LaunchTemplateSpecification specification =
@@ -915,7 +917,8 @@ public class AutoScalingReconciler {
specification.getLaunchTemplateName(),
resolvedVersion,
version.getData().effectiveAssociatePublicIpAddress(),
- version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
+ version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions(),
+ version.getData().getCapacityReservationSpecification());
}
}
@@ -1028,7 +1031,8 @@ public class AutoScalingReconciler {
String launchTemplateVersion,
Boolean associatePublicIpAddress,
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings,
- LaunchTemplateData.MetadataOptions metadataOptions) {}
+ LaunchTemplateData.MetadataOptions metadataOptions,
+ LaunchTemplateData.CapacityReservationSpecification capacityReservationSpecification) {}
// Override for describeAutoScalingGroups with null region (all regions)
// The service only filters by region when non-null; null means all.
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java
index ebfee60c83..0489edd844 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java
@@ -73,6 +73,9 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
? written.get("MetadataOptions") : null;
data.setMetadataOptions(Ec2CfnMetadataOptions.read("LaunchTemplateData/MetadataOptions",
metadataOptions, Ec2CfnMetadataOptions.LAUNCH_TEMPLATE_SHAPE, ctx.engine()));
+ JsonNode capacity = written.isObject() && !CloudFormationTemplateEngine.callsIntrinsic(written)
+ ? written.get("CapacityReservationSpecification") : null;
+ data.setCapacityReservationSpecification(capacityReservationSpecification(capacity, ctx.engine()));
if (node.has("SecurityGroupIds")) {
List<String> securityGroupIds = new ArrayList<>();
for (JsonNode securityGroup : node.get("SecurityGroupIds")) {
@@ -166,6 +169,31 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
}
}
+ private LaunchTemplateData.CapacityReservationSpecification capacityReservationSpecification(
+ JsonNode raw, CloudFormationTemplateEngine engine) {
+ CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(engine);
+ String shape = CfnPropertyTypes.memberShape(
+ CfnPropertyTypes.propertyShape("AWS::EC2::LaunchTemplate", "LaunchTemplateData"),
+ "CapacityReservationSpecification");
+ JsonNode block = types.read("LaunchTemplateData/CapacityReservationSpecification", raw, shape);
+ types.finish();
+ if (block == null || block.isEmpty()) {
+ return null;
+ }
+ LaunchTemplateData.CapacityReservationSpecification specification =
+ new LaunchTemplateData.CapacityReservationSpecification();
+ specification.setCapacityReservationPreference(block.path("CapacityReservationPreference").asText(null));
+ JsonNode targetNode = block.path("CapacityReservationTarget");
+ if (targetNode.isObject()) {
+ LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
+ target.setCapacityReservationId(targetNode.path("CapacityReservationId").asText(null));
+ target.setCapacityReservationResourceGroupArn(
+ targetNode.path("CapacityReservationResourceGroupArn").asText(null));
+ specification.setCapacityReservationTarget(target);
+ }
+ return specification;
+ }
+
/**
* Keeps the form CloudFormation supplied. EC2 stores {@code Arn} and {@code Name} as given and
* derives the ARN only at launch time, so normalizing {@code Name} into an ARN here would put
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
index e1ec374f61..79b230acc4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java
@@ -52,6 +52,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
@@ -153,6 +154,7 @@ public class Ec2ContainerManager {
private final Ec2InstanceTypeCatalog instanceTypeCatalog;
private SecurityGroupFirewallManager firewallManager;
private final ExecutorService executor;
+ private final Map<String, CompletableFuture<Void>> lifecycleOperations = new ConcurrentHashMap<>();
private final Duration userDataExecutionTimeout;
private final Set<ResultCallback<Frame>> activeUserDataCallbacks = ConcurrentHashMap.newKeySet();
@@ -916,6 +918,31 @@ public class Ec2ContainerManager {
}
}
+ private void submitLifecycleOperation(String containerId, Runnable operation) {
+ synchronized (lifecycleOperations) {
+ CompletableFuture<Void> previous = lifecycleOperations.getOrDefault(containerId,
+ CompletableFuture.completedFuture(null));
+ CompletableFuture<Void> completed = new CompletableFuture<>();
+ lifecycleOperations.put(containerId, completed);
+ previous.whenComplete((ignored, priorFailure) -> {
+ try {
+ executor.submit(() -> {
+ try {
+ operation.run();
+ } finally {
+ lifecycleOperations.remove(containerId, completed);
+ completed.complete(null);
+ }
+ });
+ } catch (RuntimeException failure) {
+ lifecycleOperations.remove(containerId, completed);
+ completed.completeExceptionally(failure);
+ LOG.warnv(failure, "Could not schedule lifecycle operation for EC2 container {0}", containerId);
+ }
+ });
+ }
+ }
+
/**
* Gracefully stops a running container (30 second timeout then SIGKILL).
* Updates instance state through stopping → stopped.
@@ -926,19 +953,20 @@ public class Ec2ContainerManager {
instance.setState(InstanceState.stopped());
return;
}
- instance.setState(InstanceState.stopping());
- executor.submit(() -> {
+ InstanceState stopping = InstanceState.stopping();
+ instance.setState(stopping);
+ submitLifecycleOperation(containerId, () -> {
// Sidecars forward to the container's current IP, which Docker reassigns on the
// next start; tear them down so no forward is left pointing at a stale address.
portForwardManager.unpublishAll(instance);
try {
dockerClient.stopContainerCmd(containerId).withTimeout(30).exec();
- } catch (NotFoundException e) {
- // already gone
+ } catch (NotFoundException ignored) {
+ // An already removed container needs no further stop.
} catch (Exception e) {
LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage());
}
- instance.setState(InstanceState.stopped());
+ instance.compareAndSetState(stopping, InstanceState.stopped());
});
}
@@ -962,8 +990,9 @@ public class Ec2ContainerManager {
}
return;
}
- instance.setState(InstanceState.pending());
- executor.submit(() -> {
+ InstanceState pending = InstanceState.pending();
+ instance.setState(pending);
+ submitLifecycleOperation(containerId, () -> {
try {
dockerClient.startContainerCmd(containerId).exec();
boolean running = false;
@@ -1000,14 +1029,16 @@ public class Ec2ContainerManager {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- instance.setState(InstanceState.stopped());
+ instance.compareAndSetState(pending, InstanceState.stopped());
return;
} catch (Exception e) {
LOG.warnv("Error starting EC2 container {0}: {1}", containerId, e.getMessage());
- instance.setState(InstanceState.stopped());
+ instance.compareAndSetState(pending, InstanceState.stopped());
+ return;
+ }
+ if (!instance.compareAndSetState(pending, InstanceState.running())) {
return;
}
- instance.setState(InstanceState.running());
if (postStart != null) {
try {
postStart.run();
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 89fc2af100..603a40ad7a 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
@@ -872,12 +872,28 @@ public class Ec2QueryHandler {
}
}
+ LaunchTemplateData.CapacityReservationSpecification capacitySpecification = launchTemplateData == null
+ ? null : launchTemplateData.getCapacityReservationSpecification();
+ if (anyParamStartsWith(p, "CapacityReservationSpecification.")) {
+ capacitySpecification = new LaunchTemplateData.CapacityReservationSpecification();
+ capacitySpecification.setCapacityReservationPreference(
+ p.getFirst("CapacityReservationSpecification.CapacityReservationPreference"));
+ if (anyParamStartsWith(p, "CapacityReservationSpecification.CapacityReservationTarget.")) {
+ LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
+ target.setCapacityReservationId(
+ p.getFirst("CapacityReservationSpecification.CapacityReservationTarget.CapacityReservationId"));
+ target.setCapacityReservationResourceGroupArn(p.getFirst(
+ "CapacityReservationSpecification.CapacityReservationTarget.CapacityReservationResourceGroupArn"));
+ capacitySpecification.setCapacityReservationTarget(target);
+ }
+ }
+
Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions,
creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")),
p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings,
- "spot".equals(marketType), privateIpAddress);
+ "spot".equals(marketType), privateIpAddress, capacitySpecification);
if (!networkInterfaceTags.isEmpty()) {
List<String> eniIds = new ArrayList<>();
@@ -896,8 +912,9 @@ public class Ec2QueryHandler {
.elem("ownerId", res.getOwnerId())
.start("groupSet").end("groupSet")
.start("instancesSet");
+ Map<String, String> capacityAssociations = service.capacityReservationAssociations(region);
for (Instance inst : res.getInstances()) {
- xml.start("item").raw(instanceXml(inst)).end("item");
+ xml.start("item").raw(instanceXml(inst, capacityAssociations)).end("item");
}
xml.end("instancesSet")
.end("RunInstancesResponse");
@@ -1021,7 +1038,8 @@ public class Ec2QueryHandler {
null,
0,
launch.availabilityZone(), launch.metadataOptions(), null, launch.encodedUserData(), false,
- null, null, launch.blockDeviceMappings(), "spot".equals(capacityType));
+ null, null, launch.blockDeviceMappings(), "spot".equals(capacityType), null,
+ launch.capacityReservationSpecification());
Instance instance = reservation.getInstances().get(0);
launchedInstanceIds.add(instance.getInstanceId());
results.add(new FleetLaunchResult(instance, launch));
@@ -1185,7 +1203,7 @@ public class Ec2QueryHandler {
template.getMetadataOptions(),
template.effectiveSecurityGroupIds(),
new ArrayList<>(tags.values()),
- template.getBlockDeviceMappings());
+ template.getBlockDeviceMappings(), template.getCapacityReservationSpecification());
}
/**
@@ -1233,7 +1251,8 @@ public class Ec2QueryHandler {
Boolean associatePublicIpAddress,
LaunchTemplateData.MetadataOptions metadataOptions,
List<String> securityGroupIds, List<Tag> instanceTags,
- List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings) {}
+ List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings,
+ LaunchTemplateData.CapacityReservationSpecification capacityReservationSpecification) {}
private record FleetLaunchKey(String launchTemplateId, String launchTemplateName, String launchTemplateVersion,
String instanceType, String imageId, String subnetId, String availabilityZone) {
@@ -1355,6 +1374,7 @@ public class Ec2QueryHandler {
.start("DescribeInstancesResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("reservationSet");
+ Map<String, String> capacityAssociations = service.capacityReservationAssociations(region);
for (Reservation res : reservations) {
xml.start("item")
.elem("reservationId", res.getReservationId())
@@ -1362,7 +1382,7 @@ public class Ec2QueryHandler {
.start("groupSet").end("groupSet")
.start("instancesSet");
for (Instance inst : res.getInstances()) {
- xml.start("item").raw(instanceXml(inst)).end("item");
+ xml.start("item").raw(instanceXml(inst, capacityAssociations)).end("item");
}
xml.end("instancesSet").end("item");
}
@@ -4254,6 +4274,10 @@ public class Ec2QueryHandler {
p.getFirst("OutpostArn"),
p.getFirst("PlacementGroupArn"));
applyResourceTags(resourceTags, region, reservation.getCapacityReservationId());
+ if (!resourceTags.isEmpty()) {
+ reservation = service.describeCapacityReservations(
+ region, List.of(reservation.getCapacityReservationId()), Map.of()).getFirst();
+ }
XmlBuilder xml = new XmlBuilder()
.start("CreateCapacityReservationResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4928,7 +4952,7 @@ public class Ec2QueryHandler {
// ─── XML fragment builders ────────────────────────────────────────────────
- private String instanceXml(Instance inst) {
+ private String instanceXml(Instance inst, Map<String, String> capacityAssociations) {
XmlBuilder xml = new XmlBuilder()
.elem("instanceId", inst.getInstanceId())
.elem("imageId", inst.getImageId())
@@ -5045,8 +5069,17 @@ public class Ec2QueryHandler {
.elem("enableResourceNameDnsAAAARecord", "false")
.end("privateDnsNameOptions")
.start("capacityReservationSpecification")
- .elem("capacityReservationPreference", "open")
- .end("capacityReservationSpecification");
+ .elem("capacityReservationPreference", inst.getCapacityReservationPreference());
+ if (inst.getCapacityReservationTarget() != null) {
+ xml.start("capacityReservationTarget")
+ .elem("capacityReservationId", inst.getCapacityReservationTarget())
+ .end("capacityReservationTarget");
+ }
+ xml.end("capacityReservationSpecification");
+ String capacityReservationId = capacityAssociations.get(inst.getInstanceId());
+ if (capacityReservationId != null) {
+ xml.elem("capacityReservationId", capacityReservationId);
+ }
if (inst.getRootVolumeId() != null) {
xml.start("blockDeviceMapping")
.start("item")
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 1e265922f1..50d0022c2f 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
@@ -307,6 +307,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final StorageBackend<String, CapacityReservation> capacityReservations;
+ private final Object capacityReservationLock = new Object();
private final StorageBackend<String, Host> hosts;
private final StorageBackend<String, EgressOnlyInternetGateway> egressOnlyInternetGateways;
// Serialises a launch onto a host against ModifyHosts/ReleaseHosts, so a host cannot be
@@ -3651,6 +3652,41 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
String hostId, String tenancy,
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings, boolean spot,
String privateIpAddress) {
+ return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
+ securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
+ associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone,
+ metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy,
+ blockDeviceMappings, spot, privateIpAddress, null);
+ }
+
+ public Reservation runInstances(String region, String imageId, String instanceType,
+ int minCount, int maxCount, String keyName,
+ List<String> securityGroupIds, String subnetId,
+ String clientToken, List<Tag> instanceTags,
+ String userData, String iamInstanceProfileArn,
+ Boolean associatePublicIp, String networkInterfaceId,
+ int networkInterfaceDeviceIndex, String availabilityZone,
+ LaunchTemplateData.MetadataOptions metadataOptions,
+ String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun,
+ String hostId, String tenancy,
+ List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings, boolean spot,
+ String privateIpAddress,
+ LaunchTemplateData.CapacityReservationSpecification capacitySpecification) {
+ String capacityPreference = capacitySpecification == null
+ || capacitySpecification.getCapacityReservationPreference() == null ? "open"
+ : capacitySpecification.getCapacityReservationPreference();
+ LaunchTemplateData.CapacityReservationTarget capacityTarget = capacitySpecification == null ? null
+ : capacitySpecification.getCapacityReservationTarget();
+ String capacityTargetId = capacityTarget == null ? null : capacityTarget.getCapacityReservationId();
+ if (!Set.of("open", "none").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)) {
+ throw new AwsException("InvalidParameterCombination", "Invalid Capacity Reservation target combination.", 400);
+ }
if (privateIpAddress != null && privateIpAddress.isBlank()) {
privateIpAddress = null;
}
@@ -3753,6 +3789,29 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (privateIpAddress != null) {
privateIpAddress = validateRequestedPrivateIp(privateIpAddress, subnet, suppliedEni, maxCount);
}
+ int capacityMaxCount = maxCount;
+ if (capacityTargetId != null) {
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ CapacityReservation target = getRequiredCapacityReservation(region, capacityTargetId);
+ Instance requested = new Instance();
+ requested.setOwnerId(callerAccountId());
+ requested.setRegion(region);
+ requested.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
+ requested.setInstanceType(effectiveInstanceType);
+ Placement requestedPlacement = new Placement(az);
+ if (tenancy != null && !tenancy.isBlank()) {
+ requestedPlacement.setTenancy(tenancy);
+ }
+ requested.setPlacement(requestedPlacement);
+ if (!matchesCapacityReservation(requested, target) || target.getAvailableInstanceCount() < minCount) {
+ throw new AwsException("InsufficientInstanceCapacity",
+ "The targeted Capacity Reservation has no matching available capacity.", 400);
+ }
+ capacityMaxCount = Math.min(maxCount, target.getAvailableInstanceCount());
+ count = capacityMaxCount;
+ }
+ }
String architecture = architectureFor(region, imageId, effectiveInstanceType);
// An entry with NoDevice set removes its device whatever else it names, as on AWS.
List<LaunchTemplateData.BlockDeviceMapping> mappedDevices = blockDeviceMappings == null ? List.of()
@@ -3796,7 +3855,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
synchronized (privateIpAllocationLock) {
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
- ? count : admittedInstanceCount(region, effectiveInstanceType, minCount, maxCount);
+ ? count : admittedInstanceCount(region, effectiveInstanceType, minCount, capacityMaxCount);
synchronized (hostLock) {
if (hostId != null) {
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
@@ -3816,6 +3875,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
inst.setState(InstanceState.pending());
inst.setInstanceType(effectiveInstanceType);
inst.setSpot(spot);
+ inst.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
+ inst.setCapacityReservationPreference(capacityTargetId == null ? capacityPreference : null);
+ inst.setCapacityReservationTarget(capacityTargetId);
Placement placement = new Placement(az);
placement.setHostId(hostId);
if (tenancy != null && !tenancy.isBlank()) {
@@ -3931,6 +3993,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
+ try {
+ acquireCapacity(region, launched);
+ } catch (RuntimeException failure) {
+ try {
+ terminateInstances(region, launched.stream().map(Instance::getInstanceId).toList());
+ } catch (RuntimeException cleanupFailure) {
+ failure.addSuppressed(cleanupFailure);
+ LOG.errorv(cleanupFailure, "Failed to clean up rejected capacity launch in {0}", region);
+ }
+ throw failure;
+ }
+
// Outside the lock: the containers are what the lock protects a reference to, not part of
// the registry, and a launch is slow.
if (!config.services().ec2().mock()) {
@@ -4754,6 +4828,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
detachAttachedVolumesOnTermination(region, inst);
releaseStandaloneInterfacesOnTermination(region, inst);
instances.put(key(region, id), inst);
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ }
// The last instance depending on a deregistered AMI's capture has just gone away.
// Cheap and usually sufficient: by here the container is often already removed.
reclaimCapturesPinnedBy(region, inst, terminating);
@@ -4860,6 +4937,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
instances.put(key(region, id), inst);
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ }
Map<String, String> entry = new LinkedHashMap<>();
entry.put("instanceId", id);
entry.put("previousState", prev.getName());
@@ -4913,6 +4993,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
"The instance '" + id + "' is not in a state from which it can be started.", 400);
}
InstanceState prev = inst.getState();
+ synchronized (capacityReservationLock) {
+ if ("stopped".equals(prev.getName()) || "stopping".equals(prev.getName())) {
+ inst.setState(InstanceState.pending());
+ try {
+ instances.put(key(region, id), inst);
+ acquireCapacity(region, List.of(inst));
+ } catch (RuntimeException failure) {
+ inst.setState(prev);
+ instances.put(key(region, id), inst);
+ throw failure;
+ }
+ }
+ }
if (config.services().ec2().mock()) {
completeMockLaunch(region, inst, true);
} else {
@@ -9495,8 +9588,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
Vpc vpc = vpcs.get(storeKey).orElse(null);
if (vpc != null) { vpc.setTags(new ArrayList<>(tagList)); vpcs.put(storeKey, vpc); return; }
- CapacityReservation cr = capacityReservations.get(storeKey).orElse(null);
- if (cr != null) { cr.setTags(new ArrayList<>(tagList)); capacityReservations.put(storeKey, cr); return; }
+ if (resourceId.startsWith("cr-")) {
+ synchronized (capacityReservationLock) {
+ CapacityReservation reservation = capacityReservations.get(storeKey).orElse(null);
+ if (reservation != null) {
+ CapacityReservation updated = new CapacityReservation(reservation);
+ updated.setTags(new ArrayList<>(tagList));
+ capacityReservations.put(storeKey, updated);
+ return;
+ }
+ }
+ }
Host host = hosts.get(storeKey).orElse(null);
if (host != null) {
host.setTags(new ArrayList<>(tagList));
@@ -9833,6 +9935,123 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── Capacity Reservations ─────────────────────────────────────────────────
+ /**
+ * Membership lives with the reservation and is published atomically with its available
+ * capacity. The instance stores only
+ * launch eligibility, never a second authoritative copy of the acquired reservation.
+ */
+ public String instanceCapacityReservationId(Instance instance) {
+ return Objects.equals(callerAccountId(), instance.getOwnerId())
+ ? capacityReservationAssociations(instance.getRegion()).get(instance.getInstanceId()) : null;
+ }
+
+ Map<String, String> capacityReservationAssociations(String region) {
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ Map<String, String> associations = new HashMap<>();
+ for (CapacityReservation reservation : capacityReservations.scan(k -> k.startsWith(region + "::"))) {
+ for (String instanceId : reservation.getInstanceIds()) {
+ associations.put(instanceId, reservation.getCapacityReservationId());
+ }
+ }
+ return associations;
+ }
+ }
+
+ private void reconcileCapacityMembership(String region) {
+ Map<String, CapacityReservation> changed = new LinkedHashMap<>();
+ for (CapacityReservation stored : capacityReservations.scan(k -> k.startsWith(region + "::"))) {
+ CapacityReservation updated = new CapacityReservation(stored);
+ boolean expired = "active".equals(updated.getState()) && updated.getEndDate() != null
+ && !updated.getEndDate().isAfter(Instant.now());
+ if (expired) {
+ updated.setState("expired");
+ }
+ updated.getInstanceIds().removeIf(id -> !"active".equals(updated.getState())
+ || instances.get(key(region, id)).map(instance -> !holdsCapacity(instance)).orElse(true));
+ int released = stored.getInstanceIds().size() - updated.getInstanceIds().size();
+ if (expired || released > 0) {
+ updated.setAvailableInstanceCount("active".equals(updated.getState())
+ ? updated.getAvailableInstanceCount() + released : 0);
+ changed.put(key(region, updated.getCapacityReservationId()), updated);
+ }
+ }
+ if (!changed.isEmpty()) {
+ persistCapacityMembership(changed);
+ }
+ }
+
+ private boolean holdsCapacity(Instance instance) {
+ return instance.getState() != null && ("pending".equals(instance.getState().getName())
+ || "running".equals(instance.getState().getName()));
+ }
+
+ void acquireCapacity(String region, List<Instance> admitted) {
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ List<CapacityReservation> candidates = capacityReservations.scan(k -> k.startsWith(region + "::"))
+ .stream().map(CapacityReservation::new).toList();
+ Map<String, CapacityReservation> changed = new LinkedHashMap<>();
+ for (Instance instance : admitted) {
+ if (!holdsCapacity(instance) || instance.isSpot()
+ || "none".equals(instance.getCapacityReservationPreference())) {
+ continue;
+ }
+ if (candidates.stream().anyMatch(r -> r.getInstanceIds().contains(instance.getInstanceId()))) {
+ continue;
+ }
+ String target = instance.getCapacityReservationTarget();
+ CapacityReservation selected = candidates.stream()
+ .filter(r -> target == null ? "open".equals(r.getInstanceMatchCriteria())
+ : target.equals(r.getCapacityReservationId()))
+ .filter(r -> matchesCapacityReservation(instance, r))
+ .filter(r -> r.getAvailableInstanceCount() > 0).findFirst().orElse(null);
+ if (selected == null) {
+ if (target != null) {
+ getRequiredCapacityReservation(region, target);
+ throw new AwsException("InsufficientInstanceCapacity",
+ "The targeted Capacity Reservation has no matching available capacity.", 400);
+ }
+ continue;
+ }
+ selected.getInstanceIds().add(instance.getInstanceId());
+ selected.setAvailableInstanceCount(selected.getAvailableInstanceCount() - 1);
+ changed.put(key(region, selected.getCapacityReservationId()), selected);
+ }
+ if (!changed.isEmpty()) {
+ persistCapacityMembership(changed);
+ }
+ }
+ }
+
+ private void persistCapacityMembership(Map<String, CapacityReservation> changed) {
+ try {
+ capacityReservations.putAllAtomically(changed);
+ } catch (RuntimeException failure) {
+ LOG.errorv(failure, "Failed to persist Capacity Reservation membership for {0}", changed.keySet());
+ AwsException error = new AwsException("InternalError", "Could not persist capacity membership.", 500);
+ error.initCause(failure);
+ throw error;
+ }
+ }
+
+ private String capacityReservationPlatform(String region, String imageId) {
+ String platform = registeredImages.get(key(region, imageId)).map(Image::getPlatform)
+ .or(() -> imageCatalog.findByIdOrAlias(imageId).map(image -> image.platform)).orElse("");
+ return "windows".equals(platform) ? "Windows" : "Linux/UNIX";
+ }
+
+ private boolean matchesCapacityReservation(Instance instance, CapacityReservation reservation) {
+ return "active".equals(reservation.getState())
+ && Objects.equals(instance.getOwnerId(), reservation.getOwnerId())
+ && Objects.equals(instance.getInstanceType(), reservation.getInstanceType())
+ && instance.getPlacement() != null
+ && Objects.equals(instance.getPlacement().getAvailabilityZone(),
+ capacityReservationZone(instance.getRegion(), reservation))
+ && Objects.equals(instance.getPlacement().getTenancy(), reservation.getTenancy())
+ && Objects.equals(instance.getCapacityReservationPlatform(), reservation.getInstancePlatform());
+ }
+
/**
* Creates a Capacity Reservation, {@code active} on the create response and on the first
* describe. Real AWS passes through {@code payment-pending}/{@code assessing} first;
@@ -9862,6 +10081,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
"The request must contain the parameter AvailabilityZone or AvailabilityZoneId.", 400);
}
int count = requirePositiveInstanceCount(instanceCount);
+ if (isSet(availabilityZoneId)) {
+ zoneNameForZoneId(region, availabilityZoneId);
+ }
CapacityReservation reservation = new CapacityReservation();
reservation.setCapacityReservationId("cr-" + randomHex(17));
String ownerAccountId = callerAccountId();
@@ -9886,7 +10108,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
reservation.setInstanceMatchCriteria(instanceMatchCriteria != null ? instanceMatchCriteria : "open");
reservation.setOutpostArn(outpostArn);
reservation.setPlacementGroupArn(placementGroupArn);
- capacityReservations.put(key(region, reservation.getCapacityReservationId()), reservation);
+ synchronized (capacityReservationLock) {
+ reconcileCapacityMembership(region);
+ if ("open".equals(reservation.getInstanceMatchCriteria())) {
+ Set<String> associated = capacityReservations.scan(k -> k.startsWith(region + "::")).stream()
+ .flatMap(existing -> existing.getInstanceIds().stream()).collect(Collectors.toSet());
+ for (Instance instance : instances.scan(k -> k.startsWith(region + "::"))) {
+ if (reservation.getAvailableInstanceCount() == 0) {
+ break;
+ }
+ if ("running".equals(instance.getState().getName()) && !instance.isSpot()
+ && "open".equals(instance.getCapacityReservationPreference())
+ && instance.getCapacityReservationTarget() == null
+ && !associated.contains(instance.getInstanceId())
+ && matchesCapacityReservation(instance, reservation)) {
+ reservation.getInstanceIds().add(instance.getInstanceId());
+ reservation.setAvailableInstanceCount(reservation.getAvailableInstanceCount() - 1);
+ }
+ }
+ }
+ capacityReservations.put(key(region, reservation.getCapacityReservationId()), reservation);
+ }
return reservation;
}
@@ -9897,15 +10139,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
List<CapacityReservation> describeCapacityReservations(String region, List<String> ids,
List<Map.Entry<String, List<String>>> filters) {
- ensureDefaultResources(region);
- for (String id : ids) {
- getRequiredCapacityReservation(region, id);
+ synchronized (capacityReservationLock) {
+ ensureDefaultResources(region);
+ reconcileCapacityMembership(region);
+ for (String id : ids) {
+ getRequiredCapacityReservation(region, id);
+ }
+ return capacityReservations.scan(k -> true).stream()
+ .filter(r -> r.getRegion().equals(region))
+ .filter(r -> ids.isEmpty() || ids.contains(r.getCapacityReservationId()))
+ .filter(r -> matchesFilters(r, filters, region))
+ .map(CapacityReservation::new)
+ .collect(Collectors.toList());
}
- return capacityReservations.scan(k -> true).stream()
- .filter(r -> r.getRegion().equals(region))
- .filter(r -> ids.isEmpty() || ids.contains(r.getCapacityReservationId()))
- .filter(r -> matchesFilters(r, filters, region))
- .collect(Collectors.toList());
}
/**
@@ -9915,29 +10161,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public CapacityReservation modifyCapacityReservation(String region, String capacityReservationId,
Integer instanceCount, java.time.Instant endDate, String endDateType, String instanceMatchCriteria) {
- ensureDefaultResources(region);
- CapacityReservation reservation = getRequiredCapacityReservation(region, capacityReservationId);
- if (instanceCount != null) {
- int delta = requirePositiveInstanceCount(instanceCount) - reservation.getTotalInstanceCount();
- reservation.setTotalInstanceCount(instanceCount);
- reservation.setAvailableInstanceCount(Math.max(0, reservation.getAvailableInstanceCount() + delta));
- }
- if (endDateType != null) {
- reservation.setEndDateType(endDateType);
- }
- // AWS clears EndDate when EndDateType moves back to "unlimited"; ModifyCapacityReservation
- // has no way to explicitly clear EndDate otherwise (CancelCapacityReservation is the only
- // other transition), so mirror that here rather than leaving a stale date behind.
- if ("unlimited".equals(reservation.getEndDateType())) {
- reservation.setEndDate(null);
- } else if (endDate != null) {
- reservation.setEndDate(endDate);
- }
- if (instanceMatchCriteria != null) {
- reservation.setInstanceMatchCriteria(instanceMatchCriteria);
- }
- capacityReservations.put(key(region, capacityReservationId), reservation);
- return reservation;
+ synchronized (capacityReservationLock) {
+ ensureDefaultResources(region);
+ reconcileCapacityMembership(region);
+ CapacityReservation reservation = new CapacityReservation(
+ getRequiredCapacityReservation(region, capacityReservationId));
+ if (instanceCount != null) {
+ int delta = requirePositiveInstanceCount(instanceCount) - reservation.getTotalInstanceCount();
+ if (reservation.getAvailableInstanceCount() + delta < 0) {
+ throw new AwsException("InvalidParameterValue",
+ "The instance count cannot be less than the consumed capacity.", 400);
+ }
+ reservation.setTotalInstanceCount(instanceCount);
+ reservation.setAvailableInstanceCount(reservation.getAvailableInstanceCount() + delta);
+ }
+ if (endDateType != null) {
+ reservation.setEndDateType(endDateType);
+ }
+ // AWS clears EndDate when EndDateType moves back to "unlimited"; ModifyCapacityReservation
+ // has no way to explicitly clear EndDate otherwise (CancelCapacityReservation is the only
+ // other transition), so mirror that here rather than leaving a stale date behind.
+ if ("unlimited".equals(reservation.getEndDateType())) {
+ reservation.setEndDate(null);
+ } else if (endDate != null) {
+ reservation.setEndDate(endDate);
+ }
+ if (instanceMatchCriteria != null) {
+ reservation.setInstanceMatchCriteria(instanceMatchCriteria);
+ }
+ capacityReservations.put(key(region, capacityReservationId), reservation);
+ return reservation;
+ }
}
/**
@@ -9946,11 +10200,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* appears in DescribeCapacityReservations.
*/
public void cancelCapacityReservation(String region, String capacityReservationId) {
- ensureDefaultResources(region);
- CapacityReservation reservation = getRequiredCapacityReservation(region, capacityReservationId);
- reservation.setState("cancelled");
- reservation.setAvailableInstanceCount(0);
- capacityReservations.put(key(region, capacityReservationId), reservation);
+ synchronized (capacityReservationLock) {
+ ensureDefaultResources(region);
+ reconcileCapacityMembership(region);
+ CapacityReservation reservation = new CapacityReservation(
+ getRequiredCapacityReservation(region, capacityReservationId));
+ reservation.setState("cancelled");
+ reservation.getInstanceIds().clear();
+ reservation.setAvailableInstanceCount(0);
+ capacityReservations.put(key(region, capacityReservationId), reservation);
+ }
}
private int requirePositiveInstanceCount(int instanceCount) {
@@ -9962,6 +10221,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return instanceCount;
}
+ private String capacityReservationZone(String region, CapacityReservation reservation) {
+ if (!isSet(reservation.getAvailabilityZoneId())) {
+ return reservation.getAvailabilityZone();
+ }
+ int index = AvailabilityZoneIds.indexOf(region, reservation.getAvailabilityZoneId());
+ return index >= 1 && index <= MODELLED_ZONE_SUFFIXES.length
+ ? region + MODELLED_ZONE_SUFFIXES[index - 1] : null;
+ }
+
private CapacityReservation getRequiredCapacityReservation(String region, String capacityReservationId) {
CapacityReservation reservation = capacityReservations.get(key(region, capacityReservationId)).orElse(null);
if (reservation == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/CapacityReservation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/CapacityReservation.java
index 36f1a263bf..3ae034c151 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/CapacityReservation.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/CapacityReservation.java
@@ -43,9 +43,36 @@ public class CapacityReservation {
private String placementGroupArn;
private String region;
private List<Tag> tags = new ArrayList<>();
+ private List<String> instanceIds = new ArrayList<>();
public CapacityReservation() {}
+ public CapacityReservation(CapacityReservation other) {
+ capacityReservationId = other.capacityReservationId;
+ ownerId = other.ownerId;
+ capacityReservationArn = other.capacityReservationArn;
+ availabilityZone = other.availabilityZone;
+ availabilityZoneId = other.availabilityZoneId;
+ instanceType = other.instanceType;
+ instancePlatform = other.instancePlatform;
+ tenancy = other.tenancy;
+ totalInstanceCount = other.totalInstanceCount;
+ availableInstanceCount = other.availableInstanceCount;
+ ebsOptimized = other.ebsOptimized;
+ ephemeralStorage = other.ephemeralStorage;
+ state = other.state;
+ startDate = other.startDate;
+ endDate = other.endDate;
+ endDateType = other.endDateType;
+ instanceMatchCriteria = other.instanceMatchCriteria;
+ createDate = other.createDate;
+ outpostArn = other.outpostArn;
+ placementGroupArn = other.placementGroupArn;
+ region = other.region;
+ tags = new ArrayList<>(other.tags);
+ instanceIds = new ArrayList<>(other.instanceIds);
+ }
+
public String getCapacityReservationId() { return capacityReservationId; }
public void setCapacityReservationId(String capacityReservationId) { this.capacityReservationId = capacityReservationId; }
@@ -110,4 +137,8 @@ public class CapacityReservation {
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
+
+ public List<String> getInstanceIds() { return instanceIds; }
+ public void setInstanceIds(List<String> instanceIds) { this.instanceIds = instanceIds; }
+
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java
index ef7c28848f..6ae52211c5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java
@@ -19,6 +19,9 @@ public class Instance {
private String stateTransitionReason;
private String instanceType;
private boolean spot;
+ private String capacityReservationPlatform = "Linux/UNIX";
+ private String capacityReservationPreference = "open";
+ private String capacityReservationTarget;
private Placement placement;
private String subnetId;
private String vpcId;
@@ -106,11 +109,26 @@ public class Instance {
public void setImageId(String imageId) { this.imageId = imageId; }
public InstanceState getState() { return state; }
- public void setState(InstanceState state) { this.state = state; }
+ public synchronized void setState(InstanceState state) { this.state = state; }
+
+ public synchronized boolean compareAndSetState(InstanceState expected, InstanceState updated) {
+ if (state != expected) {
+ return false;
+ }
+ state = updated;
+ return true;
+ }
public String getStateTransitionReason() { return stateTransitionReason; }
public void setStateTransitionReason(String stateTransitionReason) { this.stateTransitionReason = stateTransitionReason; }
+ public String getCapacityReservationPlatform() { return capacityReservationPlatform; }
+ public void setCapacityReservationPlatform(String platform) { capacityReservationPlatform = platform; }
+ public String getCapacityReservationPreference() { return capacityReservationPreference; }
+ public void setCapacityReservationPreference(String preference) { capacityReservationPreference = preference; }
+ public String getCapacityReservationTarget() { return capacityReservationTarget; }
+ public void setCapacityReservationTarget(String target) { capacityReservationTarget = target; }
+
public boolean isSpot() { return spot; }
public void setSpot(boolean spot) { this.spot = spot; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingCapacitySuspensionTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingCapacitySuspensionTest.java
index 23e3002fb9..051b5e82d8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingCapacitySuspensionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingCapacitySuspensionTest.java
@@ -68,7 +68,7 @@ class AutoScalingCapacitySuspensionTest {
.thenReturn(List.of(template));
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull(),
- anyBoolean(), isNull(), isNull(), any()))
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull()))
.thenReturn(reservation("i-replacement"));
}
@@ -85,7 +85,7 @@ class AutoScalingCapacitySuspensionTest {
verify(ec2, never()).terminateInstances(anyString(), anyList());
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull(),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
assertEquals(List.of("i-original"), group.getInstances().stream()
.map(AsgInstance::getInstanceId).toList());
service.resumeProcesses(REGION, "suspended-group", processes);
@@ -97,7 +97,7 @@ class AutoScalingCapacitySuspensionTest {
} else {
verify(ec2).runInstances(eq(REGION), any(), any(), eq(1), eq(1), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull(),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
}
}
@@ -165,7 +165,7 @@ class AutoScalingCapacitySuspensionTest {
reconciler.reconcile(group);
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull(),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
verify(ec2, never()).terminateInstances(anyString(), anyList());
} finally {
releaseOperation.countDown();
@@ -188,7 +188,7 @@ class AutoScalingCapacitySuspensionTest {
reconciler.reconcile(group);
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), isNull(), eq(0), isNull(), isNull(), isNull(), isNull(),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
if (recreate) {
assertTrue(service.describeAutoScalingGroups(REGION, List.of("suspended-group"))
.getFirst().getInstances().isEmpty());
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingPlacementTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingPlacementTest.java
index 765cc7f61f..e7cfd2635b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingPlacementTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingPlacementTest.java
@@ -34,6 +34,7 @@ import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -356,7 +357,7 @@ class AutoScalingPlacementTest {
});
when(ec2.runInstances(any(), any(), any(), anyInt(), anyInt(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(),
- anyBoolean(), any(), any(), any())).thenAnswer(call -> {
+ anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())).thenAnswer(call -> {
if (allocations >= failAfter) {
if (deleteOnFailure) {
groupPresent = false;
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
index 23eb41728d..15a719cc8f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
@@ -22,6 +22,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.List;
@@ -131,7 +132,7 @@ class AutoScalingReconcilerTest {
verify(service).completeInstanceRefreshIfSettled("us-east-1", "bad-data");
verify(ec2, never()).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
}
static Stream<Arguments> templateUserData() {
@@ -198,7 +199,7 @@ class AutoScalingReconcilerTest {
anyList(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
isNull(), eq(0), isNull(), eq(metadata), isNull(), eq(expectedEncoding),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -212,7 +213,7 @@ class AutoScalingReconcilerTest {
tags.capture(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
isNull(), eq(0), isNull(), eq(metadata), isNull(), eq(expectedEncoding),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
assertEquals(storedText, version.getData().getUserData());
assertEquals(storedEncoding, version.getData().getEncodedUserData());
assertEquals(propagatedTags.size(), tags.getValue().size());
@@ -240,7 +241,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()),
eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -269,17 +270,54 @@ class AutoScalingReconcilerTest {
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
- anyBoolean(), any(), any(), any())).thenReturn(reservation);
+ anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
ArgumentCaptor<List<LaunchTemplateData.BlockDeviceMapping>> mappings = ArgumentCaptor.captor();
verify(ec2Service).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
- anyBoolean(), any(), any(), mappings.capture());
+ anyBoolean(), any(), any(), mappings.capture(), eq(false), isNull(), isNull());
assertEquals(List.of(root), mappings.getValue());
}
+ @ParameterizedTest
+ @ValueSource(strings = {"none", "targeted"})
+ void scaleOutPassesTheLaunchTemplateCapacityReservationSpecification(String preference) {
+ AutoScalingService asgService = scalingService();
+ Ec2Service ec2Service = mock(Ec2Service.class);
+ AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
+ AutoScalingGroup asg = launchTemplateAsg();
+ stubLaunchTemplate(ec2Service, "ami-version-1", "t3.micro");
+ LaunchTemplateData.CapacityReservationSpecification capacity =
+ new LaunchTemplateData.CapacityReservationSpecification();
+ LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
+ target.setCapacityReservationId("cr-0123456789abcdef0");
+ if ("none".equals(preference)) {
+ capacity.setCapacityReservationPreference("none");
+ } else {
+ capacity.setCapacityReservationTarget(target);
+ }
+ ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1"))
+ .getFirst().getData().setCapacityReservationSpecification(capacity);
+ when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
+ Instance ec2Instance = new Instance();
+ ec2Instance.setInstanceId("i-gp3");
+ Reservation reservation = new Reservation();
+ reservation.setInstances(List.of(ec2Instance));
+ when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
+ any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
+ anyBoolean(), any(), any(), any(), eq(false), isNull(), eq(capacity))).thenReturn(reservation);
+
+ reconciler.reconcile(asg);
+
+ ArgumentCaptor<LaunchTemplateData.CapacityReservationSpecification> specification = ArgumentCaptor.captor();
+ verify(ec2Service).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
+ any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
+ anyBoolean(), any(), any(), any(), eq(false), isNull(), specification.capture());
+ assertEquals(capacity, specification.getValue());
+ }
+
@Test
void scaleOutPersistsInstancesWhenGroupStillExists() {
AutoScalingService asgService = scalingService();
@@ -298,7 +336,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), eq(List.of()),
eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -344,14 +382,14 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
anyList(), eq(null), eq(null), eq(associatePublicIp),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
anyList(), eq(null), eq(null), eq(associatePublicIp),
- isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any());
+ isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
}
@Test
@@ -386,7 +424,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -444,7 +482,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
isNull(), eq(0), isNull(), eq(metadata), isNull(), any(),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -456,7 +494,7 @@ class AutoScalingReconcilerTest {
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
- isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any());
+ isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
assertNull(version.getData().getUserData());
}
@@ -532,7 +570,7 @@ class AutoScalingReconcilerTest {
org.mockito.ArgumentMatchers.anyBoolean(),
org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.isNull(),
- org.mockito.ArgumentMatchers.any());
+ org.mockito.ArgumentMatchers.any(), eq(false), isNull(), isNull());
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRefreshStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRefreshStorageTest.java
index 523941c7c2..a80d3bed6b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRefreshStorageTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingRefreshStorageTest.java
@@ -84,7 +84,7 @@ class AutoScalingRefreshStorageTest {
when(ec2.describeLaunchTemplateVersions(eq(REGION), eq("lt-original"), isNull(), anyList()))
.thenReturn(List.of(template));
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any())).thenReturn(reservation("i-replacement"));
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())).thenReturn(reservation("i-replacement"));
}
private AutoScalingService storedService(String mode) {
@@ -132,7 +132,7 @@ class AutoScalingRefreshStorageTest {
Reservation accepted = reservation("i-replacement");
accepted.getInstances().getFirst().setPlacement(new Placement("us-east-1b"));
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any())).thenReturn(accepted);
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())).thenReturn(accepted);
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "suspended-group", new InstanceRefresh());
reconciler.reconcile(group);
assertEquals("i-replacement", group.getInstances().getFirst().getInstanceId());
@@ -203,7 +203,7 @@ class AutoScalingRefreshStorageTest {
assertAll(
() -> verify(ec2, never()).terminateInstances(anyString(), anyList()),
() -> verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(),
- any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()),
+ any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()),
() -> assertEquals(List.of("i-original"), group.getInstances().stream()
.map(AsgInstance::getInstanceId).toList()),
() -> assertNotEquals("Successful", service.describeInstanceRefreshes(
@@ -215,7 +215,7 @@ class AutoScalingRefreshStorageTest {
void failedReplacementLaunchRemainsPausedAfterRestart(String mode) throws IOException {
setUp(mode);
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()))
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenThrow(new IllegalStateException("launch unavailable"))
.thenReturn(reservation("i-replacement"));
service.startInstanceRefresh(REGION, "suspended-group", new InstanceRefresh());
@@ -231,7 +231,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
assertAll(
() -> verify(ec2, times(1)).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(),
- anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()),
+ anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()),
() -> assertTrue(group.getInstances().isEmpty()));
}
@@ -287,7 +287,7 @@ class AutoScalingRefreshStorageTest {
void failedReplacementRecordsActivityAndRetainsRetryOwnership(String mode) throws IOException {
setUp(mode);
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()))
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenThrow(new AwsException(
"InsufficientInstanceCapacity", "replacement capacity unavailable", 500))
.thenThrow(new AwsException("InsufficientInstanceCapacity", "replacement capacity unavailable", 500))
@@ -319,7 +319,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
reconciler.reconcile(group);
verify(ec2, times(4)).runInstances(eq(REGION), any(), any(), eq(1), eq(1), any(), anyList(), any(),
- eq(token), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ eq(token), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
assertEquals("Successful", service.describeInstanceRefreshes(REGION, "suspended-group", null, null, null)
.instanceRefreshes().getFirst().getStatus());
}
@@ -340,7 +340,7 @@ class AutoScalingRefreshStorageTest {
when(ec2.describeInstances(REGION, List.of(), null)).thenReturn(List.of(unrelated));
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(),
- anyBoolean(), any(), any(), any()))
+ anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenThrow(new IllegalStateException("first replacement launch unavailable"))
.thenReturn(reservation("i-sibling"))
.thenReturn(reservation("i-retry"));
@@ -385,7 +385,7 @@ class AutoScalingRefreshStorageTest {
void launchRetryResumesWithSavedToken(String mode) throws IOException {
setUp(mode);
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()))
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenThrow(new IllegalStateException("launch unavailable"))
.thenReturn(reservation("i-replacement"));
InstanceRefresh refresh = service.startInstanceRefresh(REGION, "suspended-group", new InstanceRefresh());
@@ -395,7 +395,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
reconciler.reconcile(group);
verify(ec2, times(2)).runInstances(eq(REGION), any(), any(), eq(1), eq(1), any(), anyList(), any(),
- eq(token), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ eq(token), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
verify(ec2, times(1)).terminateInstances(REGION, List.of("i-original"));
assertEquals("Successful", service.describeInstanceRefreshes(REGION, "suspended-group", null, null, null)
.instanceRefreshes().getFirst().getStatus());
@@ -415,7 +415,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
assertEquals(List.of("i-recovered"), group.getInstances().stream().map(AsgInstance::getInstanceId).toList());
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
reconciler.reconcile(group);
assertEquals(1, group.getInstances().size());
}
@@ -445,7 +445,7 @@ class AutoScalingRefreshStorageTest {
verify(ec2).terminateInstances(REGION, List.of("i-original"));
assertTrue(group.getInstances().isEmpty());
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
}
@ParameterizedTest
@@ -460,7 +460,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
verify(ec2, never()).terminateInstances(anyString(), anyList());
verify(ec2).runInstances(eq(REGION), any(), any(), eq(1), eq(1), any(), anyList(), any(), isNull(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
assertEquals(2, group.getInstances().size());
}
@@ -475,7 +475,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
verify(ec2).terminateInstances(REGION, List.of("i-original"));
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
assertTrue(group.getInstances().isEmpty());
assertEquals("Successful", service.describeInstanceRefreshes(REGION, "suspended-group", null, null, null)
.instanceRefreshes().getFirst().getStatus());
@@ -492,7 +492,7 @@ class AutoScalingRefreshStorageTest {
reconciler.reconcile(group);
assertTrue(group.getInstances().isEmpty());
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
service.resumeProcesses(REGION, "suspended-group", List.of("InstanceRefresh"));
restart(mode);
reconciler.reconcile(group);
@@ -522,7 +522,7 @@ class AutoScalingRefreshStorageTest {
assertEquals("i-recovered", restored.getReplacements().getFirst().getReplacementInstanceId());
assertEquals("Successful", restored.getStatus());
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
}
@ParameterizedTest
@@ -594,7 +594,7 @@ class AutoScalingRefreshStorageTest {
verify(ec2, never()).terminateInstances(anyString(), argThat(ids -> ids.contains(detachedId)));
if (decrement) {
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
}
assertEquals("Successful", restored.getStatus());
}
@@ -613,7 +613,7 @@ class AutoScalingRefreshStorageTest {
List<Reservation> launched = new ArrayList<>();
when(ec2.describeInstances(REGION, List.of(), null)).thenAnswer(invocation -> List.copyOf(launched));
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any())).thenAnswer(invocation -> {
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull())).thenAnswer(invocation -> {
Reservation accepted = reservation("i-accepted");
accepted.getInstances().getFirst().setClientToken(invocation.getArgument(8));
accepted.getInstances().getFirst().setInstanceType("t3.micro");
@@ -646,7 +646,7 @@ class AutoScalingRefreshStorageTest {
() -> assertEquals("t3.micro", recovered.getInstanceType()),
() -> assertEquals("us-east-1a", recovered.getAvailabilityZone()));
verify(ec2, times(1)).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
}
@ParameterizedTest
@@ -673,7 +673,7 @@ class AutoScalingRefreshStorageTest {
() -> assertNull(recovered.getLaunchTemplateName()),
() -> assertNull(recovered.getLaunchTemplateVersion()));
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
}
@ParameterizedTest
@@ -689,7 +689,7 @@ class AutoScalingRefreshStorageTest {
service.saveAutoScalingGroupIfPresent(group);
when(ec2.describeInstances(REGION, List.of(), null)).thenReturn(List.of());
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
- anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any()))
+ anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenReturn(reservation("i-first-replacement"))
.thenThrow(new IllegalStateException("Second launch unavailable"))
.thenReturn(reservation("i-second-replacement"));
@@ -708,7 +708,7 @@ class AutoScalingRefreshStorageTest {
assertEquals(1, restored.getInstancesToUpdate());
assertEquals("Complete", restored.getReplacements().getFirst().getPhase());
verify(ec2, times(2)).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
service.resumeProcesses(REGION, "suspended-group", List.of("InstanceRefresh"));
reconciler.reconcile(group);
reconciler.reconcile(group);
@@ -717,7 +717,7 @@ class AutoScalingRefreshStorageTest {
assertEquals(List.of("i-first-replacement", "i-second-replacement"), group.getInstances().stream()
.map(AsgInstance::getInstanceId).toList());
verify(ec2, times(3)).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
- any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
+ any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
verify(ec2).terminateInstances(REGION, List.of("i-original", "i-second"));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/LaunchConfigurationUserDataStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/LaunchConfigurationUserDataStorageTest.java
index 6b7cd15d54..8ed585aa02 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/LaunchConfigurationUserDataStorageTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/LaunchConfigurationUserDataStorageTest.java
@@ -104,7 +104,7 @@ class LaunchConfigurationUserDataStorageTest {
when(ec2.runInstances(eq(REGION), eq("ami-original"), eq("t3.micro"), eq(1), eq(1),
isNull(), anyList(), isNull(), isNull(), anyList(), eq(text), isNull(), isNull(),
isNull(), eq(0), isNull(), isNull(), isNull(), eq(encoded),
- anyBoolean(), isNull(), isNull(), any())).thenReturn(result);
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(result);
AutoScalingReconciler reconciler = new AutoScalingReconciler(service, ec2, mock(ElbV2Service.class));
try {
reconciler.reconcile(group);
@@ -112,7 +112,7 @@ class LaunchConfigurationUserDataStorageTest {
verify(ec2).runInstances(eq(REGION), eq("ami-original"), eq("t3.micro"), eq(1), eq(1),
isNull(), anyList(), isNull(), isNull(), anyList(), eq(text), isNull(), isNull(),
isNull(), eq(0), isNull(), isNull(), isNull(), eq(encoded),
- anyBoolean(), isNull(), isNull(), any());
+ anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
assertEquals(origin.equals("legacy") ? null : Boolean.TRUE, restored.getUserDataBase64Encoded());
assertEquals(origin.equals("legacy") ? input : encoded, restored.getUserData());
} finally {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java
index 64f3232380..f69005c6ca 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java
@@ -74,6 +74,38 @@ class Ec2LaunchTemplateCfnProvisionerTest {
return lt;
}
+ @Test
+ void retainsCapacityReservationPreferenceAndTarget() throws Exception {
+ when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), any(), any()))
+ .thenReturn(template("lt-capacity"));
+ JsonNode props = mapper.readTree("""
+ {"LaunchTemplateName":"my-lt","LaunchTemplateData":{
+ "ImageId":"ami-test","CapacityReservationSpecification":{
+ "CapacityReservationPreference":"open",
+ "CapacityReservationTarget":{"CapacityReservationId":"cr-0123456789abcdef0"}}}}
+ """);
+
+ provisioner.provision(resource("Template"), props, ctx());
+
+ ArgumentCaptor<LaunchTemplateData> data = ArgumentCaptor.forClass(LaunchTemplateData.class);
+ verify(ec2).createLaunchTemplate(eq("us-east-1"), eq("my-lt"), data.capture(), any());
+ assertEquals("open", data.getValue().getCapacityReservationSpecification().getCapacityReservationPreference());
+ assertEquals("cr-0123456789abcdef0", data.getValue().getCapacityReservationSpecification()
+ .getCapacityReservationTarget().getCapacityReservationId());
+ }
+
+ @Test
+ void refusesMalformedCapacityReservationDeclarationBeforeCreatingTemplate() throws Exception {
+ JsonNode props = mapper.readTree("""
+ {"LaunchTemplateName":"my-lt","LaunchTemplateData":{
+ "CapacityReservationSpecification":{"CapacityReservationPreference":["none"]}}}
+ """);
+
+ assertThrows(AwsException.class, () -> provisioner.provision(resource("Template"), props, ctx()));
+
+ verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any());
+ }
+
@Test
void setsPhysicalIdAndGetAttAttributes() {
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), any(), any()))
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.java
new file mode 100644
index 0000000000..875ac32286
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CapacityReservationAssociationServiceTest.java
@@ -0,0 +1,340 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
+import io.github.hectorvent.floci.services.ec2.model.Instance;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+class Ec2CapacityReservationAssociationServiceTest {
+ private static final String ACCOUNT = "111111111111";
+ private static final String REGION = "us-east-1";
+ private static final String FILE = "ec2-capacity-reservations.json";
+
+ @TempDir
+ Path directory;
+
+ @Test
+ void unknownZoneIdIsRejectedBeforeReservationPublication() {
+ try (Fixture fixture = new Fixture("memory", directory)) {
+ AwsException failure = assertThrows(AwsException.class, () ->
+ fixture.service.createCapacityReservation(REGION, "t3.micro", "Linux/UNIX", null,
+ "use1-az99", 1, null, null, null, null, null, null, null, null));
+ assertEquals("InvalidParameterValue", failure.getErrorCode());
+ assertTrue(fixture.service.describeCapacityReservations(REGION, List.of(), Map.of()).isEmpty());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"persistent", "hybrid", "wal"})
+ void legacyUnknownZoneDoesNotBlockLaunchOrRestart(String mode) {
+ String invalidId;
+ try (Fixture fixture = new Fixture(mode, directory)) {
+ CapacityReservation invalid = fixture.create(1);
+ invalid.setAvailabilityZoneId("use1-az99");
+ invalidId = invalid.getCapacityReservationId();
+ fixture.store.put(REGION + "::" + invalidId, invalid);
+ }
+ try (Fixture recovered = new Fixture(mode, directory)) {
+ Instance instance = recovered.launch();
+ assertEquals(null, recovered.service.instanceCapacityReservationId(instance));
+ recovered.service.stopInstances(REGION, List.of(instance.getInstanceId()));
+ recovered.service.startInstances(REGION, List.of(instance.getInstanceId()));
+ assertEquals(null, recovered.service.instanceCapacityReservationId(instance));
+ CapacityReservation invalid = recovered.service.describeCapacityReservations(REGION,
+ List.of(invalidId), Map.of()).getFirst();
+ assertEquals(1, invalid.getAvailableInstanceCount());
+ assertTrue(invalid.getInstanceIds().isEmpty());
+ }
+ }
+
+ @Test
+ void newOpenReservationAdoptsOnlyEligibleUnassociatedRunningInstances() {
+ try (Fixture fixture = new Fixture("memory", directory)) {
+ Instance open = fixture.launchWithPreference("open");
+ Instance excluded = fixture.launchWithPreference("none");
+ fixture.service.describeInstances(REGION,
+ List.of(open.getInstanceId(), excluded.getInstanceId()), Map.of());
+ CapacityReservation first = fixture.create(2);
+ CapacityReservation second = fixture.create(2);
+
+ assertEquals(List.of(open.getInstanceId()), fixture.describe(first).getInstanceIds());
+ assertEquals(1, fixture.describe(first).getAvailableInstanceCount());
+ assertEquals(2, fixture.describe(second).getAvailableInstanceCount());
+ assertEquals(first.getCapacityReservationId(), fixture.service.instanceCapacityReservationId(open));
+ assertEquals(null, fixture.service.instanceCapacityReservationId(excluded));
+ fixture.service.terminateInstances(REGION, List.of(open.getInstanceId(), excluded.getInstanceId()));
+ assertEquals(2, fixture.describe(first).getAvailableInstanceCount());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"persistent", "hybrid", "wal"})
+ void adoptedRunningMembershipSurvivesRestart(String mode) {
+ CapacityReservation capacity;
+ String instanceId;
+ try (Fixture fixture = new Fixture(mode, directory)) {
+ instanceId = fixture.launch().getInstanceId();
+ fixture.service.describeInstances(REGION, List.of(instanceId), Map.of());
+ capacity = fixture.create(2);
+ assertEquals(List.of(instanceId), fixture.describe(capacity).getInstanceIds());
+ }
+ try (Fixture restarted = new Fixture(mode, directory)) {
+ assertEquals(List.of(instanceId), restarted.describe(capacity).getInstanceIds());
+ assertEquals(1, restarted.describe(capacity).getAvailableInstanceCount());
+ restarted.service.stopInstances(REGION, List.of(instanceId));
+ assertTrue(restarted.describe(capacity).getInstanceIds().isEmpty());
+ assertEquals(2, restarted.describe(capacity).getAvailableInstanceCount());
+ }
+ }
+
+ @Test
+ void failedReleaseRetainsMembershipUntilRetryReconcilesPersistedStop() {
+ try (Fixture fixture = new Fixture("persistent", directory)) {
+ CapacityReservation source = fixture.create(1);
+ Instance instance = fixture.launch();
+ doThrow(new IllegalStateException("injected release failure")).when(fixture.store).putAllAtomically(any());
+ assertThrows(AwsException.class,
+ () -> fixture.service.stopInstances(REGION, List.of(instance.getInstanceId())));
+ assertEquals(0, fixture.store.get(REGION + "::" + source.getCapacityReservationId())
+ .orElseThrow().getAvailableInstanceCount());
+ reset(fixture.store);
+ assertEquals(1, fixture.describe(source).getAvailableInstanceCount());
+ assertTrue(fixture.describe(source).getInstanceIds().isEmpty());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void admissionSerializesWithCancellation(boolean restart) throws Exception {
+ try (Fixture fixture = new Fixture("memory", directory);
+ ExecutorService workers = Executors.newFixedThreadPool(2)) {
+ CapacityReservation source = fixture.create(1);
+ CapacityReservation destination = fixture.create(1);
+ Instance stopped = restart ? fixture.launch() : null;
+ if (stopped != null) {
+ fixture.service.stopInstances(REGION, List.of(stopped.getInstanceId()));
+ }
+ CountDownLatch beforePublish = new CountDownLatch(1);
+ CountDownLatch resume = new CountDownLatch(1);
+ AtomicReference<String> acquiredId = new AtomicReference<>();
+ doAnswer(invocation -> {
+ Map<String, CapacityReservation> batch = invocation.getArgument(0);
+ acquiredId.compareAndSet(null, batch.values().iterator().next().getCapacityReservationId());
+ beforePublish.countDown();
+ assertTrue(resume.await(10, TimeUnit.SECONDS));
+ return invocation.callRealMethod();
+ }).when(fixture.store).putAllAtomically(any());
+ Future<Instance> admission = workers.submit(() -> {
+ if (stopped == null) {
+ return fixture.launch();
+ }
+ fixture.service.startInstances(REGION, List.of(stopped.getInstanceId()));
+ return stopped;
+ });
+ try {
+ assertTrue(beforePublish.await(10, TimeUnit.SECONDS));
+ CapacityReservation admittedSource = source.getCapacityReservationId().equals(acquiredId.get())
+ ? source : destination;
+ CapacityReservation other = admittedSource == source ? destination : source;
+ AtomicReference<Thread> mutationThread = new AtomicReference<>();
+ Future<?> mutation = workers.submit(() -> {
+ mutationThread.set(Thread.currentThread());
+ fixture.service.cancelCapacityReservation(REGION, admittedSource.getCapacityReservationId());
+ });
+ await().atMost(Duration.ofSeconds(10)).until(() -> mutation.isDone()
+ || mutationThread.get() != null && mutationThread.get().getState() == Thread.State.BLOCKED);
+ assertTrue(!mutation.isDone(), "Mutation must wait for atomic admission publication");
+ resume.countDown();
+ Instance instance = admission.get(10, TimeUnit.SECONDS);
+ mutation.get(10, TimeUnit.SECONDS);
+ CapacityReservation currentSource = fixture.describe(admittedSource);
+ CapacityReservation currentDestination = fixture.describe(other);
+ assertTrue(currentSource.getInstanceIds().isEmpty());
+ assertEquals(null, fixture.service.instanceCapacityReservationId(instance));
+ assertEquals(1, currentDestination.getAvailableInstanceCount());
+ } finally {
+ resume.countDown();
+ }
+ }
+ }
+
+ @Test
+ void rejectedLaunchAfterCancellationReclaimsItsPublishedResources() throws Exception {
+ try (Fixture fixture = new Fixture("persistent", directory);
+ ExecutorService workers = Executors.newSingleThreadExecutor()) {
+ CapacityReservation source = fixture.create(1);
+ CapacityReservation destination = fixture.create(1);
+ CountDownLatch beforeAdmission = new CountDownLatch(1);
+ CountDownLatch resume = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ beforeAdmission.countDown();
+ assertTrue(resume.await(10, TimeUnit.SECONDS));
+ return invocation.callRealMethod();
+ }).when(fixture.service).acquireCapacity(eq(REGION), any());
+ Future<Instance> launch = workers.submit(() -> fixture.launch(source.getCapacityReservationId()));
+ try {
+ assertTrue(beforeAdmission.await(10, TimeUnit.SECONDS));
+ fixture.service.cancelCapacityReservation(REGION, source.getCapacityReservationId());
+ resume.countDown();
+ ExecutionException failure = assertThrows(ExecutionException.class,
+ () -> launch.get(10, TimeUnit.SECONDS));
+ assertTrue(failure.getCause() instanceof AwsException);
+ assertTrue(fixture.describe(source).getInstanceIds().isEmpty());
+ assertTrue(fixture.describe(destination).getInstanceIds().isEmpty());
+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).stream()
+ .flatMap(reservation -> reservation.getInstances().stream())
+ .allMatch(instance -> "terminated".equals(instance.getState().getName())));
+ assertTrue(fixture.service.describeVolumes(REGION, List.of(), Map.of()).isEmpty());
+ } finally {
+ resume.countDown();
+ }
+ }
+ }
+
+ @Test
+ void failedLaunchMembershipPublicationReleasesOwnedVolumeAndInstanceCapacity() {
+ try (Fixture fixture = new Fixture("persistent", directory)) {
+ CapacityReservation source = fixture.create(1);
+ doThrow(new IllegalStateException("injected admission failure"))
+ .when(fixture.store).putAllAtomically(any());
+
+ AwsException failure = assertThrows(AwsException.class, fixture::launch);
+
+ assertEquals("InternalError", failure.getErrorCode());
+ reset(fixture.store);
+ assertEquals(1, fixture.describe(source).getAvailableInstanceCount());
+ assertTrue(fixture.describe(source).getInstanceIds().isEmpty());
+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).stream()
+ .flatMap(reservation -> reservation.getInstances().stream())
+ .allMatch(instance -> "terminated".equals(instance.getState().getName())));
+ assertTrue(fixture.service.describeVolumes(REGION, List.of(), Map.of()).isEmpty());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void targetedAdmissionLaunchesOnlyTheAvailableCapacity(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 capacity = fixture.create(2);
+ LaunchTemplateData.CapacityReservationSpecification specification =
+ new LaunchTemplateData.CapacityReservationSpecification();
+ LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
+ target.setCapacityReservationId(capacity.getCapacityReservationId());
+ specification.setCapacityReservationTarget(target);
+ 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(capacity).getAvailableInstanceCount());
+ assertEquals(2, fixture.describe(capacity).getInstanceIds().size());
+ assertTrue(fixture.service.describeInstances(REGION, List.of(), Map.of()).stream()
+ .flatMap(reservation -> reservation.getInstances().stream())
+ .noneMatch(instance -> "terminated".equals(instance.getState().getName())));
+ }
+ }
+
+ private static final class Fixture implements AutoCloseable {
+ private final EmulatorConfig config;
+ private final StorageFactory factory;
+ private final AccountAwareStorageBackend<CapacityReservation> store;
+ private final Ec2Service service;
+
+ private Fixture(String mode, Path path) {
+ config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.defaultAccountId()).thenReturn(ACCOUNT);
+ when(config.services().ec2().mock()).thenReturn(true);
+ when(config.services().ec2().mockPublicAddresses())
+ .thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
+ when(config.storage().persistentPath()).thenReturn(path.toString());
+ when(config.storage().wal().compactionIntervalMs()).thenReturn(3600000L);
+ ServiceConfigAccess access = mock(ServiceConfigAccess.class);
+ when(access.storageMode("ec2")).thenReturn(mode);
+ when(access.storageFlushInterval("ec2")).thenReturn(3600000L);
+ factory = new StorageFactory(config, access);
+ store = spy(factory.create("ec2", FILE, new TypeReference<Map<String, CapacityReservation>>() {}));
+ StorageFactory serviceFactory = spy(factory);
+ doReturn(store).when(serviceFactory).create(eq("ec2"), eq(FILE), any());
+ Ec2ImageCatalog catalog = new Ec2ImageCatalog();
+ service = spy(new Ec2Service(config, null, null, new AmiImageResolver(catalog),
+ catalog, new Ec2InstanceTypeCatalog(), serviceFactory));
+ }
+
+ private Instance launch() {
+ return service.runInstances(REGION, "ami-test", "t3.micro", 1, 1,
+ null, List.of(), null, null, List.of(), null, null).getInstances().getFirst();
+ }
+
+ private Instance launch(String targetId) {
+ LaunchTemplateData.CapacityReservationSpecification specification =
+ new LaunchTemplateData.CapacityReservationSpecification();
+ LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
+ target.setCapacityReservationId(targetId);
+ specification.setCapacityReservationTarget(target);
+ return 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,
+ false, null, specification).getInstances().getFirst();
+ }
+
+ private Instance launchWithPreference(String preference) {
+ LaunchTemplateData.CapacityReservationSpecification specification =
+ new LaunchTemplateData.CapacityReservationSpecification();
+ specification.setCapacityReservationPreference(preference);
+ return 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,
+ false, null, specification).getInstances().getFirst();
+ }
+
+ private CapacityReservation create(int count) {
+ return service.createCapacityReservation(REGION, "t3.micro", "Linux/UNIX", REGION + "a",
+ null, count, null, null, null, null, null, null, null, null);
+ }
+
+ private CapacityReservation describe(CapacityReservation reservation) {
+ return service.describeCapacityReservations(REGION,
+ List.of(reservation.getCapacityReservationId()), Map.of()).getFirst();
+ }
+
+ @Override
+ public void close() {
+ factory.shutdownAll();
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
index 8068fcaf65..14e69e1ee5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java
@@ -13,6 +13,7 @@ import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.PingCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
+import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerConfig;
@@ -324,6 +325,61 @@ class Ec2ContainerManagerTest {
"a transient Docker failure must not drop an existing IMDS source registration");
}
+ @Test
+ void restartWaitsForPhysicalStopBeforeStartingTheContainer() {
+ ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
+ when(lifecycle.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
+ DockerClient docker = mock(DockerClient.class);
+ when(docker.startContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
+ InspectContainerCmd inspect = mock(InspectContainerCmd.class);
+ when(docker.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
+ InspectContainerResponse response = vpcAttachedInspectResponse("10.0.1.10", "172.17.0.9");
+ when(inspect.exec()).thenReturn(response);
+ StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
+ when(docker.stopContainerCmd(TEST_CONTAINER_ID)).thenReturn(stop);
+ ExecutorService executor = mock(ExecutorService.class);
+ List<Runnable> tasks = new ArrayList<>();
+ doAnswer(invocation -> {
+ tasks.add(invocation.getArgument(0));
+ return null;
+ }).when(executor).submit(any(Runnable.class));
+ Ec2ContainerManager manager = new Ec2ContainerManager(mock(ContainerBuilder.class), lifecycle,
+ mock(ContainerLogStreamer.class), mock(ContainerDetector.class), mock(DockerHostResolver.class),
+ docker, mock(PortAllocator.class), mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
+ mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class), mock(RegionResolver.class),
+ mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class),
+ mock(ContainerReachableEndpoint.class), executor, Duration.ofSeconds(5));
+ Instance instance = new Instance();
+ instance.setInstanceId("i-stop-restart");
+ instance.setDockerContainerId(TEST_CONTAINER_ID);
+ List<String> operations = new ArrayList<>();
+ AtomicBoolean physicalRunning = new AtomicBoolean(true);
+ when(lifecycle.isContainerRunning(TEST_CONTAINER_ID)).thenAnswer(invocation -> physicalRunning.get());
+ doAnswer(invocation -> {
+ operations.add("stop");
+ physicalRunning.set(false);
+ return null;
+ }).when(stop).exec();
+ StartContainerCmd start = docker.startContainerCmd(TEST_CONTAINER_ID);
+ doAnswer(invocation -> {
+ operations.add("start");
+ physicalRunning.set(true);
+ return null;
+ }).when(start).exec();
+
+ manager.stop(instance);
+ manager.start(instance);
+ assertEquals(1, tasks.size(), "start must wait until the physical stop completes");
+ tasks.getFirst().run();
+ assertEquals(List.of("stop"), operations);
+ assertEquals(2, tasks.size());
+ tasks.get(1).run();
+
+ assertEquals(List.of("stop", "start"), operations);
+ assertTrue(physicalRunning.get());
+ assertEquals("running", instance.getState().getName());
+ }
+
@Test
void startRegistersTheNewBridgeAddressDockerHandsOutOnRestart() throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java
index c3066e0863..41468ad263 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java
@@ -5,6 +5,10 @@ import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@@ -28,6 +32,62 @@ class Ec2CreateFleetIntegrationTest {
private static final String CONTRACT_IMAGE_ID = "ami-create-fleet-contract";
private static String launchTemplateId;
+ @ParameterizedTest
+ @ValueSource(strings = {"none", "targeted"})
+ void fleetRetainsCapacityReservationEligibility(String preference) {
+ String capacityId = given().header("Authorization", AUTH_HEADER)
+ .formParam("Action", "CreateCapacityReservation")
+ .formParam("InstanceType", "t3.small").formParam("InstancePlatform", "Linux/UNIX")
+ .formParam("AvailabilityZone", "us-east-1a").formParam("InstanceCount", "1")
+ .formParam("InstanceMatchCriteria", "targeted".equals(preference) ? "targeted" : "open")
+ .post("/").then().statusCode(200).extract()
+ .xmlPath().getString("CreateCapacityReservationResponse.capacityReservation.capacityReservationId");
+ String templateId = null;
+ String instanceId = null;
+ try {
+ String selector = "none".equals(preference)
+ ? "CapacityReservationPreference" : "CapacityReservationTarget.CapacityReservationId";
+ templateId = given().header("Authorization", AUTH_HEADER)
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", "fleet-capacity-" + UUID.randomUUID())
+ .formParam("LaunchTemplateData.ImageId", "ami-test")
+ .formParam("LaunchTemplateData.InstanceType", "t3.small")
+ .formParam("LaunchTemplateData.Placement.AvailabilityZone", "us-east-1a")
+ .formParam("LaunchTemplateData.CapacityReservationSpecification." + selector,
+ "none".equals(preference) ? "none" : capacityId)
+ .post("/").then().statusCode(200).extract()
+ .xmlPath().getString("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
+ instanceId = given().header("Authorization", AUTH_HEADER)
+ .formParam("Action", "CreateFleet").formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", templateId)
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "1")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .post("/").then().statusCode(200).extract()
+ .xmlPath().getString("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item");
+ given().header("Authorization", AUTH_HEADER)
+ .formParam("Action", "DescribeCapacityReservations").formParam("CapacityReservationId.1", capacityId)
+ .post("/").then().statusCode(200)
+ .body("DescribeCapacityReservationsResponse.capacityReservationSet.item.availableInstanceCount",
+ equalTo("none".equals(preference) ? "1" : "0"));
+ given().header("Authorization", AUTH_HEADER)
+ .formParam("Action", "DescribeInstances").formParam("InstanceId.1", instanceId)
+ .post("/").then().statusCode(200)
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.capacityReservationId.text()",
+ equalTo("none".equals(preference) ? "" : capacityId));
+ } finally {
+ if (instanceId != null) {
+ given().header("Authorization", AUTH_HEADER).formParam("Action", "TerminateInstances")
+ .formParam("InstanceId.1", instanceId).post("/").then().statusCode(200);
+ }
+ if (templateId != null) {
+ given().header("Authorization", AUTH_HEADER).formParam("Action", "DeleteLaunchTemplate")
+ .formParam("LaunchTemplateId", templateId).post("/").then().statusCode(200);
+ }
+ given().header("Authorization", AUTH_HEADER).formParam("Action", "CancelCapacityReservation")
+ .formParam("CapacityReservationId", capacityId).post("/").then().statusCode(200);
+ }
+ }
+
@Test
@Order(1)
void createFleetDryRunReturnsAwsCompatibleExceptionWithoutLaunching() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java
index bf82b20d57..4ca0eb9af6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java
@@ -44,7 +44,7 @@ class Ec2CreateFleetRollbackTest {
nullable(String.class), nullable(Boolean.class), nullable(String.class), anyInt(),
nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class),
nullable(String.class), nullable(String.class), eq(false), nullable(String.class),
- nullable(String.class), anyList(), eq(false)))
+ nullable(String.class), anyList(), eq(false), nullable(String.class), nullable(LaunchTemplateData.CapacityReservationSpecification.class)))
.thenReturn(reservation("i-first"))
.thenReturn(reservation("i-second"))
.thenThrow(new AwsException("InvalidSubnetID.NotFound", "launch failed", 400));
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
index 996e937d14..527bc534b1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2RunInstancesPublicIpParamTest.java
@@ -64,7 +64,8 @@ class Ec2RunInstancesPublicIpParamTest {
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class),
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
- nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class)))
+ nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class),
+ nullable(LaunchTemplateData.CapacityReservationSpecification.class)))
.thenReturn(new Reservation());
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
@@ -79,7 +80,8 @@ class Ec2RunInstancesPublicIpParamTest {
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class),
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
- nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class));
+ nullable(String.class), nullable(String.class), nullable(List.class), eq(false), nullable(String.class),
+ nullable(LaunchTemplateData.CapacityReservationSpecification.class));
if (expected == null) {
assertNull(associatePublicIp.getValue(),
"an absent override must stay null so the subnet default decides");
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
index b3e27a8ba2..872d883175 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
@@ -8580,4 +8580,27 @@ class Ec2ServiceTest {
assertEquals(1, service.allocateHosts("us-east-1", "us-east-1c", "m5.large", null, 1,
null, null, null, null, null).size());
}
+ @Test
+ void capacityAssociationScansStayWithinTheCallerAccount() {
+ // Instance is the EC2 model in this file, so qualify the CDI Instance type.
+ jakarta.enterprise.inject.Instance<RequestContext> contexts = mock(jakarta.enterprise.inject.Instance.class);
+ RequestContext context = new RequestContext();
+ context.setAccountId("111111111111");
+ when(contexts.isResolvable()).thenReturn(true);
+ when(contexts.get()).thenReturn(context);
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(contexts), contexts);
+ String region = "us-east-1";
+ String capacityId = service.createCapacityReservation(region, "t3.micro", "Linux/UNIX", region + "a",
+ null, 1, null, null, null, null, null, null, null, null).getCapacityReservationId();
+ String instanceId = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null, List.of(),
+ null, null, List.of(), null, null).getInstances().getFirst().getInstanceId();
+ assertEquals(capacityId, service.capacityReservationAssociations(region).get(instanceId));
+ context.setAccountId("222222222222");
+ assertTrue(service.capacityReservationAssociations(region).isEmpty());
+ assertTrue(service.describeInstances(region, List.of(), Map.of()).isEmpty());
+ context.setAccountId("111111111111");
+ assertEquals(capacityId, service.capacityReservationAssociations(region).get(instanceId));
+ }
}