Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ec2): implement instant CreateFleet (#2956)

luiseterc1f87f7c48238
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java
index 8ffebce028..b0db3504c3 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2Tests.java
@@ -7,6 +7,8 @@ import software.amazon.awssdk.services.ec2.model.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.*;
@@ -14,6 +16,7 @@ import static org.assertj.core.api.Assertions.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2Tests {
+ private static final Logger LOG = Logger.getLogger(Ec2Tests.class.getName());
private static Ec2Client ec2;
private static String vpcId;
private static String subnetId;
@@ -24,6 +27,7 @@ class Ec2Tests {
private static String rtbAssocId;
private static String allocationId;
private static String instanceId;
+ private static String fleetInstanceId;
@BeforeAll
static void setup() {
@@ -34,6 +38,13 @@ class Ec2Tests {
@AfterAll
static void cleanup() {
if (ec2 != null) {
+ try {
+ if (fleetInstanceId != null) {
+ ec2.terminateInstances(TerminateInstancesRequest.builder().instanceIds(fleetInstanceId).build());
+ }
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to terminate CreateFleet test instance " + fleetInstanceId, e);
+ }
try {
if (instanceId != null) {
ec2.terminateInstances(TerminateInstancesRequest.builder().instanceIds(instanceId).build());
@@ -223,6 +234,58 @@ class Ec2Tests {
.containsExactly("arm64");
}
+ @Test
+ @Order(7)
+ @DisplayName("CreateFleet - dry-run and instant on-demand launch")
+ void createFleetDryRunAndLaunch() {
+ String launchTemplateId = ec2.createLaunchTemplate(CreateLaunchTemplateRequest.builder()
+ .launchTemplateName("sdk-create-fleet")
+ .launchTemplateData(RequestLaunchTemplateData.builder()
+ .imageId("ami-0abcdef1234567890")
+ .instanceType(InstanceType.T3_MICRO)
+ .build())
+ .build()).launchTemplate().launchTemplateId();
+
+ FleetLaunchTemplateConfigRequest config = FleetLaunchTemplateConfigRequest.builder()
+ .launchTemplateSpecification(FleetLaunchTemplateSpecificationRequest.builder()
+ .launchTemplateId(launchTemplateId)
+ .version("1")
+ .build())
+ .overrides(FleetLaunchTemplateOverridesRequest.builder()
+ .instanceType(InstanceType.T3_MICRO)
+ .imageId("ami-0abcdef1234567890")
+ .build())
+ .build();
+ CreateFleetRequest request = CreateFleetRequest.builder()
+ .type(FleetType.INSTANT)
+ .launchTemplateConfigs(config)
+ .targetCapacitySpecification(TargetCapacitySpecificationRequest.builder()
+ .totalTargetCapacity(1)
+ .defaultTargetCapacityType(DefaultTargetCapacityType.ON_DEMAND)
+ .build())
+ .build();
+
+ try {
+ assertThatThrownBy(() -> ec2.createFleet(request.toBuilder().dryRun(true).build()))
+ .isInstanceOf(Ec2Exception.class)
+ .satisfies(error -> assertThat(((Ec2Exception) error).awsErrorDetails().errorCode())
+ .isEqualTo("DryRunOperation"));
+
+ CreateFleetResponse response = ec2.createFleet(request);
+ assertThat(response.fleetId()).startsWith("fleet-");
+ assertThat(response.instances()).hasSize(1);
+ assertThat(response.instances().get(0).instanceIds()).hasSize(1);
+ fleetInstanceId = response.instances().get(0).instanceIds().get(0);
+ assertThat(response.instances().get(0).instanceType()).isEqualTo(InstanceType.T3_MICRO);
+ assertThat(response.instances().get(0).lifecycle()).isEqualTo(InstanceLifecycle.ON_DEMAND);
+ }
+ finally {
+ ec2.deleteLaunchTemplate(DeleteLaunchTemplateRequest.builder()
+ .launchTemplateId(launchTemplateId)
+ .build());
+ }
+ }
+
@Test
@Order(8)
@DisplayName("CreateVpc - create VPC with CIDR")
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 64b281adc2..c810eff8b0 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -160,6 +160,7 @@ Floci seeds the following resources on first use in each region so Terraform, th
| Action | Description |
|--------|-------------|
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. |
+| CreateFleet | Creates an instant local fleet from launch-template configurations and on-demand or spot overrides. DryRun returns the AWS-compatible `DryRunOperation` error without launching instances. |
| DescribeInstances | Lists or returns stored EC2 instances. |
| TerminateInstances | Terminates instances and updates their stored lifecycle state. |
| StartInstances | Starts stopped instances and their local runtime when applicable. |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 8d56c718b8..b8ab737cda 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -142,7 +142,7 @@ public class AwsQueryController {
);
private static final Set<String> EC2_ACTIONS = Set.of(
- "RunInstances", "DescribeInstances", "TerminateInstances", "StartInstances", "StopInstances",
+ "RunInstances", "CreateFleet", "DescribeInstances", "TerminateInstances", "StartInstances", "StopInstances",
"RebootInstances", "DescribeInstanceStatus", "DescribeInstanceAttribute", "ModifyInstanceAttribute",
"CreateVpc", "DescribeVpcs", "DeleteVpc", "ModifyVpcAttribute", "DescribeVpcAttribute",
"DescribeVpcEndpointServices", "CreateVpcEndpoint", "DescribeVpcEndpoints", "DeleteVpcEndpoints",
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index 4a7a99a788..56b74b8448 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -59,6 +59,7 @@ public class Ec2QueryHandler {
return switch (action) {
// Instances
case "RunInstances" -> handleRunInstances(params, region);
+ case "CreateFleet" -> handleCreateFleet(params, region);
case "DescribeInstances" -> handleDescribeInstances(params, region);
case "DescribeIamInstanceProfileAssociations" ->
handleDescribeIamInstanceProfileAssociations(params, region);
@@ -715,6 +716,291 @@ public class Ec2QueryHandler {
return service.resolveLaunchTemplateData(region, id, name, version);
}
+ /**
+ * Handles the synchronous EC2 Fleet form used by Karpenter for node launches and
+ * authorization dry-runs. Floci does not model fleet requests as a separate long-lived
+ * resource: an instant fleet is represented by the instances it launches, which keeps
+ * DescribeInstances and termination behavior consistent with RunInstances.
+ *
+ * <p>The EC2 Query model calls this member {@code LaunchTemplateConfigs}, while the wire
+ * location name emitted by SDK serializers is {@code LaunchTemplateConfig.N}. Accept both
+ * spellings because callers in the ecosystem use both forms.</p>
+ */
+ private Response handleCreateFleet(MultivaluedMap<String, String> p, String region) {
+ String fleetType = firstNonBlank(p.getFirst("Type"), "instant");
+ if (!"instant".equals(fleetType)) {
+ throw new AwsException("InvalidParameterValue",
+ "Only instant fleets are supported for local EC2 launches.", 400);
+ }
+ String capacityType = firstNonBlank(
+ p.getFirst("TargetCapacitySpecification.DefaultTargetCapacityType"), "on-demand");
+ if (!Set.of("on-demand", "spot").contains(capacityType)) {
+ throw new AwsException("InvalidParameterValue",
+ "DefaultTargetCapacityType must be on-demand or spot.", 400);
+ }
+
+ int targetCapacity = parseIntParam(p, "TargetCapacitySpecification.TotalTargetCapacity", 0);
+ if (targetCapacity <= 0) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter TargetCapacitySpecification.TotalTargetCapacity.", 400);
+ }
+
+ List<FleetLaunch> launches = parseFleetLaunches(p, region);
+ if (launches.isEmpty()) {
+ throw new AwsException("MissingParameter",
+ "The request must contain the parameter LaunchTemplateConfigs.", 400);
+ }
+
+ // Resolve and validate every launch template before honoring DryRun. AWS returns
+ // DryRunOperation only after it has established that the request could succeed.
+ for (FleetLaunch launch : launches) {
+ if (launch.imageId() == null || launch.imageId().isBlank()) {
+ throw new AwsException("MissingParameter",
+ "Each fleet launch must specify an ImageId in the launch template or override.", 400);
+ }
+ if (launch.instanceType() == null || launch.instanceType().isBlank()) {
+ throw new AwsException("MissingParameter",
+ "Each fleet launch must specify an InstanceType in the launch template or override.", 400);
+ }
+ }
+ checkDryRun(p);
+
+ List<FleetLaunchResult> results = new ArrayList<>(targetCapacity);
+ List<String> launchedInstanceIds = new ArrayList<>(targetCapacity);
+ try {
+ for (int i = 0; i < targetCapacity; i++) {
+ FleetLaunch launch = launches.get(i % launches.size());
+ Reservation reservation = service.runInstances(
+ region,
+ launch.imageId(),
+ launch.instanceType(),
+ 1,
+ 1,
+ launch.keyName(),
+ launch.securityGroupIds(),
+ launch.subnetId(),
+ p.getFirst("ClientToken"),
+ launch.instanceTags(),
+ launch.userData(),
+ launch.iamInstanceProfileArn(),
+ null,
+ null,
+ 0,
+ launch.availabilityZone());
+ Instance instance = reservation.getInstances().get(0);
+ launchedInstanceIds.add(instance.getInstanceId());
+ results.add(new FleetLaunchResult(instance, launch));
+ }
+ } catch (RuntimeException e) {
+ if (!launchedInstanceIds.isEmpty()) {
+ LOG.warnv("CreateFleet failed after launching instances {0}; rolling them back: {1}",
+ launchedInstanceIds, e.getMessage());
+ List<String> rollbackFailureInstanceIds = new ArrayList<>();
+ List<RuntimeException> rollbackFailures = new ArrayList<>();
+ for (String instanceId : launchedInstanceIds) {
+ try {
+ service.terminateInstances(region, List.of(instanceId));
+ } catch (RuntimeException cleanupFailure) {
+ rollbackFailureInstanceIds.add(instanceId);
+ rollbackFailures.add(cleanupFailure);
+ LOG.errorv(cleanupFailure, "CreateFleet rollback failed for instance {0}: {1}",
+ instanceId, cleanupFailure.getMessage());
+ }
+ }
+ if (!rollbackFailures.isEmpty()) {
+ String rollbackMessage = "CreateFleet rollback incomplete for instance(s): "
+ + String.join(", ", rollbackFailureInstanceIds);
+ if (e instanceof AwsException awsFailure) {
+ AwsException enrichedFailure = new AwsException(
+ awsFailure.getErrorCode(),
+ awsFailure.getMessage() + " " + rollbackMessage,
+ awsFailure.getHttpStatus());
+ enrichedFailure.addSuppressed(e);
+ rollbackFailures.forEach(enrichedFailure::addSuppressed);
+ throw enrichedFailure;
+ }
+ rollbackFailures.forEach(e::addSuppressed);
+ }
+ }
+ throw e;
+ }
+
+ XmlBuilder xml = new XmlBuilder()
+ .start("CreateFleetResponse", AwsNamespaces.EC2)
+ .elem("requestId", UUID.randomUUID().toString())
+ .elem("fleetId", "fleet-" + UUID.randomUUID().toString().replace("-", ""))
+ .start("fleetInstanceSet");
+ // AWS groups instances that share a launch template and overrides into one fleet
+ // instance entry. Keep the first-seen order stable while collecting all instance IDs.
+ Map<FleetLaunchKey, List<FleetLaunchResult>> groupedResults = new LinkedHashMap<>();
+ for (FleetLaunchResult result : results) {
+ groupedResults.computeIfAbsent(FleetLaunchKey.from(result.launch()), ignored -> new ArrayList<>())
+ .add(result);
+ }
+ for (List<FleetLaunchResult> group : groupedResults.values()) {
+ FleetLaunchResult first = group.getFirst();
+ Instance instance = first.instance();
+ FleetLaunch launch = first.launch();
+ xml.start("item")
+ .start("instanceIds");
+ for (FleetLaunchResult result : group) {
+ xml.elem("item", result.instance().getInstanceId());
+ }
+ xml.end("instanceIds")
+ .elem("instanceType", instance.getInstanceType())
+ .elem("availabilityZone", instance.getPlacement() != null
+ ? instance.getPlacement().getAvailabilityZone() : null)
+ .elem("subnetId", instance.getSubnetId())
+ .elem("lifecycle", capacityType)
+ .start("launchTemplateAndOverrides")
+ .start("launchTemplateSpecification")
+ .elem("launchTemplateId", launch.launchTemplateId())
+ .elem("launchTemplateName", launch.launchTemplateName())
+ .elem("version", launch.launchTemplateVersion())
+ .end("launchTemplateSpecification")
+ .start("overrides")
+ .elem("instanceType", launch.instanceType())
+ .elem("imageId", launch.imageId())
+ .elem("subnetId", launch.subnetId())
+ .elem("availabilityZone", launch.availabilityZone())
+ .end("overrides")
+ .end("launchTemplateAndOverrides")
+ .end("item");
+ }
+ xml.end("fleetInstanceSet")
+ .end("CreateFleetResponse");
+ return xmlResponse(xml.build());
+ }
+
+ private List<FleetLaunch> parseFleetLaunches(MultivaluedMap<String, String> p, String region) {
+ List<FleetLaunch> launches = new ArrayList<>();
+ for (int i = 1; ; i++) {
+ String base = fleetConfigBase(p, i);
+ if (base == null) {
+ break;
+ }
+ String launchTemplateId = p.getFirst(base + ".LaunchTemplateSpecification.LaunchTemplateId");
+ String launchTemplateName = p.getFirst(base + ".LaunchTemplateSpecification.LaunchTemplateName");
+ String version = p.getFirst(base + ".LaunchTemplateSpecification.Version");
+ LaunchTemplateData template = service.resolveLaunchTemplateData(
+ region, launchTemplateId, launchTemplateName, version);
+ List<Tag> fleetInstanceTags = parseTagsForResource(p, "instance");
+
+ boolean hasOverride = false;
+ for (int j = 1; ; j++) {
+ String overrideBase = base + ".Overrides." + j;
+ String instanceType = p.getFirst(overrideBase + ".InstanceType");
+ String imageId = p.getFirst(overrideBase + ".ImageId");
+ String subnetId = p.getFirst(overrideBase + ".SubnetId");
+ String availabilityZone = p.getFirst(overrideBase + ".AvailabilityZone");
+ if (instanceType == null && imageId == null && subnetId == null && availabilityZone == null) {
+ break;
+ }
+ hasOverride = true;
+ launches.add(fleetLaunch(region, template, launchTemplateId, launchTemplateName, version,
+ instanceType, imageId, subnetId, availabilityZone, fleetInstanceTags));
+ }
+ if (!hasOverride) {
+ launches.add(fleetLaunch(region, template, launchTemplateId, launchTemplateName, version,
+ null, null, null, null, fleetInstanceTags));
+ }
+ }
+ return launches;
+ }
+
+ private FleetLaunch fleetLaunch(String region, LaunchTemplateData template, String launchTemplateId,
+ String launchTemplateName, String version,
+ String overrideInstanceType, String overrideImageId,
+ String overrideSubnetId, String overrideAvailabilityZone,
+ List<Tag> fleetInstanceTags) {
+ Map<String, Tag> tags = new LinkedHashMap<>();
+ for (Tag tag : template.getInstanceTags()) {
+ tags.put(tag.getKey(), tag);
+ }
+ for (Tag tag : fleetInstanceTags) {
+ tags.put(tag.getKey(), tag);
+ }
+ String templateSubnetId = template.getNetworkInterfaces().stream()
+ .map(networkInterface -> networkInterface.getSubnetId())
+ .filter(Objects::nonNull)
+ .filter(value -> !value.isBlank())
+ .findFirst()
+ .orElse(null);
+ String subnetId = firstNonBlank(overrideSubnetId, templateSubnetId);
+ String templateAvailabilityZone = template.getPlacement() != null
+ ? template.getPlacement().getAvailabilityZone() : null;
+ String availabilityZone = resolveFleetAvailabilityZone(
+ region, templateSubnetId, templateAvailabilityZone, overrideSubnetId, overrideAvailabilityZone);
+ return new FleetLaunch(
+ launchTemplateId,
+ launchTemplateName,
+ version,
+ firstNonBlank(overrideInstanceType, template.getInstanceType()),
+ firstNonBlank(overrideImageId, template.getImageId()),
+ subnetId,
+ availabilityZone,
+ template.getKeyName(),
+ template.getUserData(),
+ service.iamInstanceProfileArn(template),
+ template.effectiveSecurityGroupIds(),
+ new ArrayList<>(tags.values()));
+ }
+
+ /**
+ * Resolves the placement represented by one CreateFleet launch override.
+ *
+ * <p>A subnet supplied by an override replaces the subnet inherited from the launch template.
+ * Its availability zone therefore also replaces a template placement zone when the override
+ * does not carry an explicit zone. Passing the template zone through in that case creates a
+ * valid subnet-only AWS override that is incorrectly rejected as a subnet/AZ mismatch. Resolve
+ * the subnet here so both the launch request and the response describe the same placement.</p>
+ */
+ private String resolveFleetAvailabilityZone(String region, String templateSubnetId,
+ String templateAvailabilityZone, String overrideSubnetId,
+ String overrideAvailabilityZone) {
+ if (isSet(overrideAvailabilityZone)) {
+ return overrideAvailabilityZone;
+ }
+ if (isSet(overrideSubnetId)) {
+ return service.requireSubnet(region, overrideSubnetId).getAvailabilityZone();
+ }
+ if (isSet(templateAvailabilityZone)) {
+ return templateAvailabilityZone;
+ }
+ if (isSet(templateSubnetId)) {
+ return service.requireSubnet(region, templateSubnetId).getAvailabilityZone();
+ }
+ return null;
+ }
+
+ private String fleetConfigBase(MultivaluedMap<String, String> p, int index) {
+ String singular = "LaunchTemplateConfig." + index;
+ String plural = "LaunchTemplateConfigs." + index;
+ if (anyParamStartsWith(p, singular + ".")) {
+ return singular;
+ }
+ if (anyParamStartsWith(p, plural + ".")) {
+ return plural;
+ }
+ return null;
+ }
+
+ private record FleetLaunch(String launchTemplateId, String launchTemplateName, String launchTemplateVersion,
+ String instanceType, String imageId, String subnetId, String availabilityZone,
+ String keyName, String userData, String iamInstanceProfileArn,
+ List<String> securityGroupIds, List<Tag> instanceTags) {}
+
+ private record FleetLaunchKey(String launchTemplateId, String launchTemplateName, String launchTemplateVersion,
+ String instanceType, String imageId, String subnetId, String availabilityZone) {
+ private static FleetLaunchKey from(FleetLaunch launch) {
+ return new FleetLaunchKey(launch.launchTemplateId(), launch.launchTemplateName(),
+ launch.launchTemplateVersion(), launch.instanceType(), launch.imageId(), launch.subnetId(),
+ launch.availabilityZone());
+ }
+ }
+
+ private record FleetLaunchResult(Instance instance, FleetLaunch launch) {}
+
private static String firstNonBlank(String first, String fallback) {
return first != null && !first.isBlank() ? first : fallback;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index fad1c44d33..0e54c5d125 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -2231,6 +2231,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String clientToken, List<Tag> instanceTags,
String userData, String iamInstanceProfileArn,
Boolean associatePublicIp, String networkInterfaceId, int networkInterfaceDeviceIndex) {
+ return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
+ securityGroupIds, subnetId, clientToken, instanceTags, userData,
+ iamInstanceProfileArn, associatePublicIp, networkInterfaceId,
+ networkInterfaceDeviceIndex, null);
+ }
+
+ /**
+ * Launches instances with an optional placement availability zone. When no subnet is
+ * supplied, the zone selects the default subnet for that zone, matching EC2's placement
+ * semantics instead of silently falling back to the first subnet in the region.
+ */
+ public 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) {
if (imageId == null || imageId.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
}
@@ -2252,6 +2270,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
Subnet subnet = null;
if (subnetId != null && !subnetId.isEmpty()) {
subnet = requireSubnet(region, subnetId);
+ if (availabilityZone != null && !availabilityZone.isBlank()
+ && !availabilityZone.equals(subnet.getAvailabilityZone())) {
+ throw new AwsException("InvalidParameterCombination",
+ "The subnet '" + subnetId + "' is not in availability zone '"
+ + availabilityZone + "'.",
+ 400);
+ }
+ } else if (availabilityZone != null && !availabilityZone.isBlank()) {
+ subnet = resolveSubnetForAvailabilityZone(region, availabilityZone);
} else {
// Pick first default subnet
subnet = subnets.scan(k -> true).stream()
@@ -2261,7 +2288,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
String vpcId = subnet != null ? subnet.getVpcId() : resolveDefaultVpcId(region);
- String az = subnet != null ? subnet.getAvailabilityZone() : region + "a";
+ String az = subnet != null ? subnet.getAvailabilityZone()
+ : availabilityZone != null && !availabilityZone.isBlank() ? availabilityZone : region + "a";
String finalSubnetId = subnet != null ? subnet.getSubnetId() : null;
// Resolve security groups
@@ -2542,6 +2570,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return subnet;
}
+ /**
+ * Resolves a subnet for an EC2 placement availability zone. Prefer the seeded default subnet
+ * when several local subnets share the zone, but allow user-created subnets to make custom
+ * VPC fixtures useful for CreateFleet as well.
+ */
+ public Subnet resolveSubnetForAvailabilityZone(String region, String availabilityZone) {
+ ensureDefaultResources(region);
+ return subnets.scan(k -> true).stream()
+ .filter(subnet -> region.equals(subnet.getRegion()))
+ .filter(subnet -> availabilityZone.equals(subnet.getAvailabilityZone()))
+ .sorted(Comparator.comparing(Subnet::isDefaultForAz).reversed()
+ .thenComparing(Subnet::getSubnetId))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("InvalidAvailabilityZone.NotFound",
+ "The availability zone '" + availabilityZone + "' has no subnet in this region.", 400));
+ }
+
private String assignPrivateIp(String region, String subnetId) {
if (subnetId == null) {
return "172.31.0." + (10 + new Random().nextInt(200));
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java
new file mode 100644
index 0000000000..b7f76d9d36
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetIntegrationTest.java
@@ -0,0 +1,218 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.everyItem;
+import static org.hamcrest.Matchers.startsWith;
+
+/**
+ * Contract coverage for the instant CreateFleet request used by Karpenter's EC2 provider.
+ *
+ * <p>The test deliberately exercises both the singular EC2 Query wire location name
+ * ({@code LaunchTemplateConfig.N}) and the AWS-compatible DryRun exception. No real Docker
+ * runtime is required because the test profile runs EC2 in mock mode.</p>
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class Ec2CreateFleetIntegrationTest {
+
+ private static final String AUTH_HEADER =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
+ private static final String CONTRACT_IMAGE_ID = "ami-create-fleet-contract";
+ private static String launchTemplateId;
+
+ @Test
+ @Order(1)
+ void createFleetDryRunReturnsAwsCompatibleExceptionWithoutLaunching() {
+ launchTemplateId = createLaunchTemplate();
+
+ given()
+ .formParam("Action", "CreateFleet")
+ .formParam("Type", "instant")
+ .formParam("DryRun", "true")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", launchTemplateId)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "1")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(412)
+ .body(containsString("<Code>DryRunOperation</Code>"));
+
+ given()
+ .formParam("Action", "DescribeInstances")
+ .formParam("Filter.1.Name", "image-id")
+ .formParam("Filter.1.Value.1", CONTRACT_IMAGE_ID)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(2)
+ void createFleetRejectsConflictingSubnetAndAvailabilityZone() {
+ given()
+ .formParam("Action", "CreateFleet")
+ .formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", launchTemplateId)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("LaunchTemplateConfig.1.Overrides.1.SubnetId", "subnet-default-us-east-1-a")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.AvailabilityZone", "us-east-1b")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "1")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidParameterCombination"));
+ }
+
+ @Test
+ @Order(3)
+ void createFleetSubnetOverrideDerivesAvailabilityZoneInsteadOfInheritingTemplateZone() {
+ String placementLaunchTemplateId = createLaunchTemplateWithAvailabilityZone();
+
+ given()
+ .formParam("Action", "CreateFleet")
+ .formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId",
+ placementLaunchTemplateId)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("LaunchTemplateConfig.1.Overrides.1.SubnetId", "subnet-default-us-east-1-b")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "1")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateFleetResponse.fleetInstanceSet.item.availabilityZone", equalTo("us-east-1b"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.subnetId",
+ equalTo("subnet-default-us-east-1-b"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.launchTemplateAndOverrides.overrides.subnetId",
+ equalTo("subnet-default-us-east-1-b"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.launchTemplateAndOverrides.overrides.availabilityZone",
+ equalTo("us-east-1b"));
+ }
+
+ @Test
+ @Order(4)
+ void createFleetRollsBackEarlierLaunchesWhenLaterLaunchFails() {
+ given()
+ .formParam("Action", "CreateFleet")
+ .formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", launchTemplateId)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.ImageId", "ami-rollback-test")
+ .formParam("LaunchTemplateConfig.1.Overrides.2.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.2.ImageId", "ami-rollback-test")
+ .formParam("LaunchTemplateConfig.1.Overrides.2.SubnetId", "subnet-does-not-exist")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "2")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidSubnetID.NotFound"));
+
+ given()
+ .formParam("Action", "DescribeInstances")
+ .formParam("Filter.1.Name", "image-id")
+ .formParam("Filter.1.Value.1", "ami-rollback-test")
+ .formParam("Filter.2.Name", "instance-state-name")
+ .formParam("Filter.2.Value.1", "running")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.size()", equalTo(0));
+ }
+
+ @Test
+ @Order(5)
+ void createFleetLaunchesInstanceAndReturnsFleetShape() {
+ if (launchTemplateId == null) {
+ launchTemplateId = createLaunchTemplate();
+ }
+
+ given()
+ .formParam("Action", "CreateFleet")
+ .formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", launchTemplateId)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateConfig.1.Overrides.1.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("LaunchTemplateConfig.1.Overrides.1.AvailabilityZone", "us-east-1b")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", "2")
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CreateFleetResponse.fleetId", startsWith("fleet-"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.size()", equalTo(1))
+ .body("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item.size()", equalTo(2))
+ .body("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item", everyItem(startsWith("i-")))
+ .body("CreateFleetResponse.fleetInstanceSet.item.instanceType", equalTo("t3.micro"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.availabilityZone", equalTo("us-east-1b"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.lifecycle", equalTo("on-demand"))
+ .body("CreateFleetResponse.fleetInstanceSet.item.launchTemplateAndOverrides.launchTemplateSpecification.launchTemplateId",
+ equalTo(launchTemplateId))
+ .body("CreateFleetResponse.fleetInstanceSet.item.launchTemplateAndOverrides.overrides.imageId",
+ equalTo(CONTRACT_IMAGE_ID));
+ }
+
+ private static String createLaunchTemplate() {
+ return given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", "create-fleet-contract")
+ .formParam("LaunchTemplateData.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
+ }
+
+ private static String createLaunchTemplateWithAvailabilityZone() {
+ return given()
+ .formParam("Action", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", "create-fleet-placement-contract")
+ .formParam("LaunchTemplateData.ImageId", CONTRACT_IMAGE_ID)
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateData.Placement.AvailabilityZone", "us-east-1a")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java
new file mode 100644
index 0000000000..9381cab072
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateFleetRollbackTest.java
@@ -0,0 +1,80 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ec2.model.Instance;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
+import io.github.hectorvent.floci.services.ec2.model.Reservation;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
+import jakarta.ws.rs.core.Response;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Ensures CreateFleet rollback keeps attempting every instance when one termination call fails.
+ */
+class Ec2CreateFleetRollbackTest {
+
+ private static final String REGION = "us-east-1";
+
+ @Test
+ void rollbackContinuesAfterOneTerminationFailureAndReportsIncompleteCleanup() {
+ Ec2Service service = mock(Ec2Service.class);
+ LaunchTemplateData template = new LaunchTemplateData();
+ template.setImageId("ami-test");
+ template.setInstanceType("t3.micro");
+ when(service.resolveLaunchTemplateData(REGION, "lt-test", null, "1")).thenReturn(template);
+
+ when(service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), nullable(String.class),
+ anyList(), nullable(String.class), nullable(String.class), anyList(), nullable(String.class),
+ nullable(String.class), nullable(Boolean.class), nullable(String.class), anyInt(),
+ nullable(String.class)))
+ .thenReturn(reservation("i-first"))
+ .thenReturn(reservation("i-second"))
+ .thenThrow(new AwsException("InvalidSubnetID.NotFound", "launch failed", 400));
+ when(service.terminateInstances(REGION, List.of("i-first")))
+ .thenThrow(new AwsException("InternalError", "cleanup failed", 500));
+ when(service.terminateInstances(REGION, List.of("i-second"))).thenReturn(List.of());
+
+ Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
+ mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class), mock(Ec2IpamService.class));
+ Response response = handler.handle("CreateFleet", params(), REGION);
+
+ assertEquals(400, response.getStatus());
+ String responseBody = response.getEntity().toString();
+ assertTrue(responseBody.contains("<Code>InvalidSubnetID.NotFound</Code>"));
+ assertTrue(responseBody.contains("CreateFleet rollback incomplete for instance(s): i-first"));
+ verify(service).terminateInstances(REGION, List.of("i-first"));
+ verify(service).terminateInstances(REGION, List.of("i-second"));
+ }
+
+ private static Reservation reservation(String instanceId) {
+ Instance instance = new Instance();
+ instance.setInstanceId(instanceId);
+ Reservation reservation = new Reservation();
+ reservation.getInstances().add(instance);
+ return reservation;
+ }
+
+ private static MultivaluedMap<String, String> params() {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ params.putSingle("Type", "instant");
+ params.putSingle("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", "lt-test");
+ params.putSingle("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1");
+ params.putSingle("LaunchTemplateConfig.1.Overrides.1.InstanceType", "t3.micro");
+ params.putSingle("TargetCapacitySpecification.TotalTargetCapacity", "3");
+ return params;
+ }
+}