feat(ec2): support Dedicated Hosts (AllocateHosts, DescribeHosts, ModifyHosts, ReleaseHosts) (#4816)

* feat(ec2): support Dedicated Hosts (AllocateHosts, DescribeHosts, ModifyHosts, ReleaseHosts)

terraform's aws_ec2_host failed at create with "Operation AllocateHosts is
not supported". Add the four host actions following the Capacity
Reservation pattern: region-scoped store, dedicated-host tags through
TagSpecification and CreateTags, released hosts kept in DescribeHosts with
state "released", and unknown ids as InvalidHostID.NotFound on describe.
ModifyHosts and ReleaseHosts answer per host, putting an unknown, released
or (on release) occupied host in the unsuccessful set rather than failing
the call.

RunInstances now honours Placement.HostId and Placement.Tenancy: the host
must exist, tenancy defaults to "host", the zone defaults to the host's,
and DescribeInstances reports placement.hostId. DescribeHosts lists the
instances placed on each host.

* fix(ec2): default AllocateHosts AutoPlacement to off and drop the non-AWS host-recovery filter

AWS documents AutoPlacement as defaulting to off; the host record defaulted it
to on. host-recovery is not a DescribeHosts filter in the EC2 API, so it is no
longer matched.

* fix(ec2): validate Dedicated Host zone, settings and launch placement, serialise release against launch

RunInstances now rejects a host placement whose zone, tenancy or instance type
contradicts the host, re-checked under a lock shared with ModifyHosts and
ReleaseHosts. AllocateHosts rejects unknown zones; on/off host settings are
validated on allocate and modify. The hosts store is final again, braces and
the Consumer import follow AGENTS.md, and the RunInstances mock matcher in
Ec2RunInstancesPublicIpParamTest gains the two host parameters.

* test(ec2): pin exact host placement error codes and the in-lock host re-check

* fix(ec2): validate AllocateHosts zone against modelled zones, import classes

* style(ec2): fix import order and hostLock indentation, match AWS occupied-host message

* style(ec2): put java.util.Arrays after the non-java imports in the dedicated host test

* style(ec2): brace the host tag update and host tag lookup conditionals
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-02 17:18:58 -04:00
1 parent 5ad97781ef
commit a4c952db54
8 files changed
+1011 -106

No files matched your search

+18
View File
@@ -542,6 +542,24 @@ through `payment-pending`/`assessing`. `DescribeCapacityReservations` supports t
`instance-type`, `state` and `tenancy` filters alongside the shared `tag:`, `tag-key` and
`tag-value` filters.
### Dedicated Hosts
| Action | Description |
|--------|-------------|
| AllocateHosts | Allocates `Quantity` (default `1`) Dedicated Hosts, `available` immediately, with `dedicated-host` tags from `TagSpecification`. |
| DescribeHosts | Lists or returns stored hosts, including the instances placed on each. |
| ModifyHosts | Updates `AutoPlacement`, `HostRecovery`, `HostMaintenance`, `InstanceType` or `InstanceFamily`. |
| ReleaseHosts | Marks hosts `released`; they stay visible in `DescribeHosts`, as on AWS. |
`AvailabilityZone` and exactly one of `InstanceType` or `InstanceFamily` are required.
`AutoPlacement` and `HostRecovery` default to `off` and `HostMaintenance` to `on`.
`DescribeHosts` with an unknown id fails with `InvalidHostID.NotFound`. `ModifyHosts` and
`ReleaseHosts` report each host separately: an unknown or already released host, or a host
still carrying instances on release, goes to `unsuccessful` instead of failing the call.
`RunInstances` accepts `Placement.HostId` and `Placement.Tenancy`; naming a host defaults the
tenancy to `host` and, without a subnet, the zone to the host's. `hostProperties` reports a
fixed socket/core/vCPU shape rather than one derived from the instance family.
### Elastic IPs
| Action | Description |
@@ -21,6 +21,7 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
@ApplicationScoped
public class Ec2QueryHandler {
@@ -237,6 +238,11 @@ public class Ec2QueryHandler {
case "DescribeCapacityReservations" -> handleDescribeCapacityReservations(params, region);
case "ModifyCapacityReservation" -> handleModifyCapacityReservation(params, region);
case "CancelCapacityReservation" -> handleCancelCapacityReservation(params, region);
// Dedicated Hosts
case "AllocateHosts" -> handleAllocateHosts(params, region);
case "DescribeHosts" -> handleDescribeHosts(params, region);
case "ModifyHosts" -> handleModifyHosts(params, region);
case "ReleaseHosts" -> handleReleaseHosts(params, region);
// Elastic IPs
case "AllocateAddress" -> handleAllocateAddress(params, region);
case "AssociateAddress" -> handleAssociateAddress(params, region);
@@ -793,7 +799,8 @@ public class Ec2QueryHandler {
Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount,
keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions,
creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")));
creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")),
p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"));
if (!networkInterfaceTags.isEmpty()) {
List<String> eniIds = new ArrayList<>();
@@ -4056,6 +4063,125 @@ public class Ec2QueryHandler {
return xml.build();
}
// ─── Dedicated Host handlers ──────────────────────────────────────────────
private Response handleAllocateHosts(MultivaluedMap<String, String> p, String region) {
List<String> assetIds = getList(p, "AssetId");
List<Host> allocated = service.allocateHosts(
region,
p.getFirst("AvailabilityZone"),
p.getFirst("InstanceType"),
p.getFirst("InstanceFamily"),
intOrNull(p, "Quantity"),
p.getFirst("AutoPlacement"),
p.getFirst("HostRecovery"),
p.getFirst("HostMaintenance"),
p.getFirst("OutpostArn"),
assetIds.isEmpty() ? null : assetIds.get(0));
XmlBuilder xml = new XmlBuilder()
.start("AllocateHostsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("hostIdSet");
for (Host host : allocated) {
applyResourceTags(p, region, "dedicated-host", host.getHostId());
xml.elem("item", host.getHostId());
}
xml.end("hostIdSet").end("AllocateHostsResponse");
return xmlResponse(xml.build());
}
private Response handleDescribeHosts(MultivaluedMap<String, String> p, String region) {
List<Host> found = service.describeHosts(region, getList(p, "HostId"), getFilters(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeHostsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("hostSet");
for (Host host : found) {
xml.start("item").raw(hostXml(region, host)).end("item");
}
xml.end("hostSet").end("DescribeHostsResponse");
return xmlResponse(xml.build());
}
private Response handleModifyHosts(MultivaluedMap<String, String> p, String region) {
// Invalid values fail the whole call rather than landing in each host's unsuccessful item.
service.validateHostSettings(p.getFirst("AutoPlacement"), p.getFirst("HostRecovery"),
p.getFirst("HostMaintenance"));
return hostBatchResponse("ModifyHosts", getList(p, "HostId"), id -> service.modifyHost(region, id,
p.getFirst("AutoPlacement"), p.getFirst("HostRecovery"), p.getFirst("HostMaintenance"),
p.getFirst("InstanceType"), p.getFirst("InstanceFamily")));
}
private Response handleReleaseHosts(MultivaluedMap<String, String> p, String region) {
return hostBatchResponse("ReleaseHosts", getList(p, "HostId"), id -> service.releaseHost(region, id));
}
// ModifyHosts and ReleaseHosts answer per host: a host that cannot be changed goes to
// unsuccessful with a Client.-prefixed code instead of failing the whole call.
private Response hostBatchResponse(String action, List<String> hostIds,
Consumer<String> perHost) {
if (hostIds.isEmpty()) {
throw new AwsException("MissingParameter", "The request must contain the parameter HostId.", 400);
}
XmlBuilder successful = new XmlBuilder();
XmlBuilder unsuccessful = new XmlBuilder();
for (String id : hostIds) {
try {
perHost.accept(id);
successful.elem("item", id);
} catch (AwsException e) {
unsuccessful.start("item")
.start("error")
.elem("code", "Client." + e.getErrorCode())
.elem("message", e.getMessage())
.end("error")
.elem("resourceId", id)
.end("item");
}
}
XmlBuilder xml = new XmlBuilder()
.start(action + "Response", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("successful").raw(successful.build()).end("successful")
.start("unsuccessful").raw(unsuccessful.build()).end("unsuccessful")
.end(action + "Response");
return xmlResponse(xml.build());
}
// ponytail: hostProperties cores/sockets/totalVCpus are a fixed m5-sized host shape; derive
// per family from the instance type catalog if a caller ever asserts on them.
private String hostXml(String region, Host host) {
XmlBuilder xml = new XmlBuilder()
.elem("hostId", host.getHostId())
.elem("ownerId", host.getOwnerId())
.elem("availabilityZone", host.getAvailabilityZone())
.elem("autoPlacement", host.getAutoPlacement())
.elem("hostRecovery", host.getHostRecovery())
.elem("hostMaintenance", host.getHostMaintenance())
.elem("state", host.getState())
.elem("outpostArn", host.getOutpostArn())
.elem("assetId", host.getAssetId())
.elem("allocationTime", host.getAllocationTime() != null ? ISO_FMT.format(host.getAllocationTime()) : null)
.elem("releaseTime", host.getReleaseTime() != null ? ISO_FMT.format(host.getReleaseTime()) : null)
.start("hostProperties")
.elem("instanceFamily", host.getInstanceFamily())
.elem("instanceType", host.getInstanceType())
.elem("sockets", 2)
.elem("cores", 48)
.elem("totalVCpus", 96)
.end("hostProperties")
.start("instances");
for (Instance inst : service.hostInstances(region, host.getHostId())) {
xml.start("item")
.elem("instanceId", inst.getInstanceId())
.elem("instanceType", inst.getInstanceType())
.elem("ownerId", host.getOwnerId())
.end("item");
}
xml.end("instances").raw(tagSetXml(host.getTags()));
return xml.build();
}
// Unlike intOrNull's silent skip of absent values, a present but unparseable timestamp is a
// caller mistake and is rejected rather than coerced to null.
private java.time.Instant instantOrNull(MultivaluedMap<String, String> p, String name) {
@@ -4541,6 +4667,7 @@ public class Ec2QueryHandler {
xml.start("placement")
.elem("availabilityZone", inst.getPlacement().getAvailabilityZone())
.elem("tenancy", inst.getPlacement().getTenancy())
.elem("hostId", inst.getPlacement().getHostId())
.end("placement");
}
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.Host;
import io.github.hectorvent.floci.services.ec2.model.IamInstanceProfileAssociation;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -105,6 +106,7 @@ import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
@@ -259,6 +261,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final StorageBackend<String, CapacityReservation> capacityReservations;
private final StorageBackend<String, Host> hosts;
// Serialises a launch onto a host against ModifyHosts/ReleaseHosts, so a host cannot be
// released between the launch's availability check and the store of its instance.
private final Object hostLock = new Object();
private final Set<String> seededAccountRegions = ConcurrentHashMap.newKeySet();
// region::subnetId → offset the next synthesised address is tried at. Only an ordering hint:
// restart forgets it, and privateIpsInUse is what keeps addresses from being handed out twice.
@@ -460,7 +466,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
new TypeReference<Map<String, CapacityReservation>>() {}),
storageFactory.create("ec2", "ec2-volume-modifications.json",
new TypeReference<Map<String, VolumeModification>>() {}),
requestContextInstance, iamService, volumeBlockDeviceManager);
requestContextInstance, iamService, volumeBlockDeviceManager,
storageFactory.create("ec2", "ec2-hosts.json", new TypeReference<Map<String, Host>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -659,6 +666,56 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService,
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, vpcs, subnets, securityGroups, securityGroupRules,
internetGateways, routeTables, keyPairs, addresses, instances,
volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections,
networkInterfaces, capacityReservations, volumeModifications,
requestContextInstance, iamService, volumeBlockDeviceManager, new InMemoryStorage<>());
}
// The terminal constructor. Dedicated Hosts ride on their own parameter so the shorter
// overloads above keep their arity for existing fixtures.
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
StorageBackend<String, NetworkInterface> networkInterfaces,
StorageBackend<String, CapacityReservation> capacityReservations,
StorageBackend<String, VolumeModification> volumeModifications,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService,
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
StorageBackend<String, Host> hosts) {
this.hosts = hosts;
this.iamService = iamService;
this.volumeBlockDeviceManager = volumeBlockDeviceManager;
this.defaultAccountId = config.defaultAccountId();
@@ -2893,6 +2950,40 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
int networkInterfaceDeviceIndex, String availabilityZone,
LaunchTemplateData.MetadataOptions metadataOptions,
String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun) {
return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone,
metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, null, null);
}
/**
* @param hostId Placement.HostId: the Dedicated Host to launch onto. It must exist and not be
* released; with no subnet or zone named, the launch lands in the host's zone.
* @param tenancy Placement.Tenancy; defaults to {@code host} when a host is named.
*/
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,
LaunchTemplateData.MetadataOptions metadataOptions,
String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun,
String hostId, String tenancy) {
if (hostId != null && !hostId.isBlank()) {
Host host = getRequiredAvailableHost(region, hostId);
if ((availabilityZone == null || availabilityZone.isBlank())
&& (subnetId == null || subnetId.isBlank())
&& (networkInterfaceId == null || networkInterfaceId.isBlank())) {
availabilityZone = host.getAvailabilityZone();
}
if (tenancy == null || tenancy.isBlank()) {
tenancy = "host";
}
} else {
hostId = null;
}
if (imageId == null || imageId.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400);
}
@@ -2970,6 +3061,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
reservation.setOwnerId(callerAccountId());
String effectiveInstanceType = instanceType != null ? instanceType : "t2.micro";
if (hostId != null) {
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
}
validateArchitectureCompatibility(region, imageId, effectiveInstanceType);
int count = Math.min(maxCount, Math.max(minCount, 1));
String architecture = architectureFor(region, imageId, effectiveInstanceType);
@@ -3007,112 +3101,124 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412);
}
synchronized (privateIpAllocationLock) {
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, count);
for (int i = 0; i < count; i++) {
String instanceId = "i-" + randomHex(17);
String privateIp = privateIps.get(i);
Instance inst = new Instance();
inst.setInstanceId(instanceId);
inst.setImageId(imageId);
inst.setState(InstanceState.pending());
inst.setInstanceType(effectiveInstanceType);
inst.setPlacement(new Placement(az));
inst.setSubnetId(finalSubnetId);
inst.setVpcId(vpcId);
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
// override wins in both directions; the subnet's MapPublicIpOnLaunch
// attribute is only the default when the launch does not specify it.
inst.setAssociatePublicIp(associatePublicIp != null
? associatePublicIp
: subnet != null && subnet.isMapPublicIpOnLaunch());
inst.setPrivateIpAddress(privateIp);
inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");
inst.setKeyName(keyName);
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
inst.setArchitecture(architecture);
inst.setLaunchTime(Instant.now());
inst.setAmiLaunchIndex(i);
inst.setClientToken(clientToken);
inst.setRegion(region);
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
if (iamInstanceProfileArn != null) {
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
}
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
if (instanceTags != null && !instanceTags.isEmpty()) {
inst.setTags(new ArrayList<>(instanceTags));
tags.put(instanceId, new ArrayList<>(instanceTags));
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++) {
String instanceId = "i-" + randomHex(17);
String privateIp = privateIps.get(i);
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
// floci-kt9) or a freshly-minted implicit primary interface.
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId(suppliedEni != null
? suppliedEni.getNetworkInterfaceId()
: "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
}
inst.getNetworkInterfaces().add(eni);
if (suppliedEni != null) {
// The standalone record stays authoritative rather than being folded into the
// instance: AWS defaults deleteOnTermination to false for an interface the caller
// created and handed to a launch, so it outlives the instance and returns to
// "available" on termination instead of vanishing with it. Double-counting is
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
// id the standalone store owns.
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
launchAttachment.setAttachmentId(eni.getAttachmentId());
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
launchAttachment.setInstanceOwnerId(callerAccountId());
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
}
Instance inst = new Instance();
inst.setInstanceId(instanceId);
inst.setImageId(imageId);
inst.setState(InstanceState.pending());
inst.setInstanceType(effectiveInstanceType);
Placement placement = new Placement(az);
placement.setHostId(hostId);
if (tenancy != null && !tenancy.isBlank()) {
placement.setTenancy(tenancy);
}
inst.setPlacement(placement);
inst.setSubnetId(finalSubnetId);
inst.setVpcId(vpcId);
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
// override wins in both directions; the subnet's MapPublicIpOnLaunch
// attribute is only the default when the launch does not specify it.
inst.setAssociatePublicIp(associatePublicIp != null
? associatePublicIp
: subnet != null && subnet.isMapPublicIpOnLaunch());
inst.setPrivateIpAddress(privateIp);
inst.setPrivateDnsName("ip-" + privateIp.replace('.', '-') + ".ec2.internal");
inst.setKeyName(keyName);
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
inst.setArchitecture(architecture);
inst.setLaunchTime(Instant.now());
inst.setAmiLaunchIndex(i);
inst.setClientToken(clientToken);
inst.setRegion(region);
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
if (iamInstanceProfileArn != null) {
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
}
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
if (instanceTags != null && !instanceTags.isEmpty()) {
inst.setTags(new ArrayList<>(instanceTags));
tags.put(instanceId, new ArrayList<>(instanceTags));
}
// Root EBS volume
String rootVolId = "vol-" + randomHex(17);
inst.setRootVolumeId(rootVolId);
Volume rootVol = new Volume();
rootVol.setVolumeId(rootVolId);
rootVol.setAvailabilityZone(az);
rootVol.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
rootVol.setSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
rootVol.setState("in-use");
rootVol.setRegion(region);
rootVol.setCreateTime(Instant.now());
VolumeAttachment att = new VolumeAttachment();
att.setVolumeId(rootVolId);
att.setInstanceId(instanceId);
att.setDevice(inst.getRootDeviceName());
att.setState("attached");
att.setDeleteOnTermination(true);
att.setAttachTime(Instant.now());
rootVol.getAttachments().add(att);
volumes.put(key(region, rootVolId), rootVol);
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
// floci-kt9) or a freshly-minted implicit primary interface.
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId(suppliedEni != null
? suppliedEni.getNetworkInterfaceId()
: "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
}
inst.getNetworkInterfaces().add(eni);
if (suppliedEni != null) {
// The standalone record stays authoritative rather than being folded into the
// instance: AWS defaults deleteOnTermination to false for an interface the caller
// created and handed to a launch, so it outlives the instance and returns to
// "available" on termination instead of vanishing with it. Double-counting is
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
// id the standalone store owns.
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
launchAttachment.setAttachmentId(eni.getAttachmentId());
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
launchAttachment.setInstanceOwnerId(callerAccountId());
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
}
instances.put(key(region, instanceId), inst);
launched.add(inst);
reservation.getInstances().add(inst);
// Root EBS volume
String rootVolId = "vol-" + randomHex(17);
inst.setRootVolumeId(rootVolId);
Volume rootVol = new Volume();
rootVol.setVolumeId(rootVolId);
rootVol.setAvailabilityZone(az);
rootVol.setVolumeType(DEFAULT_ROOT_VOLUME_TYPE);
rootVol.setSize(DEFAULT_ROOT_VOLUME_SIZE_GIB);
rootVol.setState("in-use");
rootVol.setRegion(region);
rootVol.setCreateTime(Instant.now());
VolumeAttachment att = new VolumeAttachment();
att.setVolumeId(rootVolId);
att.setInstanceId(instanceId);
att.setDevice(inst.getRootDeviceName());
att.setState("attached");
att.setDeleteOnTermination(true);
att.setAttachTime(Instant.now());
rootVol.getAttachments().add(att);
volumes.put(key(region, rootVolId), rootVol);
instances.put(key(region, instanceId), inst);
launched.add(inst);
reservation.getInstances().add(inst);
}
}
}
}
@@ -7099,6 +7205,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (vpc != null) { vpc.setTags(new ArrayList<>(tagList)); vpcs.put(storeKey, vpc); return; }
CapacityReservation cr = capacityReservations.get(storeKey).orElse(null);
if (cr != null) { cr.setTags(new ArrayList<>(tagList)); capacityReservations.put(storeKey, cr); return; }
Host host = hosts.get(storeKey).orElse(null);
if (host != null) {
host.setTags(new ArrayList<>(tagList));
hosts.put(storeKey, host);
return;
}
Subnet subnet = subnets.get(storeKey).orElse(null);
if (subnet != null) { subnet.setTags(new ArrayList<>(tagList)); subnets.put(storeKey, subnet); return; }
SecurityGroup sg = securityGroups.get(storeKey).orElse(null);
@@ -7227,6 +7339,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (resourceId.startsWith("cr-")) {
return "capacity-reservation";
}
if (resourceId.startsWith("h-")) {
return "dedicated-host";
}
if (resourceId.startsWith("vpc-")) {
return "vpc";
}
@@ -7470,6 +7585,179 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return reservation;
}
// ─── Dedicated Hosts ───────────────────────────────────────────────────────
public List<Host> allocateHosts(String region, String availabilityZone, String instanceType,
String instanceFamily, Integer quantity, String autoPlacement, String hostRecovery,
String hostMaintenance, String outpostArn, String assetId) {
ensureDefaultResources(region);
if (availabilityZone == null || availabilityZone.isBlank()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter AvailabilityZone.", 400);
}
boolean hasType = instanceType != null && !instanceType.isBlank();
boolean hasFamily = instanceFamily != null && !instanceFamily.isBlank();
if (hasType == hasFamily) {
throw new AwsException("InvalidParameterCombination",
"Specify exactly one of InstanceType or InstanceFamily.", 400);
}
int count = quantity == null ? 1 : quantity;
if (count <= 0) {
throw new AwsException("InvalidParameterValue",
"Value (" + count + ") for parameter Quantity is invalid.", 400);
}
validateHostSettings(autoPlacement, hostRecovery, hostMaintenance);
boolean zoneExists = Arrays.stream(MODELLED_ZONE_SUFFIXES)
.anyMatch(suffix -> availabilityZone.equals(region + suffix));
if (!zoneExists) {
throw new AwsException("InvalidParameterValue",
"Invalid availability zone: [" + availabilityZone + "]", 400);
}
List<Host> allocated = new ArrayList<>();
for (int i = 0; i < count; i++) {
Host host = new Host();
host.setHostId("h-" + randomHex(17));
host.setOwnerId(callerAccountId());
host.setRegion(region);
host.setAvailabilityZone(availabilityZone);
host.setInstanceType(hasType ? instanceType : null);
host.setInstanceFamily(hasFamily ? instanceFamily : null);
if (autoPlacement != null) {
host.setAutoPlacement(autoPlacement);
}
if (hostRecovery != null) {
host.setHostRecovery(hostRecovery);
}
if (hostMaintenance != null) {
host.setHostMaintenance(hostMaintenance);
}
host.setOutpostArn(outpostArn);
host.setAssetId(assetId);
host.setAllocationTime(Instant.now());
hosts.put(key(region, host.getHostId()), host);
allocated.add(host);
}
return allocated;
}
public List<Host> describeHosts(String region, List<String> ids, Map<String, List<String>> filters) {
ensureDefaultResources(region);
for (String id : ids) {
getRequiredHost(region, id);
}
return hosts.scan(k -> true).stream()
.filter(h -> h.getRegion().equals(region))
.filter(h -> ids.isEmpty() || ids.contains(h.getHostId()))
.filter(h -> matchesFilters(h, filters, region))
.collect(Collectors.toList());
}
/** Instances placed on the host that still occupy it, i.e. not shutting down or terminated. */
public List<Instance> hostInstances(String region, String hostId) {
return instances.scan(k -> true).stream()
.filter(i -> region.equals(i.getRegion()))
.filter(i -> i.getPlacement() != null && hostId.equals(i.getPlacement().getHostId()))
.filter(i -> i.getState() == null
|| !List.of("shutting-down", "terminated").contains(i.getState().getName()))
.collect(Collectors.toList());
}
/** One host of a ModifyHosts batch; the caller reports a throw as that id's unsuccessful item. */
public void modifyHost(String region, String hostId, String autoPlacement, String hostRecovery,
String hostMaintenance, String instanceType, String instanceFamily) {
validateHostSettings(autoPlacement, hostRecovery, hostMaintenance);
synchronized (hostLock) {
Host host = getRequiredAvailableHost(region, hostId);
if (autoPlacement != null) {
host.setAutoPlacement(autoPlacement);
}
if (hostRecovery != null) {
host.setHostRecovery(hostRecovery);
}
if (hostMaintenance != null) {
host.setHostMaintenance(hostMaintenance);
}
if (instanceType != null) {
host.setInstanceType(instanceType);
host.setInstanceFamily(null);
} else if (instanceFamily != null) {
host.setInstanceFamily(instanceFamily);
host.setInstanceType(null);
}
hosts.put(key(region, hostId), host);
}
}
/** AutoPlacement, HostRecovery and HostMaintenance each take only on or off. */
public void validateHostSettings(String autoPlacement, String hostRecovery, String hostMaintenance) {
String[][] settings = {{"AutoPlacement", autoPlacement}, {"HostRecovery", hostRecovery},
{"HostMaintenance", hostMaintenance}};
for (String[] setting : settings) {
if (setting[1] != null && !setting[1].equals("on") && !setting[1].equals("off")) {
throw new AwsException("InvalidParameterValue",
"Value (" + setting[1] + ") for parameter " + setting[0] + " is invalid.", 400);
}
}
}
// A launch onto a host must land in the host's zone, with host tenancy, on a type it accepts.
private void validateHostPlacement(Host host, String az, String instanceType, String tenancy) {
if (!host.getAvailabilityZone().equals(az)) {
throw new AwsException("InvalidParameterCombination",
"The Dedicated Host " + host.getHostId() + " is in availability zone '"
+ host.getAvailabilityZone() + "', not '" + az + "'.", 400);
}
if (tenancy != null && !tenancy.isBlank() && !"host".equals(tenancy)) {
throw new AwsException("InvalidParameterCombination",
"Tenancy '" + tenancy + "' cannot be combined with a Dedicated Host placement.", 400);
}
boolean typeOk = host.getInstanceType() != null
? host.getInstanceType().equals(instanceType)
: host.getInstanceFamily() == null
|| instanceType.startsWith(host.getInstanceFamily() + ".");
if (!typeOk) {
throw new AwsException("InvalidParameter",
"The instance type " + instanceType + " is not supported on Dedicated Host "
+ host.getHostId() + ".", 400);
}
}
/**
* One host of a ReleaseHosts batch. The record is kept with state {@code released}, which is
* how AWS reports it afterwards, and a host still carrying instances cannot be released.
*/
public void releaseHost(String region, String hostId) {
synchronized (hostLock) {
Host host = getRequiredAvailableHost(region, hostId);
if (!hostInstances(region, hostId).isEmpty()) {
throw new AwsException("InvalidHost.Occupied",
"Dedicated host '" + hostId + "' cannot be released as it is occupied.", 400);
}
host.setState("released");
host.setReleaseTime(Instant.now());
hosts.put(key(region, hostId), host);
}
}
// A released host is still describable but is gone for every other purpose.
private Host getRequiredAvailableHost(String region, String hostId) {
Host host = getRequiredHost(region, hostId);
if ("released".equals(host.getState())) {
throw new AwsException("InvalidHostID.NotFound",
"The specified Dedicated Host ID '" + hostId + "' does not exist.", 400);
}
return host;
}
private Host getRequiredHost(String region, String hostId) {
Host host = hostId == null ? null : hosts.get(key(region, hostId)).orElse(null);
if (host == null) {
throw new AwsException("InvalidHostID.NotFound",
"The specified Dedicated Host ID '" + hostId + "' does not exist.", 400);
}
return host;
}
// ─── Route Tables ──────────────────────────────────────────────────────────
public RouteTable createRouteTable(String region, String vpcId) {
@@ -8924,6 +9212,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
default -> true;
};
}
if (resource instanceof Host host) {
return switch (filterName) {
case "availability-zone" -> matchesValue(values, host.getAvailabilityZone());
case "instance-type" -> matchesValue(values, host.getInstanceType());
case "state" -> matchesValue(values, host.getState());
case "auto-placement" -> matchesValue(values, host.getAutoPlacement());
default -> true;
};
}
return true;
}
@@ -8948,6 +9245,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (resource instanceof TransitGatewayVpcAttachment attachment) return attachment.getTags();
if (resource instanceof VpcPeeringConnection pcx) return pcx.getTags();
if (resource instanceof CapacityReservation cr) return cr.getTags();
if (resource instanceof Host host) {
return host.getTags();
}
return Collections.emptyList();
}
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* An EC2 Dedicated Host from {@code AllocateHosts}. Real AWS allocates synchronously enough
* that the host is {@code available} on the first describe; it is reported that way here too.
* A released host stays in {@code DescribeHosts} with state {@code released}, as on AWS.
*
* <p>Exactly one of {@code instanceFamily}/{@code instanceType} is set, whichever the caller
* allocated with: the AWS provider treats both as optional non-computed arguments, so echoing
* one it did not send would be a perpetual diff.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Host {
private String hostId;
private String ownerId;
private String region;
private String availabilityZone;
private String instanceFamily;
private String instanceType;
private String autoPlacement = "off";
private String hostRecovery = "off";
private String hostMaintenance = "on";
private String outpostArn;
private String assetId;
private String state = "available";
private Instant allocationTime;
private Instant releaseTime;
private List<Tag> tags = new ArrayList<>();
public Host() {}
public String getHostId() { return hostId; }
public void setHostId(String hostId) { this.hostId = hostId; }
public String getOwnerId() { return ownerId; }
public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getAvailabilityZone() { return availabilityZone; }
public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
public String getInstanceFamily() { return instanceFamily; }
public void setInstanceFamily(String instanceFamily) { this.instanceFamily = instanceFamily; }
public String getInstanceType() { return instanceType; }
public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
public String getAutoPlacement() { return autoPlacement; }
public void setAutoPlacement(String autoPlacement) { this.autoPlacement = autoPlacement; }
public String getHostRecovery() { return hostRecovery; }
public void setHostRecovery(String hostRecovery) { this.hostRecovery = hostRecovery; }
public String getHostMaintenance() { return hostMaintenance; }
public void setHostMaintenance(String hostMaintenance) { this.hostMaintenance = hostMaintenance; }
public String getOutpostArn() { return outpostArn; }
public void setOutpostArn(String outpostArn) { this.outpostArn = outpostArn; }
public String getAssetId() { return assetId; }
public void setAssetId(String assetId) { this.assetId = assetId; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public Instant getAllocationTime() { return allocationTime; }
public void setAllocationTime(Instant allocationTime) { this.allocationTime = allocationTime; }
public Instant getReleaseTime() { return releaseTime; }
public void setReleaseTime(Instant releaseTime) { this.releaseTime = releaseTime; }
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
@@ -10,6 +10,7 @@ public class Placement {
private String availabilityZone;
private String tenancy = "default";
private String groupName;
private String hostId;
public Placement() {}
@@ -25,4 +26,7 @@ public class Placement {
public String getGroupName() { return groupName; }
public void setGroupName(String groupName) { this.groupName = groupName; }
public String getHostId() { return hostId; }
public void setHostId(String hostId) { this.hostId = hostId; }
}
@@ -0,0 +1,321 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
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 java.util.Arrays;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* EC2 Dedicated Hosts over the Query protocol, walked through the lifecycle terraform's
* {@code aws_ec2_host} drives: AllocateHosts, DescribeHosts until available, ModifyHosts,
* ReleaseHosts, then DescribeHosts showing the host released. Each step is read back through
* a separate DescribeHosts rather than trusting the mutating call's own response.
*
* <p>Ordered because the cases walk one host through its lifecycle.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2DedicatedHostIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static String hostId;
private static String instanceId;
@Test
@Order(1)
void allocateReturnsAHostId() {
hostId = given()
.formParam("Action", "AllocateHosts")
.formParam("InstanceType", "m5.large")
.formParam("AvailabilityZone", "us-east-1a")
.formParam("AutoPlacement", "off")
.formParam("Quantity", "1")
.formParam("TagSpecification.1.ResourceType", "dedicated-host")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "dh-test")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("AllocateHostsResponse.hostIdSet.item", startsWith("h-"))
.extract().path("AllocateHostsResponse.hostIdSet.item");
}
@Test
@Order(2)
void describeShowsTheHostAvailableWithItsPropertiesAndTags() {
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeHostsResponse.hostSet.item.hostId", equalTo(hostId))
.body("DescribeHostsResponse.hostSet.item.state", equalTo("available"))
.body("DescribeHostsResponse.hostSet.item.availabilityZone", equalTo("us-east-1a"))
.body("DescribeHostsResponse.hostSet.item.autoPlacement", equalTo("off"))
.body("DescribeHostsResponse.hostSet.item.hostRecovery", equalTo("off"))
.body("DescribeHostsResponse.hostSet.item.ownerId", equalTo("000000000000"))
.body("DescribeHostsResponse.hostSet.item.hostProperties.instanceType", equalTo("m5.large"))
// Allocated by type, so no family is echoed: terraform would read it as drift.
.body("DescribeHostsResponse.hostSet.item.hostProperties.instanceFamily.size()", equalTo(0))
.body("DescribeHostsResponse.hostSet.item.tagSet.item.key", equalTo("Name"))
.body("DescribeHostsResponse.hostSet.item.tagSet.item.value", equalTo("dh-test"));
}
@Test
@Order(3)
void modifyIsReadBackThroughDescribe() {
given()
.formParam("Action", "ModifyHosts")
.formParam("HostId.1", hostId)
.formParam("AutoPlacement", "on")
.formParam("HostRecovery", "on")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyHostsResponse.successful.item", equalTo(hostId));
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeHostsResponse.hostSet.item.autoPlacement", equalTo("on"))
.body("DescribeHostsResponse.hostSet.item.hostRecovery", equalTo("on"));
}
@Test
@Order(4)
void runInstancesOnTheHostReportsPlacementAndOccupiesIt() {
instanceId = given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567891")
.formParam("InstanceType", "m5.large")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("Placement.HostId", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
given()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.placement.hostId",
equalTo(hostId))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.placement.tenancy",
equalTo("host"))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.placement.availabilityZone",
equalTo("us-east-1a"));
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeHostsResponse.hostSet.item.instances.item.instanceId", equalTo(instanceId));
}
@Test
@Order(5)
void releaseOfAnOccupiedHostIsUnsuccessful() {
given()
.formParam("Action", "ReleaseHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ReleaseHostsResponse.unsuccessful.item.resourceId", equalTo(hostId))
.body("ReleaseHostsResponse.unsuccessful.item.error.code", equalTo("Client.InvalidHost.Occupied"))
.body("ReleaseHostsResponse.unsuccessful.item.error.message",
equalTo("Dedicated host '" + hostId + "' cannot be released as it is occupied."));
given()
.formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", instanceId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(6)
void releaseLeavesTheHostDescribableAsReleased() {
given()
.formParam("Action", "ReleaseHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ReleaseHostsResponse.successful.item", equalTo(hostId));
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeHostsResponse.hostSet.item.state", equalTo("released"));
}
@Test
@Order(7)
void describeOfAnUnknownHostIsNotFound() {
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", "h-00000000000000000")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidHostID.NotFound"))
.body("Response.Errors.Error.Message", containsString("h-00000000000000000"));
}
@Test
@Order(8)
void releaseOfAnUnknownOrAlreadyReleasedHostIsUnsuccessfulNotAnError() {
given()
.formParam("Action", "ReleaseHosts")
.formParam("HostId.1", "h-00000000000000000")
.formParam("HostId.2", hostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ReleaseHostsResponse.unsuccessful.item.size()", equalTo(2))
.body("ReleaseHostsResponse.unsuccessful.item[0].error.code", equalTo("Client.InvalidHostID.NotFound"))
.body("ReleaseHostsResponse.unsuccessful.item[1].resourceId", equalTo(hostId));
}
@Test
@Order(9)
void allocationThatOmitsAutoPlacementDefaultsItToOff() {
String defaultedHostId = given()
.formParam("Action", "AllocateHosts")
.formParam("InstanceFamily", "m5")
.formParam("AvailabilityZone", "us-east-1a")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("AllocateHostsResponse.hostIdSet.item");
given()
.formParam("Action", "DescribeHosts")
.formParam("HostId.1", defaultedHostId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeHostsResponse.hostSet.item.autoPlacement", equalTo("off"));
}
private static ValidatableResponse post(String... kv) {
RequestSpecification r = given().header("Authorization", AUTH_HEADER);
for (int i = 0; i < kv.length; i += 2) {
r = r.formParam(kv[i], kv[i + 1]);
}
return r.when().post("/").then();
}
private static String allocate(String zone) {
return post("Action", "AllocateHosts", "InstanceType", "m5.large", "AvailabilityZone", zone)
.statusCode(200).extract().path("AllocateHostsResponse.hostIdSet.item");
}
private static int hostCount() {
return post("Action", "DescribeHosts").statusCode(200)
.extract().xmlPath().getList("DescribeHostsResponse.hostSet.item").size();
}
@Test
@Order(10)
void allocateRejectsANonexistentZoneAndStoresNothing() {
int before = hostCount();
post("Action", "AllocateHosts", "InstanceType", "m5.large", "AvailabilityZone", "us-east-1z")
.statusCode(400).body(containsString("InvalidParameterValue"));
org.junit.jupiter.api.Assertions.assertEquals(before, hostCount());
}
@Test
@Order(11)
void invalidHostSettingsAreRejectedOnAllocateAndModifyAndNotStored() {
post("Action", "AllocateHosts", "InstanceType", "m5.large", "AvailabilityZone", "us-east-1a",
"AutoPlacement", "banana").statusCode(400).body(containsString("InvalidParameterValue"));
String id = allocate("us-east-1a");
post("Action", "ModifyHosts", "HostId.1", id, "HostRecovery", "banana")
.statusCode(400).body(containsString("InvalidParameterValue"));
post("Action", "DescribeHosts", "HostId.1", id).statusCode(200)
.body("DescribeHostsResponse.hostSet.item.hostRecovery", equalTo("off"));
}
@Test
@Order(12)
void launchPlacementThatContradictsTheHostIsRejected() {
String id = allocate("us-east-1a");
String subnetInB = post("Action", "DescribeSubnets", "Filter.1.Name", "availability-zone",
"Filter.1.Value.1", "us-east-1b").statusCode(200)
.extract().xmlPath().getList("DescribeSubnetsResponse.subnetSet.item.subnetId").get(0).toString();
String[] base = {"Action", "RunInstances", "ImageId", "ami-0abcdef1234567891", "MinCount", "1",
"MaxCount", "1", "Placement.HostId", id};
post(concat(base, "InstanceType", "m5.large", "SubnetId", subnetInB))
.statusCode(400).body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
post(concat(base, "InstanceType", "m5.large", "Placement.Tenancy", "default"))
.statusCode(400).body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
post(concat(base, "InstanceType", "c5.large"))
.statusCode(400).body("Response.Errors.Error.Code", equalTo("InvalidParameter"));
post("Action", "DescribeHosts", "HostId.1", id).statusCode(200)
.body("DescribeHostsResponse.hostSet.item.instances.item.size()", equalTo(0));
}
private static String[] concat(String[] a, String... b) {
String[] out = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, out, a.length, b.length);
return out;
}
}
@@ -60,7 +60,8 @@ class Ec2RunInstancesPublicIpParamTest {
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),
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false)))
nullable(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
nullable(String.class), nullable(String.class)))
.thenReturn(new Reservation());
Ec2QueryHandler handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
@@ -73,7 +74,8 @@ class Ec2RunInstancesPublicIpParamTest {
anyInt(), anyInt(), nullable(String.class), anyList(), nullable(String.class),
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(LaunchTemplateData.MetadataOptions.class), nullable(String.class), nullable(String.class), eq(false),
nullable(String.class), nullable(String.class));
if (expected == null) {
assertNull(associatePublicIp.getValue(),
"an absent override must stay null so the subnet default decides");
@@ -4898,4 +4898,52 @@ class Ec2ServiceTest {
// Provider remains untouched
assertEquals(1, nodeInstance.getTags().size());
}
// The host is released after runInstances' unlocked availability check and before its instances
// are stored. The instance-type catalog lookup sits between the two, so it stands in for the
// concurrent ReleaseHosts. Only the re-check under hostLock can still reject the launch.
@Test
void launchOntoAHostReleasedAfterTheUnlockedCheckIsRejected() {
Ec2Service[] holder = new Ec2Service[1];
String[] hostId = new String[1];
boolean[] released = {false};
Ec2InstanceTypeCatalog releasingCatalog = new Ec2InstanceTypeCatalog() {
@Override
public Optional<CatalogInstanceType> find(String instanceType) {
if (hostId[0] != null && !released[0]) {
released[0] = true;
holder[0].releaseHost("us-east-1", hostId[0]);
}
return super.find(instanceType);
}
};
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), new AmiImageResolver(imageCatalog), imageCatalog,
releasingCatalog, new InMemoryStorageFactory());
holder[0] = service;
hostId[0] = service.allocateHosts("us-east-1", "us-east-1a", "m5.large", null, 1,
null, null, null, null, null).get(0).getHostId();
AwsException e = assertThrows(AwsException.class, () -> service.runInstances("us-east-1",
"ami-ubuntu2404-amd64", "m5.large", 1, 1, null, List.of(), null, null, List.of(), null, null,
null, null, 0, null, null, null, null, false, hostId[0], null));
assertTrue(released[0], "the hook must have released the host between the two checks");
assertEquals("InvalidHostID.NotFound", e.getErrorCode());
assertTrue(service.hostInstances("us-east-1", hostId[0]).isEmpty());
}
@Test
void allocateHostsAcceptsModelledZoneWithNoSubnet() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
service.describeSubnets("us-east-1", List.of(), Map.of()).stream()
.filter(sn -> "us-east-1c".equals(sn.getAvailabilityZone()))
.forEach(sn -> service.deleteSubnet("us-east-1", sn.getSubnetId()));
assertEquals(1, service.allocateHosts("us-east-1", "us-east-1c", "m5.large", null, 1,
null, null, null, null, null).size());
}
}