fix(ec2): apply the AWS public address rules and displace earlier Elastic IPs (#5963)

* fix(ec2): assign mock public addresses and displace earlier Elastic IPs

In mock mode an instance never received a public IPv4 address, whatever
its subnet's MapPublicIpOnLaunch or its launch's AssociatePublicIpAddress
said, and an associated Elastic IP never reached DescribeInstances.

- A mock instance that asks for a public address gets one when it reaches
  running, whether DescribeInstances, DescribeInstanceStatus or
  StartInstances completes the launch. Stop and termination release it.
  An associated Elastic IP replaces it and survives a stop; disassociating
  it gives a running instance a new automatic address when its launch
  asked for one.
- AssociateAddress disassociates the Elastic IP an instance already has,
  including one a retained interface carried onto it, as the
  AssociateAddress reference describes.
- Launches from a template take AssociatePublicIpAddress from its
  device-index-0 interface (RunInstances, CreateFleet, Auto Scaling), and
  RunInstances and CreateFleet also take that interface's subnet.
- RunInstances refuses an instance-level SubnetId combined with network
  interfaces, on the request or in its launch template, with
  InvalidParameterCombination.

Split out of #5671 at review.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): scope Elastic IP displacement and automatic addresses as AWS does

- AssociateAddress ignored PrivateIpAddress, so an Elastic IP meant for
  a secondary private address displaced the one on the primary. The
  address is now recorded on the private address it names, only an
  address already on that private address is displaced, the interface
  shows it there, and in mock mode only the primary's address becomes
  the instance's public address.
- An instance launched on an existing network interface got an
  automatic public address; AWS assigns one only to an interface the
  launch creates.
- A released automatic address was replaced while a second interface
  was attached; AWS does not replace it then.
- An Elastic IP that a retained interface carried to a new instance
  stayed without an instance. It now names that instance, which shows
  the address and keeps it across a stop.
- A mock launch could complete over a concurrent stop or termination,
  and DescribeAddresses could write back an address disassociated
  meanwhile; both now re-check under the instance's lock.

The tests also cover a request's own network interfaces with an
instance-level SubnetId, and the template interface docs now say which
launches take the subnet.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): settle second-review findings on mock public addresses

- DescribeAddresses re-points associated addresses under the allocation
  lock, and a mock launch, start or stop reads the instance's Elastic IP
  under it, so none of them acts on an association written halfway or
  changed meanwhile.
- An Elastic IP that a retained interface carries is found through that
  interface, also when it is disassociated, instead of being rebound to
  the next instance at launch, which left a dead InstanceId behind when a
  container launch failed.
- StartInstances leaves a running mock instance alone.
- In container mode too, an address on a secondary private address no
  longer becomes the instance's public address.
- The second-interface test associates its address before attaching the
  interface, since AssociateAddress by InstanceId needs exactly one.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): keep terminated mock instances down and address reads unblocked

- StopInstances leaves a terminated or shutting-down mock instance as it
  is, re-checked under the lock, so terminate, stop and start no longer
  revives it with a public address.
- DescribeAddresses waits for the allocation lock only when an address
  is associated with an instance, and the container re-point no longer
  rewrites an unchanged instance.
- A mock start treats a state without a name as settled instead of
  throwing.

Tests now cover the terminated instance and, with a reachable container
address, an Elastic IP on a secondary private address leaving the
instance's public address alone.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): settle Qodo findings on mock public addresses

- AssociateAddress refuses a PrivateIpAddress that is neither the
  instance's primary private address nor a secondary address of its
  primary interface, with InvalidParameterValue and before any
  association changes, instead of treating it as the primary and
  displacing the Elastic IP already there.
- RunInstances from a launch template whose device-index-0 interface
  names an existing NetworkInterfaceId launches on that interface, in
  its subnet and without an automatic public address, as a request
  naming it would, instead of on a new interface in the default subnet.
- The SubnetId-with-interfaces refusal test now launches against a real
  subnet and checks that the refused request leaves no instance or
  interface behind.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): accept a container instance's launch address in AssociateAddress

In container mode without AWS-faithful private addresses, the container
manager replaces the instance's reported private address with its Docker
bridge address once the container runs, and nothing keeps the subnet
address RunInstances returned. The new PrivateIpAddress check therefore
refused that address with InvalidParameterValue, though callers may still
name it. Only mock mode and the AWS-faithful mode, which keep the launch
address, now refuse a stray PrivateIpAddress; elsewhere any value means
the primary address, as before.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): decide automatic public addresses the same way with containers

The public IPv4 rules were applied to mock instances only. A
container-backed instance kept its address after a stop and a
termination, got one on an existing network interface, kept its
reachable address after its Elastic IP was disassociated even when the
launch never asked for one, and had a released address replaced while
a second interface was attached.

One rule, AutomaticPublicAddress, now decides whether an instance has
an automatic address in both modes: the launch asked for one on an
interface the launch created (recorded when the instance is built), a
stop, a termination or a disassociated Elastic IP releases it, and a
replacement is held back while a second interface is attached. An
Elastic IP on the primary private address still takes precedence. Only
the value differs by mode: the container's reachable address, or an
invented one where there is no container.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): settle review findings on the shared public address rule

- DisassociateAddress decides by the association, not by comparing
  addresses: only an Elastic IP on the instance's primary private address
  gives way to another one left there, or to an automatic address when
  one is due. With a container, every Elastic IP points at the one
  reachable address, so disassociating a secondary one no longer clears
  the instance's public address, and one a restart moved no longer
  survives its disassociation.
- StartInstances on a stopped container instance releases an automatic
  address that a stop outside StopInstances, such as Floci's shutdown,
  left in place, so the start decides afresh.
- With a container, these writes no longer wait on the instance's lock
  while holding the allocation lock, since the port-forward manager holds
  that lock across Docker calls.
- A start test case now keeps an address distinct from the one it
  expects, and two comments describe the flag as it now is.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): release only the primary interface's Elastic IP on disassociation

- DisassociateAddress treats an Elastic IP as the instance's public one
  only when it sits on the primary interface, not on a retained
  interface attached at another device index, so disassociating that one
  no longer clears the instance's automatic address.
- With a container, DescribeAddresses no longer writes a re-pointed
  address back onto a terminated or shutting-down instance.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): show a carried Elastic IP on a container instance's launch

- An instance launched on a retained interface that still carries an
  Elastic IP records that address at RunInstances, and the container
  launch re-points it once the container runs. With containers, such an
  instance had no public address until a stop and start, since the
  shared rule gives an existing interface no automatic address.
- With a container, TerminateInstances clears the public address under
  the allocation lock, so a DescribeAddresses re-point already under way
  cannot write it back onto the terminated instance.
- The secondary-interface disassociation test checks the address was
  still associated before the call and is not after it.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): re-point a carried Elastic IP at its new instance

- DescribeAddresses re-points an Elastic IP that a retained interface
  carries at the instance that interface is now the primary interface
  of. With containers, the address otherwise kept the previous
  container's address for good, since termination clears its instance
  id.
- With a container, StopInstances leaves a terminated or shutting-down
  instance alone, as mock mode does, instead of stopping it into a
  startable state and writing its Elastic IP back.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): give mock instances no invented public address by default

Mock instances due an automatic public IPv4 address got a random
54.x.x.x one, a real AWS range, so a tool that connected to it reached
someone else's host. The new floci.services.ec2.mock-public-addresses
setting (FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES) chooses the address:
none (the default) gives none, documentation draws distinct addresses
from 203.0.113.0/24 as Lightsail and EMR do, and fixed gives every
instance mock-public-address (default 127.0.0.1), an address the caller
can reach.

Only the value changes. The launch still records whether it asked for
an address, so the shared rule and Elastic IP precedence work as before,
and instances with containers keep reporting their reachable address.
Elastic IP allocation still draws from 54.x.x.x, as on main.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): settle review findings on the mock public address setting

A configured mock-public-address with surrounding spaces was reported
as is; it is now stripped. The docs and the AutomaticPublicAddress
Javadoc no longer describe every mock instance as getting an address,
and the test configurations that launch mock instances name the
setting instead of leaving it null.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): allocate Elastic IPs from the documentation range

AllocateAddress handed out random 54.x.x.x addresses, a real AWS range,
and this branch shows an associated Elastic IP as a mock instance's
public address, so even with mock-public-addresses at none a client
could reach someone else's host through one. Elastic IPs now come from
203.0.113.0/24 in every mode, distinct from the account's other
Elastic IPs and its instances' public addresses; once all 254 are taken
AllocateAddress fails with AddressLimitExceeded rather than repeat one,
since callers name an Elastic IP by its address.

Under mock-public-addresses: fixed, an Elastic IP on a mock instance's
primary private address is re-pointed at the configured address, as one
on a container instance is at the container's reachable address, and
disassociation restores the allocated address.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): settle review findings on documentation-range Elastic IPs

An Elastic IP re-pointed at the fixed address kept it after a restart
under another setting; the next read now shows its allocated address
again. The re-point Javadoc and the Elastic IP docs no longer claim a
54.x.x.x allocation or addresses that never repeat, the docs say that
earlier allocations keep their address until released, and a test now
proves an allocation skips the addresses instances hold.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-19 19:48:20 -04:00
1 parent 34d904fde5
commit 456ae15684
24 files changed
+2068 -60

No files matched your search

@@ -3205,6 +3205,39 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean mock();
/**
* The automatic public IPv4 address a mock instance gets when its launch asks for one.
* Mock instances have no container to reach, so the default gives them none: an address
* from a real AWS range would send a client that connects to it to someone else's host.
* {@code documentation} draws addresses from 203.0.113.0/24, a range reserved for
* documentation that routes nowhere; {@code fixed} gives every instance
* {@link #mockPublicAddress()}, which an Elastic IP on its primary private address then
* shows too. Elastic IPs are allocated from 203.0.113.0/24 whatever this says, and
* instances with containers always report the container's reachable address.
*
* Env var: FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES
*/
@WithDefault("none")
MockPublicAddresses mockPublicAddresses();
/**
* The public IPv4 address of every mock instance due an automatic one when
* {@link #mockPublicAddresses()} is {@code fixed}: an address the caller can reach, such
* as this host's own. Unset means 127.0.0.1.
*
* Env var: FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS
*/
Optional<String> mockPublicAddress();
enum MockPublicAddresses {
/** No automatic public address. */
NONE,
/** An address from 203.0.113.0/24, distinct from other live instances while one is free. */
DOCUMENTATION,
/** The configured {@code mock-public-address}. */
FIXED
}
/**
* When true, instance containers are bounded to the CPU and memory limits defined for
* their instance type in the instance type catalog. When false, containers are launched
@@ -879,7 +879,7 @@ public class AutoScalingReconciler {
asg.getLaunchTemplateId(),
asg.getLaunchTemplateName(),
resolvedVersion,
null,
version.getData().effectiveAssociatePublicIpAddress(),
version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
}
@@ -914,7 +914,7 @@ public class AutoScalingReconciler {
: specification.getLaunchTemplateId(),
specification.getLaunchTemplateName(),
resolvedVersion,
null,
version.getData().effectiveAssociatePublicIpAddress(),
version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
}
}
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.services.ec2.model.Instance;
/**
* Whether an instance has an automatic public IPv4 address, decided the same way with and without
* containers; only the address itself depends on the mode: the container's reachable address, or
* where there is no container the one {@code mock-public-addresses} chooses, by default none.
*
* <p>As on AWS, an instance takes one when its launch asked for it (the subnet's
* MapPublicIpOnLaunch, or AssociatePublicIpAddress, which wins either way) on an interface the
* launch created; the launch records that answer in {@link Instance#isAssociatePublicIp()}. A stop
* or a disassociated Elastic IP releases the address, and its replacement is held back while a
* second interface is attached. An Elastic IP on the primary private address takes precedence.
*/
final class AutomaticPublicAddress {
private AutomaticPublicAddress() {
}
/**
* @param replacement true when the address would replace one a stop or a disassociated Elastic
* IP released
*/
static boolean isDue(Instance instance, boolean replacement) {
if (!instance.isAssociatePublicIp()) {
return false;
}
return !replacement || instance.getNetworkInterfaces() == null || instance.getNetworkInterfaces().size() <= 1;
}
}
@@ -528,10 +528,10 @@ public class Ec2ContainerManager {
return;
}
// Set public-facing addresses only for instances whose subnet
// opts in via MapPublicIpOnLaunch (#1984). Private-subnet
// instances have no public IP/DNS, matching real EC2.
if (instance.isAssociatePublicIp()) {
// Set public-facing addresses only for instances due one, by the rule mock instances
// follow too, or holding an Elastic IP their interface carries, which RunInstances
// recorded. Private-subnet instances have no public IP/DNS, matching real EC2.
if (instance.getPublicIpAddress() != null || AutomaticPublicAddress.isDue(instance, false)) {
exposeReachablePublicAddress(instance);
}
@@ -988,8 +988,10 @@ public class Ec2ContainerManager {
config.services().ec2().awsFaithfulPrivateIp());
}
// Docker hands out a new bridge IP on restart, so the previously reported
// public address can now point at another container entirely.
if (instance.isAssociatePublicIp() || instance.getPublicIpAddress() != null) {
// public address can now point at another container entirely. An address the
// stop left in place is an Elastic IP's; a released automatic one is replaced
// only when the shared rule allows it.
if (instance.getPublicIpAddress() != null || AutomaticPublicAddress.isDue(instance, true)) {
exposeReachablePublicAddress(instance);
}
metadataServer.registerContainer(containerIp, instanceId, instance);
@@ -1124,7 +1126,7 @@ public class Ec2ContainerManager {
}
instance.setContainerBridgeIp(containerIp);
exposeReachablePrivateAddress(instance, containerIp, config.services().ec2().awsFaithfulPrivateIp());
if (instance.isAssociatePublicIp() || instance.getPublicIpAddress() != null) {
if (instance.getPublicIpAddress() != null || AutomaticPublicAddress.isDue(instance, true)) {
exposeReachablePublicAddress(instance);
}
metadataServer.registerContainer(containerIp, instance.getInstanceId(), instance);
@@ -801,9 +801,32 @@ public class Ec2QueryHandler {
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(
p, region, userDataEncoded == null || userDataEncoded.isBlank());
boolean suppliedInterfaces = p.keySet().stream().anyMatch(name -> name.startsWith("NetworkInterface."));
if (p.getFirst("SubnetId") != null && (suppliedInterfaces
|| launchTemplateData != null && !launchTemplateData.getNetworkInterfaces().isEmpty())) {
throw new AwsException("InvalidParameterCombination",
"Network interfaces and an instance-level subnet ID may not be specified on the same request", 400);
}
if (launchTemplateData != null) {
blockDeviceMappings = LaunchTemplateData.BlockDeviceMapping.merge(
launchTemplateData.getBlockDeviceMappings(), blockDeviceMappings);
if (!suppliedInterfaces) {
// With neither request interfaces nor, after the check above, a request SubnetId,
// the template's primary interface places the launch.
LaunchTemplateData.NetworkInterface primary = launchTemplateData.primaryNetworkInterface();
if (primary != null) {
subnetId = primary.getSubnetId();
if (associatePublicIp == null) {
associatePublicIp = primary.getAssociatePublicIpAddress();
}
// An existing interface the template names is the instance's primary, as one
// named on the request would be.
if (isSet(primary.getNetworkInterfaceId())) {
networkInterfaceId = primary.getNetworkInterfaceId();
networkInterfaceDeviceIndex = 0;
}
}
}
if (launchTemplateData.getMetadataOptions() != null) {
metadataOptions = LaunchTemplateData.MetadataOptions.merge(
launchTemplateData.getMetadataOptions(), metadataOptions);
@@ -960,7 +983,7 @@ public class Ec2QueryHandler {
launch.instanceTags(),
launch.userData(),
launch.iamInstanceProfileArn(),
null,
launch.associatePublicIpAddress(),
null,
0,
launch.availabilityZone(), launch.metadataOptions(), null, launch.encodedUserData(), false,
@@ -1098,12 +1121,15 @@ public class Ec2QueryHandler {
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);
// The primary (device index 0) interface's subnet first; only when that names none does a
// fleet fall back, as it always has, to the first interface that names one.
LaunchTemplateData.NetworkInterface primary = template.primaryNetworkInterface();
String templateSubnetId = primary != null && isSet(primary.getSubnetId()) ? primary.getSubnetId()
: template.getNetworkInterfaces().stream()
.map(networkInterface -> networkInterface.getSubnetId())
.filter(Ec2QueryHandler::isSet)
.findFirst()
.orElse(null);
String subnetId = firstNonBlank(overrideSubnetId, templateSubnetId);
String templateAvailabilityZone = template.getPlacement() != null
? template.getPlacement().getAvailabilityZone() : null;
@@ -1121,6 +1147,7 @@ public class Ec2QueryHandler {
template.getUserData(),
template.getEncodedUserData(),
service.iamInstanceProfileArn(template),
template.effectiveAssociatePublicIpAddress(),
template.getMetadataOptions(),
template.effectiveSecurityGroupIds(),
new ArrayList<>(tags.values()),
@@ -1169,6 +1196,7 @@ public class Ec2QueryHandler {
private record FleetLaunch(String launchTemplateId, String launchTemplateName, String launchTemplateVersion,
String instanceType, String imageId, String subnetId, String availabilityZone,
String keyName, String userData, String encodedUserData, String iamInstanceProfileArn,
Boolean associatePublicIpAddress,
LaunchTemplateData.MetadataOptions metadataOptions,
List<String> securityGroupIds, List<Tag> instanceTags,
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings) {}
@@ -4349,7 +4377,7 @@ public class Ec2QueryHandler {
private Response handleAssociateAddress(MultivaluedMap<String, String> p, String region) {
String allocationId = p.getFirst("AllocationId");
String instanceId = p.getFirst("InstanceId");
Address addr = service.associateAddress(region, allocationId, instanceId);
Address addr = service.associateAddress(region, allocationId, instanceId, p.getFirst("PrivateIpAddress"));
XmlBuilder xml = new XmlBuilder()
.start("AssociateAddressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -162,6 +162,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private static final long ENDPOINT_ADDRESS_WINDOW = 50;
private static final String SYNTHETIC_FALLBACK_CIDR = "172.31.0.0/24";
private static final String DEFAULT_ROOT_VOLUME_TYPE = "gp3";
private static final String DOCUMENTATION_PREFIX = "203.0.113.";
private static final Set<String> VALID_VOLUME_TYPES =
Set.of("standard", "io1", "io2", "gp2", "sc1", "st1", "gp3");
/** The accounts behind the two non-self owner aliases DescribeImages accepts. */
@@ -291,6 +292,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// a concurrent allocation, which reads persisted resources to see what is taken, cannot pick
// the same address in between. Taken after imageRegistryLock where a caller holds both.
private final Object privateIpAllocationLock = new Object();
/** Host part (1-254) of the last 203.0.113.0/24 address handed out; guarded by the allocation lock. */
private int documentationHost;
/**
* Null in the hermetic unit tests, which reach the constructors that do not take it; CDI always
@@ -3650,10 +3653,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
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
// attribute is only the default when the launch does not specify it. An
// interface the caller created never takes an automatic address.
inst.setAssociatePublicIp(suppliedEni == null && (associatePublicIp != null
? associatePublicIp
: subnet != null && subnet.isMapPublicIpOnLaunch());
: subnet != null && subnet.isMapPublicIpOnLaunch()));
inst.setPrivateIpAddress(privateIp);
inst.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(privateIp, region));
inst.setKeyName(keyName);
@@ -3716,6 +3720,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
// An Elastic IP the interface kept from an earlier instance is this one's
// public address; with a container, the launch re-points it once it runs.
Address carried = primaryElasticAddress(region, inst);
if (carried != null) {
setPublicAddress(inst, carried.getPublicIp());
}
}
// Root EBS volume
@@ -4127,8 +4137,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
instances.scan(k -> true).stream()
.filter(i -> i.getRegion().equals(region) && "pending".equals(i.getState().getName()))
.forEach(i -> {
i.setState(InstanceState.running());
instances.put(key(i.getRegion(), i.getInstanceId()), i);
if (completeMockLaunch(region, i, false)) {
instances.put(key(i.getRegion(), i.getInstanceId()), i);
}
});
}
List<Instance> all = new ArrayList<>(instances.scan(k -> true));
@@ -4157,6 +4168,195 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return new ArrayList<>(reservationMap.values());
}
/**
* Moves a mock instance to running, only if no other request has moved it on since the caller
* looked: a launch must still be pending, and a start leaves a running, shutting-down or
* terminated instance alone. It shows the Elastic IP on its primary private address, or else an
* automatic address. The allocation lock comes first, as AssociateAddress takes it, so the
* Elastic IP read here is not half-written.
*
* @param restart true for StartInstances, where AWS assigns a replacement automatic address
* @return whether the instance changed
*/
private boolean completeMockLaunch(String region, Instance instance, boolean restart) {
synchronized (privateIpAllocationLock) {
synchronized (instance) {
String state = instance.getState() == null ? null : instance.getState().getName();
boolean settled = restart
? state == null || Set.of("running", "shutting-down", "terminated").contains(state)
: !"pending".equals(state);
if (settled) {
return false;
}
Address elastic = primaryElasticAddress(region, instance);
if (elastic != null) {
setPublicAddress(instance, elastic.getPublicIp());
} else {
assignAutomaticAddress(instance, restart);
}
instance.setState(InstanceState.running());
return true;
}
}
}
/**
* Gives an instance the automatic public address {@link AutomaticPublicAddress} says it is due:
* the container's reachable address, or where there is no container the one
* {@code mock-public-addresses} chooses, which by default is none.
*/
private void assignAutomaticAddress(Instance instance, boolean replacement) {
if (instance.getPublicIpAddress() != null || !AutomaticPublicAddress.isDue(instance, replacement)) {
return;
}
String address = config.services().ec2().mock() ? mockPublicAddress()
: containerManager.reachablePublicAddress(instance);
if (address != null) {
setPublicAddress(instance, address);
}
}
/** A stopped instance keeps the Elastic IP on its primary private address and loses an automatic one. */
private void releaseAutomaticAddress(String region, Instance instance) {
Address elastic = primaryElasticAddress(region, instance);
setPublicAddress(instance, elastic == null ? null : elastic.getPublicIp());
}
private static void setPublicAddress(Instance instance, String publicIp) {
instance.setPublicIpAddress(publicIp);
instance.setPublicDnsName("127.0.0.1".equals(publicIp) ? "localhost" : publicIp);
}
private static void clearPublicAddress(Instance instance) {
setPublicAddress(instance, null);
}
/** The automatic public address of a mock instance under {@code mock-public-addresses}, or null for none. */
private String mockPublicAddress() {
EmulatorConfig.Ec2ServiceConfig ec2 = config.services().ec2();
return switch (ec2.mockPublicAddresses()) {
case NONE -> null;
case FIXED -> fixedMockPublicAddress();
case DOCUMENTATION -> documentationPublicAddress();
};
}
/**
* The address every mock instance shows under {@code mock-public-addresses: fixed}, for its
* automatic address and for an Elastic IP on its primary private address alike; null under any
* other setting or with containers.
*/
private String fixedMockPublicAddress() {
EmulatorConfig.Ec2ServiceConfig ec2 = config.services().ec2();
if (!ec2.mock() || ec2.mockPublicAddresses() != EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.FIXED) {
return null;
}
return ec2.mockPublicAddress().map(String::strip).filter(address -> !address.isEmpty()).orElse("127.0.0.1");
}
/**
* The next address from 203.0.113.0/24 (TEST-NET-3, reserved for documentation and routed
* nowhere) after the last one handed out, skipping any the caller's account already holds as an
* instance's public address or an Elastic IP, so a restarted instance gets a different address
* as on AWS. Callers hold the allocation lock, so two requests do not pick the same one.
*
* @return the address, or null once all 254 are taken
*/
private String documentationPublicAddress() {
Set<String> taken = new HashSet<>();
for (Instance other : instances.scan(k -> true)) {
taken.add(other.getPublicIpAddress());
}
for (Address other : addresses.scan(k -> true)) {
taken.add(other.getPublicIp());
taken.add(other.getAllocatedPublicIp());
}
for (int i = 0; i < 254; i++) {
documentationHost = documentationHost % 254 + 1;
String candidate = DOCUMENTATION_PREFIX + documentationHost;
if (!taken.contains(candidate)) {
return candidate;
}
}
return null;
}
private static String primaryInterfaceId(Instance instance) {
return instance.getNetworkInterfaces() == null || instance.getNetworkInterfaces().isEmpty() ? null
: instance.getNetworkInterfaces().get(0).getNetworkInterfaceId();
}
/**
* The instance an associated Elastic IP serves: the one it was associated with, or, for one a
* retained interface carries, the instance that interface is now the primary interface of.
*/
private String addressHolder(String region, Address address) {
if (address.getInstanceId() != null) {
return address.getInstanceId();
}
String attached = instanceAttachedTo(region, address.getNetworkInterfaceId());
return attached == null ? null : instances.get(key(region, attached))
.filter(inst -> Objects.equals(primaryInterfaceId(inst), address.getNetworkInterfaceId()))
.map(Instance::getInstanceId)
.orElse(null);
}
/** The instance a standalone interface is attached to, or null. */
private String instanceAttachedTo(String region, String networkInterfaceId) {
return networkInterfaceId == null ? null : networkInterfaces.get(key(region, networkInterfaceId))
.map(NetworkInterface::getAttachment)
.map(NetworkInterfaceAttachment::getInstanceId)
.orElse(null);
}
/**
* The secondary private address of the instance's primary interface that {@code privateIp}
* names, or null when it names the primary address, or no address of that interface.
*/
private String secondaryPrivateIpOf(String region, Instance instance, String privateIp) {
String primaryInterfaceId = primaryInterfaceId(instance);
if (privateIp == null || primaryInterfaceId == null || privateIp.equals(instance.getPrivateIpAddress())) {
return null;
}
return networkInterfaces.get(key(region, primaryInterfaceId))
.filter(ni -> ni.getPrivateIpAddresses() != null && ni.getPrivateIpAddresses().stream()
.anyMatch(ip -> !ip.isPrimary() && privateIp.equals(ip.getPrivateIpAddress())))
.map(ni -> privateIp)
.orElse(null);
}
/** Whether {@code privateIp} is the primary private address of the instance's primary interface. */
private boolean isPrimaryPrivateIp(String region, Instance instance, String privateIp) {
if (privateIp.equals(instance.getPrivateIpAddress())) {
return true;
}
if (instance.getNetworkInterfaces() == null || instance.getNetworkInterfaces().isEmpty()) {
return false;
}
InstanceNetworkInterface primary = instance.getNetworkInterfaces().get(0);
return privateIp.equals(primary.getPrivateIpAddress())
|| networkInterfaces.get(key(region, primary.getNetworkInterfaceId()))
.map(ni -> privateIp.equals(ni.getPrivateIpAddress()))
.orElse(false);
}
/**
* The Elastic IP associated with the instance's primary private address, by instance or by
* the primary interface it was associated through, or null.
*/
private Address primaryElasticAddress(String region, Instance instance) {
String primaryInterfaceId = primaryInterfaceId(instance);
for (Address address : addresses.scan(k -> k.startsWith(region + "::"))) {
boolean onInstance = instance.getInstanceId().equals(address.getInstanceId())
|| primaryInterfaceId != null && primaryInterfaceId.equals(address.getNetworkInterfaceId());
if (onInstance && address.getAssociationId() != null
&& secondaryPrivateIpOf(region, instance, address.getPrivateIpAddress()) == null) {
return address;
}
}
return null;
}
public String platformDetailsForInstance(Instance instance) {
Image image = findImageForCapture(instance.getRegion(), instance.getImageId());
return image != null && "windows".equalsIgnoreCase(image.getPlatform())
@@ -4186,7 +4386,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
InstanceState prev = inst.getState();
if (config.services().ec2().mock()) {
inst.setState(InstanceState.terminated());
// Under the instance's lock, so a concurrent Elastic IP write sees the new state.
synchronized (inst) {
inst.setState(InstanceState.terminated());
// Termination also disassociates an Elastic IP, so nothing public is left.
clearPublicAddress(inst);
}
inst.setTerminatedAt(System.currentTimeMillis());
} else {
// Also attempt the reclaim once this container is really gone. The synchronous
@@ -4195,6 +4400,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// daemon and, without this, nothing would try again.
containerManager.terminate(inst, () ->
RequestScopes.runAs(owner, () -> reclaimCapturesPinnedBy(region, inst, terminating)));
// Termination releases the public address with a container too, under the lock a
// DescribeAddresses re-point holds, so one already under way cannot write it back.
synchronized (privateIpAllocationLock) {
writePublicAddress(inst, () -> clearPublicAddress(inst));
}
}
// Delete root volume if deleteOnTermination (matches real AWS behavior)
if (inst.getRootVolumeId() != null) {
@@ -4299,9 +4509,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
InstanceState prev = inst.getState();
if (config.services().ec2().mock()) {
inst.setState(InstanceState.stopped());
} else {
// The allocation lock first, as in completeMockLaunch. A terminated or terminating
// instance stays so: stopping it must not bring it back to be started again.
synchronized (privateIpAllocationLock) {
synchronized (inst) {
String state = inst.getState() == null ? null : inst.getState().getName();
if (!"terminated".equals(state) && !"shutting-down".equals(state)) {
inst.setState(InstanceState.stopped());
releaseAutomaticAddress(region, inst);
}
}
}
} else if (!"terminated".equals(prev.getName()) && !"shutting-down".equals(prev.getName())) {
// As in mock mode, a terminated or terminating instance stays so.
containerManager.stop(inst);
// A stop releases the automatic address with a container too; the next start
// decides on a replacement, and re-points an Elastic IP kept here.
synchronized (privateIpAllocationLock) {
writePublicAddress(inst, () -> releaseAutomaticAddress(region, inst));
}
}
instances.put(key(region, id), inst);
Map<String, String> entry = new LinkedHashMap<>();
@@ -4331,8 +4557,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
InstanceState prev = inst.getState();
if (config.services().ec2().mock()) {
inst.setState(InstanceState.running());
completeMockLaunch(region, inst, true);
} else {
if ("stopped".equals(prev.getName())) {
// Whatever stopped it, StopInstances or Floci's own shutdown, an automatic
// address does not outlive the stop: what is left for the container manager to
// re-point is then only an Elastic IP's, and otherwise it assigns one when due.
synchronized (privateIpAllocationLock) {
writePublicAddress(inst, () -> releaseAutomaticAddress(region, inst));
}
}
restoreInstanceFirewall(inst);
String accountId = callerAccountId();
containerManager.start(inst, () ->
@@ -4389,8 +4623,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.filter(i -> i.getRegion().equals(region) && "pending".equals(i.getState().getName()))
.filter(i -> instanceIds.isEmpty() || instanceIds.contains(i.getInstanceId()))
.forEach(i -> {
i.setState(InstanceState.running());
instances.put(key(i.getRegion(), i.getInstanceId()), i);
if (completeMockLaunch(region, i, false)) {
instances.put(key(i.getRegion(), i.getInstanceId()), i);
}
});
}
List<Instance> all = new ArrayList<>(instances.scan(k -> true));
@@ -10074,22 +10309,44 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return allocateAddress(region, null, null);
}
/**
* Allocates an Elastic IP from 203.0.113.0/24, in every mode: an address from a real AWS range
* would send a client that connects to it to someone else's host. Callers name an Elastic IP by
* its address, so once the account holds all 254 the allocation fails rather than repeat one.
*/
public Address allocateAddress(String region, String publicIpv4Pool, String networkBorderGroup) {
ensureDefaultResources(region);
String allocId = "eipalloc-" + randomHex(17);
String ip = "54." + (new Random().nextInt(256)) + "." + (new Random().nextInt(256)) + "." + (new Random().nextInt(256));
Address addr = new Address();
addr.setAllocationId(allocId);
addr.setPublicIp(ip);
addr.setRegion(region);
// shortcut: pool and border group are metadata until real pool allocation is modeled.
addr.setPublicIpv4Pool(publicIpv4Pool);
addr.setNetworkBorderGroup(networkBorderGroup);
addresses.put(key(region, allocId), addr);
synchronized (privateIpAllocationLock) {
String publicIp = documentationPublicAddress();
if (publicIp == null) {
throw new AwsException("AddressLimitExceeded",
"The maximum number of addresses has been reached.", 400);
}
addr.setPublicIp(publicIp);
addresses.put(key(region, allocId), addr);
}
return addr;
}
public Address associateAddress(String region, String allocationId, String instanceId) {
return associateAddress(region, allocationId, instanceId, null);
}
/**
* Associates the Elastic IP with one private address of the instance.
*
* @param privateIpAddress the instance's private address the Elastic IP is for: null or the
* primary private address, or a secondary address of the instance's primary interface;
* any other address is refused before anything changes
*/
public Address associateAddress(String region, String allocationId, String instanceId, String privateIpAddress) {
ensureDefaultResources(region);
// Under the lock createNatGateway and deleteNatGateway take, so the gateway check and the
// write cannot interleave with a gateway claiming or releasing the same allocation.
@@ -10101,10 +10358,38 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
throw new AwsException("Resource.AlreadyAssociated",
"Elastic IP address " + allocationId + " is already associated with a NAT gateway.", 400);
}
Instance target = instanceId == null ? null : instances.get(key(region, instanceId)).orElse(null);
String secondary = target == null ? null : secondaryPrivateIpOf(region, target, privateIpAddress);
// A container instance reporting its Docker bridge address no longer records the subnet
// address it launched with, which callers may still name, so there only the mock and
// AWS-faithful address modes can tell a stray address from the primary one.
boolean addressesKnown = config.services().ec2().mock() || config.services().ec2().awsFaithfulPrivateIp();
if (addressesKnown && target != null && isSet(privateIpAddress) && secondary == null
&& !isPrimaryPrivateIp(region, target, privateIpAddress)) {
throw new AwsException("InvalidParameterValue", "The private IP address " + privateIpAddress
+ " is not assigned to the primary network interface of instance " + instanceId + ".", 400);
}
if (addr.getAssociationId() != null) {
disassociateAddress(region, addr.getAssociationId());
}
// An Elastic IP already on the same private address of the instance is disassociated and
// stays allocated, as on AWS. That includes one a retained interface carried onto this
// instance as its primary.
if (target != null) {
String primaryInterfaceId = primaryInterfaceId(target);
for (Address existing : addresses.scan(k -> k.startsWith(region + "::"))) {
boolean onInstance = instanceId.equals(existing.getInstanceId())
|| primaryInterfaceId != null && primaryInterfaceId.equals(existing.getNetworkInterfaceId());
if (onInstance && existing.getAssociationId() != null
&& !allocationId.equals(existing.getAllocationId())
&& Objects.equals(secondary, secondaryPrivateIpOf(region, target, existing.getPrivateIpAddress()))) {
disassociateAddress(region, existing.getAssociationId());
}
}
}
// Kept for a secondary address; pointAddressAtInstance records the primary one otherwise.
addr.setPrivateIpAddress(secondary);
addr.setInstanceId(instanceId);
addr.setAssociationId("eipassoc-" + randomHex(17));
pointAddressAtInstance(addr, region, instanceId);
@@ -10116,7 +10401,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/**
* Re-points an associated EIP at an address that actually answers.
*
* <p>{@link #allocateAddress} can only invent a plausible {@code 54.x.x.x}, because at
* <p>{@link #allocateAddress} can only hand out an address from 203.0.113.0/24, because at
* allocation time there is no instance to be reachable at. Real AWS then keeps that address
* fixed and makes the network route it; Floci cannot, so an EIP left at its allocated value
* routes nowhere — and it is precisely the value Terraform surfaces as
@@ -10144,16 +10429,48 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (addr.getAllocatedPublicIp() == null) {
addr.setAllocatedPublicIp(addr.getPublicIp());
}
// An address on a secondary private address leaves the instance's own public address alone.
String secondary = secondaryPrivateIpOf(region, inst, addr.getPrivateIpAddress());
String reachable = containerManager.reachablePublicAddress(inst);
if (reachable != null) {
addr.setPublicIp(reachable);
// An EIP association gives the instance a public address even in a subnet that does
// not map one on launch, exactly as on AWS.
inst.setPublicIpAddress(reachable);
inst.setPublicDnsName("127.0.0.1".equals(reachable) ? "localhost" : reachable);
instances.put(key(region, instanceId), inst);
// not map one on launch, exactly as on AWS. An unchanged address is not written again.
String dnsName = "127.0.0.1".equals(reachable) ? "localhost" : reachable;
String state = inst.getState() == null ? null : inst.getState().getName();
boolean ended = "terminated".equals(state) || "shutting-down".equals(state);
if (secondary == null && !ended && (!reachable.equals(inst.getPublicIpAddress())
|| !dnsName.equals(inst.getPublicDnsName()))) {
inst.setPublicIpAddress(reachable);
inst.setPublicDnsName(dnsName);
instances.put(key(region, instanceId), inst);
}
} else if (config.services().ec2().mock() && secondary == null) {
// With no container to reach, the address on the primary private address replaces any
// automatic one: the configured address under mock-public-addresses: fixed, re-pointed
// as a container's is, otherwise the allocated one, which also undoes a re-point made
// under an earlier setting or with a container. A terminated instance keeps none,
// an unchanged address is not written again, and neither is one disassociated since
// the caller read it.
String fixed = fixedMockPublicAddress();
boolean changed = false;
synchronized (inst) {
String state = inst.getState() == null ? null : inst.getState().getName();
if (!"terminated".equals(state) && !"shutting-down".equals(state)
&& addr.getAssociationId() != null && instanceId.equals(addr.getInstanceId())) {
// The allocated address again once the setting is no longer fixed.
addr.setPublicIp(fixed != null ? fixed : addr.getAllocatedPublicIp());
if (!Objects.equals(addr.getPublicIp(), inst.getPublicIpAddress())) {
setPublicAddress(inst, addr.getPublicIp());
changed = true;
}
}
}
if (changed) {
instances.put(key(region, instanceId), inst);
}
}
addr.setPrivateIpAddress(inst.getPrivateIpAddress());
addr.setPrivateIpAddress(secondary != null ? secondary : inst.getPrivateIpAddress());
if (inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
addr.setNetworkInterfaceId(inst.getNetworkInterfaces().get(0).getNetworkInterfaceId());
}
@@ -10166,12 +10483,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
String interfaceKey = key(address.getRegion(), address.getNetworkInterfaceId());
networkInterfaces.get(interfaceKey).ifPresent(ni -> {
// The address sits on the secondary private address it names, otherwise on the primary.
boolean onSecondary = ni.getPrivateIpAddresses().stream()
.anyMatch(ip -> !ip.isPrimary() && Objects.equals(ip.getPrivateIpAddress(), address.getPrivateIpAddress()));
for (NetworkInterfacePrivateIpAddress ip : ni.getPrivateIpAddresses()) {
if (!ip.isPrimary()) {
continue;
}
boolean target = onSecondary
? !ip.isPrimary() && Objects.equals(ip.getPrivateIpAddress(), address.getPrivateIpAddress())
: ip.isPrimary();
if (address.getAssociationId() != null) {
ip.setAssociation(networkInterfaceAssociation(address, ni.getOwnerId()));
if (target) {
ip.setAssociation(networkInterfaceAssociation(address, ni.getOwnerId()));
}
} else if (ip.getAssociation() != null
&& address.getAllocationId().equals(ip.getAssociation().getAllocationId())) {
ip.setAssociation(null);
@@ -10213,6 +10535,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
+ " belongs to a NAT gateway and cannot be disassociated; delete the NAT gateway.",
400);
}
// An address a retained interface carries names no instance; the instance that
// interface is attached to now holds it.
String instanceId = addr.getInstanceId() != null ? addr.getInstanceId()
: instanceAttachedTo(region, addr.getNetworkInterfaceId());
Instance holder = instanceId == null ? null : instances.get(key(region, instanceId)).orElse(null);
// Only the address on the primary private address of the primary interface is the
// instance's public one; a retained interface may be attached at another index.
boolean onPrimary = holder != null
&& (addr.getInstanceId() != null
|| Objects.equals(addr.getNetworkInterfaceId(), primaryInterfaceId(holder)))
&& secondaryPrivateIpOf(region, holder, addr.getPrivateIpAddress()) == null;
addr.setInstanceId(null);
addr.setAssociationId(null);
updateStoredAddressAssociation(addr);
@@ -10224,12 +10557,55 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
addr.setPublicIp(addr.getAllocatedPublicIp());
}
addresses.put(key(region, addr.getAllocationId()), addr);
if (onPrimary) {
releaseElasticAddress(region, holder);
}
return;
}
}
}
}
/**
* An instance whose Elastic IP on its primary private address was just disassociated shows
* another Elastic IP left on that address, or else, while running, a new automatic address when
* {@link AutomaticPublicAddress} says it is due, as on AWS; otherwise none. A terminated
* instance is left as it is.
*/
private void releaseElasticAddress(String region, Instance inst) {
writePublicAddress(inst, () -> {
String state = inst.getState() == null ? null : inst.getState().getName();
if ("terminated".equals(state) || "shutting-down".equals(state)) {
return;
}
Address remaining = primaryElasticAddress(region, inst);
if (remaining != null) {
setPublicAddress(inst, remaining.getPublicIp());
return;
}
clearPublicAddress(inst);
if ("running".equals(state)) {
assignAutomaticAddress(inst, true);
}
});
instances.put(key(region, inst.getInstanceId()), inst);
}
/**
* Writes an instance's public address under the instance's lock where mock launches complete
* under it. With containers, the port-forward manager holds that lock across Docker calls, so the
* write goes without it rather than keep the allocation lock waiting on Docker.
*/
private void writePublicAddress(Instance instance, Runnable write) {
if (config.services().ec2().mock()) {
synchronized (instance) {
write.run();
}
} else {
write.run();
}
}
/**
* The caller's gateways, including unmigrated pre-account-isolation records when the caller is
* the default account (they belong to it); never another account's.
@@ -10314,13 +10690,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// reporting an address that no longer answers. Re-resolve BEFORE filtering: a public-ip
// or association filter must be judged against the address the response will carry, not
// the one persisted before the restart. This is also the call Terraform refreshes
// public_ip from, so it is the last chance to be right.
for (Address addr : candidates) {
if (addr.getInstanceId() != null) {
String before = addr.getPublicIp();
pointAddressAtInstance(addr, region, addr.getInstanceId());
if (!Objects.equals(before, addr.getPublicIp())) {
addresses.put(key(region, addr.getAllocationId()), addr);
// public_ip from, so it is the last chance to be right. Under the lock AssociateAddress and
// DisassociateAddress take, so a re-point never writes back an association they changed;
// a call with no associated address does not wait for it.
if (candidates.stream().anyMatch(addr -> addr.getAssociationId() != null)) {
synchronized (privateIpAllocationLock) {
for (Address addr : candidates) {
String holder = addr.getAssociationId() == null ? null : addressHolder(region, addr);
if (holder != null) {
String before = addr.getPublicIp();
pointAddressAtInstance(addr, region, holder);
if (!Objects.equals(before, addr.getPublicIp())) {
addresses.put(key(region, addr.getAllocationId()), addr);
}
}
}
}
}
@@ -26,8 +26,9 @@ public class Instance {
private String publicIpAddress;
private String privateDnsName;
private String publicDnsName;
// Whether this instance should be assigned a public IP — true when its subnet
// has MapPublicIpOnLaunch (#1984). Instances in private subnets get none.
// Whether this instance's launch asked for an automatic public IP: the launch's
// AssociatePublicIpAddress, else its subnet's MapPublicIpOnLaunch, and never for an
// interface the caller created. AutomaticPublicAddress decides from it in every mode.
private boolean associatePublicIp = false;
private String keyName;
private List<GroupIdentifier> securityGroups = new ArrayList<>();
@@ -350,6 +350,21 @@ public class LaunchTemplateData {
return fromInterfaces;
}
/** The interface a launch from this template attaches at device index 0, or null when it names none. */
@JsonIgnore
public NetworkInterface primaryNetworkInterface() {
return networkInterfaces.stream()
.filter(networkInterface -> Integer.valueOf(0).equals(networkInterface.getDeviceIndex()))
.findFirst()
.orElse(null);
}
@JsonIgnore
public Boolean effectiveAssociatePublicIpAddress() {
NetworkInterface primary = primaryNetworkInterface();
return primary == null ? null : primary.getAssociatePublicIpAddress();
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class IamInstanceProfile {