mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(ec2): model scheduled capacity reservations (#6764)
* fix(ec2): reject unsupported future capacity reservations Reject StartDate before capacity reservation creation or client-token replay. Preserve immediate reservation behavior. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): model scheduled capacity reservations Retain future start and commitment metadata, activate through capacity reconciliation, and preserve client-token replay. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): preserve activation membership and replay tags Reuse open-reservation instance matching during activation, persist creation tag identity, and keep replay from overwriting later tag edits. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com> * fix(ec2): validate future reservation matching and capacity Require targeted matching, supported instance families and at least 32 vCPUs before future reservation publication. Preserve scheduling, tag replay and immediate reservation behavior. Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com> Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
3649b18e15
commit
b5033e970d
6 files changed
+715
-73
No files matched your search
@@ -0,0 +1,108 @@
|
||||
"""Future reservations retain their scheduling metadata and client-token identity."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def test_future_reservation_is_scheduled_and_replayed(ec2_client, unique_name):
|
||||
zone = ec2_client.describe_availability_zones()["AvailabilityZones"][0]["ZoneName"]
|
||||
start = (datetime.now(timezone.utc) + timedelta(days=7)).replace(microsecond=0)
|
||||
request = {
|
||||
"InstanceType": "t3.micro", "InstancePlatform": "Linux/UNIX", "InstanceCount": 16, "InstanceMatchCriteria": "targeted",
|
||||
"AvailabilityZone": zone, "ClientToken": unique_name,
|
||||
"StartDate": start, "CommitmentDuration": 86400, "DeliveryPreference": "incremental",
|
||||
"TagSpecifications": [
|
||||
{"ResourceType": "capacity-reservation", "Tags": [{"Key": "Name", "Value": unique_name}]}
|
||||
],
|
||||
}
|
||||
created = ec2_client.create_capacity_reservation(**request)["CapacityReservation"]
|
||||
identifier = created["CapacityReservationId"]
|
||||
try:
|
||||
assert created["State"] == "scheduled"
|
||||
assert created["StartDate"] == start
|
||||
assert created["AvailableInstanceCount"] == 0
|
||||
assert created["DeliveryPreference"] == "incremental"
|
||||
assert created["CommitmentInfo"] == {
|
||||
"CommitmentDuration": 86400, "CommitmentEndDate": start + timedelta(days=1),
|
||||
"CommittedInstanceCount": 16,
|
||||
}
|
||||
assert ec2_client.describe_tags(Filters=[{"Name": "resource-id", "Values": [identifier]}])["Tags"] == [
|
||||
{"ResourceId": identifier, "ResourceType": "capacity-reservation", "Key": "Name", "Value": unique_name}
|
||||
]
|
||||
replay = ec2_client.create_capacity_reservation(**request)["CapacityReservation"]
|
||||
assert replay == created
|
||||
with pytest.raises(ClientError) as error:
|
||||
ec2_client.create_capacity_reservation(**{**request, "CommitmentDuration": 86401})
|
||||
assert error.value.response["Error"]["Code"] == "IdempotentParameterMismatch"
|
||||
described = ec2_client.describe_capacity_reservations(
|
||||
Filters=[{"Name": "tag:Name", "Values": [unique_name]}]
|
||||
)["CapacityReservations"]
|
||||
assert described == [created]
|
||||
ec2_client.create_tags(Resources=[identifier], Tags=[{"Key": "Name", "Value": unique_name + "-edited"}])
|
||||
replay = ec2_client.create_capacity_reservation(**request)["CapacityReservation"]
|
||||
assert replay["Tags"] == [{"Key": "Name", "Value": unique_name + "-edited"}]
|
||||
with pytest.raises(ClientError) as tag_error:
|
||||
ec2_client.create_capacity_reservation(**{
|
||||
**request, "TagSpecifications": [{"ResourceType": "capacity-reservation",
|
||||
"Tags": [{"Key": "Name", "Value": "different"}]}],
|
||||
})
|
||||
assert tag_error.value.response["Error"]["Code"] == "IdempotentParameterMismatch"
|
||||
after = ec2_client.describe_capacity_reservations(CapacityReservationIds=[identifier])["CapacityReservations"]
|
||||
assert after == [replay]
|
||||
finally:
|
||||
ec2_client.cancel_capacity_reservation(CapacityReservationId=identifier)
|
||||
|
||||
|
||||
def test_invalid_schedule_does_not_create_capacity(ec2_client, unique_name):
|
||||
request = {
|
||||
"InstanceType": "t3.micro", "InstancePlatform": "Linux/UNIX", "InstanceCount": 1,
|
||||
"AvailabilityZone": ec2_client.describe_availability_zones()["AvailabilityZones"][0]["ZoneName"],
|
||||
"ClientToken": unique_name,
|
||||
"StartDate": datetime.now(timezone.utc) + timedelta(days=7),
|
||||
"CommitmentDuration": 86400, "DeliveryPreference": "fixed",
|
||||
"TagSpecifications": [
|
||||
{"ResourceType": "capacity-reservation", "Tags": [{"Key": "Name", "Value": unique_name}]}
|
||||
],
|
||||
}
|
||||
with pytest.raises(ClientError) as error:
|
||||
ec2_client.create_capacity_reservation(**request)
|
||||
assert error.value.response["Error"]["Code"] == "InvalidParameterValue"
|
||||
assert ec2_client.describe_capacity_reservations(
|
||||
Filters=[{"Name": "tag:Name", "Values": [unique_name]}]
|
||||
)["CapacityReservations"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("overrides", [
|
||||
{}, {"InstanceMatchCriteria": "open"},
|
||||
{"InstanceMatchCriteria": "targeted", "InstanceCount": 7},
|
||||
{"InstanceMatchCriteria": "targeted", "InstanceType": "p5.48xlarge"},
|
||||
])
|
||||
def test_future_constraints_reject_before_reservation_or_tags(ec2_client, unique_name, overrides):
|
||||
request = {
|
||||
"InstanceType": "m5.xlarge", "InstancePlatform": "Linux/UNIX", "InstanceCount": 8,
|
||||
"AvailabilityZone": ec2_client.describe_availability_zones()["AvailabilityZones"][0]["ZoneName"],
|
||||
"ClientToken": unique_name,
|
||||
"StartDate": (datetime.now(timezone.utc) + timedelta(days=7)).replace(microsecond=0),
|
||||
"CommitmentDuration": 1209600, "DeliveryPreference": "incremental",
|
||||
"TagSpecifications": [{"ResourceType": "capacity-reservation",
|
||||
"Tags": [{"Key": "Name", "Value": unique_name}]}],
|
||||
**overrides,
|
||||
}
|
||||
identifier = None
|
||||
try:
|
||||
with pytest.raises(ClientError) as error:
|
||||
response = ec2_client.create_capacity_reservation(**request)
|
||||
identifier = response["CapacityReservation"]["CapacityReservationId"]
|
||||
assert error.value.response["Error"]["Code"] == "InvalidParameterValue"
|
||||
assert ec2_client.describe_capacity_reservations(
|
||||
Filters=[{"Name": "tag:Name", "Values": [unique_name]}])["CapacityReservations"] == []
|
||||
assert ec2_client.describe_tags(Filters=[{"Name": "value", "Values": [unique_name]}])["Tags"] == []
|
||||
corrected = {**request, "InstanceType": "m5.xlarge", "InstanceCount": 8,
|
||||
"InstanceMatchCriteria": "targeted"}
|
||||
identifier = ec2_client.create_capacity_reservation(**corrected)["CapacityReservation"]["CapacityReservationId"]
|
||||
assert identifier
|
||||
finally:
|
||||
if identifier is not None:
|
||||
ec2_client.cancel_capacity_reservation(CapacityReservationId=identifier)
|
||||
@@ -768,6 +768,23 @@ through `payment-pending`/`assessing`. `DescribeCapacityReservations` supports t
|
||||
`availability-zone`, `end-date-type`, `instance-match-criteria`, `instance-platform`,
|
||||
`instance-type`, `state` and `tenancy` filters alongside the shared `tag:`, `tag-key` and
|
||||
`tag-value` filters.
|
||||
Future-dated requests store a `scheduled` reservation with `StartDate`,
|
||||
`DeliveryPreference: incremental` and `CommitmentInfo`. `StartDate` must be 5 to 120
|
||||
days ahead and requires `CommitmentDuration` (1 to 200000000 seconds). Scheduled
|
||||
capacity cannot satisfy instance launches. The existing capacity reconciliation
|
||||
activates it when its start time is reached. Repeating a `ClientToken` returns the
|
||||
same reservation; changed reservation parameters, including creation tags, are rejected.
|
||||
Creation tags are persisted with the reservation and are not reapplied on replay, so
|
||||
later `CreateTags` edits survive a retry. Tag order does not change request identity.
|
||||
Future-dated requests require explicit `InstanceMatchCriteria: targeted`, at least
|
||||
32 vCPUs in total using the instance-type catalog, and an instance type in the C, G,
|
||||
I, M, R, T, U or X families. Omitted or `open` matching is rejected before publication.
|
||||
Activation does not adopt existing running instances; launches must explicitly target
|
||||
the reservation. Immediate reservations retain their existing open-matching behavior.
|
||||
|
||||
Assessment and incremental delivery are modeled synchronously, without AWS capacity
|
||||
assessment or billing. Cancellation retains Floci's immediate cancellation behavior;
|
||||
cancellation quotes and charges are not modeled.
|
||||
|
||||
On-demand launches consume matching open reservation capacity unless their preference is
|
||||
`none`. RunInstances also honors an explicit reservation target, including one supplied by
|
||||
|
||||
@@ -4463,12 +4463,9 @@ public class Ec2QueryHandler {
|
||||
instantOrNull(p, "EndDate"),
|
||||
p.getFirst("InstanceMatchCriteria"),
|
||||
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();
|
||||
}
|
||||
p.getFirst("PlacementGroupArn"),
|
||||
instantOrNull(p, "StartDate"), longOrNull(p, "CommitmentDuration"),
|
||||
p.getFirst("DeliveryPreference"), p.getFirst("ClientToken"), resourceTags);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateCapacityReservationResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
@@ -4523,6 +4520,7 @@ public class Ec2QueryHandler {
|
||||
.elem("ebsOptimized", reservation.isEbsOptimized())
|
||||
.elem("ephemeralStorage", reservation.isEphemeralStorage())
|
||||
.elem("state", reservation.getState())
|
||||
.elem("deliveryPreference", reservation.getDeliveryPreference())
|
||||
.elem("startDate", reservation.getStartDate() != null ? ISO_FMT.format(reservation.getStartDate()) : null)
|
||||
.elem("endDate", reservation.getEndDate() != null ? ISO_FMT.format(reservation.getEndDate()) : null)
|
||||
.elem("endDateType", reservation.getEndDateType())
|
||||
@@ -4531,6 +4529,13 @@ public class Ec2QueryHandler {
|
||||
.elem("outpostArn", reservation.getOutpostArn())
|
||||
.elem("placementGroupArn", reservation.getPlacementGroupArn())
|
||||
.raw(tagSetXml(reservation.getTags()));
|
||||
if (reservation.getCommitmentDuration() != null) {
|
||||
xml.start("commitmentInfo")
|
||||
.elem("commitmentDuration", reservation.getCommitmentDuration())
|
||||
.elem("commitmentEndDate", ISO_FMT.format(reservation.getCommitmentEndDate()))
|
||||
.elem("committedInstanceCount", reservation.getCommittedInstanceCount())
|
||||
.end("commitmentInfo");
|
||||
}
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -10642,21 +10642,82 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
Instant capacityReservationNow() {
|
||||
return Instant.now();
|
||||
}
|
||||
|
||||
private void validateCapacityReservationSchedule(Instant start, Long duration, String delivery,
|
||||
Instant end, Instant now) {
|
||||
if (start == null) {
|
||||
if (duration != null || delivery != null) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"CommitmentDuration and DeliveryPreference require StartDate.", 400);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (start.isBefore(now.plusSeconds(5 * 86400L)) || start.isAfter(now.plusSeconds(120 * 86400L))) {
|
||||
throw new AwsException("InvalidParameterValue", "StartDate must be 5 to 120 days in the future.", 400);
|
||||
}
|
||||
if (duration == null || delivery == null) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"Future-dated reservations require CommitmentDuration and DeliveryPreference.", 400);
|
||||
}
|
||||
if (duration < 1 || duration > 200000000L || !"incremental".equals(delivery)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"CommitmentDuration must be 1 to 200000000 seconds and DeliveryPreference must be incremental.", 400);
|
||||
}
|
||||
if (end != null && end.isBefore(start.plusSeconds(duration))) {
|
||||
throw new AwsException("InvalidParameterValue", "EndDate cannot precede the commitment end date.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFutureCapacityReservation(String instanceType, int count, String matching) {
|
||||
if (!"targeted".equals(matching)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Future-dated Capacity Reservations require targeted instance matching criteria.", 400);
|
||||
}
|
||||
boolean supportedFamily = switch (instanceType.charAt(0)) {
|
||||
case 'c', 'g', 'i', 'm', 'r', 't', 'u', 'x' -> !instanceType.startsWith("mac")
|
||||
&& !instanceType.startsWith("inf") && !instanceType.startsWith("trn");
|
||||
default -> false;
|
||||
};
|
||||
if (!supportedFamily) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Future-dated Capacity Reservations support only C, G, I, M, R, T, U and X instance families.", 400);
|
||||
}
|
||||
int vcpus = instanceTypeCatalog.defaultVcpus(instanceType)
|
||||
.orElseThrow(() -> new AwsException("InvalidParameterValue",
|
||||
"Instance type '" + instanceType + "' is not supported for future-dated reservations.", 400));
|
||||
if ((long) count * vcpus < 32) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Future-dated Capacity Reservations require at least 32 vCPUs per request.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileCapacityMembership(String region) {
|
||||
Instant now = capacityReservationNow();
|
||||
List<CapacityReservation> reconciled = new ArrayList<>();
|
||||
List<CapacityReservation> activatedReservations = new ArrayList<>();
|
||||
Map<String, CapacityReservation> changed = new LinkedHashMap<>();
|
||||
for (CapacityReservation stored : capacityReservations.scan(k -> k.startsWith(region + "::"))) {
|
||||
CapacityReservation updated = new CapacityReservation(stored);
|
||||
reconciled.add(updated);
|
||||
boolean activated = "scheduled".equals(updated.getState()) && updated.getStartDate() != null
|
||||
&& !updated.getStartDate().isAfter(now);
|
||||
if (activated) {
|
||||
activatedReservations.add(updated);
|
||||
updated.setState("active");
|
||||
updated.setAvailableInstanceCount(updated.getTotalInstanceCount());
|
||||
}
|
||||
boolean expired = "active".equals(updated.getState()) && updated.getEndDate() != null
|
||||
&& !updated.getEndDate().isAfter(Instant.now());
|
||||
&& !updated.getEndDate().isAfter(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) {
|
||||
if (activated || expired || released > 0) {
|
||||
updated.setAvailableInstanceCount("active".equals(updated.getState())
|
||||
? updated.getAvailableInstanceCount() + released : 0);
|
||||
changed.put(key(region, updated.getCapacityReservationId()), updated);
|
||||
@@ -10671,6 +10732,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
for (CapacityReservation reservation : reconciled) {
|
||||
associated.addAll(reservation.getInstanceIds());
|
||||
}
|
||||
for (CapacityReservation reservation : activatedReservations) {
|
||||
matchOpenCapacityInstances(region, reservation, associated);
|
||||
}
|
||||
Map<String, Set<String>> membersByGroup = new HashMap<>();
|
||||
for (Instance instance : groupInstances) {
|
||||
if (instance.getState() == null || !"running".equals(instance.getState().getName())
|
||||
@@ -10699,6 +10763,29 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
private void matchOpenCapacityInstances(String region, CapacityReservation reservation,
|
||||
Set<String> associated) {
|
||||
if (!"active".equals(reservation.getState()) || !"open".equals(reservation.getInstanceMatchCriteria())
|
||||
|| reservation.getAvailableInstanceCount() == 0) {
|
||||
return;
|
||||
}
|
||||
for (Instance instance : instances.scan(k -> k.startsWith(region + "::"))) {
|
||||
if (reservation.getAvailableInstanceCount() == 0) {
|
||||
break;
|
||||
}
|
||||
if (instance.getState() != null && "running".equals(instance.getState().getName()) && !instance.isSpot()
|
||||
&& "open".equals(instance.getCapacityReservationPreference())
|
||||
&& instance.getCapacityReservationTarget() == null
|
||||
&& instance.getCapacityReservationGroupArn() == null
|
||||
&& !associated.contains(instance.getInstanceId())
|
||||
&& matchesCapacityReservation(instance, reservation)) {
|
||||
reservation.getInstanceIds().add(instance.getInstanceId());
|
||||
reservation.setAvailableInstanceCount(reservation.getAvailableInstanceCount() - 1);
|
||||
associated.add(instance.getInstanceId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<Instance> capacityGroupInstances(String region) {
|
||||
String account = callerAccountId();
|
||||
Set<String> ids = capacityGroupInstanceIds.computeIfAbsent(account + "::" + region, ignored -> {
|
||||
@@ -10842,76 +10929,137 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
public CapacityReservation createCapacityReservation(String region, String instanceType,
|
||||
String instancePlatform, String availabilityZone, String availabilityZoneId, Integer instanceCount,
|
||||
String tenancy, Boolean ebsOptimized, Boolean ephemeralStorage, String endDateType,
|
||||
java.time.Instant endDate, String instanceMatchCriteria, String outpostArn, String placementGroupArn) {
|
||||
ensureDefaultResources(region);
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstanceType.", 400);
|
||||
Instant endDate, String instanceMatchCriteria, String outpostArn, String placementGroupArn) {
|
||||
return createCapacityReservation(region, instanceType, instancePlatform, availabilityZone,
|
||||
availabilityZoneId, instanceCount, tenancy, ebsOptimized, ephemeralStorage, endDateType,
|
||||
endDate, instanceMatchCriteria, outpostArn, placementGroupArn, null, null, null, null);
|
||||
}
|
||||
|
||||
public CapacityReservation createCapacityReservation(String region, String instanceType,
|
||||
String instancePlatform, String availabilityZone, String availabilityZoneId, Integer instanceCount,
|
||||
String tenancy, Boolean ebsOptimized, Boolean ephemeralStorage, String endDateType,
|
||||
Instant endDate, String instanceMatchCriteria, String outpostArn, String placementGroupArn,
|
||||
Instant startDate, Long commitmentDuration, String deliveryPreference, String clientToken) {
|
||||
return createCapacityReservation(region, instanceType, instancePlatform, availabilityZone,
|
||||
availabilityZoneId, instanceCount, tenancy, ebsOptimized, ephemeralStorage, endDateType,
|
||||
endDate, instanceMatchCriteria, outpostArn, placementGroupArn, startDate, commitmentDuration,
|
||||
deliveryPreference, clientToken, List.of());
|
||||
}
|
||||
|
||||
public CapacityReservation createCapacityReservation(String region, String instanceType,
|
||||
String instancePlatform, String availabilityZone, String availabilityZoneId, Integer instanceCount,
|
||||
String tenancy, Boolean ebsOptimized, Boolean ephemeralStorage, String endDateType,
|
||||
Instant endDate, String instanceMatchCriteria, String outpostArn, String placementGroupArn,
|
||||
Instant startDate, Long commitmentDuration, String deliveryPreference, String clientToken,
|
||||
List<Tag> resourceTags) {
|
||||
validateNewResourceTags(resourceTags);
|
||||
Map<String, String> requestTags = new LinkedHashMap<>();
|
||||
for (Tag tag : resourceTags) {
|
||||
requestTags.put(tag.getKey(), tag.getValue());
|
||||
}
|
||||
if (instancePlatform == null || instancePlatform.isBlank()) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstancePlatform.", 400);
|
||||
}
|
||||
if (instanceCount == null) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstanceCount.", 400);
|
||||
}
|
||||
if ((availabilityZone == null || availabilityZone.isBlank())
|
||||
&& (availabilityZoneId == null || availabilityZoneId.isBlank())) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"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();
|
||||
reservation.setOwnerId(ownerAccountId);
|
||||
reservation.setRegion(region);
|
||||
reservation.setCapacityReservationArn(
|
||||
AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "capacity-reservation/" + reservation.getCapacityReservationId()).toString());
|
||||
reservation.setAvailabilityZone(availabilityZone);
|
||||
reservation.setAvailabilityZoneId(availabilityZoneId);
|
||||
reservation.setInstanceType(instanceType);
|
||||
reservation.setInstancePlatform(instancePlatform);
|
||||
reservation.setTenancy(tenancy != null ? tenancy : "default");
|
||||
reservation.setTotalInstanceCount(count);
|
||||
reservation.setAvailableInstanceCount(count);
|
||||
reservation.setEbsOptimized(Boolean.TRUE.equals(ebsOptimized));
|
||||
reservation.setEphemeralStorage(Boolean.TRUE.equals(ephemeralStorage));
|
||||
reservation.setState("active");
|
||||
reservation.setStartDate(Instant.now());
|
||||
reservation.setCreateDate(Instant.now());
|
||||
reservation.setEndDate(endDate);
|
||||
reservation.setEndDateType(endDateType != null ? endDateType : "unlimited");
|
||||
reservation.setInstanceMatchCriteria(instanceMatchCriteria != null ? instanceMatchCriteria : "open");
|
||||
reservation.setOutpostArn(outpostArn);
|
||||
reservation.setPlacementGroupArn(placementGroupArn);
|
||||
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
|
||||
&& instance.getCapacityReservationGroupArn() == null
|
||||
&& !associated.contains(instance.getInstanceId())
|
||||
&& matchesCapacityReservation(instance, reservation)) {
|
||||
reservation.getInstanceIds().add(instance.getInstanceId());
|
||||
reservation.setAvailableInstanceCount(reservation.getAvailableInstanceCount() - 1);
|
||||
List<String> parameters = Arrays.asList(instanceType, instancePlatform, availabilityZone,
|
||||
availabilityZoneId, String.valueOf(instanceCount), tenancy, String.valueOf(ebsOptimized),
|
||||
String.valueOf(ephemeralStorage), endDateType, String.valueOf(endDate), instanceMatchCriteria,
|
||||
outpostArn, placementGroupArn, String.valueOf(startDate), String.valueOf(commitmentDuration),
|
||||
deliveryPreference);
|
||||
if (isSet(clientToken)) {
|
||||
for (CapacityReservation existing : capacityReservations.scan(k -> k.startsWith(region + "::"))) {
|
||||
if (clientToken.equals(existing.getClientToken()) && callerAccountId().equals(existing.getOwnerId())) {
|
||||
if (!parameters.equals(existing.getRequestParameters())
|
||||
|| !requestTags.equals(existing.getRequestTags())) {
|
||||
throw new AwsException("IdempotentParameterMismatch",
|
||||
"Parameters differ from the previous request with this ClientToken.", 400);
|
||||
}
|
||||
reconcileCapacityMembership(region);
|
||||
return new CapacityReservation(getRequiredCapacityReservation(region,
|
||||
existing.getCapacityReservationId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
capacityReservations.put(key(region, reservation.getCapacityReservationId()), reservation);
|
||||
Instant now = capacityReservationNow();
|
||||
validateCapacityReservationSchedule(startDate, commitmentDuration, deliveryPreference, endDate, now);
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstanceType.", 400);
|
||||
}
|
||||
if (instancePlatform == null || instancePlatform.isBlank()) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstancePlatform.", 400);
|
||||
}
|
||||
if (instanceCount == null) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter InstanceCount.", 400);
|
||||
}
|
||||
if ((availabilityZone == null || availabilityZone.isBlank())
|
||||
&& (availabilityZoneId == null || availabilityZoneId.isBlank())) {
|
||||
throw new AwsException("MissingParameter",
|
||||
"The request must contain the parameter AvailabilityZone or AvailabilityZoneId.", 400);
|
||||
}
|
||||
int count = requirePositiveInstanceCount(instanceCount);
|
||||
if (startDate != null) {
|
||||
validateFutureCapacityReservation(instanceType, count, instanceMatchCriteria);
|
||||
}
|
||||
ensureDefaultResources(region);
|
||||
if (isSet(availabilityZoneId)) {
|
||||
zoneNameForZoneId(region, availabilityZoneId);
|
||||
}
|
||||
CapacityReservation reservation = new CapacityReservation();
|
||||
reservation.setCapacityReservationId("cr-" + randomHex(17));
|
||||
String ownerAccountId = callerAccountId();
|
||||
reservation.setOwnerId(ownerAccountId);
|
||||
reservation.setRegion(region);
|
||||
reservation.setCapacityReservationArn(
|
||||
AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "capacity-reservation/" + reservation.getCapacityReservationId()).toString());
|
||||
reservation.setAvailabilityZone(availabilityZone);
|
||||
reservation.setAvailabilityZoneId(availabilityZoneId);
|
||||
reservation.setInstanceType(instanceType);
|
||||
reservation.setInstancePlatform(instancePlatform);
|
||||
reservation.setTenancy(tenancy != null ? tenancy : "default");
|
||||
reservation.setTotalInstanceCount(count);
|
||||
reservation.setAvailableInstanceCount(startDate == null ? count : 0);
|
||||
reservation.setEbsOptimized(Boolean.TRUE.equals(ebsOptimized));
|
||||
reservation.setEphemeralStorage(Boolean.TRUE.equals(ephemeralStorage));
|
||||
reservation.setState(startDate == null ? "active" : "scheduled");
|
||||
reservation.setStartDate(startDate == null ? now : startDate);
|
||||
reservation.setCreateDate(now);
|
||||
reservation.setClientToken(clientToken);
|
||||
reservation.setRequestParameters(parameters);
|
||||
reservation.setRequestTags(new LinkedHashMap<>(requestTags));
|
||||
reservation.setTags(requestTags.entrySet().stream()
|
||||
.map(tag -> new Tag(tag.getKey(), tag.getValue())).collect(Collectors.toCollection(ArrayList::new)));
|
||||
reservation.setDeliveryPreference(deliveryPreference);
|
||||
if (startDate != null) {
|
||||
reservation.setCommitmentDuration(commitmentDuration);
|
||||
reservation.setCommitmentEndDate(startDate.plusSeconds(commitmentDuration));
|
||||
reservation.setCommittedInstanceCount(count);
|
||||
}
|
||||
reservation.setEndDate(endDate);
|
||||
reservation.setEndDateType(endDateType != null ? endDateType : "unlimited");
|
||||
reservation.setInstanceMatchCriteria(instanceMatchCriteria != null ? instanceMatchCriteria : "open");
|
||||
reservation.setOutpostArn(outpostArn);
|
||||
reservation.setPlacementGroupArn(placementGroupArn);
|
||||
reconcileCapacityMembership(region);
|
||||
Set<String> associated = capacityReservations.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.flatMap(existing -> existing.getInstanceIds().stream()).collect(Collectors.toSet());
|
||||
matchOpenCapacityInstances(region, reservation, associated);
|
||||
if (!reservation.getTags().isEmpty()) {
|
||||
putTags(region, reservation.getCapacityReservationId(), new ArrayList<>(reservation.getTags()));
|
||||
}
|
||||
try {
|
||||
capacityReservations.put(key(region, reservation.getCapacityReservationId()), reservation);
|
||||
} catch (RuntimeException failure) {
|
||||
try {
|
||||
removeTags(region, reservation.getCapacityReservationId());
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
LOG.warnv(cleanupFailure, "Could not remove creation tags for failed Capacity Reservation {0}",
|
||||
reservation.getCapacityReservationId());
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
return new CapacityReservation(reservation);
|
||||
}
|
||||
return reservation;
|
||||
}
|
||||
|
||||
public List<CapacityReservation> describeCapacityReservations(String region, List<String> ids,
|
||||
@@ -10948,6 +11096,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
reconcileCapacityMembership(region);
|
||||
CapacityReservation reservation = new CapacityReservation(
|
||||
getRequiredCapacityReservation(region, capacityReservationId));
|
||||
if ("scheduled".equals(reservation.getState())) {
|
||||
throw new AwsException("IncorrectState", "A scheduled Capacity Reservation cannot be modified.", 400);
|
||||
}
|
||||
if (reservation.getCommitmentEndDate() != null
|
||||
&& capacityReservationNow().isBefore(reservation.getCommitmentEndDate())
|
||||
&& (instanceCount != null && instanceCount < reservation.getCommittedInstanceCount()
|
||||
|| endDate != null && endDate.isBefore(reservation.getCommitmentEndDate()))) {
|
||||
throw new AwsException("InvalidParameterValue", "The modification violates the capacity commitment.", 400);
|
||||
}
|
||||
if (instanceCount != null) {
|
||||
int delta = requirePositiveInstanceCount(instanceCount) - reservation.getTotalInstanceCount();
|
||||
if (reservation.getAvailableInstanceCount() + delta < 0) {
|
||||
|
||||
+33
-1
@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A reservation of EC2 instance capacity in a specific Availability Zone, created ahead of
|
||||
@@ -14,7 +16,7 @@ import java.util.List;
|
||||
*
|
||||
* <p>Real AWS transitions a Capacity Reservation through {@code payment-pending}/
|
||||
* {@code assessing} before {@code active}; nothing about creating one is slow here, so it is
|
||||
* {@code active} on the create response and on the first describe, the same synchronous-create
|
||||
* {@code active} for immediate requests and {@code scheduled} for future requests, using the same
|
||||
* simplification the other regional EC2 resources make.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@@ -35,6 +37,13 @@ public class CapacityReservation {
|
||||
private boolean ephemeralStorage;
|
||||
private String state = "active";
|
||||
private Instant startDate;
|
||||
private Long commitmentDuration;
|
||||
private Instant commitmentEndDate;
|
||||
private Integer committedInstanceCount;
|
||||
private String deliveryPreference;
|
||||
private String clientToken;
|
||||
private List<String> requestParameters = new ArrayList<>();
|
||||
private Map<String, String> requestTags = new LinkedHashMap<>();
|
||||
private Instant endDate;
|
||||
private String endDateType = "unlimited";
|
||||
private String instanceMatchCriteria = "open";
|
||||
@@ -62,6 +71,13 @@ public class CapacityReservation {
|
||||
ephemeralStorage = other.ephemeralStorage;
|
||||
state = other.state;
|
||||
startDate = other.startDate;
|
||||
commitmentDuration = other.commitmentDuration;
|
||||
commitmentEndDate = other.commitmentEndDate;
|
||||
committedInstanceCount = other.committedInstanceCount;
|
||||
deliveryPreference = other.deliveryPreference;
|
||||
clientToken = other.clientToken;
|
||||
requestParameters = new ArrayList<>(other.requestParameters);
|
||||
requestTags = new LinkedHashMap<>(other.requestTags);
|
||||
endDate = other.endDate;
|
||||
endDateType = other.endDateType;
|
||||
instanceMatchCriteria = other.instanceMatchCriteria;
|
||||
@@ -73,6 +89,9 @@ public class CapacityReservation {
|
||||
instanceIds = new ArrayList<>(other.instanceIds);
|
||||
}
|
||||
|
||||
public Map<String, String> getRequestTags() { return requestTags; }
|
||||
public void setRequestTags(Map<String, String> requestTags) { this.requestTags = requestTags; }
|
||||
|
||||
public String getCapacityReservationId() { return capacityReservationId; }
|
||||
public void setCapacityReservationId(String capacityReservationId) { this.capacityReservationId = capacityReservationId; }
|
||||
|
||||
@@ -114,6 +133,19 @@ public class CapacityReservation {
|
||||
public Instant getStartDate() { return startDate; }
|
||||
public void setStartDate(Instant startDate) { this.startDate = startDate; }
|
||||
|
||||
public Long getCommitmentDuration() { return commitmentDuration; }
|
||||
public void setCommitmentDuration(Long value) { commitmentDuration = value; }
|
||||
public Instant getCommitmentEndDate() { return commitmentEndDate; }
|
||||
public void setCommitmentEndDate(Instant value) { commitmentEndDate = value; }
|
||||
public Integer getCommittedInstanceCount() { return committedInstanceCount; }
|
||||
public void setCommittedInstanceCount(Integer value) { committedInstanceCount = value; }
|
||||
public String getDeliveryPreference() { return deliveryPreference; }
|
||||
public void setDeliveryPreference(String value) { deliveryPreference = value; }
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String value) { clientToken = value; }
|
||||
public List<String> getRequestParameters() { return requestParameters; }
|
||||
public void setRequestParameters(List<String> value) { requestParameters = new ArrayList<>(value); }
|
||||
|
||||
public Instant getEndDate() { return endDate; }
|
||||
public void setEndDate(Instant endDate) { this.endDate = endDate; }
|
||||
|
||||
|
||||
+323
@@ -10,6 +10,7 @@ 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 io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.resourcegroups.ResourceGroupsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -18,6 +19,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -34,6 +36,7 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -60,6 +63,308 @@ class Ec2CapacityReservationAssociationServiceTest {
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"default", "open", "targeted"})
|
||||
void futureMatchingRequiresExplicitTargetedBeforePublication(String matching) {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
String criteria = "default".equals(matching) ? null : matching;
|
||||
if ("targeted".equals(matching)) {
|
||||
assertEquals("scheduled", fixture.future("m5.xlarge", 8, criteria).getState());
|
||||
} else {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> fixture.future("m5.xlarge", 8, criteria));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("targeted"));
|
||||
verify(fixture.store, never()).put(any(), any());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"m5.xlarge", "t3.micro"})
|
||||
void futureMinimumUsesCatalogVcpusAndRejectedTokenCanBeRetried(String type) {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
int minimum = "m5.xlarge".equals(type) ? 8 : 16;
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> fixture.future(type, minimum - 1, "targeted"));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("32 vCPUs"));
|
||||
verify(fixture.store, never()).put(any(), any());
|
||||
assertEquals("scheduled", fixture.future(type, minimum, "targeted").getState());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"p5.48xlarge", "a1.4xlarge", "d3.8xlarge", "hpc7a.96xlarge",
|
||||
"inf2.48xlarge", "trn1.32xlarge", "mac2.metal", "z1d.12xlarge"})
|
||||
void futureUnsupportedFamiliesAreRejectedBeforePublication(String type) {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> fixture.future(type, 32, "targeted"));
|
||||
assertEquals("InvalidParameterValue", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("instance families"));
|
||||
verify(fixture.store, never()).put(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"c5.4xlarge", "g4dn.4xlarge", "im4gn.4xlarge", "m5.4xlarge",
|
||||
"r5.4xlarge", "t3.micro", "u-6tb1.56xlarge", "x2idn.16xlarge"})
|
||||
void futureSupportedFamiliesUseCatalogIncludingAcceleratedAndHighMemory(String type) {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
assertEquals("scheduled", fixture.future(type, 32, "targeted").getState());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void immediateCapacityKeepsOpenAndSmallRequestBehavior() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
assertEquals("active", fixture.create(1).getState());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduledReservationActivatesOnlyAtItsStartAndReplaysAfterActivation() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation scheduled = fixture.schedule(start, 86400L, "incremental", "scheduled-token");
|
||||
assertEquals("scheduled", scheduled.getState());
|
||||
assertEquals(0, scheduled.getAvailableInstanceCount());
|
||||
assertEquals(start, scheduled.getStartDate());
|
||||
assertEquals(start.plusSeconds(86400), scheduled.getCommitmentEndDate());
|
||||
assertEquals(16, scheduled.getCommittedInstanceCount());
|
||||
Instance unreserved = fixture.launch();
|
||||
fixture.service.describeInstances(REGION, List.of(unreserved.getInstanceId()), Map.of());
|
||||
assertEquals(null, fixture.service.instanceCapacityReservationId(unreserved));
|
||||
assertThrows(AwsException.class, () -> fixture.launch(scheduled.getCapacityReservationId()));
|
||||
assertTrue(fixture.describe(scheduled).getInstanceIds().isEmpty());
|
||||
doReturn(start.minusSeconds(1)).when(fixture.service).capacityReservationNow();
|
||||
assertEquals("scheduled", fixture.describe(scheduled).getState());
|
||||
doReturn(start).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation active = fixture.describe(scheduled);
|
||||
assertEquals("active", active.getState());
|
||||
assertEquals(16, active.getAvailableInstanceCount());
|
||||
assertTrue(active.getInstanceIds().isEmpty());
|
||||
Instance reserved = fixture.launch(scheduled.getCapacityReservationId());
|
||||
assertEquals(scheduled.getCapacityReservationId(), fixture.service.instanceCapacityReservationId(reserved));
|
||||
CapacityReservation replay = fixture.schedule(start, 86400L, "incremental", "scheduled-token");
|
||||
assertEquals(scheduled.getCapacityReservationId(), replay.getCapacityReservationId());
|
||||
assertEquals("active", replay.getState());
|
||||
assertEquals(15, replay.getAvailableInstanceCount());
|
||||
assertEquals(1, fixture.service.describeCapacityReservations(REGION, List.of(), Map.of()).size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void activatingTargetedCapacityDoesNotAdoptRunningInstances() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation occupied = fixture.create(1);
|
||||
Instance assigned = fixture.launch();
|
||||
Instance optedOut = fixture.launchWithPreference("none");
|
||||
Instance eligible = fixture.launch();
|
||||
fixture.service.describeInstances(REGION,
|
||||
List.of(assigned.getInstanceId(), optedOut.getInstanceId(), eligible.getInstanceId()), Map.of());
|
||||
CapacityReservation first = fixture.schedule(start, 86400L, "incremental", "first");
|
||||
CapacityReservation second = fixture.schedule(start, 86400L, "incremental", "second");
|
||||
doReturn(start).when(fixture.service).capacityReservationNow();
|
||||
Map<String, String> associations = fixture.service.capacityReservationAssociations(REGION);
|
||||
assertEquals(occupied.getCapacityReservationId(), associations.get(assigned.getInstanceId()));
|
||||
assertFalse(associations.containsKey(optedOut.getInstanceId()));
|
||||
assertFalse(associations.containsKey(eligible.getInstanceId()));
|
||||
assertEquals(32, fixture.describe(first).getAvailableInstanceCount()
|
||||
+ fixture.describe(second).getAvailableInstanceCount());
|
||||
assertEquals(associations, fixture.service.capacityReservationAssociations(REGION));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedTargetedActivationRollsBackStateBeforeRetry() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation reservation = fixture.schedule(start, 86400L, "incremental", "failure");
|
||||
Instance instance = fixture.launch();
|
||||
fixture.service.describeInstances(REGION, List.of(instance.getInstanceId()), Map.of());
|
||||
doReturn(start).when(fixture.service).capacityReservationNow();
|
||||
doThrow(new IllegalStateException("activation storage failure"))
|
||||
.when(fixture.store).putAllAtomically(any());
|
||||
assertThrows(AwsException.class, () -> fixture.describe(reservation));
|
||||
CapacityReservation stored = fixture.store.get(REGION + "::" + reservation.getCapacityReservationId())
|
||||
.orElseThrow();
|
||||
assertEquals("scheduled", stored.getState());
|
||||
assertTrue(stored.getInstanceIds().isEmpty());
|
||||
reset(fixture.store);
|
||||
assertTrue(fixture.describe(reservation).getInstanceIds().isEmpty());
|
||||
assertEquals(16, fixture.describe(reservation).getAvailableInstanceCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedReservationPublicationDoesNotLeaveCreationTags() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
doThrow(new IllegalStateException("creation storage failure")).when(fixture.store).put(any(), any());
|
||||
assertThrows(IllegalStateException.class, () -> fixture.scheduleWithTags(
|
||||
Instant.now().plus(Duration.ofDays(7)), List.of(new Tag("Name", "not-published"))));
|
||||
assertTrue(fixture.service.describeCapacityReservations(REGION, List.of(), Map.of()).isEmpty());
|
||||
assertTrue(fixture.service.describeTags(REGION, Map.of("value", List.of("not-published"))).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"memory", "persistent", "hybrid", "wal"})
|
||||
void creationTagSnapshotSurvivesEditsAndReplay(String mode) {
|
||||
Instant start = Instant.now().plus(Duration.ofDays(7));
|
||||
String id;
|
||||
try (Fixture fixture = new Fixture(mode, directory)) {
|
||||
CapacityReservation reservation = fixture.scheduleWithTags(start,
|
||||
List.of(new Tag("Name", "original"), new Tag("team", "one")));
|
||||
id = reservation.getCapacityReservationId();
|
||||
assertEquals(Map.of("Name", "original", "team", "one"), reservation.getRequestTags());
|
||||
assertEquals(2, fixture.service.describeTags(REGION, Map.of("resource-id", List.of(id))).size());
|
||||
fixture.service.createTags(REGION, List.of(id), List.of(new Tag("Name", "edited")));
|
||||
CapacityReservation replay = fixture.scheduleWithTags(start,
|
||||
List.of(new Tag("team", "one"), new Tag("Name", "original")));
|
||||
assertEquals(id, replay.getCapacityReservationId());
|
||||
assertTrue(replay.getTags().stream()
|
||||
.anyMatch(tag -> "Name".equals(tag.getKey()) && "edited".equals(tag.getValue())));
|
||||
assertEquals("IdempotentParameterMismatch", assertThrows(AwsException.class,
|
||||
() -> fixture.scheduleWithTags(start, List.of(new Tag("Name", "different")))).getErrorCode());
|
||||
}
|
||||
if (!"memory".equals(mode)) {
|
||||
try (Fixture fixture = new Fixture(mode, directory)) {
|
||||
CapacityReservation replay = fixture.scheduleWithTags(start,
|
||||
List.of(new Tag("Name", "original"), new Tag("team", "one")));
|
||||
assertEquals(id, replay.getCapacityReservationId());
|
||||
assertTrue(replay.getTags().stream()
|
||||
.anyMatch(tag -> "Name".equals(tag.getKey()) && "edited".equals(tag.getValue())));
|
||||
assertEquals("IdempotentParameterMismatch", assertThrows(AwsException.class,
|
||||
() -> fixture.scheduleWithTags(start, List.of())).getErrorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void scheduledMetadataAndReplaySurviveStorageReload(String mode) {
|
||||
Instant start = Instant.now().plus(Duration.ofDays(7));
|
||||
String id;
|
||||
try (Fixture fixture = new Fixture(mode, directory)) {
|
||||
id = fixture.schedule(start, 86400L, "incremental", "reload").getCapacityReservationId();
|
||||
}
|
||||
try (Fixture fixture = new Fixture(mode, directory)) {
|
||||
CapacityReservation replay = fixture.schedule(start, 86400L, "incremental", "reload");
|
||||
assertEquals(id, replay.getCapacityReservationId());
|
||||
assertEquals("scheduled", replay.getState());
|
||||
assertEquals(start, replay.getStartDate());
|
||||
assertEquals(86400L, replay.getCommitmentDuration());
|
||||
assertEquals("incremental", replay.getDeliveryPreference());
|
||||
assertEquals(16, replay.getCommittedInstanceCount());
|
||||
assertEquals(start.plusSeconds(86400), replay.getCommitmentEndDate());
|
||||
assertEquals(0, replay.getAvailableInstanceCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduledValidationAndMismatchedReplayPreserveStoredCapacity() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
for (Instant invalid : List.of(now.plus(Duration.ofDays(4)), now.plus(Duration.ofDays(121)))) {
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(invalid, 86400L, "incremental", null)).getErrorCode());
|
||||
}
|
||||
assertEquals("MissingParameter", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(start, null, "incremental", null)).getErrorCode());
|
||||
assertEquals("MissingParameter", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(start, 86400L, null, null)).getErrorCode());
|
||||
for (long invalid : new long[]{0, 200000001L}) {
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(start, invalid, "incremental", null)).getErrorCode());
|
||||
}
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(start, 86400L, "fixed", null)).getErrorCode());
|
||||
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(null, 86400L, "incremental", null)).getErrorCode());
|
||||
assertTrue(fixture.service.describeCapacityReservations(REGION, List.of(), Map.of()).isEmpty());
|
||||
CapacityReservation scheduled = fixture.schedule(start, 86400L, "incremental", "same-token");
|
||||
assertEquals("IdempotentParameterMismatch", assertThrows(AwsException.class,
|
||||
() -> fixture.schedule(start.plusSeconds(1), 86400L, "incremental", "same-token")).getErrorCode());
|
||||
assertEquals("IncorrectState", assertThrows(AwsException.class,
|
||||
() -> fixture.service.modifyCapacityReservation(REGION, scheduled.getCapacityReservationId(),
|
||||
3, null, null, null)).getErrorCode());
|
||||
assertEquals(16, fixture.describe(scheduled).getTotalInstanceCount());
|
||||
assertEquals(scheduled.getCapacityReservationId(), fixture.schedule(start, 86400L,
|
||||
"incremental", "same-token").getCapacityReservationId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedActivationRetainsScheduledCapacityForRetry() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation reservation = fixture.schedule(start, 86400L, "incremental", "retry");
|
||||
doReturn(start).when(fixture.service).capacityReservationNow();
|
||||
doThrow(new IllegalStateException("storage failed")).when(fixture.store).putAllAtomically(any());
|
||||
assertEquals("InternalError", assertThrows(AwsException.class,
|
||||
() -> fixture.describe(reservation)).getErrorCode());
|
||||
assertEquals("scheduled", fixture.store.get(REGION + "::" + reservation.getCapacityReservationId())
|
||||
.orElseThrow().getState());
|
||||
reset(fixture.store);
|
||||
assertEquals("active", fixture.describe(reservation).getState());
|
||||
assertEquals(16, fixture.describe(reservation).getAvailableInstanceCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellationCannotBeReactivatedAndActiveCommitmentRestrictsModification() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
Instant start = now.plus(Duration.ofDays(7));
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
CapacityReservation cancelled = fixture.schedule(start, 86400L, "incremental", "cancelled");
|
||||
fixture.service.cancelCapacityReservation(REGION, cancelled.getCapacityReservationId());
|
||||
CapacityReservation reservation = fixture.schedule(start, 86400L, "incremental", "active");
|
||||
doReturn(start).when(fixture.service).capacityReservationNow();
|
||||
assertEquals("cancelled", fixture.describe(cancelled).getState());
|
||||
assertEquals(0, fixture.describe(cancelled).getAvailableInstanceCount());
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> fixture.service.modifyCapacityReservation(REGION, reservation.getCapacityReservationId(),
|
||||
1, null, null, null)).getErrorCode());
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> fixture.service.modifyCapacityReservation(REGION, reservation.getCapacityReservationId(),
|
||||
null, start.plusSeconds(1), "limited", null)).getErrorCode());
|
||||
assertEquals(16, fixture.describe(reservation).getTotalInstanceCount());
|
||||
doReturn(start.plusSeconds(86400)).when(fixture.service).capacityReservationNow();
|
||||
assertEquals(1, fixture.service.modifyCapacityReservation(REGION, reservation.getCapacityReservationId(),
|
||||
1, null, null, null).getTotalInstanceCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulingBoundariesAndImmediateReservationsRemainDistinct() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
Instant now = Instant.parse("2026-10-01T00:00:00Z");
|
||||
doReturn(now).when(fixture.service).capacityReservationNow();
|
||||
assertEquals("scheduled", fixture.schedule(now.plus(Duration.ofDays(5)), 1L,
|
||||
"incremental", null).getState());
|
||||
assertEquals("scheduled", fixture.schedule(now.plus(Duration.ofDays(120)), 200000000L,
|
||||
"incremental", null).getState());
|
||||
CapacityReservation immediate = fixture.create(2);
|
||||
assertEquals("active", immediate.getState());
|
||||
assertEquals(2, immediate.getAvailableInstanceCount());
|
||||
assertEquals(null, immediate.getCommitmentDuration());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownZoneIdIsRejectedBeforeReservationPublication() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
@@ -778,6 +1083,24 @@ class Ec2CapacityReservationAssociationServiceTest {
|
||||
false, null, specification).getInstances().getFirst();
|
||||
}
|
||||
|
||||
private CapacityReservation future(String type, int count, String matching) {
|
||||
return service.createCapacityReservation(REGION, type, "Linux/UNIX", REGION + "a",
|
||||
null, count, null, null, null, null, null, matching, null, null,
|
||||
Instant.now().plus(Duration.ofDays(7)), 1209600L, "incremental", "validation-token");
|
||||
}
|
||||
|
||||
private CapacityReservation schedule(Instant start, Long duration, String delivery, String token) {
|
||||
return service.createCapacityReservation(REGION, "t3.micro", "Linux/UNIX", REGION + "a",
|
||||
null, 16, null, null, null, null, null, "targeted", null, null,
|
||||
start, duration, delivery, token);
|
||||
}
|
||||
|
||||
private CapacityReservation scheduleWithTags(Instant start, List<Tag> tags) {
|
||||
return service.createCapacityReservation(REGION, "t3.micro", "Linux/UNIX", REGION + "a",
|
||||
null, 16, null, null, null, null, null, "targeted", null, null,
|
||||
start, 86400L, "incremental", "tag-token", tags);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user