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:
Andre Kurait authored and GitHub committed 2026-10-27 23:15:52 -04:00
1 parent 3649b18e15
commit b5033e970d
6 files changed
+715 -73

No files matched your search

@@ -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) {
@@ -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; }