mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -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
+204
@@ -0,0 +1,204 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.CreateFleetResponse;
|
||||
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
|
||||
import software.amazon.awssdk.services.ec2.model.InstanceType;
|
||||
import software.amazon.awssdk.services.ec2.model.RequestSpotLaunchSpecification;
|
||||
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
|
||||
import software.amazon.awssdk.services.ec2.model.SpotInstanceRequest;
|
||||
import software.amazon.awssdk.services.servicequotas.ServiceQuotasClient;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
class Ec2VcpuAdmissionTest {
|
||||
@Test
|
||||
void quotaAdmissionFollowsOptInWhileSpotAndOtherAccountsRemainIndependent() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Local opt-in admission and mock guest lifecycle only");
|
||||
Region region = TestFixtures.region();
|
||||
String owner = "765432101234";
|
||||
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(owner, "test"));
|
||||
List<String> ids = new ArrayList<>();
|
||||
List<String> otherIds = new ArrayList<>();
|
||||
List<String> regionIds = new ArrayList<>();
|
||||
String templateId = null;
|
||||
String spotRequestId = null;
|
||||
try (Ec2Client ec2 = client(region, owner);
|
||||
Ec2Client other = client(region, "765432101235");
|
||||
Ec2Client otherRegion = client(Region.of(region.id().startsWith("cn-")
|
||||
? "cn-northwest-1" : "eu-west-1"), owner);
|
||||
ServiceQuotasClient quotas = ServiceQuotasClient.builder().endpointOverride(TestFixtures.endpoint())
|
||||
.region(region).credentialsProvider(credentials).build()) {
|
||||
int limit = quotas.getServiceQuota(r -> r.serviceCode("ec2").quotaCode("L-1216C47A"))
|
||||
.quota().value().intValue();
|
||||
int expectedLimit = Integer.parseInt(System.getenv().getOrDefault(
|
||||
"FLOCI_TEST_EXPECTED_STANDARD_ON_DEMAND_VCPUS", "5"));
|
||||
assertThat(limit).as("applied quota retains the ordinary default or explicit fixture value")
|
||||
.isEqualTo(expectedLimit);
|
||||
if (!enforcementExpected()) {
|
||||
try {
|
||||
ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T2_MICRO)
|
||||
.minCount(6).maxCount(6)).instances().forEach(i -> ids.add(i.instanceId()));
|
||||
ids.add(ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890")
|
||||
.instanceType(InstanceType.M5_2_XLARGE).minCount(1).maxCount(1))
|
||||
.instances().get(0).instanceId());
|
||||
assertThat(ids).hasSize(7);
|
||||
ec2.stopInstances(r -> r.instanceIds(ids));
|
||||
ec2.startInstances(r -> r.instanceIds(ids));
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(ids)).reservations())
|
||||
.flatExtracting(reservation -> reservation.instances())
|
||||
.allSatisfy(instance -> assertThat(instance.state().nameAsString()).isEqualTo("running"));
|
||||
} finally {
|
||||
if (!ids.isEmpty()) {
|
||||
ec2.terminateInstances(r -> r.instanceIds(ids));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
assertThat(limit).as("compatibility fixture uses a small positive applied quota")
|
||||
.isBetween(2, 32);
|
||||
int guests = limit / 2;
|
||||
try {
|
||||
RunInstancesResponse batch = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890")
|
||||
.instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(guests + 2));
|
||||
batch.instances().forEach(i -> ids.add(i.instanceId()));
|
||||
assertThat(ids).hasSize(guests);
|
||||
ec2.waiter().waitUntilInstanceRunning(r -> r.instanceIds(ids));
|
||||
Ec2Exception full = assertThrows(Ec2Exception.class, () -> launch(ec2));
|
||||
assertThat(full.statusCode()).isEqualTo(400);
|
||||
assertThat(full.awsErrorDetails().errorCode()).isEqualTo("VcpuLimitExceeded");
|
||||
otherIds.add(launch(other));
|
||||
regionIds.add(launch(otherRegion));
|
||||
|
||||
SpotInstanceRequest spot = ec2.requestSpotInstances(r -> r.instanceCount(1).type("one-time")
|
||||
.launchSpecification(RequestSpotLaunchSpecification.builder()
|
||||
.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO).build()))
|
||||
.spotInstanceRequests().get(0);
|
||||
spotRequestId = spot.spotInstanceRequestId();
|
||||
ids.add(spot.instanceId());
|
||||
String spotId = spot.instanceId();
|
||||
ec2.stopInstances(r -> r.instanceIds(spotId));
|
||||
ec2.startInstances(r -> r.instanceIds(spotId));
|
||||
|
||||
templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName("quota-" + UUID.randomUUID())
|
||||
.launchTemplateData(d -> d.imageId("ami-0abcdef1234567890")
|
||||
.instanceType(InstanceType.T3_MICRO))).launchTemplate().launchTemplateId();
|
||||
String directSpot = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890")
|
||||
.instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)
|
||||
.instanceMarketOptions(m -> m.marketType("spot"))).instances().get(0).instanceId();
|
||||
ids.add(directSpot);
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(directSpot)).reservations().get(0)
|
||||
.instances().get(0).instanceLifecycleAsString()).isEqualTo("spot");
|
||||
ec2.stopInstances(r -> r.instanceIds(directSpot));
|
||||
ec2.startInstances(r -> r.instanceIds(directSpot));
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(directSpot)).reservations().get(0)
|
||||
.instances().get(0).instanceLifecycleAsString()).isEqualTo("spot");
|
||||
String template = templateId;
|
||||
ec2.createLaunchTemplateVersion(r -> r.launchTemplateId(template)
|
||||
.launchTemplateData(d -> d.imageId("ami-0abcdef1234567890")
|
||||
.instanceType(InstanceType.T3_MICRO).instanceMarketOptions(m -> m.marketType("spot"))));
|
||||
RunInstancesResponse templateSpot = ec2.runInstances(r -> r.minCount(1).maxCount(1)
|
||||
.launchTemplate(t -> t.launchTemplateId(template).version("$Latest")));
|
||||
ids.add(templateSpot.instances().get(0).instanceId());
|
||||
assertThat(templateSpot.instances().get(0).instanceLifecycleAsString()).isEqualTo("spot");
|
||||
assertThat(assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> r.minCount(1).maxCount(1)
|
||||
.launchTemplate(t -> t.launchTemplateId(template).version("$Latest"))
|
||||
.instanceMarketOptions(m -> m.marketType("on-demand"))))
|
||||
.awsErrorDetails().errorCode()).isEqualTo("VcpuLimitExceeded");
|
||||
CreateFleetResponse fleet = ec2.createFleet(r -> r.type("instant").launchTemplateConfigs(c ->
|
||||
c.launchTemplateSpecification(t -> t.launchTemplateId(template).version("$Latest")))
|
||||
.targetCapacitySpecification(t -> t.totalTargetCapacity(1).defaultTargetCapacityType("spot")));
|
||||
fleet.instances().forEach(group -> ids.addAll(group.instanceIds()));
|
||||
assertThat(fleet.instances()).hasSize(1);
|
||||
assertThat(assertThrows(Ec2Exception.class, () -> launch(ec2)).awsErrorDetails().errorCode())
|
||||
.isEqualTo("VcpuLimitExceeded");
|
||||
|
||||
String stopped = ids.get(0);
|
||||
ec2.stopInstances(r -> r.instanceIds(stopped));
|
||||
String replacement = launch(ec2);
|
||||
ids.add(replacement);
|
||||
ec2.waiter().waitUntilInstanceRunning(r -> r.instanceIds(replacement));
|
||||
assertThat(assertThrows(Ec2Exception.class, () -> ec2.startInstances(r -> r.instanceIds(stopped)))
|
||||
.awsErrorDetails().errorCode()).isEqualTo("VcpuLimitExceeded");
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(stopped)).reservations().get(0)
|
||||
.instances().get(0).state().nameAsString()).isEqualTo("stopped");
|
||||
ec2.terminateInstances(r -> r.instanceIds(replacement));
|
||||
ec2.startInstances(r -> r.instanceIds(stopped));
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(stopped)).reservations().get(0)
|
||||
.instances().get(0).state().nameAsString()).isEqualTo("running");
|
||||
} finally {
|
||||
List<Executable> cleanup = new ArrayList<>();
|
||||
if (!ids.isEmpty()) {
|
||||
cleanup.add(() -> ec2.terminateInstances(r -> r.instanceIds(ids)));
|
||||
}
|
||||
if (!otherIds.isEmpty()) {
|
||||
cleanup.add(() -> other.terminateInstances(r -> r.instanceIds(otherIds)));
|
||||
}
|
||||
if (!regionIds.isEmpty()) {
|
||||
cleanup.add(() -> otherRegion.terminateInstances(r -> r.instanceIds(regionIds)));
|
||||
}
|
||||
if (spotRequestId != null) {
|
||||
String requestId = spotRequestId;
|
||||
cleanup.add(() -> ec2.cancelSpotInstanceRequests(r -> r.spotInstanceRequestIds(requestId)));
|
||||
}
|
||||
if (templateId != null) {
|
||||
String template = templateId;
|
||||
cleanup.add(() -> ec2.deleteLaunchTemplate(r -> r.launchTemplateId(template)));
|
||||
}
|
||||
assertAll(cleanup);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownTypesFollowTheEnforcementOptIn() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Local unsupported-type mapping is not an AWS response claim");
|
||||
try (Ec2Client ec2 = client(TestFixtures.region(), "765432101236")) {
|
||||
if (!enforcementExpected()) {
|
||||
String id = ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890")
|
||||
.instanceType("m999.unmeasured").minCount(1).maxCount(1)).instances().get(0).instanceId();
|
||||
try {
|
||||
ec2.stopInstances(r -> r.instanceIds(id));
|
||||
ec2.startInstances(r -> r.instanceIds(id));
|
||||
assertThat(ec2.describeInstances(r -> r.instanceIds(id)).reservations().get(0)
|
||||
.instances().get(0).state().nameAsString()).isEqualTo("running");
|
||||
} finally {
|
||||
ec2.terminateInstances(r -> r.instanceIds(id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
Ec2Exception unsupported = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r ->
|
||||
r.imageId("ami-0abcdef1234567890").instanceType("m999.unmeasured").minCount(1).maxCount(1)));
|
||||
assertThat(unsupported.statusCode()).isEqualTo(400);
|
||||
assertThat(unsupported.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue");
|
||||
assertThat(ec2.describeInstances().reservations()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean enforcementExpected() {
|
||||
return Boolean.parseBoolean(System.getenv().getOrDefault("FLOCI_TEST_EC2_ENFORCE_VCPU_QUOTAS", "false"));
|
||||
}
|
||||
|
||||
private static String launch(Ec2Client ec2) {
|
||||
return ec2.runInstances(r -> r.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO)
|
||||
.minCount(1).maxCount(1)).instances().get(0).instanceId();
|
||||
}
|
||||
|
||||
private static Ec2Client client(Region region, String account) {
|
||||
return Ec2Client.builder().endpointOverride(TestFixtures.endpoint()).region(region)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -536,6 +536,7 @@ These services spawn Docker containers. They require access to the Docker socket
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS` | `false` | Opt in to EC2 Run/Start admission against current running Standard On-Demand vCPU usage |
|
||||
| `FLOCI_SERVICES_EC2_ENABLED` | `true` | Enable the EC2 service |
|
||||
| `FLOCI_SERVICES_EC2_MOCK` | `false` | When `true`, instances are registered in state but no containers are spawned |
|
||||
| `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` | `none` | Automatic public IPv4 address of a mock instance: `none`, `documentation` (from `203.0.113.0/24`) or `fixed` (`FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS`) |
|
||||
@@ -610,6 +611,7 @@ See [Web Console](../ui/index.md) for running the console and swapping in a thir
|
||||
| `FLOCI_SERVICES_CODEPIPELINE_SOURCE_POLL_INTERVAL_MS` | `500` | How often (ms) the CodePipeline S3 source poller checks a configured `S3Bucket`/`S3ObjectKey` for a new object revision |
|
||||
| `FLOCI_SERVICES_NETWORKFIREWALL_ENABLED` | `true` | Enable the AWS Network Firewall service |
|
||||
| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enable the Service Quotas service |
|
||||
| `FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` | `5` | Non-negative Standard On-Demand vCPU limit per account and region; EC2 launches and starts reserve capacity against this applied limit |
|
||||
| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enable the AWS RAM service |
|
||||
| `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service |
|
||||
| `FLOCI_SERVICES_BACKUP_JOB_COMPLETION_DELAY_SECONDS` | `3` | Simulated delay before backup jobs transition to `COMPLETED` |
|
||||
|
||||
+30
-1
@@ -22,9 +22,38 @@ By default, Docker containers launched for EC2 instances are bounded to the CPU
|
||||
|
||||
- **CPU limit**: Each vCPU corresponds to 1024 CPU units (Docker nanoCPUs = `vcpu * 1_000_000_000`). If the host machine has fewer physical cores than requested, Floci clamps execution to available host CPUs and warns (since Docker refuses a nanoCPUs value exceeding the host CPU count).
|
||||
- **Memory limit**: Container memory is bounded to the exact MiB value specified for the instance type in the catalog.
|
||||
- **Unknown instance types**: If an instance type is not present in the catalog, the container launches unbounded without CPU or memory restrictions, avoiding launch failures for custom or unmodeled instance types.
|
||||
- **Types outside the full catalog**: Docker CPU and memory limits are not applied when the full catalog lacks a type. When opted in, Standard On-Demand admission requires a known default vCPU count, as described below.
|
||||
- **Configuration knob**: To disable container resource limits (for example, running a large instance type on a developer machine with limited resources), set `floci.services.ec2.instance-resource-limits: false` (or environment variable `FLOCI_SERVICES_EC2_INSTANCE_RESOURCE_LIMITS=false`).
|
||||
|
||||
## Standard On-Demand admission
|
||||
|
||||
Quota admission is opt-in. Set `FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS=true` to
|
||||
check `RunInstances` and `StartInstances` against the applied Standard On-Demand
|
||||
quota (`L-1216C47A`) for the caller's account and region. The flag defaults to
|
||||
`false`, including mock mode. Disabled admission does not refuse a type merely
|
||||
because its default vCPU count is absent from the snapshot.
|
||||
|
||||
`FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` supplies the applied value
|
||||
(default `5`). Service Quotas reports this value independently of admission.
|
||||
With admission enabled, a launch batch can return fewer than `MaxCount` when at
|
||||
least `MinCount` fits, otherwise it returns `VcpuLimitExceeded`. A refused start
|
||||
leaves stopped instances unchanged. Types in the Standard bucket require a
|
||||
known default vCPU count; the separate CPU-only snapshot supplements the full
|
||||
instance metadata catalog without inventing memory sizes or regional availability.
|
||||
|
||||
Only current `running` Standard On-Demand instances count. Pending, stopping,
|
||||
stopped, shutting-down and terminated instances do not reserve capacity. Spot
|
||||
and dedicated-host instances do not consume this bucket. RunInstances retains
|
||||
direct or inherited launch-template Spot selection; explicit request market
|
||||
options override the template. Requests for Spot through the other supported
|
||||
launch APIs retain that provenance too.
|
||||
|
||||
These are checks of running usage at request admission, not a reservation ledger
|
||||
or an eventual running ceiling. Accepted pending operations can complete after
|
||||
other work consumes capacity, and changing a running instance's type is not
|
||||
covered by the Run/Start checks. Admission does not change guest cleanup,
|
||||
restart, user-data, public-address or CloudFormation lifecycle behavior.
|
||||
|
||||
## AMI to Docker Image Mapping
|
||||
|
||||
Floci resolves AMI IDs to Docker images from the EC2 image catalog at
|
||||
|
||||
@@ -20,8 +20,8 @@ instances") reports a configurable applied value through `GetServiceQuota` and
|
||||
change that value for all local accounts and regions. Use a nonnegative integer;
|
||||
negative values prevent Floci from starting, even when Service Quotas is disabled.
|
||||
It defaults to 5. The AWS
|
||||
default read actions always return 5. This setting does not enforce a vCPU
|
||||
admission limit on EC2.
|
||||
default read actions always return 5. EC2 can use this applied value for opt-in
|
||||
Standard On-Demand launch/start admission for each account and region; see [EC2 admission](ec2.md#standard-on-demand-admission).
|
||||
|
||||
All other applied quotas and AWS default quotas return the same catalog data.
|
||||
`RequestServiceQuotaIncrease` is accepted and validated, records the request, and lets you read
|
||||
@@ -74,7 +74,7 @@ Limitations.
|
||||
| Environment variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enables the service |
|
||||
| `FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` | `5` | Applied EC2 Standard On-Demand vCPU quota reported for every local account and region; does not enforce EC2 admission |
|
||||
| `FLOCI_SERVICES_SERVICEQUOTAS_STANDARD_ON_DEMAND_VCPUS` | `5` | Applied EC2 Standard On-Demand vCPU quota reported per local account and region; used by opt-in EC2 admission |
|
||||
|
||||
## Example
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -651,6 +651,8 @@ floci:
|
||||
proxy-max-port: 9499
|
||||
keep-running-on-shutdown: false
|
||||
ec2:
|
||||
# Opt-in Standard On-Demand vCPU admission. FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS
|
||||
enforce-vcpu-quotas: false
|
||||
# Optional complete catalog override for locally built guest images.
|
||||
image-catalog-path: ${FLOCI_SERVICES_EC2_IMAGE_CATALOG_PATH:}
|
||||
enabled: true
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -44,7 +44,7 @@ class Ec2CreateFleetRollbackTest {
|
||||
nullable(String.class), nullable(Boolean.class), nullable(String.class), anyInt(),
|
||||
nullable(String.class), nullable(LaunchTemplateData.MetadataOptions.class),
|
||||
nullable(String.class), nullable(String.class), eq(false), nullable(String.class),
|
||||
nullable(String.class), anyList()))
|
||||
nullable(String.class), anyList(), eq(false)))
|
||||
.thenReturn(reservation("i-first"))
|
||||
.thenReturn(reservation("i-second"))
|
||||
.thenThrow(new AwsException("InvalidSubnetID.NotFound", "launch failed", 400));
|
||||
|
||||
@@ -74,6 +74,39 @@ class Ec2InstanceTypeCatalogTest {
|
||||
assertFalse(instanceTypeCatalog.find("m8gd.xlarge").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultCpuSnapshotDoesNotInventOtherDescribeMetadata() {
|
||||
assertEquals(Optional.of(2), instanceTypeCatalog.defaultVcpus("t3.large"));
|
||||
assertEquals(Optional.of(144), instanceTypeCatalog.defaultVcpus("p6e-gb200.36xlarge"));
|
||||
assertEquals(Optional.of(2), instanceTypeCatalog.defaultVcpus("cc1.4xlarge"));
|
||||
assertTrue(instanceTypeCatalog.find("t3.large").isEmpty());
|
||||
assertTrue(instanceTypeCatalog.find("p6e-gb200.36xlarge").isEmpty());
|
||||
assertTrue(instanceTypeCatalog.defaultVcpus("m9g.metal-24xl").isEmpty());
|
||||
assertTrue(instanceTypeCatalog.defaultVcpus("m9gd.metal-24xl").isEmpty());
|
||||
assertTrue(instanceTypeCatalog.defaultVcpus(null).isEmpty());
|
||||
assertTrue(instanceTypeCatalog.defaultVcpus("").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitFullCatalogEntryTakesPrecedenceOverTheCpuOnlySnapshot() {
|
||||
Ec2InstanceTypeCatalog.CatalogInstanceType configured =
|
||||
instanceTypeCatalog.find("t3.micro").orElseThrow();
|
||||
Ec2InstanceTypeCatalog.Catalog catalog = new Ec2InstanceTypeCatalog.Catalog();
|
||||
// Make a detached entry so this test cannot alter the injected application catalog.
|
||||
Ec2InstanceTypeCatalog.CatalogInstanceType override = new Ec2InstanceTypeCatalog.CatalogInstanceType();
|
||||
override.instanceType = configured.instanceType;
|
||||
override.vcpu = 3;
|
||||
override.memoryMib = configured.memoryMib;
|
||||
override.supportedArchitectures = configured.supportedArchitectures;
|
||||
override.encryptionInTransitSupported = configured.encryptionInTransitSupported;
|
||||
override.defaultNetworkCardIndex = configured.defaultNetworkCardIndex;
|
||||
override.ipv4AddressesPerInterface = configured.ipv4AddressesPerInterface;
|
||||
override.networkCards = configured.networkCards;
|
||||
catalog.instanceTypes = List.of(override);
|
||||
assertEquals(Optional.of(3), new Ec2InstanceTypeCatalog(catalog).defaultVcpus("t3.micro"));
|
||||
assertEquals(2, configured.vcpu);
|
||||
}
|
||||
|
||||
@Test
|
||||
void catalogEntriesIncludeNetworkCompatibilityMetadata() {
|
||||
instanceTypeCatalog.instanceTypes().forEach(instanceType ->
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(Ec2QuotaDefaultOffIntegrationTest.Disabled.class)
|
||||
class Ec2QuotaDefaultOffIntegrationTest {
|
||||
public static class Disabled implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.servicequotas.standard-on-demand-vcpus", "5");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultOffKeepsSixMicroInstancesAcceptable() {
|
||||
try {
|
||||
given().header("Authorization", auth("687432101241")).formParams("Action", "RunInstances",
|
||||
"ImageId", "ami-0abcdef1234567890", "InstanceType", "t2.micro", "MinCount", "6", "MaxCount", "6")
|
||||
.post("/").then().statusCode(200);
|
||||
} finally {
|
||||
given().post("/_floci/state/reset").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultOffDoesNotRequireAVcpuSnapshotEntry() {
|
||||
try {
|
||||
given().header("Authorization", auth("687432101242")).formParams("Action", "RunInstances",
|
||||
"ImageId", "ami-0abcdef1234567890", "InstanceType", "m999.unmeasured",
|
||||
"MinCount", "1", "MaxCount", "1").post("/").then().statusCode(200);
|
||||
} finally {
|
||||
given().post("/_floci/state/reset").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String account) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20261020/us-east-1/ec2/aws4_request";
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -64,7 +64,7 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
nullable(Boolean.class), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
|
||||
nullable(String.class), nullable(String.class), nullable(List.class)))
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false)))
|
||||
.thenReturn(new Reservation());
|
||||
|
||||
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
|
||||
@@ -79,7 +79,7 @@ class Ec2RunInstancesPublicIpParamTest {
|
||||
nullable(String.class), anyList(), nullable(String.class), nullable(String.class),
|
||||
associatePublicIp.capture(), nullable(String.class), anyInt(), nullable(String.class),
|
||||
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
|
||||
nullable(String.class), nullable(String.class), nullable(List.class));
|
||||
nullable(String.class), nullable(String.class), nullable(List.class), eq(false));
|
||||
if (expected == null) {
|
||||
assertNull(associatePublicIp.getValue(),
|
||||
"an absent override must stay null so the subnet default decides");
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(Ec2VcpuAdmissionIntegrationTest.TwoVcpus.class)
|
||||
class Ec2VcpuAdmissionIntegrationTest {
|
||||
public static class TwoVcpus implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.servicequotas.standard-on-demand-vcpus", "2",
|
||||
"floci.services.ec2.enforce-vcpu-quotas", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260205/us-east-1/" + service + "/aws4_request";
|
||||
}
|
||||
|
||||
@Test
|
||||
void directAndTemplateSpotDoNotConsumeOnDemandCapacityAndRequestOverridesTemplate() {
|
||||
String account = "687432101234";
|
||||
String header = auth(account, "ec2");
|
||||
given().header("Authorization", header).formParams("Action", "RunInstances",
|
||||
"ImageId", "ami-0abcdef1234567890", "InstanceType", "t3.micro", "MinCount", "1", "MaxCount", "1")
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", header).formParam("Action", "DescribeInstances")
|
||||
.post("/").then().statusCode(200).body(containsString("<name>running</name>"));
|
||||
try {
|
||||
given().header("Authorization", header).formParams("Action", "RunInstances",
|
||||
"ImageId", "ami-0abcdef1234567890", "InstanceType", "t3.micro", "MinCount", "1", "MaxCount", "1",
|
||||
"InstanceMarketOptions.MarketType", "spot")
|
||||
.post("/").then().statusCode(200).body(containsString("<instanceLifecycle>spot</instanceLifecycle>"));
|
||||
String template = given().header("Authorization", header).formParams("Action", "CreateLaunchTemplate",
|
||||
"LaunchTemplateName", "quota-market-" + UUID.randomUUID(),
|
||||
"LaunchTemplateData.ImageId", "ami-0abcdef1234567890", "LaunchTemplateData.InstanceType", "t3.micro",
|
||||
"LaunchTemplateData.InstanceMarketOptions.MarketType", "spot")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
|
||||
try {
|
||||
given().header("Authorization", header).formParams("Action", "RunInstances",
|
||||
"LaunchTemplate.LaunchTemplateId", template, "MinCount", "1", "MaxCount", "1")
|
||||
.post("/").then().statusCode(200)
|
||||
.body(containsString("<instanceLifecycle>spot</instanceLifecycle>"));
|
||||
given().header("Authorization", header).formParams("Action", "RunInstances",
|
||||
"LaunchTemplate.LaunchTemplateId", template, "MinCount", "1", "MaxCount", "1",
|
||||
"InstanceMarketOptions.MarketType", "on-demand")
|
||||
.post("/").then().statusCode(400).body(containsString("VcpuLimitExceeded"));
|
||||
given().header("Authorization", header).formParam("Action", "DescribeInstances")
|
||||
.post("/").then().statusCode(200)
|
||||
.body(containsString("<instanceLifecycle>spot</instanceLifecycle>"));
|
||||
} finally {
|
||||
given().header("Authorization", header).formParams("Action", "DeleteLaunchTemplate",
|
||||
"LaunchTemplateId", template).post("/").then().statusCode(200);
|
||||
}
|
||||
} finally {
|
||||
given().post("/_floci/state/reset").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class Ec2VcpuPersistenceTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void reloadedInstancesRetainSpotProvenance(String mode, @TempDir Path dir) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.storage().persistentPath()).thenReturn(dir.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(60000L);
|
||||
when(config.services().ec2().mock()).thenReturn(true);
|
||||
when(config.services().ec2().mockPublicAddresses())
|
||||
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
|
||||
when(config.services().ec2().mockPublicAddress()).thenReturn(Optional.empty());
|
||||
when(config.services().servicequotas().standardOnDemandVcpus()).thenReturn(5);
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode("ec2")).thenReturn(mode);
|
||||
when(access.storageFlushInterval("ec2")).thenReturn(60000L);
|
||||
StorageFactory first = new StorageFactory(config, access);
|
||||
try {
|
||||
Ec2Service service = service(config, first);
|
||||
Instance spot = guest("i-persisted-spot", InstanceState.running());
|
||||
spot.setSpot(true);
|
||||
Instance ordinary = guest("i-persisted-ordinary", InstanceState.running());
|
||||
service.putInstanceForTest(spot);
|
||||
service.putInstanceForTest(ordinary);
|
||||
} finally {
|
||||
first.shutdownAll();
|
||||
}
|
||||
StorageFactory reloaded = new StorageFactory(config, access);
|
||||
try {
|
||||
Ec2Service service = service(config, reloaded);
|
||||
Map<String, Instance> instances = service.describeInstances("us-east-1", List.of(), Map.of()).stream()
|
||||
.flatMap(reservation -> reservation.getInstances().stream())
|
||||
.collect(Collectors.toMap(Instance::getInstanceId, i -> i));
|
||||
assertTrue(instances.get("i-persisted-spot").isSpot());
|
||||
assertFalse(instances.get("i-persisted-ordinary").isSpot());
|
||||
} finally {
|
||||
reloaded.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
private static Instance guest(String id, InstanceState state) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(id);
|
||||
instance.setInstanceType("t3.large");
|
||||
instance.setOwnerId("000000000000");
|
||||
instance.setRegion("us-east-1");
|
||||
instance.setState(state);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static Ec2Service service(EmulatorConfig config, StorageFactory storage) {
|
||||
return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), new Ec2ImageCatalog(), new Ec2InstanceTypeCatalog(), storage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Placement;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class Ec2VcpuQuotaTest {
|
||||
@Test
|
||||
void defaultOffPreservesLargeBatchesAndUnsizedTypes() {
|
||||
Ec2Service service = service(5, false);
|
||||
assertEquals(6, service.runInstances("us-east-1", "ami-test", "t2.micro", 6, 6, null,
|
||||
List.of(), null, null, List.of(), null, null).getInstances().size());
|
||||
assertNotNull(launch(service, "m5.2xlarge"));
|
||||
assertNotNull(launch(service, "m999.unmeasured"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"pending", "running", "stopping", "stopped", "shutting-down", "terminated"})
|
||||
void enabledAdmissionCountsOnlyRunningInstances(String state) {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance existing = instance("i-existing", state);
|
||||
service.putInstanceForTest(existing);
|
||||
if ("running".equals(state)) {
|
||||
AwsException failure = assertThrows(AwsException.class, () -> launch(service, "t3.micro"));
|
||||
assertEquals("VcpuLimitExceeded", failure.getErrorCode());
|
||||
assertEquals(400, failure.getHttpStatus());
|
||||
existing.setState(InstanceState.stopping());
|
||||
assertNotNull(launch(service, "t3.micro"));
|
||||
} else {
|
||||
assertNotNull(launch(service, "t3.micro"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void partialBatchesFitCurrentRunningUsageAndRefusedMinimumPublishesNothing() {
|
||||
Ec2Service service = service(5, true);
|
||||
Instance running = instance("i-running", "running");
|
||||
running.setInstanceType("t3.large");
|
||||
service.putInstanceForTest(running);
|
||||
assertEquals(1, service.runInstances("us-east-1", "ami-test", "t3.micro", 1, 4, null,
|
||||
List.of(), null, null, List.of(), null, null).getInstances().size());
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.runInstances("us-east-1", "ami-test",
|
||||
"t3.micro", 2, 4, null, List.of(), null, null, List.of(), null, null));
|
||||
assertEquals("VcpuLimitExceeded", refused.getErrorCode());
|
||||
assertEquals(2, service.describeInstances("us-east-1", List.of(), Map.of()).stream()
|
||||
.mapToInt(reservation -> reservation.getInstances().size()).sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingLaunchesDoNotReserveFutureRunningCapacity() {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance first = launch(service, "t3.micro");
|
||||
assertEquals("pending", first.getState().getName());
|
||||
Instance second = launch(service, "t3.micro");
|
||||
assertEquals("pending", second.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsUseCurrentRunningUsageDeduplicateIdsAndRetryAfterStop() {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance running = instance("i-running", "running");
|
||||
Instance stopped = instance("i-stopped", "stopped");
|
||||
service.putInstanceForTest(running);
|
||||
service.putInstanceForTest(stopped);
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.startInstances("us-east-1",
|
||||
List.of(stopped.getInstanceId(), stopped.getInstanceId())));
|
||||
assertEquals("VcpuLimitExceeded", refused.getErrorCode());
|
||||
assertEquals("stopped", stopped.getState().getName());
|
||||
service.stopInstances("us-east-1", List.of(running.getInstanceId()));
|
||||
service.startInstances("us-east-1", List.of(stopped.getInstanceId(), stopped.getInstanceId()));
|
||||
assertEquals("running", stopped.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startingAStoppingTargetChecksItsNewRunningCostAndCanRetry() {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance running = instance("i-running", "running");
|
||||
Instance stopping = instance("i-stopping", "stopping");
|
||||
service.putInstanceForTest(running);
|
||||
service.putInstanceForTest(stopping);
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.startInstances("us-east-1", List.of(stopping.getInstanceId())));
|
||||
assertEquals("VcpuLimitExceeded", refused.getErrorCode());
|
||||
assertEquals("stopping", stopping.getState().getName());
|
||||
service.stopInstances("us-east-1", List.of(running.getInstanceId()));
|
||||
service.startInstances("us-east-1", List.of(stopping.getInstanceId()));
|
||||
assertEquals("running", stopping.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminatedTargetIsRejectedBeforeQuotaAndNoEarlierTargetStarts() {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance running = instance("i-running", "running");
|
||||
Instance stopped = instance("i-stopped", "stopped");
|
||||
Instance terminated = instance("i-terminated", "terminated");
|
||||
service.putInstanceForTest(running);
|
||||
service.putInstanceForTest(stopped);
|
||||
service.putInstanceForTest(terminated);
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.startInstances("us-east-1",
|
||||
List.of(stopped.getInstanceId(), terminated.getInstanceId())));
|
||||
assertEquals("IncorrectInstanceState", refused.getErrorCode());
|
||||
assertEquals("stopped", stopped.getState().getName());
|
||||
assertEquals("terminated", terminated.getState().getName());
|
||||
service.stopInstances("us-east-1", List.of(running.getInstanceId()));
|
||||
service.startInstances("us-east-1", List.of(stopped.getInstanceId()));
|
||||
assertEquals("running", stopped.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultOffStartsLargeAndUnsizedStoppedTargets() {
|
||||
Ec2Service service = service(0, false);
|
||||
Instance large = instance("i-large", "stopped");
|
||||
large.setInstanceType("m5.2xlarge");
|
||||
Instance unsized = instance("i-unsized", "stopped");
|
||||
unsized.setInstanceType("m999.unmeasured");
|
||||
service.putInstanceForTest(large);
|
||||
service.putInstanceForTest(unsized);
|
||||
service.startInstances("us-east-1", List.of(large.getInstanceId(), unsized.getInstanceId()));
|
||||
assertEquals("running", large.getState().getName());
|
||||
assertEquals("running", unsized.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledUnknownTypesAreRefusedBeforePublicationAndKnownTypesCanRetry() {
|
||||
Ec2Service service = service(4, true);
|
||||
AwsException failure = assertThrows(AwsException.class, () -> launch(service, "m999.unmeasured"));
|
||||
assertEquals("InvalidParameterValue", failure.getErrorCode());
|
||||
assertTrue(service.describeInstances("us-east-1", List.of(), Map.of()).isEmpty());
|
||||
assertNotNull(launch(service, "t3.large"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void spotHostsAndOtherRegionsDoNotConsumeThisRegionalBucket() {
|
||||
Ec2Service service = service(2, true);
|
||||
Instance spot = instance("i-spot", "running");
|
||||
spot.setSpot(true);
|
||||
Instance host = instance("i-host", "running");
|
||||
Placement placement = new Placement("us-east-1a");
|
||||
placement.setTenancy("host");
|
||||
host.setPlacement(placement);
|
||||
Instance other = instance("i-other-region", "running");
|
||||
other.setRegion("eu-west-1");
|
||||
service.putInstanceForTest(spot);
|
||||
service.putInstanceForTest(host);
|
||||
service.putInstanceForTest(other);
|
||||
assertNotNull(launch(service, "t3.micro"));
|
||||
}
|
||||
|
||||
private static Instance instance(String id, String state) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(id);
|
||||
instance.setRegion("us-east-1");
|
||||
instance.setOwnerId("000000000000");
|
||||
instance.setInstanceType("t3.micro");
|
||||
instance.setState(new InstanceState(0, state));
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static Instance launch(Ec2Service service, String type) {
|
||||
return service.runInstances("us-east-1", "ami-test", type, 1, 1, null,
|
||||
List.of(), null, null, List.of(), null, null).getInstances().getFirst();
|
||||
}
|
||||
|
||||
private static Ec2Service service(int limit, boolean enabled) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.services().ec2().mock()).thenReturn(true);
|
||||
when(config.services().ec2().enforceVcpuQuotas()).thenReturn(enabled);
|
||||
when(config.services().ec2().mockPublicAddresses())
|
||||
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
|
||||
when(config.services().ec2().mockPublicAddress()).thenReturn(Optional.empty());
|
||||
when(config.services().servicequotas().standardOnDemandVcpus()).thenReturn(limit);
|
||||
return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new MemoryFactory());
|
||||
}
|
||||
|
||||
private static final class MemoryFactory extends StorageFactory {
|
||||
private MemoryFactory() { super(null, null); }
|
||||
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String service, String file,
|
||||
TypeReference<Map<String, V>> type) {
|
||||
return AccountAwareStorageBackend.inMemory("000000000000");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,8 @@ floci:
|
||||
proxy-base-port: 9400
|
||||
proxy-max-port: 9499
|
||||
ec2:
|
||||
# Opt-in Standard On-Demand vCPU admission. FLOCI_SERVICES_EC2_ENFORCE_VCPU_QUOTAS
|
||||
enforce-vcpu-quotas: false
|
||||
# Optional complete catalog override for locally built guest images.
|
||||
image-catalog-path: ${FLOCI_SERVICES_EC2_IMAGE_CATALOG_PATH:}
|
||||
enabled: true
|
||||
|
||||
Reference in new issue
Block a user