mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ec2): add opt-in Standard On-Demand vCPU admission (#6058)
* feat(ec2): enforce Standard On-Demand vCPU limits Keep EC2 launches and restarts within regional account limits. * fix(ec2): preserve quota lifecycle and launch semantics Keep Spot launches independent and pending restarts recoverable. Report incomplete CloudFormation restoration accurately. * fix(ec2): make vCPU admission opt-in and running-only
This commit is contained in:
1 parent
8bff1ba0f3
commit
689201122f
19 files changed
+2287
-12
No files matched your search
@@ -3141,6 +3141,10 @@ public interface EmulatorConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/** Enables RunInstances and StartInstances checks against current running vCPU usage. */
|
||||
@WithDefault("false")
|
||||
boolean enforceVcpuQuotas();
|
||||
|
||||
/**
|
||||
* When true, DescribeInstances and IMDS report each instance's CFN- and
|
||||
* subnet-allocated private IP (AWS-faithful) instead of the Docker
|
||||
|
||||
@@ -37,6 +37,7 @@ public class Ec2InstanceTypeCatalog {
|
||||
"t4g", "unlimited");
|
||||
|
||||
private volatile Loaded loaded;
|
||||
private volatile Map<String, Integer> defaultVcpus;
|
||||
|
||||
public Ec2InstanceTypeCatalog() {
|
||||
// Load lazily so tests and mock-mode paths that do not need instance type
|
||||
@@ -58,6 +59,32 @@ public class Ec2InstanceTypeCatalog {
|
||||
return Optional.ofNullable(loaded().instanceTypesByName.get(instanceType));
|
||||
}
|
||||
|
||||
/** Default hardware vCPUs for quota accounting, independently of the full network catalog. */
|
||||
public Optional<Integer> defaultVcpus(String instanceType) {
|
||||
Optional<CatalogInstanceType> full = find(instanceType);
|
||||
if (full.isPresent()) {
|
||||
return Optional.of(full.get().vcpu);
|
||||
}
|
||||
Map<String, Integer> values = defaultVcpus;
|
||||
if (values == null) {
|
||||
synchronized (this) {
|
||||
values = defaultVcpus;
|
||||
if (values == null) {
|
||||
VcpuCatalog catalog = readResource("ec2/instance-type-vcpus.yaml", VcpuCatalog.class);
|
||||
if (catalog.defaultVcpus == null || catalog.defaultVcpus.isEmpty()
|
||||
|| catalog.defaultVcpus.entrySet().stream().anyMatch(entry ->
|
||||
entry.getKey() == null || entry.getKey().isBlank()
|
||||
|| entry.getValue() == null || entry.getValue() <= 0)) {
|
||||
throw new IllegalStateException("EC2 vCPU catalog must contain positive default vCPU counts");
|
||||
}
|
||||
values = Map.copyOf(catalog.defaultVcpus);
|
||||
defaultVcpus = values;
|
||||
}
|
||||
}
|
||||
}
|
||||
return instanceType == null ? Optional.empty() : Optional.ofNullable(values.get(instanceType));
|
||||
}
|
||||
|
||||
/**
|
||||
* The credit option a launch of this instance type gets when it names no CreditSpecification,
|
||||
* or empty when the type has no burstable credit model.
|
||||
@@ -180,6 +207,12 @@ public class Ec2InstanceTypeCatalog {
|
||||
return value;
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public static final class VcpuCatalog {
|
||||
public Map<String, Integer> defaultVcpus = Map.of();
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@RegisterForReflection
|
||||
public static final class Catalog {
|
||||
|
||||
@@ -795,6 +795,7 @@ public class Ec2QueryHandler {
|
||||
// Absent fields stay null so the launch default, or the launch template's value, applies.
|
||||
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
|
||||
String creditSpecificationCpuCredits = p.getFirst("CreditSpecification.CpuCredits");
|
||||
String marketType = p.getFirst("InstanceMarketOptions.MarketType");
|
||||
|
||||
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings =
|
||||
parseLaunchTemplateBlockDeviceMappings(p, "");
|
||||
@@ -808,6 +809,9 @@ public class Ec2QueryHandler {
|
||||
"Network interfaces and an instance-level subnet ID may not be specified on the same request", 400);
|
||||
}
|
||||
if (launchTemplateData != null) {
|
||||
if (marketType == null && launchTemplateData.getInstanceMarketOptions() != null) {
|
||||
marketType = launchTemplateData.getInstanceMarketOptions().getMarketType();
|
||||
}
|
||||
blockDeviceMappings = LaunchTemplateData.BlockDeviceMapping.merge(
|
||||
launchTemplateData.getBlockDeviceMappings(), blockDeviceMappings);
|
||||
if (!suppliedInterfaces) {
|
||||
@@ -860,7 +864,8 @@ public class Ec2QueryHandler {
|
||||
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);
|
||||
p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings,
|
||||
"spot".equals(marketType));
|
||||
|
||||
if (!networkInterfaceTags.isEmpty()) {
|
||||
List<String> eniIds = new ArrayList<>();
|
||||
@@ -987,7 +992,7 @@ public class Ec2QueryHandler {
|
||||
null,
|
||||
0,
|
||||
launch.availabilityZone(), launch.metadataOptions(), null, launch.encodedUserData(), false,
|
||||
null, null, launch.blockDeviceMappings());
|
||||
null, null, launch.blockDeviceMappings(), "spot".equals(capacityType));
|
||||
Instance instance = reservation.getInstances().get(0);
|
||||
launchedInstanceIds.add(instance.getInstanceId());
|
||||
results.add(new FleetLaunchResult(instance, launch));
|
||||
@@ -4845,6 +4850,10 @@ public class Ec2QueryHandler {
|
||||
.elem("instanceType", inst.getInstanceType())
|
||||
.elem("launchTime", inst.getLaunchTime() != null ? ISO_FMT.format(inst.getLaunchTime()) : "");
|
||||
|
||||
if (inst.isSpot()) {
|
||||
xml.elem("instanceLifecycle", "spot");
|
||||
}
|
||||
|
||||
if (inst.getPlacement() != null) {
|
||||
xml.start("placement")
|
||||
.elem("availabilityZone", inst.getPlacement().getAvailabilityZone())
|
||||
|
||||
@@ -3535,6 +3535,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun,
|
||||
String hostId, String tenancy,
|
||||
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings) {
|
||||
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, false);
|
||||
}
|
||||
|
||||
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) {
|
||||
if (hostId != null && !hostId.isBlank()) {
|
||||
Host host = getRequiredAvailableHost(region, hostId);
|
||||
if ((availabilityZone == null || availabilityZone.isBlank())
|
||||
@@ -3673,14 +3691,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412);
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
|
||||
? count : admittedInstanceCount(region, effectiveInstanceType, minCount, maxCount);
|
||||
synchronized (hostLock) {
|
||||
if (hostId != null) {
|
||||
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
|
||||
// since the unlocked check above.
|
||||
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
|
||||
}
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, admitted);
|
||||
for (int i = 0; i < admitted; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = privateIps.get(i);
|
||||
|
||||
@@ -3690,6 +3710,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
inst.setImageId(imageId);
|
||||
inst.setState(InstanceState.pending());
|
||||
inst.setInstanceType(effectiveInstanceType);
|
||||
inst.setSpot(spot);
|
||||
Placement placement = new Placement(az);
|
||||
placement.setHostId(hostId);
|
||||
if (tenancy != null && !tenancy.isBlank()) {
|
||||
@@ -4590,6 +4611,33 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
public List<Map<String, String>> startInstances(String region, List<String> instanceIds) {
|
||||
ensureDefaultResources(region);
|
||||
if (config.services().ec2().enforceVcpuQuotas()) {
|
||||
synchronized (privateIpAllocationLock) {
|
||||
long additional = 0;
|
||||
Set<String> legacySpot = spotInstanceIds(region);
|
||||
List<Instance> targets = new ArrayList<>();
|
||||
for (String id : new LinkedHashSet<>(instanceIds)) {
|
||||
Instance instance = getRequiredInstance(region, id);
|
||||
if (isExternalInstance(region, id)) {
|
||||
throw new AwsException("OperationNotPermitted",
|
||||
"The instance '" + id + "' is a cluster node and cannot be started through EC2", 400);
|
||||
}
|
||||
if ("terminated".equals(instance.getState().getName())) {
|
||||
throw new AwsException("IncorrectInstanceState",
|
||||
"The instance '" + id + "' is not in a state from which it can be started.", 400);
|
||||
}
|
||||
targets.add(instance);
|
||||
}
|
||||
for (Instance instance : targets) {
|
||||
String state = instance.getState().getName();
|
||||
if (("stopped".equals(state) || "stopping".equals(state))
|
||||
&& !isSpot(instance, legacySpot) && !onDedicatedHost(instance)) {
|
||||
additional += standardOnDemandVcpus(instance.getInstanceType());
|
||||
}
|
||||
}
|
||||
enforceStandardOnDemandQuota(region, additional);
|
||||
}
|
||||
}
|
||||
List<Map<String, String>> result = new ArrayList<>();
|
||||
for (String id : instanceIds) {
|
||||
Instance inst = getRequiredInstance(region, id);
|
||||
@@ -4631,6 +4679,71 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return result;
|
||||
}
|
||||
|
||||
private int appliedStandardOnDemandLimit() {
|
||||
return config.services().servicequotas() == null ? 5
|
||||
: config.services().servicequotas().standardOnDemandVcpus();
|
||||
}
|
||||
|
||||
private int admittedInstanceCount(String region, String instanceType, int minimum, int maximum) {
|
||||
int vcpus = standardOnDemandVcpus(instanceType);
|
||||
int requested = Math.max(maximum, Math.max(minimum, 1));
|
||||
if (vcpus == 0) {
|
||||
return requested;
|
||||
}
|
||||
long available = Math.max(0L, (long) appliedStandardOnDemandLimit() - runningStandardOnDemandVcpus(region));
|
||||
int admitted = (int) Math.min(requested, available / vcpus);
|
||||
if (admitted < Math.max(minimum, 1)) {
|
||||
throw vcpuLimitExceeded();
|
||||
}
|
||||
return admitted;
|
||||
}
|
||||
|
||||
private void enforceStandardOnDemandQuota(String region, long additional) {
|
||||
if (additional > 0 && runningStandardOnDemandVcpus(region) + additional > appliedStandardOnDemandLimit()) {
|
||||
throw vcpuLimitExceeded();
|
||||
}
|
||||
}
|
||||
|
||||
private AwsException vcpuLimitExceeded() {
|
||||
return new AwsException("VcpuLimitExceeded", "You have requested more vCPU capacity than your current vCPU limit of "
|
||||
+ appliedStandardOnDemandLimit() + " allows for the instance bucket that the specified instance type belongs to.", 400);
|
||||
}
|
||||
|
||||
private Set<String> spotInstanceIds(String region) {
|
||||
return spotInstanceRequests.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.map(SpotInstanceRequest::getInstanceId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private static boolean isSpot(Instance instance, Set<String> legacySpot) {
|
||||
return instance.isSpot() || legacySpot.contains(instance.getInstanceId());
|
||||
}
|
||||
|
||||
private static boolean onDedicatedHost(Instance instance) {
|
||||
return instance.getPlacement() != null && "host".equals(instance.getPlacement().getTenancy());
|
||||
}
|
||||
|
||||
/** Current running usage only: pending operations do not reserve admission capacity. */
|
||||
private long runningStandardOnDemandVcpus(String region) {
|
||||
Set<String> legacySpot = spotInstanceIds(region);
|
||||
return instances.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(i -> !isSpot(i, legacySpot) && !onDedicatedHost(i))
|
||||
.filter(i -> i.getState() != null && "running".equals(i.getState().getName()))
|
||||
.mapToLong(i -> standardOnDemandVcpus(i.getInstanceType())).sum();
|
||||
}
|
||||
|
||||
private int standardOnDemandVcpus(String type) {
|
||||
if (type == null || type.isBlank() || type.startsWith("mac") || type.startsWith("dl")
|
||||
|| type.startsWith("hpc") || type.startsWith("inf") || type.startsWith("trn")) {
|
||||
return 0;
|
||||
}
|
||||
return switch (Character.toLowerCase(type.charAt(0))) {
|
||||
case 'a', 'c', 'd', 'h', 'i', 'm', 'r', 't', 'z' -> instanceTypeCatalog.defaultVcpus(type)
|
||||
.orElseThrow(() -> new AwsException("InvalidParameterValue",
|
||||
"Instance type '" + type + "' is not supported for quota-enforced launches.", 400));
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
public void rebootInstances(String region, List<String> instanceIds) {
|
||||
ensureDefaultResources(region);
|
||||
for (String id : instanceIds) {
|
||||
@@ -12727,7 +12840,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
securityGroupIds, subnetId, null, instanceTags, userData, iamInstanceProfileArn,
|
||||
/* associatePublicIp */ null, /* networkInterfaceId */ null,
|
||||
/* networkInterfaceDeviceIndex */ 0, /* availabilityZone */ null,
|
||||
/* metadataOptions */ null, /* creditSpecificationCpuCredits */ null, encodedUserData);
|
||||
/* metadataOptions */ null, /* creditSpecificationCpuCredits */ null, encodedUserData,
|
||||
false, null, null, null, true);
|
||||
|
||||
Instance launchedInstance = reservation.getInstances().get(0);
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ public class Instance {
|
||||
private volatile InstanceState state;
|
||||
private String stateTransitionReason;
|
||||
private String instanceType;
|
||||
private boolean spot;
|
||||
private Placement placement;
|
||||
private String subnetId;
|
||||
private String vpcId;
|
||||
@@ -110,6 +111,9 @@ public class Instance {
|
||||
public String getStateTransitionReason() { return stateTransitionReason; }
|
||||
public void setStateTransitionReason(String stateTransitionReason) { this.stateTransitionReason = stateTransitionReason; }
|
||||
|
||||
public boolean isSpot() { return spot; }
|
||||
public void setSpot(boolean spot) { this.spot = spot; }
|
||||
|
||||
public String getInstanceType() { return instanceType; }
|
||||
public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user