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

@@ -537,6 +537,8 @@ These services spawn Docker containers. They require access to the Docker socket
|---|---|---|
| `FLOCI_SERVICES_EC2_ENABLED` | `true` | Enable the EC2 service |
| `FLOCI_SERVICES_EC2_MOCK` | `false` | When `true`, instances are registered in state but no containers are spawned |
| `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` | `none` | Automatic public IPv4 address of a mock instance: `none`, `documentation` (from `203.0.113.0/24`) or `fixed` (`FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS`) |
| `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS` | `127.0.0.1` | Address given to every mock instance due one when `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` is `fixed`, and shown by an Elastic IP on its primary private address |
| `FLOCI_SERVICES_EC2_IMAGE_CATALOG_PATH` | (unset) | Path to a complete YAML image catalog replacing the bundled EC2 catalog; mount the file at this path when running in Docker |
| `FLOCI_SERVICES_EC2_IMDS_PORT` | `9169` | Port for the EC2 Instance Metadata Service (IMDS) endpoint |
| `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_START` | `2200` | First port in the SSH port range for EC2 instances |
+77 -6
View File
@@ -638,16 +638,31 @@ and [Elastic IP allocation](https://docs.aws.amazon.com/vpc/latest/userguide/Wor
In a nondefault VPC it returns `InvalidIPAddress.InUse` without changing the association;
call `DisassociateAddress` first, as specified by the
[EC2 API reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseAddress.html).
Associating an Elastic IP with an instance that already has one on the same private address
disassociates the earlier address, which stays allocated, as the
[AssociateAddress reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateAddress.html)
describes. That is the primary private address unless `PrivateIpAddress` names a secondary
address of the instance's primary interface, so an address on a secondary private address
leaves the primary one, and the instance's public address, in place. For an existing instance,
any other `PrivateIpAddress` fails with `InvalidParameterValue` and changes no association. The
exception is container mode without AWS-faithful private addresses: the instance reports its Docker
bridge address there, so any value means its primary address.
Deleting an interface, including deletion on instance termination, disassociates its
Elastic IP without releasing the allocation. A retained interface keeps its association
after termination; release still follows that interface's VPC rules.
An allocated Elastic IP's `54.x.x.x` address is invented and routes nowhere, so associating
it re-points it at the address the instance is actually reachable on — the same value
DescribeInstances reports. This is a deliberate deviation from AWS, where an EIP's public IP
is fixed from allocation: without it, `aws_eip.x.public_ip` hands every caller a dead address.
The allocation ID, association ID and domain are unaffected, and disassociating restores the
AllocateAddress draws Elastic IPs from `203.0.113.0/24`, a range reserved for documentation that
no host answers on, in every mode, so a client never reaches someone else's host through one. An
allocation never takes an address the account's other Elastic IPs or instances already hold; once
all 254 are taken, AllocateAddress fails with `AddressLimitExceeded`. Elastic IPs allocated by an
earlier Floci version keep their `54.x.x.x` address until released. Associating an Elastic IP with an
instance that has a container re-points it at the address the instance is actually reachable on
(the same value DescribeInstances reports), and so does associating one with a mock instance's
primary private address under `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES=fixed`, where it becomes
the configured address. This is a deliberate deviation from AWS, where an EIP's public IP is fixed
from allocation: without it, `aws_eip.x.public_ip` hands every caller a dead address. The
allocation ID, association ID and domain are unaffected, and disassociating restores the
allocated address.
### Availability Zones & Regions
@@ -746,7 +761,15 @@ Two behaviours worth calling out, because they are what Terraform reads back:
requests and `CreateFleet` launches, so `aws_launch_template.iam_instance_profile.name` converges.
- **`NetworkInterfaces` stays a `NetworkInterfaces` block.** Its `Groups` are not hoisted into
top-level `SecurityGroupIds`; on AWS the two are mutually exclusive. A launch from the template
resolves its security groups from whichever of the two is populated.
resolves its security groups from whichever of the two is populated. `RunInstances` and
`CreateFleet` launches take their subnet and `AssociatePublicIpAddress` from the interface at
device index 0; when that interface names no subnet, `CreateFleet` still uses the first
interface that does. A `RunInstances` launch whose template interface at device index 0 names
an existing `NetworkInterfaceId` launches on that interface, in its subnet, as a request
naming it would. Auto Scaling launches take only its `AssociatePublicIpAddress`, since the
group's `VPCZoneIdentifier` places them. Network interfaces, on the `RunInstances` request or
in its launch template, cannot be combined with an instance-level `SubnetId`
(`InvalidParameterCombination`); place the subnet on the primary network interface instead.
#### Launch template versions
@@ -952,6 +975,8 @@ State is reported settled rather than transitional, as elsewhere in this service
| `FLOCI_SERVICES_EC2_MAX_PUBLISHED_PORTS_PER_INSTANCE` | `20` | Max published ports per instance; also the widest single-rule span published |
| `FLOCI_SERVICES_EC2_SOCAT_IMAGE` | `alpine/socat` | Image used for the port-forwarding sidecar |
| `FLOCI_SERVICES_EC2_MOCK` | `false` | Skip Docker; instances jump directly to final state (useful for tests) |
| `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` | `none` | Automatic public IPv4 address of a mock instance: `none`, `documentation` (from `203.0.113.0/24`, which routes nowhere) or `fixed` (see below). Instances with containers always report their reachable address (see [Public IPv4 addresses](#public-ipv4-addresses)) |
| `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS` | `127.0.0.1` | The address every mock instance due one gets when `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` is `fixed`, for example this host's own address; an Elastic IP associated with its primary private address shows it too |
| `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` | `false` | Report the CFN/subnet-allocated private IP instead of the container bridge IP; routing and IMDS are unaffected |
| `FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE` | auto-detect | Whether an instance's container IP is reachable from the machines consuming Floci's API (Terraform, Terratest, your shell). When it is, DescribeInstances and DescribeAddresses report the container IP, so port 22 really is port 22; when it is not, they report `127.0.0.1` and reachability goes through the published high host ports. Detected by a throwaway TCP connect; set explicitly when Floci itself runs as a container |
| `FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP` | `true` | On startup, remove instance containers this Floci left on the daemon whose record did not survive the restart or came back terminated; stopped instances are never swept |
@@ -1123,3 +1148,49 @@ The file uses the same schema as `src/main/resources/ec2/image-catalog.yaml` and
include every image that process should expose. Missing or invalid files fail on first
catalog use; leaving the setting unset preserves the bundled catalog. Containerized
Floci needs the file mounted at the configured container path.
### Public IPv4 addresses
Whether an instance has an automatic public IPv4 address is decided by the same rule with and
without containers. Only the address itself depends on the mode. With a container, it is the
container's reachable address: its own IP when Floci's clients can route to it, otherwise
`127.0.0.1` with the DNS name `localhost`. In mock mode there is no container to reach, so
`FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES` chooses:
- `none` (the default): no automatic address. DescribeInstances shows no `ipAddress` or `dnsName`
unless an Elastic IP is associated. The launch still records whether it asked for one, so
switching the setting takes effect at the instance's next start.
- `documentation`: an address from `203.0.113.0/24`, a range reserved for documentation that no
host answers on, as Lightsail and EMR use. Instances get addresses distinct from each other and
from the account's Elastic IPs while any are free (none once all are taken), and a restart gets
a different one.
- `fixed`: `FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS` (default `127.0.0.1`, DNS name `localhost`)
for every instance, so a tool that connects to the public address reaches a host you choose. An
Elastic IP associated with the primary private address shows that address too.
For an address that reaches the instance itself, run it with a container (`FLOCI_SERVICES_EC2_MOCK`
`false`). Elastic IPs come from `203.0.113.0/24` in both modes (see [Elastic IPs](#elastic-ips)).
- An instance applies `MapPublicIpOnLaunch` unless the primary launch interface explicitly sets
`AssociatePublicIpAddress`. Direct launches, EC2 Fleet launches and Auto Scaling launch
templates preserve both `true` and `false` overrides.
- As the
[InstanceNetworkInterfaceSpecification reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceNetworkInterfaceSpecification.html)
specifies, only an interface the launch creates gets an automatic address. An instance launched
on an existing network interface has none.
- The address appears when the instance reaches `running` and remains stable while it runs. A
stop or termination releases it, and a restart assigns a new one (the same one again under
`fixed`); the private address does not change. As the
[EC2 User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#concepts-public-addresses)
describes, a released address is not replaced while a second network interface is attached.
- An Elastic IP associated with the instance's primary private address takes the place of the
automatic address and is kept across a stop. Disassociating it from a running instance assigns
a new automatic address when the rule above allows one.
- An Elastic IP that a retained interface carries becomes the public address of the next instance
launched on that interface, although DescribeAddresses does not report that instance as its
`InstanceId`.
Under `none` the rule still runs, but a mock instance has only the Elastic IP, if any, to show.
Otherwise a mock instance's address appears whether DescribeInstances or DescribeInstanceStatus
observes the launch first. A terminated mock instance has no public address, and stopping it does not bring it
back.
@@ -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 {
+5
View File
@@ -663,6 +663,11 @@ floci:
volume-block-devices: true
volume-helper-image: alpine:3.21
mock: false
# Automatic public IPv4 address of a mock instance: none, documentation (203.0.113.0/24,
# routed nowhere) or fixed (mock-public-address, default 127.0.0.1). Instances with
# containers report the container's reachable address. FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES
mock-public-addresses: none
# mock-public-address: 127.0.0.1 # FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESS
# Bound instance containers to their instance type's CPU and memory limits from the catalog.
# FLOCI_SERVICES_EC2_INSTANCE_RESOURCE_LIMITS
instance-resource-limits: true
@@ -38,6 +38,8 @@ import io.github.hectorvent.floci.services.ec2.model.InstanceNetworkInterface;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.io.Closeable;
@@ -354,6 +356,42 @@ class Ec2ContainerManagerTest {
+ "from an address nothing knows about");
}
@ParameterizedTest
@CsvSource({"1,,127.0.0.1", "2,,", "2,54.1.2.3,127.0.0.1"})
void startReplacesAReleasedAddressOnlyWhileTheInstanceHasOneInterface(int interfaces, String kept,
String expected) throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
InspectContainerResponse response = inspectResponse("172.17.0.9");
when(inspect.exec()).thenReturn(response);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, metadataServer);
// A stopped instance whose launch asked for an address: the stop released the automatic
// one, and an Elastic IP, when there is one, kept its address.
Instance instance = new Instance();
instance.setInstanceId("i-restarted");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setAssociatePublicIp(true);
instance.setPublicIpAddress(kept);
List<InstanceNetworkInterface> attached = new ArrayList<>();
for (int i = 0; i < interfaces; i++) {
attached.add(new InstanceNetworkInterface());
}
instance.setNetworkInterfaces(attached);
manager.start(instance);
verify(metadataServer, timeout(2000)).registerContainer("172.17.0.9", "i-restarted", instance);
// As on AWS, a released address is not replaced while a second interface is attached.
assertEquals(expected, instance.getPublicIpAddress());
}
@Test
void startOfAProtectedInstanceReusesTheHelperTransportAddress() throws Exception {
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
@@ -1092,6 +1130,25 @@ class Ec2ContainerManagerTest {
Set.of("10.0.1.10", "172.17.0.4", "192.0.2.10"), guest);
}
@Test
void launchPublishesTheReachableAddressForAnElasticIpTheInterfaceCarries() throws Exception {
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.11");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
// Launched on an existing interface, so not due an automatic address, but the interface
// carries an Elastic IP, which RunInstances records on the instance.
Instance instance = instance("i-carried");
instance.setAssociatePublicIp(false);
instance.setPublicIpAddress("54.9.9.9");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "127.0.0.1".equals(instance.getPublicIpAddress()), Duration.ofSeconds(2));
}
@Test
void launchWaitsForContainerBridgeIpBeforeRegisteringImds() throws Exception {
Ec2ContainerManager.containerBridgeIpAttempts = 3;
@@ -2276,15 +2276,15 @@ class Ec2IntegrationTest {
.body("DescribeAddressesResponse.addressesSet.item.size()", equalTo(1))
.body("DescribeAddressesResponse.addressesSet.item.allocationId", equalTo(targetAllocationId));
// Negative, resource-specific field filter: floci's synthesized public IPs always
// start with "54." (Ec2Service.allocateAddress), so an RFC 5737 TEST-NET-3 address is
// Negative, resource-specific field filter: floci allocates Elastic IPs only from
// 203.0.113.0/24 (Ec2Service.allocateAddress), so an RFC 5737 TEST-NET-2 address is
// guaranteed not to match anything this test (or any other) could have allocated.
given()
.formParam("Action", "DescribeAddresses")
.formParam("Filter.1.Name", "tag:Suite")
.formParam("Filter.1.Value.1", suiteTag)
.formParam("Filter.2.Name", "public-ip")
.formParam("Filter.2.Value.1", "203.0.113.99")
.formParam("Filter.2.Value.1", "198.51.100.99")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
@@ -0,0 +1,75 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import static io.github.hectorvent.floci.services.ec2.Ec2MockPublicAddressSettingIntegrationTest.INSTANCE;
import static io.github.hectorvent.floci.services.ec2.Ec2MockPublicAddressSettingIntegrationTest.describe;
import static io.github.hectorvent.floci.services.ec2.Ec2MockPublicAddressSettingIntegrationTest.launchInPublicSubnet;
import static io.github.hectorvent.floci.services.ec2.Ec2MockPublicAddressSettingIntegrationTest.publicIp;
import static io.github.hectorvent.floci.services.ec2.Ec2MockPublicAddressSettingIntegrationTest.request;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Mock instances under {@code mock-public-addresses: fixed} all show the configured address. */
@QuarkusTest
@TestProfile(Ec2MockFixedPublicAddressIntegrationTest.FixedAddress.class)
class Ec2MockFixedPublicAddressIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(724000000000L);
private static final String CONFIGURED = "192.168.65.2";
@Test
void everyMockInstanceDueAnAddressShowsTheConfiguredOne() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String first = launchInPublicSubnet(owner, "10.95");
String second = launchInPublicSubnet(owner, "10.96");
ValidatableResponse described = describe(owner, first);
assertEquals(CONFIGURED, described.extract().xmlPath().getString(INSTANCE + "ipAddress"));
assertEquals(CONFIGURED, described.extract().xmlPath().getString(INSTANCE + "dnsName"));
assertEquals(CONFIGURED, publicIp(owner, second));
// The rule still decides when the address applies: none while stopped, an Elastic IP first.
request("StopInstances", owner).formParam("InstanceId.1", first).post("/").then().statusCode(200);
assertEquals("", publicIp(owner, first));
request("StartInstances", owner).formParam("InstanceId.1", first).post("/").then().statusCode(200);
assertEquals(CONFIGURED, publicIp(owner, first));
ValidatableResponse allocated = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String allocation = allocated.extract().path("AllocateAddressResponse.allocationId");
String association = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", first).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
String elastic = allocated.extract().path("AllocateAddressResponse.publicIp");
assertTrue(elastic.matches("203\\.0\\.113\\.[0-9]+"), elastic);
// Associated, the Elastic IP stands for the configured address too, as a container's does.
assertEquals(CONFIGURED, publicIp(owner, first));
assertEquals(CONFIGURED, address(owner, allocation));
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
assertEquals(CONFIGURED, publicIp(owner, first));
assertEquals(elastic, address(owner, allocation));
request("TerminateInstances", owner).formParam("InstanceId.1", first).formParam("InstanceId.2", second)
.post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
}
private static String address(String owner, String allocation) {
return request("DescribeAddresses", owner).formParam("AllocationId.1", allocation).post("/").then()
.statusCode(200).extract().path("DescribeAddressesResponse.addressesSet.item.publicIp");
}
public static class FixedAddress implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ec2.mock-public-addresses", "fixed",
"floci.services.ec2.mock-public-address", CONFIGURED);
}
}
}
@@ -0,0 +1,670 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingReconciler;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(Ec2MockPublicAddressIntegrationTest.DocumentationAddresses.class)
class Ec2MockPublicAddressIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(722000000000L);
private static final String DOCUMENTATION_ADDRESS = "203\\.0\\.113\\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])";
private static final String REGION = "us-east-1";
private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
private static final String ADDRESS = "DescribeAddressesResponse.addressesSet.item.";
private static final String INTERFACE_ADDRESS =
"DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddressesSet.item.";
@Inject AutoScalingReconciler reconciler;
@Inject AutoScalingService groups;
@ParameterizedTest
@CsvSource({
"direct,false,true,true", "direct,true,false,false",
"direct,true,unset,true", "direct,false,unset,false",
"template,false,true,true", "template,true,false,false",
"template,true,unset,true", "template,false,unset,false",
"asg,false,true,true", "asg,true,false,false",
"asg,true,unset,true", "asg,false,unset,false",
"fleet,false,true,true", "fleet,true,false,false",
"fleet,true,unset,true", "fleet,false,unset,false"
})
void publicIpUsesTheSelectedLaunchValueAndSurvivesOnlyTheRunningLifetime(
String source, boolean subnetDefault, String override, boolean publicExpected) {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.86.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.86.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", subnetDefault).post("/").then().statusCode(200);
String image = "ami-amazonlinux2023";
String template = null;
if (!"direct".equals(source)) {
RequestSpecification create = request("CreateLaunchTemplate", owner)
.formParam("LaunchTemplateName", "public-address")
.formParam("LaunchTemplateData.ImageId", image)
.formParam("LaunchTemplateData.InstanceType", "t3.micro");
if (!"unset".equals(override)) {
create.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
.formParam("LaunchTemplateData.NetworkInterface.1.AssociatePublicIpAddress",
!Boolean.parseBoolean(override));
}
template = create.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
RequestSpecification version = request("CreateLaunchTemplateVersion", owner)
.formParam("LaunchTemplateId", template).formParam("SourceVersion", "1")
.formParam("LaunchTemplateData.InstanceType", "t3.micro");
if (!"unset".equals(override)) {
version.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
.formParam("LaunchTemplateData.NetworkInterface.1.AssociatePublicIpAddress", override);
}
if (!"asg".equals(source) && !"unset".equals(override)) {
version.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", subnet);
}
version.post("/").then().statusCode(200);
}
String instance;
if ("fleet".equals(source)) {
RequestSpecification fleet = request("CreateFleet", owner).formParam("Type", "instant")
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", template)
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "2")
.formParam("TargetCapacitySpecification.TotalTargetCapacity", 1)
.formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand");
if ("unset".equals(override)) {
fleet.formParam("LaunchTemplateConfig.1.Overrides.1.SubnetId", subnet);
}
instance = fleet.post("/").then().statusCode(200)
.extract().path("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item");
} else if ("asg".equals(source)) {
request("CreateAutoScalingGroup", owner).formParam("AutoScalingGroupName", "public-address")
.formParam("MinSize", 0).formParam("MaxSize", 1).formParam("DesiredCapacity", 1)
.formParam("VPCZoneIdentifier", subnet)
.formParam("LaunchTemplate.LaunchTemplateId", template).formParam("LaunchTemplate.Version", "2")
.post("/").then().statusCode(200);
RequestScopes.runAs(owner, () -> reconciler.reconcile(
groups.describeAutoScalingGroups(REGION, List.of("public-address")).getFirst()));
instance = request("DescribeAutoScalingGroups", owner).post("/").then().statusCode(200).extract()
.path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member.Instances.member.InstanceId");
} else {
RequestSpecification launch = request("RunInstances", owner)
.formParam("MinCount", 1).formParam("MaxCount", 1);
if (template != null) {
launch.formParam("LaunchTemplate.LaunchTemplateId", template).formParam("LaunchTemplate.Version", "2");
if ("unset".equals(override)) {
launch.formParam("SubnetId", subnet);
}
} else {
launch.formParam("ImageId", image).formParam("InstanceType", "t3.micro");
if (!"unset".equals(override)) {
launch.formParam("NetworkInterface.1.DeviceIndex", 0)
.formParam("NetworkInterface.1.SubnetId", subnet)
.formParam("NetworkInterface.1.AssociatePublicIpAddress", override);
} else {
launch.formParam("SubnetId", subnet);
}
}
instance = launch.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
}
ValidatableResponse first = describe(owner, instance).body(INSTANCE + "subnetId", equalTo(subnet));
String privateIp = first.extract().path(INSTANCE + "privateIpAddress");
String publicIp = first.extract().xmlPath().getString(INSTANCE + "ipAddress");
assertEquals(publicExpected, !publicIp.isEmpty());
if (publicExpected) {
assertTrue(publicIp.matches(DOCUMENTATION_ADDRESS));
}
assertEquals(publicIp, describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress"));
if (!"asg".equals(source)) {
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress"));
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
ValidatableResponse restarted = describe(owner, instance);
assertEquals(privateIp, restarted.extract().path(INSTANCE + "privateIpAddress"));
String replacement = restarted.extract().xmlPath().getString(INSTANCE + "ipAddress");
assertEquals(publicExpected, !replacement.isEmpty());
if (publicExpected) {
assertNotEquals(publicIp, replacement);
}
} else {
request("UpdateAutoScalingGroup", owner).formParam("AutoScalingGroupName", "public-address")
.formParam("DesiredCapacity", 0).post("/").then().statusCode(200);
request("DeleteAutoScalingGroup", owner).formParam("AutoScalingGroupName", "public-address")
.formParam("ForceDelete", true).post("/").then().statusCode(200);
}
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress"));
if (template != null) {
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template).post("/").then().statusCode(200);
}
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void networkInterfacesRejectAnInstanceLevelSubnet(boolean fromTemplate) {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
// A real subnet, so a check made only after the launch would have created something.
String subnet = request("DescribeSubnets", owner).formParam("Filter.1.Name", "default-for-az")
.formParam("Filter.1.Value.1", true).post("/").then().statusCode(200).extract().xmlPath()
.getString("DescribeSubnetsResponse.subnetSet.item[0].subnetId");
RequestSpecification launch = request("RunInstances", owner).formParam("MinCount", 1)
.formParam("MaxCount", 1).formParam("SubnetId", subnet);
String template = null;
if (fromTemplate) {
template = request("CreateLaunchTemplate", owner)
.formParam("LaunchTemplateName", "invalid-subnet-combination")
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
.formParam("LaunchTemplateData.NetworkInterface.1.AssociatePublicIpAddress", true)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
launch.formParam("LaunchTemplate.LaunchTemplateId", template);
} else {
launch.formParam("ImageId", "ami-amazonlinux2023").formParam("InstanceType", "t3.micro")
.formParam("NetworkInterface.1.DeviceIndex", 0)
.formParam("NetworkInterface.1.AssociatePublicIpAddress", true);
}
launch.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
// The refusal leaves nothing behind: no instance and no interface in the caller's account.
request("DescribeInstances", owner).post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.size()", equalTo(0));
request("DescribeNetworkInterfaces", owner).post("/").then().statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(0));
if (template != null) {
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template)
.post("/").then().statusCode(200);
}
}
@Test
void describeInstanceStatusCompletesTheLaunchWithItsAutomaticAddress() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String instance = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
request("DescribeInstanceStatus", owner).formParam("InstanceId.1", instance).post("/").then()
.statusCode(200)
.body("DescribeInstanceStatusResponse.instanceStatusSet.item.instanceState.name", equalTo("running"));
String publicIp = describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress");
assertTrue(publicIp.matches(DOCUMENTATION_ADDRESS), publicIp);
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
}
@Test
void aTerminatedInstanceStaysTerminatedWithoutAnAddress() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String instance = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
assertTrue(publicIp(owner, instance).matches(DOCUMENTATION_ADDRESS));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
// Whatever StopInstances answers, it must not bring the instance back to be started again.
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/");
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState"));
describe(owner, instance).body(INSTANCE + "instanceState.name", equalTo("terminated"));
assertEquals("", publicIp(owner, instance));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void elasticIpReplacesTheAutomaticAddressUntilItIsDisassociated(boolean automatic) {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.87.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.87.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", automatic).post("/").then().statusCode(200);
String instance = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.formParam("SubnetId", subnet).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
String launched = publicIp(owner, instance);
assertEquals(automatic, !launched.isEmpty());
ValidatableResponse allocated = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String allocation = allocated.extract().path("AllocateAddressResponse.allocationId");
String elastic = allocated.extract().path("AllocateAddressResponse.publicIp");
String association = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
assertEquals(elastic, publicIp(owner, instance));
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals(elastic, publicIp(owner, instance));
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals(elastic, publicIp(owner, instance));
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
String replacement = publicIp(owner, instance);
assertEquals(automatic, !replacement.isEmpty());
assertNotEquals(elastic, replacement);
request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200);
// A second address associated with the same instance replaces the first, which stays
// allocated, so a later DescribeAddresses cannot flip the instance back to it.
ValidatableResponse second = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String secondAllocation = second.extract().path("AllocateAddressResponse.allocationId");
String secondElastic = second.extract().path("AllocateAddressResponse.publicIp");
request("AssociateAddress", owner).formParam("AllocationId", secondAllocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200);
request("DescribeAddresses", owner).formParam("AllocationId.1", allocation).post("/").then()
.statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId.size()", equalTo(0));
assertEquals(secondElastic, publicIp(owner, instance));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", publicIp(owner, instance));
// Whatever the association answers, a terminated instance takes no public address.
String lateAssociation = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", instance).post("/").then()
.extract().path("AssociateAddressResponse.associationId");
assertEquals("", publicIp(owner, instance));
if (lateAssociation != null) {
request("DisassociateAddress", owner).formParam("AssociationId", lateAssociation).post("/").then()
.statusCode(200);
}
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", secondAllocation).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@Test
void secondAddressDisplacesTheOneARetainedInterfaceCarried() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.89.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.89.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
String eni = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)
.post("/").then().statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String first = launchOnInterface(owner, eni);
ValidatableResponse carried = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String carriedAllocation = carried.extract().path("AllocateAddressResponse.allocationId");
request("AssociateAddress", owner).formParam("AllocationId", carriedAllocation)
.formParam("InstanceId", first).post("/").then().statusCode(200);
// The interface outlives the instance and keeps the address associated with it.
request("TerminateInstances", owner).formParam("InstanceId.1", first).post("/").then().statusCode(200);
String second = launchOnInterface(owner, eni);
ValidatableResponse replacement = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String replacementAllocation = replacement.extract().path("AllocateAddressResponse.allocationId");
String replacementIp = replacement.extract().path("AllocateAddressResponse.publicIp");
String replacementAssociation = request("AssociateAddress", owner)
.formParam("AllocationId", replacementAllocation).formParam("InstanceId", second)
.post("/").then().statusCode(200).extract().path("AssociateAddressResponse.associationId");
request("DescribeAddresses", owner).formParam("AllocationId.1", carriedAllocation).post("/").then()
.statusCode(200)
.body("DescribeAddressesResponse.addressesSet.item.associationId.size()", equalTo(0));
assertEquals(replacementIp, publicIp(owner, second));
request("TerminateInstances", owner).formParam("InstanceId.1", second).post("/").then().statusCode(200);
request("DisassociateAddress", owner).formParam("AssociationId", replacementAssociation).post("/").then()
.statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", replacementAllocation).post("/").then()
.statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", carriedAllocation).post("/").then().statusCode(200);
request("DeleteNetworkInterface", owner).formParam("NetworkInterfaceId", eni).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@Test
void elasticIpOnASecondaryAddressLeavesThePrimaryAddressAndTheInstanceAlone() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.90.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.90.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
String eni = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)
.formParam("PrivateIpAddress", "10.90.1.10")
.formParam("PrivateIpAddresses.1.PrivateIpAddress", "10.90.1.11")
.post("/").then().statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String instance = launchOnInterface(owner, eni);
ValidatableResponse primary = allocateAddress(owner);
String primaryAllocation = primary.extract().path("AllocateAddressResponse.allocationId");
String primaryIp = primary.extract().path("AllocateAddressResponse.publicIp");
ValidatableResponse secondary = allocateAddress(owner);
String secondaryAllocation = secondary.extract().path("AllocateAddressResponse.allocationId");
String secondaryIp = secondary.extract().path("AllocateAddressResponse.publicIp");
request("AssociateAddress", owner).formParam("AllocationId", primaryAllocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200);
request("AssociateAddress", owner).formParam("AllocationId", secondaryAllocation)
.formParam("InstanceId", instance).formParam("PrivateIpAddress", "10.90.1.11")
.post("/").then().statusCode(200);
// Each address stays on its own private address, and the instance shows the primary's.
address(owner, primaryAllocation).body(ADDRESS + "instanceId", equalTo(instance))
.body(ADDRESS + "privateIpAddress", equalTo("10.90.1.10"));
address(owner, secondaryAllocation).body(ADDRESS + "instanceId", equalTo(instance))
.body(ADDRESS + "privateIpAddress", equalTo("10.90.1.11"));
request("DescribeNetworkInterfaces", owner).formParam("NetworkInterfaceId.1", eni).post("/").then()
.statusCode(200)
.body(INTERFACE_ADDRESS + "find { it.privateIpAddress == '10.90.1.10' }.association.publicIp",
equalTo(primaryIp))
.body(INTERFACE_ADDRESS + "find { it.privateIpAddress == '10.90.1.11' }.association.publicIp",
equalTo(secondaryIp));
assertEquals(primaryIp, publicIp(owner, instance));
// A new address for the primary private address displaces only the address already there.
ValidatableResponse replacement = allocateAddress(owner);
String replacementAllocation = replacement.extract().path("AllocateAddressResponse.allocationId");
String replacementIp = replacement.extract().path("AllocateAddressResponse.publicIp");
request("AssociateAddress", owner).formParam("AllocationId", replacementAllocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200);
address(owner, primaryAllocation).body(ADDRESS + "associationId.size()", equalTo(0));
address(owner, secondaryAllocation).body(ADDRESS + "privateIpAddress", equalTo("10.90.1.11"));
assertEquals(replacementIp, publicIp(owner, instance));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
// The retained interface keeps its associations, which must go before the release.
for (String allocation : List.of(secondaryAllocation, replacementAllocation)) {
String association = address(owner, allocation).extract().path(ADDRESS + "associationId");
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
}
for (String allocation : List.of(primaryAllocation, secondaryAllocation, replacementAllocation)) {
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
}
request("DeleteNetworkInterface", owner).formParam("NetworkInterfaceId", eni).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@Test
void anExistingInterfaceTakesNoAutomaticAddressButKeepsTheElasticIpItCarries() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.91.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.91.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", true).post("/").then().statusCode(200);
String eni = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)
.post("/").then().statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
// AWS assigns an automatic public address only to an interface the launch creates.
String first = launchOnInterface(owner, eni);
assertEquals("", publicIp(owner, first));
ValidatableResponse carried = allocateAddress(owner);
String allocation = carried.extract().path("AllocateAddressResponse.allocationId");
String elastic = carried.extract().path("AllocateAddressResponse.publicIp");
String association = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", first).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
assertEquals(elastic, publicIp(owner, first));
request("TerminateInstances", owner).formParam("InstanceId.1", first).post("/").then().statusCode(200);
// The interface outlives the instance and brings its address to the next one launched on it.
String second = launchOnInterface(owner, eni);
assertEquals(elastic, publicIp(owner, second));
address(owner, allocation).body(ADDRESS + "associationId", equalTo(association))
.body(ADDRESS + "networkInterfaceId", equalTo(eni));
request("StopInstances", owner).formParam("InstanceId.1", second).post("/").then().statusCode(200);
assertEquals(elastic, publicIp(owner, second));
request("StartInstances", owner).formParam("InstanceId.1", second).post("/").then().statusCode(200);
assertEquals(elastic, publicIp(owner, second));
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
assertEquals("", publicIp(owner, second));
request("TerminateInstances", owner).formParam("InstanceId.1", second).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
request("DeleteNetworkInterface", owner).formParam("NetworkInterfaceId", eni).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@Test
void aTemplateInterfaceNamingAnExistingInterfaceLaunchesOnIt() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.93.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.93.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", true).post("/").then().statusCode(200);
String eni = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)
.post("/").then().statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String template = request("CreateLaunchTemplate", owner).formParam("LaunchTemplateName", "existing-interface")
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 0)
.formParam("LaunchTemplateData.NetworkInterface.1.NetworkInterfaceId", eni)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
String instance = request("RunInstances", owner).formParam("MinCount", 1).formParam("MaxCount", 1)
.formParam("LaunchTemplate.LaunchTemplateId", template).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
// The interface the template names becomes the primary, so the launch lands in its subnet
// and, being on an existing interface, takes no automatic address.
describe(owner, instance).body(INSTANCE + "networkInterfaceSet.item.networkInterfaceId", equalTo(eni))
.body(INSTANCE + "subnetId", equalTo(subnet));
assertEquals("", publicIp(owner, instance));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template).post("/").then().statusCode(200);
request("DeleteNetworkInterface", owner).formParam("NetworkInterfaceId", eni).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
@Test
void anElasticIpForAnUnknownPrivateAddressIsRefusedWithoutDisplacingAnything() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
ValidatableResponse launched = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.post("/").then().statusCode(200);
String instance = launched.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
String privateIp = launched.extract().path("RunInstancesResponse.instancesSet.item.privateIpAddress");
ValidatableResponse primary = allocateAddress(owner);
String primaryAllocation = primary.extract().path("AllocateAddressResponse.allocationId");
String primaryIp = primary.extract().path("AllocateAddressResponse.publicIp");
String primaryAssociation = request("AssociateAddress", owner).formParam("AllocationId", primaryAllocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
ValidatableResponse other = allocateAddress(owner);
String otherAllocation = other.extract().path("AllocateAddressResponse.allocationId");
String otherIp = other.extract().path("AllocateAddressResponse.publicIp");
request("AssociateAddress", owner).formParam("AllocationId", otherAllocation)
.formParam("InstanceId", instance).formParam("PrivateIpAddress", "10.99.99.99")
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
address(owner, primaryAllocation).body(ADDRESS + "associationId", equalTo(primaryAssociation));
address(owner, otherAllocation).body(ADDRESS + "associationId.size()", equalTo(0));
assertEquals(primaryIp, publicIp(owner, instance));
// Naming the primary private address itself is the same as naming none.
request("AssociateAddress", owner).formParam("AllocationId", otherAllocation)
.formParam("InstanceId", instance).formParam("PrivateIpAddress", privateIp)
.post("/").then().statusCode(200);
address(owner, primaryAllocation).body(ADDRESS + "associationId.size()", equalTo(0));
assertEquals(otherIp, publicIp(owner, instance));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", primaryAllocation).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", otherAllocation).post("/").then().statusCode(200);
}
@Test
void aSecondInterfaceWithholdsTheReplacementAutomaticAddress() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.92.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.92.1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", true).post("/").then().statusCode(200);
String instance = request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.formParam("SubnetId", subnet).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
assertTrue(publicIp(owner, instance).matches(DOCUMENTATION_ADDRESS));
// AssociateAddress by InstanceId needs exactly one interface, so the address goes on first.
ValidatableResponse allocated = allocateAddress(owner);
String allocation = allocated.extract().path("AllocateAddressResponse.allocationId");
String elastic = allocated.extract().path("AllocateAddressResponse.publicIp");
String association = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
assertEquals(elastic, publicIp(owner, instance));
String extra = request("CreateNetworkInterface", owner).formParam("SubnetId", subnet)
.post("/").then().statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String attachment = request("AttachNetworkInterface", owner).formParam("NetworkInterfaceId", extra)
.formParam("InstanceId", instance).formParam("DeviceIndex", 1)
.post("/").then().statusCode(200).extract().path("AttachNetworkInterfaceResponse.attachmentId");
// A released public address is not replaced while a second interface is attached.
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
assertEquals("", publicIp(owner, instance));
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", publicIp(owner, instance));
// With the second interface gone, starting the still-running instance changes nothing, and
// the next real start assigns an address again.
request("DetachNetworkInterface", owner).formParam("AttachmentId", attachment).post("/").then()
.statusCode(200);
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", publicIp(owner, instance));
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertTrue(publicIp(owner, instance).matches(DOCUMENTATION_ADDRESS));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
request("DeleteNetworkInterface", owner).formParam("NetworkInterfaceId", extra).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", subnet).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
private ValidatableResponse allocateAddress(String owner) {
return request("AllocateAddress", owner).formParam("Domain", "vpc").post("/").then().statusCode(200);
}
private ValidatableResponse address(String owner, String allocation) {
return request("DescribeAddresses", owner).formParam("AllocationId.1", allocation).post("/").then()
.statusCode(200);
}
private String launchOnInterface(String owner, String networkInterface) {
return request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.formParam("NetworkInterface.1.DeviceIndex", 0)
.formParam("NetworkInterface.1.NetworkInterfaceId", networkInterface)
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
}
@Test
void fleetLaunchesIntoThePrimaryInterfaceSubnetWhateverTheInterfaceOrder() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String vpc = request("CreateVpc", owner).formParam("CidrBlock", "10.88.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String secondary = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.88.1.0/24").formParam("AvailabilityZone", REGION + "b")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
String primary = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", "10.88.2.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
String template = request("CreateLaunchTemplate", owner).formParam("LaunchTemplateName", "fleet-primary")
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", 1)
.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", secondary)
.formParam("LaunchTemplateData.NetworkInterface.2.DeviceIndex", 0)
.formParam("LaunchTemplateData.NetworkInterface.2.SubnetId", primary)
.formParam("LaunchTemplateData.NetworkInterface.2.AssociatePublicIpAddress", true)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
String instance = request("CreateFleet", owner).formParam("Type", "instant")
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", template)
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
.formParam("TargetCapacitySpecification.TotalTargetCapacity", 1)
.formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
.post("/").then().statusCode(200)
.extract().path("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item");
describe(owner, instance).body(INSTANCE + "subnetId", equalTo(primary))
.body(INSTANCE + "placement.availabilityZone", equalTo(REGION + "a"));
assertTrue(publicIp(owner, instance).matches(DOCUMENTATION_ADDRESS));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("DeleteLaunchTemplate", owner).formParam("LaunchTemplateId", template).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", primary).post("/").then().statusCode(200);
request("DeleteSubnet", owner).formParam("SubnetId", secondary).post("/").then().statusCode(200);
request("DeleteVpc", owner).formParam("VpcId", vpc).post("/").then().statusCode(200);
}
private String publicIp(String owner, String instance) {
return describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress");
}
private ValidatableResponse describe(String owner, String instance) {
return request("DescribeInstances", owner).formParam("InstanceId.1", instance)
.post("/").then().statusCode(200);
}
private RequestSpecification request(String action, String owner) {
String service = action.contains("AutoScaling") ? "autoscaling" : "ec2";
return given().formParam("Action", action).header("Authorization", EnforcementFixtures.auth(owner, service));
}
/** Mock instances due an automatic address take one from 203.0.113.0/24. */
public static class DocumentationAddresses implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ec2.mock-public-addresses", "documentation");
}
}
}
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicLong;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Mock instances under the default {@code mock-public-addresses: none}: a launch that asks for an
* automatic public address gets none, while Elastic IPs work as before. The {@code fixed} setting
* is covered by {@link Ec2MockFixedPublicAddressIntegrationTest}, {@code documentation} by
* {@link Ec2MockPublicAddressIntegrationTest}.
*/
@QuarkusTest
class Ec2MockPublicAddressSettingIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(723000000000L);
static final String REGION = "us-east-1";
static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
@Test
void byDefaultAMockInstanceGetsNoAutomaticAddressButKeepsElasticIps() {
String owner = Long.toString(ACCOUNTS.incrementAndGet());
String instance = launchInPublicSubnet(owner, "10.94");
ValidatableResponse described = describe(owner, instance);
assertEquals("running", described.extract().path(INSTANCE + "instanceState.name"));
assertEquals("", described.extract().xmlPath().getString(INSTANCE + "ipAddress"));
assertEquals("", described.extract().xmlPath().getString(INSTANCE + "dnsName"));
ValidatableResponse allocated = request("AllocateAddress", owner).formParam("Domain", "vpc")
.post("/").then().statusCode(200);
String allocation = allocated.extract().path("AllocateAddressResponse.allocationId");
String elastic = allocated.extract().path("AllocateAddressResponse.publicIp");
assertTrue(elastic.matches("203\\.0\\.113\\.[0-9]+"), elastic);
String association = request("AssociateAddress", owner).formParam("AllocationId", allocation)
.formParam("InstanceId", instance).post("/").then().statusCode(200)
.extract().path("AssociateAddressResponse.associationId");
assertEquals(elastic, publicIp(owner, instance));
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals(elastic, publicIp(owner, instance));
// Disassociating leaves the instance without an address rather than inventing one.
request("DisassociateAddress", owner).formParam("AssociationId", association).post("/").then()
.statusCode(200);
assertEquals("", publicIp(owner, instance));
request("StopInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("StartInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
assertEquals("", publicIp(owner, instance));
request("TerminateInstances", owner).formParam("InstanceId.1", instance).post("/").then().statusCode(200);
request("ReleaseAddress", owner).formParam("AllocationId", allocation).post("/").then().statusCode(200);
}
/** Launches an instance into a new subnet whose MapPublicIpOnLaunch is on. */
static String launchInPublicSubnet(String owner, String prefix) {
String vpc = request("CreateVpc", owner).formParam("CidrBlock", prefix + ".0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
String subnet = request("CreateSubnet", owner).formParam("VpcId", vpc)
.formParam("CidrBlock", prefix + ".1.0/24").formParam("AvailabilityZone", REGION + "a")
.post("/").then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId");
request("ModifySubnetAttribute", owner).formParam("SubnetId", subnet)
.formParam("MapPublicIpOnLaunch.Value", true).post("/").then().statusCode(200);
return request("RunInstances", owner).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("MinCount", 1).formParam("MaxCount", 1)
.formParam("SubnetId", subnet).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
}
static String publicIp(String owner, String instance) {
return describe(owner, instance).extract().xmlPath().getString(INSTANCE + "ipAddress");
}
static ValidatableResponse describe(String owner, String instance) {
return request("DescribeInstances", owner).formParam("InstanceId.1", instance)
.post("/").then().statusCode(200);
}
static RequestSpecification request(String action, String owner) {
return given().formParam("Action", action).header("Authorization", EnforcementFixtures.auth(owner, "ec2"));
}
}
@@ -191,6 +191,7 @@ class Ec2OwnerAttributionTest {
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
return new Ec2Service(config, null, mock(Ec2PortForwardManager.class),
@@ -127,6 +127,7 @@ class Ec2PublicIpOnLaunchTest {
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2Cfg);
when(ec2Cfg.mock()).thenReturn(true);
when(ec2Cfg.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
// A mock container manager makes launch() a no-op — the associatePublicIp
// flag is set on the instance BEFORE launch, so no Docker is needed here.
@@ -280,6 +280,7 @@ class Ec2ServiceConcurrencyTest {
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
return config;
}
@@ -452,6 +452,7 @@ class Ec2ServicePersistenceTest {
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
return new Ec2Service(config, null, mock(Ec2PortForwardManager.class),
new AmiImageResolver(imageCatalog), imageCatalog,
@@ -65,6 +65,7 @@ import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
@@ -81,6 +82,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -1248,6 +1250,538 @@ class Ec2ServiceTest {
assertTrue(service.describeAddresses(region, List.of(address.getAllocationId()), Map.of()).isEmpty());
}
@Test
void elasticIpOnASecondaryAddressLeavesAReachableInstancesPublicAddressAlone() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(any())).thenReturn("192.0.2.10");
Ec2Service service = new Ec2Service(mockConfig(true), containerManager,
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String region = "us-east-1";
String subnetId = service.createSubnet(region, service.createVpc(region, "10.238.0.0/24", false).getVpcId(),
"10.238.0.0/26", region + "a").getSubnetId();
NetworkInterface eni = service.createNetworkInterface(region, subnetId, null, "10.238.0.10",
List.of("10.238.0.11"), List.of(), List.of());
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null,
null, eni.getNetworkInterfaceId(), 0).getInstances().getFirst();
Address secondary = service.allocateAddress(region);
service.associateAddress(region, secondary.getAllocationId(), instance.getInstanceId(), "10.238.0.11");
assertEquals("10.238.0.11", secondary.getPrivateIpAddress());
assertNull(instance.getPublicIpAddress());
Address primary = service.allocateAddress(region);
service.associateAddress(region, primary.getAllocationId(), instance.getInstanceId());
assertEquals("10.238.0.10", primary.getPrivateIpAddress());
assertEquals("192.0.2.10", instance.getPublicIpAddress());
assertNotNull(secondary.getAssociationId());
assertEquals("10.238.0.11", service.describeAddresses(region, List.of(secondary.getAllocationId()), Map.of())
.getFirst().getPrivateIpAddress());
}
@Test
void aContainerInstanceReportingItsBridgeAddressStillTakesAnElasticIpForItsLaunchAddress() {
EmulatorConfig config = mockConfig(true);
Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String region = "us-east-1";
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), null, null, List.of(), null, null, null).getInstances().getFirst();
String launchAddress = instance.getPrivateIpAddress();
// Container mode without AWS-faithful private addresses: the container manager replaces the
// reported address with the Docker bridge one once the container runs.
when(config.services().ec2().mock()).thenReturn(false);
instance.setPrivateIpAddress("172.17.0.5");
instance.getNetworkInterfaces().getFirst().setPrivateIpAddress("172.17.0.5");
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), instance.getInstanceId(), launchAddress);
assertNotNull(address.getAssociationId());
assertEquals(instance.getInstanceId(), address.getInstanceId());
}
@Test
void containerModeStopReleasesTheAutomaticAddressButKeepsAnElasticIp() {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.239.0.0/24");
Instance automatic = runningContainerInstance(service, region, subnetId, null);
Instance elastic = runningContainerInstance(service, region, subnetId, null);
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), elastic.getInstanceId());
service.stopInstances(region, List.of(automatic.getInstanceId(), elastic.getInstanceId()));
assertNull(automatic.getPublicIpAddress());
assertNull(automatic.getPublicDnsName());
assertEquals("127.0.0.1", elastic.getPublicIpAddress());
}
@Test
void containerModeTerminationLeavesNoPublicAddress() {
Ec2Service service = containerModeService();
String region = "us-east-1";
Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.240.0.0/24"), null);
service.terminateInstances(region, List.of(instance.getInstanceId()));
assertNull(instance.getPublicIpAddress());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void anInstanceLaunchedOnAnExistingInterfaceIsNotDueAnAutomaticAddressInEitherMode(boolean mockMode) {
Ec2Service service = mockMode ? mockModeService() : containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.241.0.0/24");
NetworkInterface eni = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(), List.of());
Instance onExisting = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null,
null, eni.getNetworkInterfaceId(), 0).getInstances().getFirst();
Instance onNew = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null, null).getInstances().getFirst();
assertFalse(onExisting.isAssociatePublicIp());
assertTrue(onNew.isAssociatePublicIp());
}
@ParameterizedTest
@CsvSource({"true,1,127.0.0.1", "true,2,", "false,1,"})
void containerModeDisassociationGivesBackOnlyAnAddressTheRulesAllow(boolean publicSubnet, int interfaces,
String expected) {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet
? publicSubnet(service, region, "10.242.0.0/24")
: service.createSubnet(region, service.createVpc(region, "10.243.0.0/24", false).getVpcId(),
"10.243.0.0/26", region + "a").getSubnetId();
Instance instance = runningContainerInstance(service, region, subnetId, null);
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), instance.getInstanceId());
assertEquals("127.0.0.1", instance.getPublicIpAddress());
if (interfaces > 1) {
NetworkInterface extra = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(),
List.of());
service.attachNetworkInterface(region, extra.getNetworkInterfaceId(), instance.getInstanceId(), 1);
}
service.disassociateAddress(region, address.getAssociationId());
assertEquals(expected, instance.getPublicIpAddress());
}
@Test
void containerModeDisassociatingASecondaryAddressLeavesThePublicAddressAlone() {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.244.0.0/24");
NetworkInterface eni = service.createNetworkInterface(region, subnetId, null, "10.244.0.10",
List.of("10.244.0.11"), List.of(), List.of());
Instance instance = runningContainerInstance(service, region, subnetId, eni.getNetworkInterfaceId());
Address primary = service.allocateAddress(region);
service.associateAddress(region, primary.getAllocationId(), instance.getInstanceId());
Address secondary = service.allocateAddress(region);
service.associateAddress(region, secondary.getAllocationId(), instance.getInstanceId(), "10.244.0.11");
// With a container, both addresses point at the one reachable address.
assertEquals("127.0.0.1", instance.getPublicIpAddress());
service.disassociateAddress(region, secondary.getAssociationId());
assertEquals("127.0.0.1", instance.getPublicIpAddress());
assertNotNull(primary.getAssociationId());
}
@Test
void containerModeDisassociationReleasesAnAddressARestartMoved() {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = service.createSubnet(region, service.createVpc(region, "10.245.0.0/24", false).getVpcId(),
"10.245.0.0/26", region + "a").getSubnetId();
Instance instance = runningContainerInstance(service, region, subnetId, null);
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), instance.getInstanceId());
// A restart gives the container a new address, which the start publishes for the Elastic IP.
instance.setPublicIpAddress("172.17.0.9");
service.disassociateAddress(region, address.getAssociationId());
assertNull(instance.getPublicIpAddress(), "nothing backs a public address once the Elastic IP is gone");
}
@ParameterizedTest
@CsvSource({"false,", "true,127.0.0.1"})
void containerModeStartDecidesAfreshWhateverStoppedTheInstance(boolean elasticIp, String kept) {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.246.0.0/24");
Instance instance = runningContainerInstance(service, region, subnetId, null);
if (elasticIp) {
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), instance.getInstanceId());
}
// Stopped without StopInstances, as Floci's shutdown or a failed firewall restore does, so
// the automatic address was never released.
instance.setState(InstanceState.stopped());
instance.setPublicIpAddress("172.17.0.9");
service.startInstances(region, List.of(instance.getInstanceId()));
// The container manager then re-points what is left, which is only an Elastic IP's.
assertEquals(kept, instance.getPublicIpAddress());
}
@Test
void disassociatingAnAddressOnASecondaryInterfaceLeavesThePrimaryPublicAddressAlone() {
Ec2Service service = mockModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.247.0.0/24");
NetworkInterface retained = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(),
List.of());
Instance first = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null,
null, retained.getNetworkInterfaceId(), 0).getInstances().getFirst();
Address carried = service.allocateAddress(region);
service.associateAddress(region, carried.getAllocationId(), first.getInstanceId());
// The interface outlives the instance and keeps the address.
service.terminateInstances(region, List.of(first.getInstanceId()));
Instance second = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null, null).getInstances().getFirst();
service.describeInstances(region, List.of(second.getInstanceId()), Map.of());
String automatic = second.getPublicIpAddress();
assertNotNull(automatic);
service.attachNetworkInterface(region, retained.getNetworkInterfaceId(), second.getInstanceId(), 1);
String association = carried.getAssociationId();
assertNotNull(association, "the retained interface keeps the address associated");
service.disassociateAddress(region, association);
assertNull(carried.getAssociationId());
assertEquals(automatic, second.getPublicIpAddress());
}
@Test
void mockInstancesGetNoAutomaticAddressUnlessConfiguredButStillRecordTheLaunchIntent() {
EmulatorConfig config = mockConfig(true);
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
Ec2Service service = mockModeService(config);
String region = "us-east-1";
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), publicSubnet(service, region, "10.243.0.0/24"), null, List.of(), null, null,
null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
assertEquals("running", instance.getState().getName());
assertNull(instance.getPublicIpAddress());
assertNull(instance.getPublicDnsName());
assertTrue(instance.isAssociatePublicIp(), "the launch still records that it asked for an address");
// An Elastic IP still takes the primary private address, and leaves nothing behind.
Address elastic = service.allocateAddress(region);
service.associateAddress(region, elastic.getAllocationId(), instance.getInstanceId());
assertEquals(elastic.getPublicIp(), instance.getPublicIpAddress());
service.disassociateAddress(region, elastic.getAssociationId());
assertNull(instance.getPublicIpAddress());
// The recorded intent is what a later start decides from.
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.DOCUMENTATION);
service.stopInstances(region, List.of(instance.getInstanceId()));
service.startInstances(region, List.of(instance.getInstanceId()));
assertTrue(instance.getPublicIpAddress().startsWith("203.0.113."), instance.getPublicIpAddress());
}
@Test
void documentationAddressesAreDistinctAndChangeOnRestart() {
Ec2Service service = mockModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.242.0.0/24");
List<Instance> launched = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
3, 3, null, List.of(), subnetId, null, List.of(), null, null, null).getInstances();
service.describeInstances(region, launched.stream().map(Instance::getInstanceId).toList(), Map.of());
Set<String> addresses = new HashSet<>();
for (Instance instance : launched) {
assertTrue(instance.getPublicIpAddress().matches("203\\.0\\.113\\.[0-9]+"), instance.getPublicIpAddress());
assertEquals(instance.getPublicIpAddress(), instance.getPublicDnsName());
addresses.add(instance.getPublicIpAddress());
}
assertEquals(3, addresses.size());
Instance first = launched.getFirst();
String before = first.getPublicIpAddress();
service.stopInstances(region, List.of(first.getInstanceId()));
service.startInstances(region, List.of(first.getInstanceId()));
assertNotEquals(before, first.getPublicIpAddress());
assertFalse(launched.subList(1, 3).stream()
.anyMatch(other -> other.getPublicIpAddress().equals(first.getPublicIpAddress())));
}
@ParameterizedTest
@CsvSource(value = {"192.168.65.2,192.168.65.2,192.168.65.2", "' 192.168.65.3 ',192.168.65.3,192.168.65.3",
"' ',127.0.0.1,localhost", "NULL,127.0.0.1,localhost"}, nullValues = "NULL")
void fixedMockAddressesUseTheConfiguredAddress(String configured, String expected, String dnsName) {
EmulatorConfig config = mockConfig(true);
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.FIXED);
when(config.services().ec2().mockPublicAddress()).thenReturn(Optional.ofNullable(configured));
Ec2Service service = mockModeService(config);
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.241.0.0/24");
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null, null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
assertEquals(expected, instance.getPublicIpAddress());
assertEquals(dnsName, instance.getPublicDnsName());
// The rule still decides: released on stop, back on start.
service.stopInstances(region, List.of(instance.getInstanceId()));
assertNull(instance.getPublicIpAddress());
service.startInstances(region, List.of(instance.getInstanceId()));
assertEquals(expected, instance.getPublicIpAddress());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void elasticIpsComeFromTheDocumentationRangeApartFromEveryOtherAddress(boolean mockMode) {
Ec2Service service = mockMode ? mockModeService() : containerModeService();
String region = "us-east-1";
Set<String> seen = new HashSet<>();
if (mockMode) {
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), publicSubnet(service, region, "10.240.0.0/24"), null, List.of(), null,
null, null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
seen.add(instance.getPublicIpAddress());
}
for (int i = 0; i < 3; i++) {
String address = service.allocateAddress(region).getPublicIp();
assertTrue(address.matches("203\\.0\\.113\\.[0-9]+"), address);
assertTrue(seen.add(address), "a second holder of " + address);
}
}
@Test
void allocationFailsOnceEveryDocumentationAddressIsTaken() {
Ec2Service service = mockModeService();
String region = "us-east-1";
List<Address> allocated = new ArrayList<>();
for (int i = 0; i < 254; i++) {
allocated.add(service.allocateAddress(region));
}
assertEquals(254, allocated.stream().map(Address::getPublicIp).distinct().count());
AwsException full = assertThrows(AwsException.class, () -> service.allocateAddress(region));
assertEquals("AddressLimitExceeded", full.getErrorCode());
service.releaseAddress(region, allocated.getFirst().getAllocationId());
assertEquals(allocated.getFirst().getPublicIp(), service.allocateAddress(region).getPublicIp());
}
@Test
void underFixedAnElasticIpShowsTheConfiguredAddressUntilItIsDisassociated() {
EmulatorConfig config = mockConfig(true);
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.FIXED);
when(config.services().ec2().mockPublicAddress()).thenReturn(Optional.of("192.168.65.2"));
Ec2Service service = mockModeService(config);
String region = "us-east-1";
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), privateSubnet(service, region, "10.239.0.0/24"), null, List.of(), null, null,
null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
assertNull(instance.getPublicIpAddress());
Address elastic = service.allocateAddress(region);
String allocated = elastic.getPublicIp();
assertTrue(allocated.startsWith("203.0.113."), allocated);
service.associateAddress(region, elastic.getAllocationId(), instance.getInstanceId());
assertEquals("192.168.65.2", instance.getPublicIpAddress());
assertEquals("192.168.65.2", service.describeAddresses(region, List.of(elastic.getAllocationId()), Map.of())
.getFirst().getPublicIp());
service.disassociateAddress(region, elastic.getAssociationId());
assertEquals(allocated, service.describeAddresses(region, List.of(elastic.getAllocationId()), Map.of())
.getFirst().getPublicIp());
assertNull(instance.getPublicIpAddress(), "the launch asked for no automatic address");
}
@Test
void anElasticIpReturnsToItsAllocatedAddressOnceTheSettingIsNoLongerFixed() {
EmulatorConfig config = mockConfig(true);
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.FIXED);
Ec2Service service = mockModeService(config);
String region = "us-east-1";
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), privateSubnet(service, region, "10.238.0.0/24"), null, List.of(), null, null,
null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
Address elastic = service.allocateAddress(region);
String allocated = elastic.getPublicIp();
service.associateAddress(region, elastic.getAllocationId(), instance.getInstanceId());
assertEquals("127.0.0.1", instance.getPublicIpAddress());
// As after a restart under another setting: the next read shows the allocated address again.
when(config.services().ec2().mockPublicAddresses())
.thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
assertEquals(allocated, service.describeAddresses(region, List.of(elastic.getAllocationId()), Map.of())
.getFirst().getPublicIp());
assertEquals(allocated, instance.getPublicIpAddress());
}
@Test
void anInstanceAddressIsNeverAllocatedAsAnElasticIp() {
Ec2Service service = mockModeService();
String region = "us-east-1";
for (int i = 0; i < 253; i++) {
service.allocateAddress(region);
}
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), publicSubnet(service, region, "10.237.0.0/24"), null, List.of(), null, null,
null).getInstances().getFirst();
service.describeInstances(region, List.of(instance.getInstanceId()), Map.of());
assertEquals("203.0.113.254", instance.getPublicIpAddress());
AwsException full = assertThrows(AwsException.class, () -> service.allocateAddress(region));
assertEquals("AddressLimitExceeded", full.getErrorCode());
}
private static String privateSubnet(Ec2Service service, String region, String cidr) {
return service.createSubnet(region, service.createVpc(region, cidr, false).getVpcId(), cidr, region + "a")
.getSubnetId();
}
@Test
void containerModeLaunchOnARetainedInterfaceRecordsTheElasticIpItCarries() {
Ec2Service service = containerModeService();
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.249.0.0/24");
NetworkInterface retained = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(),
List.of());
Instance first = runningContainerInstance(service, region, subnetId, retained.getNetworkInterfaceId());
Address carried = service.allocateAddress(region);
service.associateAddress(region, carried.getAllocationId(), first.getInstanceId());
service.terminateInstances(region, List.of(first.getInstanceId()));
assertNotNull(carried.getAssociationId());
Instance second = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null,
null, retained.getNetworkInterfaceId(), 0).getInstances().getFirst();
// Not due an automatic address on an existing interface, but the container manager
// re-points the Elastic IP recorded here once the container runs.
assertFalse(second.isAssociatePublicIp());
assertEquals(carried.getPublicIp(), second.getPublicIpAddress());
}
@Test
void containerModeDescribeAddressesWritesNothingBackOntoATerminatedInstance() {
Ec2Service service = containerModeService();
String region = "us-east-1";
Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.248.0.0/24"),
null);
Address address = service.allocateAddress(region);
service.associateAddress(region, address.getAllocationId(), instance.getInstanceId());
// Terminated while the association stays, as for an instance whose interface did not go.
instance.setState(InstanceState.terminated());
instance.setPublicIpAddress(null);
instance.setPublicDnsName(null);
service.describeAddresses(region, List.of(address.getAllocationId()), Map.of());
assertNull(instance.getPublicIpAddress());
}
@Test
void containerModeDescribeAddressesRepointsAnElasticIpCarriedToANewInstance() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
// Each container answers on its own address, so a stale one shows.
Map<String, String> reachable = new ConcurrentHashMap<>();
when(containerManager.reachablePublicAddress(any())).thenAnswer(invocation -> {
Instance instance = invocation.getArgument(0);
return instance.getDockerContainerId() == null ? null : reachable.computeIfAbsent(
instance.getDockerContainerId(), container -> "192.0.2." + (reachable.size() + 1));
});
AmiImageResolver images = mock(AmiImageResolver.class);
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
Ec2Service service = new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class),
images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String region = "us-east-1";
String subnetId = publicSubnet(service, region, "10.250.0.0/24");
NetworkInterface retained = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(),
List.of());
Instance first = runningContainerInstance(service, region, subnetId, retained.getNetworkInterfaceId());
Address carried = service.allocateAddress(region);
service.associateAddress(region, carried.getAllocationId(), first.getInstanceId());
String firstAddress = carried.getPublicIp();
service.terminateInstances(region, List.of(first.getInstanceId()));
Instance second = runningContainerInstance(service, region, subnetId, retained.getNetworkInterfaceId());
String secondAddress = containerManager.reachablePublicAddress(second);
assertNotEquals(firstAddress, secondAddress);
Address described = service.describeAddresses(region, List.of(carried.getAllocationId()), Map.of()).getFirst();
assertEquals(secondAddress, described.getPublicIp());
assertEquals(secondAddress, second.getPublicIpAddress());
}
@Test
void containerModeStopLeavesATerminatedInstanceAlone() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(any())).thenReturn("127.0.0.1");
AmiImageResolver images = mock(AmiImageResolver.class);
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
Ec2Service service = new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class),
images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String region = "us-east-1";
Instance instance = runningContainerInstance(service, region, publicSubnet(service, region, "10.251.0.0/24"),
null);
service.terminateInstances(region, List.of(instance.getInstanceId()));
// What the container manager's teardown does once the container is gone.
instance.setState(InstanceState.terminated());
service.stopInstances(region, List.of(instance.getInstanceId()));
// A container stop would set it stopped and so startable again.
verify(containerManager, never()).stop(instance);
assertNull(instance.getPublicIpAddress());
}
/** Ec2Service in container mode, with a container manager whose containers answer on loopback. */
private static Ec2Service containerModeService() {
Ec2ContainerManager containerManager = mock(Ec2ContainerManager.class);
when(containerManager.reachablePublicAddress(any())).thenAnswer(invocation -> {
Instance instance = invocation.getArgument(0);
return instance.getDockerContainerId() == null ? null : "127.0.0.1";
});
AmiImageResolver images = mock(AmiImageResolver.class);
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
return new Ec2Service(mockConfig(false), containerManager, mock(Ec2PortForwardManager.class), images,
mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
}
private static String publicSubnet(Ec2Service service, String region, String cidr) {
String subnetId = service.createSubnet(region, service.createVpc(region, cidr, false).getVpcId(),
cidr, region + "a").getSubnetId();
service.modifySubnetAttribute(region, subnetId, "mapPublicIpOnLaunch", "true");
return subnetId;
}
/** Launches an instance and does what the container manager does once its container runs. */
private static Instance runningContainerInstance(Ec2Service service, String region, String subnetId,
String networkInterfaceId) {
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
1, 1, null, List.of(), subnetId, null, List.of(), null, null,
null, networkInterfaceId, 0).getInstances().getFirst();
instance.setDockerContainerId("container-" + instance.getInstanceId());
instance.setState(InstanceState.running());
if (instance.isAssociatePublicIp()) {
instance.setPublicIpAddress("127.0.0.1");
instance.setPublicDnsName("localhost");
}
return instance;
}
@Test
void networkInterfaceAssociationFiltersExcludeSecondaryAddressAssociations() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
@@ -6457,7 +6991,11 @@ class Ec2ServiceTest {
}
private static Ec2Service mockModeService() {
return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
return mockModeService(mockConfig(true));
}
private static Ec2Service mockModeService(EmulatorConfig config) {
return new Ec2Service(config, mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
@@ -6471,6 +7009,8 @@ class Ec2ServiceTest {
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(ec2Mock);
when(ec2.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.DOCUMENTATION);
when(ec2.mockPublicAddress()).thenReturn(Optional.empty());
return config;
}
@@ -508,6 +508,7 @@ class EksLaunchTemplateUserDataTest {
when(ec2Config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2ServiceConfig);
when(ec2ServiceConfig.mock()).thenReturn(true);
when(ec2ServiceConfig.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
@@ -182,6 +182,7 @@ class EksServiceTest {
when(ec2Config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2ServiceConfig);
when(ec2ServiceConfig.mock()).thenReturn(true);
when(ec2ServiceConfig.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.NONE);
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
+1
View File
@@ -318,6 +318,7 @@ floci:
volume-block-devices: false
volume-helper-image: alpine:3.21
mock: true
mock-public-addresses: none
instance-resource-limits: true
aws-faithful-private-ip: false
# container-ips-routable: true # see src/main/resources/application.yml