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:
David Phillips authored and GitHub committed 2026-10-20 08:38:21 -04:00
1 parent 8bff1ba0f3
commit 689201122f
19 files changed
+2287 -12

No files matched your search

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