feat(eks): lease VPC /28 prefixes onto the cluster node's interface (#9279)

The Amazon VPC CNI plugin's prefix delegation hands a node IPv4 /28
prefixes of its subnet, listed on the node's network interface, and the
AWS Load Balancer Controller finds the interface behind a pod address
by looking for the prefix that holds it.

With floci.services.eks.vpc-pod-network, a node holding an address in a
Docker-backed subnet now also leases vpc-pod-prefixes /28 prefixes of
that subnet, two by default, as a node running pods holds under the VPC
CNI's default WARM_PREFIX_TARGET of one. DescribeInstances and
DescribeNetworkInterfaces list them on the node's interface in
ipv4PrefixSet.

EC2 leases a prefix from the top of the subnet down, clear of the
subnet's last address and of every address something holds, Docker's
own container addresses on the VPC network included, and counts its
sixteen addresses as held, so no instance or interface gets one and
AvailableIpAddressCount leaves them out. The node keeps its prefixes
across a restart as it keeps its address, re-reserving them; an adopted
node leases no new ones, and a stopped or failed start gives them back.

Part of #5929
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-23 12:24:45 -04:00
1 parent 5909ff5b80
commit 20e0ca6946
18 files changed
+811 -13

No files matched your search

+1 -1
View File
@@ -371,7 +371,7 @@ To get a container that both answers IMDS (including instance profile credential
When an EKS cluster is running, its synthesized node instance is registered and visible through the EC2 service:
- **Visibility**: Exposed via `DescribeInstances` and `DescribeInstanceStatus` with its synthesized instance ID (`i-...`), type (`m5.large`), running state, VPC, subnet, launch time, and cluster tags (`Name`, `kubernetes.io/cluster/<cluster-name>=owned`, `eks:cluster-name=<cluster-name>`). It can be queried by ID, filtered, or listed with other instances.
- **Network interface**: A node holding an address in its subnet has a primary network interface there, at that address, holding the cluster security group, as an EKS node's interface does. A node whose subnet is not Docker-backed, or that got no address in it, has none. `DescribeInstances` reports the interface and the group with the instance, and `DescribeNetworkInterfaces` lists the interface as it lists an instance's launch-created one, with the same filters. Its ids derive from the cluster, so they survive a restart. The cluster security group cannot be deleted while the node holds it.
- **Network interface**: A node holding an address in its subnet has a primary network interface there, at that address, holding the cluster security group, as an EKS node's interface does. With [EKS VPC pod prefixes](eks.md#vpc-pod-prefixes) on, the interface also lists the node's IPv4 `/28` prefixes in `ipv4PrefixSet`. A node whose subnet is not Docker-backed, or that got no address in it, has none. `DescribeInstances` reports the interface and the group with the instance, and `DescribeNetworkInterfaces` lists the interface as it lists an instance's launch-created one, with the same filters. Its ids derive from the cluster, so they survive a restart. The cluster security group cannot be deleted while the node holds it.
- **Changes stored through EC2**: An action such as `ModifyInstanceAttribute` stores EC2's copy of the node. The copy keeps what the action changed, while the node's address, subnet and interfaces follow its cluster, which may replace the node. Deleting the cluster ends the node as terminating it would: the copy is dropped, and volumes attached to the node are detached, or deleted when their `DeleteOnTermination` is set.
- **Operations**: Supports volume attachments (`AttachVolume`, `DetachVolume`), instance attribute inspection and modification, and resource tagging (`CreateTags`, `DeleteTags`, `DescribeTags`), its network interface's tags included.
- **Lifecycle protection**: Lifecycle actions that would mutate or delete the node through EC2 (`TerminateInstances`, `StopInstances`, `StartInstances`, `RebootInstances`), `ModifyInstanceMetadataOptions`, which the node's IMDS would not see, and `ModifyNetworkInterfaceAttribute`, `AssignIpv6Addresses` and `UnassignIpv6Addresses` on its network interface are rejected with `OperationNotPermitted` (HTTP 400) as a Floci emulation limitation because the instance directly represents the underlying k3s cluster container. In real AWS, cluster node instances in an Auto Scaling group can be terminated or stopped and are subsequently replaced by the ASG. In Floci, the node instance lifecycle is managed solely through the EKS cluster lifecycle.
+25
View File
@@ -768,6 +768,31 @@ does not enable it; omitted or false values keep the simulated behavior.
| `FLOCI_SERVICES_EKS_IMDS` | `false` | Enable link-local IMDS (`169.254.169.254`) proxy in cluster containers |
| `FLOCI_SERVICES_EKS_EMBEDDED_DNS` | `true` | Inject Floci's embedded DNS server into cluster containers for Route 53 private hosted zones and internal name resolution |
| `FLOCI_SERVICES_EKS_VPC_ROUTE_PROGRAMMING` | `true` | Program emulated VPC route table entries into k3s cluster containers |
| `FLOCI_SERVICES_EKS_VPC_POD_NETWORK` | `false` | Lease IPv4 `/28` prefixes of the node's subnet onto its network interface, as the VPC CNI's prefix delegation does (see [VPC pod prefixes](#vpc-pod-prefixes)) |
| `FLOCI_SERVICES_EKS_VPC_POD_PREFIXES` | `2` | How many `/28` prefixes a node holds with `FLOCI_SERVICES_EKS_VPC_POD_NETWORK` |
### VPC pod prefixes
With `FLOCI_SERVICES_EKS_VPC_POD_NETWORK=true`, a node holding an address in a Docker-backed subnet also leases IPv4 `/28`
prefixes of that subnet, as the Amazon VPC CNI plugin's prefix delegation assigns them to a node's network interface.
The node's interface lists them in `ipv4PrefixSet`, on `DescribeInstances` and `DescribeNetworkInterfaces`, where the AWS
Load Balancer Controller looks for the interface behind a pod address.
- **Count**: `FLOCI_SERVICES_EKS_VPC_POD_PREFIXES`, two by default: under the VPC CNI's default `WARM_PREFIX_TARGET` of
one, which keeps one prefix wholly free, a node running pods holds two. With the setting on, Floci refuses to start
unless the count is between 1 and 16. A subnet without enough free `/28` blocks leaves the node the ones it could
lease, with a warning.
- **Placement**: prefixes are taken from the top of the subnet down, clear of the subnet's last address, which AWS
reserves, and of every address an instance, interface, gateway, endpoint or container already holds. A container
Floci joins to the VPC's network without an address of its own, Floci itself or a node holding no subnet address, takes the
lowest address of the VPC's range that nothing leases or holds, so it never lands in a prefix. When Docker cannot say
which addresses its containers hold, no prefix is leased or re-reserved, with a warning.
- **Held addresses**: a prefix's sixteen addresses count as held, so no instance or interface gets one, and
`DescribeSubnets` leaves them out of `AvailableIpAddressCount`.
- **Lifecycle**: the node keeps its prefixes across a restart, re-reserving them as it re-reserves its address, and leases
new ones only for those another holder took meanwhile. An adopted node keeps the prefixes it was started with and
leases no others; a container that replaces it later leases the ones it lacks. Deleting the cluster, or a first start that falls back to the bridge network, gives them back.
- Pods keep their addresses from the cluster's pod CIDR (`10.42.0.0/16`).
### Kubernetes versions and network configuration
@@ -4314,6 +4314,21 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean imdsPodNetwork();
/**
* When true, each cluster node holds IPv4 /28 prefixes of its subnet on its network interface, as the Amazon VPC
* CNI plugin's prefix delegation assigns them. A node needs an address in a Docker-backed subnet for it.
*/
@WithDefault("false")
boolean vpcPodNetwork();
/**
* How many /28 prefixes a node holds with {@link #vpcPodNetwork()}: two, as a node running pods holds under the
* VPC CNI's default {@code WARM_PREFIX_TARGET} of one. With {@link #vpcPodNetwork()} on, Floci refuses to start
* unless it is between 1 and 16.
*/
@WithDefault("2")
int vpcPodPrefixes();
/**
* When true, configures k3s with the cluster's per-cluster OIDC signing keypair and
* advertises Floci's OIDC issuer URL, enabling in-cluster IAM Roles for Service Accounts (IRSA).
@@ -5526,6 +5526,7 @@ public class Ec2QueryHandler {
xml.elem("ipv6Address", ni.getIpv6Addresses().getFirst());
}
xml.raw(ipv6AddressesSetXml(ni.getIpv6Addresses()));
xml.raw(ipv4PrefixSetXml(ni.getIpv4Prefixes()));
return xml.build();
}
@@ -5541,6 +5542,18 @@ public class Ec2QueryHandler {
return xml.end("ipv6AddressesSet").build();
}
/** The IPv4 prefixes delegated to an interface, as {@code ipv4PrefixSet}; nothing for an interface with none. */
private static String ipv4PrefixSetXml(List<String> prefixes) {
if (prefixes == null || prefixes.isEmpty()) {
return "";
}
XmlBuilder xml = new XmlBuilder().start("ipv4PrefixSet");
for (String prefix : prefixes) {
xml.start("item").elem("ipv4Prefix", prefix).end("item");
}
return xml.end("ipv4PrefixSet").build();
}
private static String networkInterfaceAssociationXml(NetworkInterfaceAssociation association) {
return new XmlBuilder().start("association")
.elem("publicIp", association.getPublicIp())
@@ -5843,6 +5856,7 @@ public class Ec2QueryHandler {
.end("item")
.end("privateIpAddressesSet")
.raw(ipv6AddressesSetXml(eni.getIpv6Addresses()))
.raw(ipv4PrefixSetXml(eni.getIpv4Prefixes()))
.end("item");
}
xml.end("networkInterfaceSet");
@@ -507,6 +507,95 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
});
}
/**
* Leases up to {@code count} IPv4 /28 prefixes of a Docker-backed subnet none of whose addresses anything else holds,
* the way a network interface is delegated them, for a container that hands their addresses out itself (an EKS
* cluster node's pods). Their addresses count as held from then on, so no instance, interface or other prefix gets
* one. Docker is asked which addresses its containers hold once, before {@link #privateIpAllocationLock} is taken,
* and nothing is leased when it cannot say.
*
* @return the prefixes leased: fewer when the subnet has no other free one, none when it is not Docker-backed
*/
public List<String> allocateVpcPrefixes(String accountId, String region, String subnetId, int count) {
if (vpcNetworkManager == null || count <= 0) {
return List.of();
}
return RequestScopes.callAs(accountId, region, () -> {
Optional<Set<String>> attached = vpcNetworkManager.networkEndpointAddresses(callerAccountId(), region,
subnetId);
if (attached.isEmpty()) {
return List.<String>of();
}
synchronized (privateIpAllocationLock) {
Set<String> held = new HashSet<>(privateIpsHeldOnVpcNetwork(region, subnetId));
held.addAll(attached.get());
List<String> leased = new ArrayList<>();
for (Cidr4 prefix : vpcNetworkManager.allocatePrefixes(callerAccountId(), region, subnetId, count, held)) {
holdPrefixAddresses(region, subnetId, prefix);
leased.add(prefix.toString());
}
return leased;
}
});
}
/**
* Re-claims prefixes a persisted container holder leased before a restart, as {@link #reserveVpcPrivateIp} does an
* address, skipping one an instance, interface or container holds an address of now. Docker is asked as
* {@link #allocateVpcPrefixes} asks it, and nothing is reserved when it cannot say.
*
* @return the prefixes reserved
*/
public List<String> reserveVpcPrefixes(String accountId, String region, String subnetId, List<String> prefixes) {
if (vpcNetworkManager == null || subnetId == null || prefixes == null || prefixes.isEmpty()) {
return List.of();
}
return RequestScopes.callAs(accountId, region, () -> {
Optional<Set<String>> attached = vpcNetworkManager.networkEndpointAddresses(callerAccountId(), region,
subnetId);
if (attached.isEmpty()) {
return List.<String>of();
}
synchronized (privateIpAllocationLock) {
Set<String> held = new HashSet<>(privateIpsHeldOnVpcNetwork(region, subnetId));
held.addAll(attached.get());
List<String> reserved = new ArrayList<>();
for (String prefix : prefixes) {
Optional<Cidr4> parsed = Cidr4.parse(prefix);
if (parsed.isPresent()
&& vpcNetworkManager.reservePrefix(callerAccountId(), region, subnetId, parsed.get(), held)) {
holdPrefixAddresses(region, subnetId, parsed.get());
reserved.add(prefix);
}
}
return reserved;
}
});
}
public void releaseVpcPrefix(String accountId, String region, String subnetId, String prefix) {
Optional<Cidr4> parsed = prefix == null ? Optional.empty() : Cidr4.parse(prefix);
if (parsed.isEmpty()) {
return;
}
List<String> addresses = VpcNetworkManager.prefixAddresses(parsed.get().network());
RequestScopes.runAs(accountId, region, () -> {
synchronized (privateIpAllocationLock) {
containerPrivateIps.computeIfPresent(containerKey(region, subnetId), (ignored, held) -> {
held.removeAll(addresses);
return held.isEmpty() ? null : held;
});
releasePrivateIps(region, subnetId, addresses);
}
});
}
/** Counts a leased prefix's addresses as a container's. The caller holds {@link #privateIpAllocationLock}. */
private void holdPrefixAddresses(String region, String subnetId, Cidr4 prefix) {
containerPrivateIps.computeIfAbsent(containerKey(region, subnetId), ignored -> new HashSet<>())
.addAll(VpcNetworkManager.prefixAddresses(prefix.network()));
}
public void detachContainerFromVpc(String accountId, String region, String vpcId, String containerId) {
if (vpcNetworkManager != null) {
RequestScopes.runAs(accountId, region,
@@ -16911,6 +17000,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
ni.setSourceDestCheck(eni.isSourceDestCheck());
ni.setGroups(new ArrayList<>(eni.getGroups()));
ni.setIpv6Addresses(new ArrayList<>(eni.getIpv6Addresses()));
ni.setIpv4Prefixes(new ArrayList<>(eni.getIpv4Prefixes()));
if (inst.getPlacement() != null) {
ni.setAvailabilityZone(inst.getPlacement().getAvailabilityZone());
}
@@ -22,6 +22,7 @@ public class InstanceNetworkInterface {
private boolean sourceDestCheck = true;
private List<GroupIdentifier> groups = new ArrayList<>();
private List<String> ipv6Addresses = new ArrayList<>();
private List<String> ipv4Prefixes = new ArrayList<>();
private String attachmentId;
private int deviceIndex;
private String attachTime;
@@ -77,6 +78,9 @@ public class InstanceNetworkInterface {
public List<String> getIpv6Addresses() { return ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; }
public List<String> getIpv4Prefixes() { return ipv4Prefixes; }
public void setIpv4Prefixes(List<String> ipv4Prefixes) { this.ipv4Prefixes = ipv4Prefixes; }
/** A copy with lists of its own, so a change to the copy does not reach this interface. */
public InstanceNetworkInterface copy() {
InstanceNetworkInterface copy = new InstanceNetworkInterface();
@@ -92,6 +96,7 @@ public class InstanceNetworkInterface {
copy.sourceDestCheck = sourceDestCheck;
copy.groups = new ArrayList<>(groups);
copy.ipv6Addresses = new ArrayList<>(ipv6Addresses);
copy.ipv4Prefixes = new ArrayList<>(ipv4Prefixes);
copy.attachmentId = attachmentId;
copy.deviceIndex = deviceIndex;
copy.attachTime = attachTime;
@@ -40,6 +40,7 @@ public class NetworkInterface {
private List<Tag> tagSet = new ArrayList<>();
private List<NetworkInterfacePrivateIpAddress> privateIpAddresses = new ArrayList<>();
private List<String> ipv6Addresses = new ArrayList<>();
private List<String> ipv4Prefixes = new ArrayList<>();
/** The permissions this interface's owner has granted other accounts over it. */
private List<NetworkInterfacePermission> permissions = new ArrayList<>();
@@ -99,6 +100,9 @@ public class NetworkInterface {
public List<NetworkInterfacePrivateIpAddress> getPrivateIpAddresses() { return privateIpAddresses; }
public List<String> getIpv6Addresses() { return ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; }
public List<String> getIpv4Prefixes() { return ipv4Prefixes; }
public void setIpv4Prefixes(List<String> ipv4Prefixes) { this.ipv4Prefixes = ipv4Prefixes; }
public void setPrivateIpAddresses(List<NetworkInterfacePrivateIpAddress> privateIpAddresses) { this.privateIpAddresses = privateIpAddresses; }
public List<NetworkInterfacePermission> getPermissions() { return permissions; }
@@ -15,6 +15,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -113,6 +114,10 @@ public class VpcNetworkManager {
*/
static final int FIRST_HOST_OFFSET = 10;
/** The length of the IPv4 prefixes a subnet leases, the /28 AWS delegates to a network interface. */
public static final int PREFIX_LENGTH = 28;
private static final long PREFIX_SIZE = 1L << (32 - PREFIX_LENGTH);
/**
* The smallest offset any block can start allocating at: past the network address, and past
* the address Docker takes for the gateway.
@@ -534,6 +539,176 @@ public class VpcNetworkManager {
}
}
/**
* Leases up to {@code count} IPv4 /28 prefixes of the subnet's effective range none of whose addresses is leased or in
* {@code held}, which names what else holds addresses there, the containers on the VPC's network among them (see
* {@link #networkEndpointAddresses}). The highest such prefixes are taken: Floci and Docker give a container
* attached without an address of its own the lowest free address of the VPC's range, so prefixes from the top of
* the subnet stay clear of those. A prefix keeps clear of the subnet's last address, which AWS reserves, and of the
* addresses below the first one the subnet hands out.
*
* @return the prefixes leased, fewer than {@code count} when the subnet has no other free one, none when it has no
* Docker-backed range
*/
public List<Cidr4> allocatePrefixes(String accountId, String region, String subnetId, int count, Set<String> held) {
if (!enabled() || subnetId == null || count <= 0) {
return List.of();
}
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
if (subnet == null || subnet.effective == null) {
return List.of();
}
List<Cidr4> leased = new ArrayList<>();
synchronized (subnet) {
for (long start = (subnet.effective.size() - PREFIX_SIZE - 1) / PREFIX_SIZE * PREFIX_SIZE;
start >= subnet.firstOffset && leased.size() < count; start -= PREFIX_SIZE) {
List<String> addresses = prefixAddresses(subnet.effective.network() + start);
if (addresses.stream().noneMatch(address -> subnet.leased.contains(address) || held.contains(address))) {
subnet.leased.addAll(addresses);
leased.add(Cidr4.parse(addresses.getFirst() + "/" + PREFIX_LENGTH).orElseThrow());
}
}
}
if (leased.size() < count) {
LOG.warnv("Subnet {0} range {1} has {2} of the {3} free /{4} prefixes asked for.",
subnetId, subnet.effective, leased.size(), count, PREFIX_LENGTH);
}
return leased;
}
/**
* Re-claims a prefix a persisted container holder (an EKS cluster node) leased before a restart.
*
* @param held what else holds addresses in the subnet, as {@link #allocatePrefixes} takes it
* @return false, with a warning, when the prefix is not a /28 of the subnet's effective range, or one of its
* addresses is leased already or held
*/
public boolean reservePrefix(String accountId, String region, String subnetId, Cidr4 prefix, Set<String> held) {
if (!enabled() || subnetId == null || prefix == null) {
return false;
}
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
if (subnet == null || subnet.effective == null) {
return false;
}
if (prefix.prefix() != PREFIX_LENGTH || !subnet.effective.contains(prefix)) {
LOG.warnv("Cannot reserve prefix {0} in subnet {1}: it is not a /{2} of the subnet''s effective range {3}.",
prefix, subnetId, PREFIX_LENGTH, subnet.effective);
return false;
}
List<String> addresses = prefixAddresses(prefix.network());
synchronized (subnet) {
if (addresses.stream().anyMatch(address -> subnet.leased.contains(address) || held.contains(address))) {
LOG.warnv("Cannot reserve prefix {0} in subnet {1}: another holder has one of its addresses.",
prefix, subnetId);
return false;
}
subnet.leased.addAll(addresses);
return true;
}
}
public void releasePrefix(String accountId, String region, String subnetId, Cidr4 prefix) {
if (prefix != null) {
prefixAddresses(prefix.network()).forEach(address -> releasePrivateIp(accountId, region, subnetId, address));
}
}
/**
* The IPv4 addresses Docker gave the containers on the subnet's VPC network: none before the network exists, and
* empty when Docker cannot say, in which case nothing that needs to know is placed. It asks Docker, so a caller
* holding a lock others wait on reads it before taking that lock.
*/
public Optional<Set<String>> networkEndpointAddresses(String accountId, String region, String subnetId) {
String vpcKey = subnetOwner.get(key(accountId, region, subnetId));
VpcBinding vpc = vpcKey == null ? null : bindings.get(vpcKey);
if (!enabled() || vpc == null || vpc.networkName == null) {
return Optional.of(Set.of());
}
return endpointAddresses(vpc.networkName);
}
/** {@link #networkEndpointAddresses} for the network named {@code networkName}. */
private Optional<Set<String>> endpointAddresses(String networkName) {
Network network;
try {
network = dockerClient.inspectNetworkCmd().withNetworkId(networkName).exec();
} catch (NotFoundException notCreatedYet) {
return Optional.of(Set.of());
} catch (RuntimeException e) {
LOG.warnv("Could not inspect VPC network {0}, so the addresses its containers hold are unknown: {1}",
networkName, e.getMessage());
return Optional.empty();
}
return Optional.of(endpointAddresses(network));
}
private static Set<String> endpointAddresses(Network network) {
Set<String> addresses = new HashSet<>();
if (network != null && network.getContainers() != null) {
for (Network.ContainerNetworkConfig container : network.getContainers().values()) {
String address = container.getIpv4Address();
if (address != null && !address.isBlank()) {
addresses.add(address.contains("/") ? address.substring(0, address.indexOf('/')) : address);
}
}
}
return addresses;
}
/**
* The address a container attached with none of its own takes on the VPC's network: the lowest of the VPC's range
* that no subnet leases and no container on the network holds. Docker would otherwise choose one itself, without
* knowing what Floci leased, and could take an address of a prefix a node's pods hold. Empty when the range has
* none left, and Docker chooses then.
*/
private static Optional<String> unleasedAddress(VpcBinding vpc, Set<String> attached) {
Set<String> leased = new HashSet<>();
vpc.subnets.values().forEach(subnet -> leased.addAll(subnet.leased));
for (long offset = MIN_HOST_OFFSET; offset < vpc.effective.size() - 1; offset++) {
String address = Cidr4.format(vpc.effective.network() + offset);
if (!leased.contains(address) && !attached.contains(address)) {
return Optional.of(address);
}
}
return Optional.empty();
}
/**
* Connects a container to the VPC's network at {@link #unleasedAddress}, or where Docker puts it when the range has
* none left or Docker refuses that one, which another attachment can take between the two.
*/
private void connectUnplaced(VpcBinding vpc, String containerId, Set<String> attached) {
Optional<String> address = unleasedAddress(vpc, attached);
if (address.isPresent()) {
try {
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
.withNetworkId(vpc.networkName)
.withContainerNetwork(new ContainerNetwork()
.withIpamConfig(new ContainerNetwork.Ipam().withIpv4Address(address.get())))
.exec();
return;
} catch (RuntimeException refused) {
LOG.debugv("Docker refused container {0} at {1} on VPC network {2}, so it picks the address: {3}",
containerId, address.get(), vpc.networkName, refused.getMessage());
}
}
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
.withNetworkId(vpc.networkName)
.exec();
}
/** The addresses of the /28 prefix starting at {@code network}. */
public static List<String> prefixAddresses(long network) {
List<String> addresses = new ArrayList<>();
for (long offset = 0; offset < PREFIX_SIZE; offset++) {
addresses.add(Cidr4.format(network + offset));
}
return addresses;
}
public void releasePrivateIp(String accountId, String region, String subnetId, String address) {
String vpcKey = subnetOwner.get(key(accountId, region, subnetId));
VpcBinding vpc = vpcKey == null ? null : bindings.get(vpcKey);
@@ -621,10 +796,7 @@ public class VpcNetworkManager {
return true;
}
}
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
.withNetworkId(networkName)
.exec();
connectUnplaced(vpc, containerId, endpointAddresses(networkName).orElse(Set.of()));
LOG.infov("Attached container {0} to VPC network {1}", containerId, networkName);
return true;
} catch (Exception e) {
@@ -753,10 +925,8 @@ public class VpcNetworkManager {
return;
}
try {
dockerClient.connectToNetworkCmd()
.withContainerId(containerId)
.withNetworkId(vpc.networkName)
.exec();
connectUnplaced(vpc, containerId, network != null ? endpointAddresses(network)
: endpointAddresses(vpc.networkName).orElse(Set.of()));
vpc.flociContainerId = containerId;
LOG.infov("Attached Floci container {0} to VPC network {1}", containerId, vpc.networkName);
} catch (Exception e) {
@@ -226,6 +226,8 @@ public class EksClusterManager
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
/** The IPv4 /28 prefixes leased for each cluster node's pods, by cluster resource name. */
private final Map<String, List<String>> clusterPodPrefixes = new ConcurrentHashMap<>();
/**
* The k3s containers whose guest setup waits for their API server to answer, by container ID. On a cgroup v2
* host, k3s moves the root cgroup's processes into {@code /init} and then enables the cgroup controllers, which
@@ -319,6 +321,47 @@ public class EksClusterManager
private VpcLease acquireClusterVpcLease(Cluster cluster, String accountId, String region,
boolean allocateWhenUnreserved) {
VpcLease lease = acquireNodeAddressLease(cluster, accountId, region, allocateWhenUnreserved);
if (lease != null) {
leasePodPrefixes(cluster, lease, allocateWhenUnreserved);
}
return lease;
}
/**
* With {@code vpc-pod-network}, leases the node's IPv4 /28 prefixes in its subnet: those it held before a restart,
* when they are still free, and new ones up to {@code vpc-pod-prefixes} when {@code allocate}. An adopted container
* does not allocate, as it keeps handing out the prefixes it was started with; a container started later on the
* same lease, one replacing it among them, tops the list up. Without the setting the node holds none.
*/
private void leasePodPrefixes(Cluster cluster, VpcLease lease, boolean allocate) {
String resourceName = clusterResourceName(cluster);
Ec2Service ec2 = ec2Service();
if (!config.services().eks().vpcPodNetwork() || ec2 == null) {
cluster.setNodePodPrefixes(null);
return;
}
List<String> prefixes = clusterPodPrefixes.get(resourceName);
if (prefixes == null) {
List<String> held = cluster.getNodePodPrefixes();
prefixes = new ArrayList<>(held == null || held.isEmpty() ? List.of()
: ec2.reserveVpcPrefixes(lease.accountId(), lease.region(), lease.subnetId(), held));
clusterPodPrefixes.put(resourceName, prefixes);
}
int wanted = config.services().eks().vpcPodPrefixes();
if (allocate && prefixes.size() < wanted) {
prefixes.addAll(ec2.allocateVpcPrefixes(lease.accountId(), lease.region(), lease.subnetId(),
wanted - prefixes.size()));
if (prefixes.size() < wanted) {
LOG.warnv("EKS cluster {0} holds {1} of its {2} pod prefixes: subnet {3} has no other free /28",
cluster.getName(), prefixes.size(), wanted, lease.subnetId());
}
}
cluster.setNodePodPrefixes(prefixes.isEmpty() ? null : new ArrayList<>(prefixes));
}
private VpcLease acquireNodeAddressLease(Cluster cluster, String accountId, String region,
boolean allocateWhenUnreserved) {
ClusterVpcSubnet subnet = resolveClusterSubnet(cluster);
if (subnet == null) {
return null;
@@ -366,9 +409,14 @@ public class EksClusterManager
private void releaseClusterVpcLease(Cluster cluster, String resourceName) {
VpcLease lease = clusterVpcLeases.remove(resourceName);
List<String> prefixes = clusterPodPrefixes.remove(resourceName);
Ec2Service ec2 = ec2Service();
if (lease != null && ec2 != null) {
ec2.releaseVpcPrivateIp(lease.accountId(), lease.region(), lease.subnetId(), lease.address());
if (prefixes != null) {
prefixes.forEach(prefix -> ec2.releaseVpcPrefix(lease.accountId(), lease.region(), lease.subnetId(),
prefix));
}
}
}
@@ -708,6 +756,7 @@ public class EksClusterManager
String resourceName = clusterResourceName(cluster);
boolean hadLeaseBeforeLaunch = clusterVpcLeases.containsKey(resourceName);
String previousNodeIp = cluster != null ? cluster.getNodePrivateIp() : null;
List<String> previousPodPrefixes = cluster != null ? cluster.getNodePodPrefixes() : null;
VpcLease vpcLease = acquireClusterVpcLease(cluster, labelAccountId, clusterRegion);
String nodeIp = vpcLease != null ? vpcLease.address() : null;
String restoredNodeIp = (previousNodeIp != null && !previousNodeIp.isBlank()
@@ -884,6 +933,7 @@ public class EksClusterManager
releaseClusterVpcLease(cluster, resourceName);
if (cluster != null) {
cluster.setNodePrivateIp(restoredNodeIp);
cluster.setNodePodPrefixes(restoredNodeIp != null ? previousPodPrefixes : null);
}
}
throw e;
@@ -908,6 +958,7 @@ public class EksClusterManager
releaseClusterVpcLease(cluster, resourceName);
if (cluster != null) {
cluster.setNodePrivateIp(null);
cluster.setNodePodPrefixes(null);
}
vpcLease = null;
lifecycleManager.removeIfExistsStrict(containerName, true);
@@ -961,6 +1012,7 @@ public class EksClusterManager
releaseClusterVpcLease(cluster, resourceName);
if (cluster != null) {
cluster.setNodePrivateIp(restoredNodeIp);
cluster.setNodePodPrefixes(restoredNodeIp != null ? previousPodPrefixes : null);
}
}
throw e;
@@ -3574,6 +3626,9 @@ public class EksClusterManager
eni.setPrivateIpAddress(inst.getPrivateIpAddress());
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(groups));
if (cluster.getNodePodPrefixes() != null) {
eni.setIpv4Prefixes(new ArrayList<>(cluster.getNodePodPrefixes()));
}
eni.setAttachmentId(deriveClusterNodeInterfaceAttachmentId(cluster, region, accountId));
eni.setDeviceIndex(0);
inst.getNetworkInterfaces().add(eni);
@@ -140,7 +140,7 @@ public class EksController {
*/
private Cluster toClusterResponse(Cluster cluster) {
if (cluster == null || (!cluster.isExplicitVersion() && cluster.getNodeInstanceType() == null
&& cluster.getNodePrivateIp() == null
&& cluster.getNodePrivateIp() == null && cluster.getNodePodPrefixes() == null
&& cluster.getClusterArgs() == null && cluster.getDefaultStorageClass() == null
&& cluster.getJoinedInstanceIds() == null && cluster.getDockerNameRegion() == null)) {
return cluster;
@@ -150,6 +150,7 @@ public class EksController {
response.setExplicitVersion(false);
response.setNodeInstanceType(null);
response.setNodePrivateIp(null);
response.setNodePodPrefixes(null);
response.setClusterArgs(null);
response.setDefaultStorageClass(null);
response.setJoinedInstanceIds(null);
@@ -9,13 +9,17 @@ import jakarta.inject.Inject;
import jakarta.interceptor.Interceptor;
/**
* Refuses to start Floci with an invalid {@code floci.services.eks.endpoint-host}. Checked once here, before
* persisted clusters are restored, so a typo stops the boot instead of failing every cluster on restore.
* Metadata-only EKS (disabled or mock) never uses the setting, so it is not checked there.
* Refuses to start Floci with an invalid {@code floci.services.eks.endpoint-host}, or, with the VPC pod network on, a
* {@code floci.services.eks.vpc-pod-prefixes} out of range. Checked once here, before persisted clusters are restored,
* so a typo stops the boot instead of failing every cluster on restore. Metadata-only EKS (disabled or mock) never uses
* the settings, so they are not checked there.
*/
@ApplicationScoped
public class EksStartupValidator {
/** A node needs a prefix for its pods, and sixteen /28 prefixes already fill a /24 subnet. */
static final int MAX_VPC_POD_PREFIXES = 16;
private final EmulatorConfig config;
@Inject
@@ -26,6 +30,15 @@ public class EksStartupValidator {
void onStart(@Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE) StartupEvent ignored) {
if (config.services().eks().enabled() && !config.services().eks().mock()) {
EksClusterManager.endpointHostFrom(config.services().eks().endpointHost());
requireVpcPodPrefixes(config.services().eks());
}
}
static void requireVpcPodPrefixes(EmulatorConfig.EksServiceConfig eks) {
int prefixes = eks.vpcPodPrefixes();
if (eks.vpcPodNetwork() && (prefixes < 1 || prefixes > MAX_VPC_POD_PREFIXES)) {
throw new IllegalArgumentException("floci.services.eks.vpc-pod-prefixes must be between 1 and "
+ MAX_VPC_POD_PREFIXES + " with floci.services.eks.vpc-pod-network on, not " + prefixes);
}
}
}
@@ -116,6 +116,11 @@ public class Cluster {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String nodePrivateIp;
/** The IPv4 /28 prefixes leased for the cluster node's pods in its subnet. Internal persisted metadata. */
@JsonProperty("nodePodPrefixes")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<String> nodePodPrefixes;
/**
* Caller-supplied k3s arguments passed at creation via reserved floci tags.
* Internal persisted metadata omitted from AWS API responses.
@@ -246,6 +251,9 @@ public class Cluster {
public String getNodePrivateIp() { return nodePrivateIp; }
public void setNodePrivateIp(String nodePrivateIp) { this.nodePrivateIp = nodePrivateIp; }
public List<String> getNodePodPrefixes() { return nodePodPrefixes; }
public void setNodePodPrefixes(List<String> nodePodPrefixes) { this.nodePodPrefixes = nodePodPrefixes; }
public List<String> getClusterArgs() { return clusterArgs; }
public void setClusterArgs(List<String> clusterArgs) { this.clusterArgs = clusterArgs; }
@@ -310,6 +318,7 @@ public class Cluster {
c.dockerNameRegion = this.dockerNameRegion;
c.nodeInstanceType = this.nodeInstanceType;
c.nodePrivateIp = this.nodePrivateIp;
c.nodePodPrefixes = this.nodePodPrefixes != null ? new ArrayList<>(this.nodePodPrefixes) : null;
c.clusterArgs = this.clusterArgs != null ? new ArrayList<>(this.clusterArgs) : null;
c.defaultStorageClass = this.defaultStorageClass;
c.joinedInstanceIds = this.joinedInstanceIds != null ? new ConcurrentHashMap<>(this.joinedInstanceIds) : null;
+2
View File
@@ -969,6 +969,8 @@ floci:
default-storage-class: false # start k3s without its bundled local-path provisioner to match EKS
imds: false # expose link-local IMDS (169.254.169.254) inside the cluster container
imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true)
vpc-pod-network: false # lease /28 prefixes of the node's subnet onto its network interface, as VPC CNI prefix delegation does
vpc-pod-prefixes: 2 # how many /28 prefixes a node holds with vpc-pod-network (1 to 16)
irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC key
pod-identity-webhook: true # register a mutating webhook that injects pod identity credentials (needs floci.tls.enabled)
embedded-dns: true # point cluster containers at Floci's embedded DNS to resolve Route 53 private zones
@@ -7,8 +7,15 @@ import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ec2.model.BlockDeviceMapping;
import io.floci.aws.services.ec2.model.EbsBlockDevice;
import io.floci.aws.services.ec2.model.Image;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.services.ec2.model.InstanceState;
import io.floci.aws.services.ec2.model.KeyPair;
import io.floci.aws.services.ec2.model.NetworkAcl;
import io.floci.aws.services.ec2.model.NetworkInterface;
import io.floci.aws.services.ec2.model.NetworkInterfaceListResult;
import io.floci.aws.services.ec2.model.Placement;
import io.floci.aws.services.ec2.model.Reservation;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2.model.Vpc;
@@ -41,6 +48,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -673,6 +681,39 @@ class Ec2QueryHandlerTest {
verify(service, never()).createSecurityGroup(any(), any(), any(), any());
}
@Test
void anInterfacesIpv4PrefixesAreDescribedWithItAndWithItsInstance() {
Ec2Service service = mock(Ec2Service.class);
List<String> prefixes = List.of("10.60.0.224/28", "10.60.0.208/28");
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId("eni-0de0000000000005a");
ni.setPrivateIpAddress("10.60.0.25");
ni.setIpv4Prefixes(prefixes);
when(service.describeNetworkInterfaces(eq("us-east-1"), anyList(), anyList(), anyInt(), any()))
.thenReturn(new NetworkInterfaceListResult(List.of(ni), null));
Instance node = new Instance();
node.setInstanceId("i-0de0000000000005a");
node.setRegion("us-east-1");
node.setState(InstanceState.running());
node.setPlacement(new Placement("us-east-1a"));
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId("eni-0de0000000000005a");
eni.setPrivateIpAddress("10.60.0.25");
eni.setIpv4Prefixes(prefixes);
node.getNetworkInterfaces().add(eni);
Reservation reservation = new Reservation();
reservation.setInstances(List.of(node));
when(service.describeInstances(eq("us-east-1"), anyList(), anyList())).thenReturn(List.of(reservation));
String prefixSet = "<ipv4PrefixSet><item><ipv4Prefix>10.60.0.224/28</ipv4Prefix></item>"
+ "<item><ipv4Prefix>10.60.0.208/28</ipv4Prefix></item></ipv4PrefixSet>";
for (String action : List.of("DescribeNetworkInterfaces", "DescribeInstances")) {
String body = ((String) handler(service).handle(action, new MultivaluedHashMap<>(), "us-east-1")
.getEntity()).replaceAll(">\\s+<", "><");
assertTrue(body.contains(prefixSet), action + ": " + body);
}
}
private Ec2QueryHandler handler(Ec2Service service) {
return handler(service, new RegionResolver("us-east-1", "000000000000"));
}
@@ -64,6 +64,7 @@ import io.floci.aws.services.ec2.model.Vpc;
import io.floci.aws.services.ec2.model.VpcCidrBlockAssociation;
import io.floci.aws.services.ec2.model.VpcEndpoint;
import io.floci.aws.services.ec2.model.VpcEndpointSubnetConfiguration;
import io.floci.aws.services.ec2.net.Cidr4;
import io.floci.aws.services.ec2.net.VpcNetworkManager;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import io.floci.aws.testing.ParkingStore;
@@ -144,6 +145,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
@@ -2990,6 +2992,57 @@ class Ec2ServiceTest {
assertTrue(fixture.service().describeNatGateways("us-east-1", List.of(), Map.of()).isEmpty());
}
/** Prefixes leased for a container's own addresses hold all their addresses until they are released. */
@Test
void leasedPrefixesHoldTheirAddressesUntilReleased() {
MockedNetworkFixture fixture = mockedNetworkFixture("10.60.0.0/24");
Ec2Service service = fixture.service();
when(fixture.vpcNetworks().networkEndpointAddresses("000000000000", "us-east-1", fixture.subnetId()))
.thenReturn(Optional.of(Set.of("10.60.0.250")));
when(fixture.vpcNetworks().allocatePrefixes(eq("000000000000"), eq("us-east-1"), eq(fixture.subnetId()),
eq(2), any())).thenReturn(List.of(Cidr4.parse("10.60.0.224/28").orElseThrow(),
Cidr4.parse("10.60.0.208/28").orElseThrow()));
when(fixture.vpcNetworks().reservePrefix(eq("000000000000"), eq("us-east-1"), eq(fixture.subnetId()),
eq(Cidr4.parse("10.60.0.192/28").orElseThrow()), any())).thenReturn(true);
int before = service.describeSubnets("us-east-1", List.of(fixture.subnetId()), Map.of()).getFirst()
.getAvailableIpAddressCount();
assertEquals(List.of("10.60.0.224/28", "10.60.0.208/28"),
service.allocateVpcPrefixes("000000000000", "us-east-1", fixture.subnetId(), 2));
assertEquals(List.of("10.60.0.192/28"), service.reserveVpcPrefixes("000000000000", "us-east-1",
fixture.subnetId(), List.of("10.60.0.192/28")));
assertEquals(before - 48, service.describeSubnets("us-east-1", List.of(fixture.subnetId()), Map.of())
.getFirst().getAvailableIpAddressCount());
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<String>> held = ArgumentCaptor.forClass(Set.class);
verify(fixture.vpcNetworks()).reservePrefix(eq("000000000000"), eq("us-east-1"), eq(fixture.subnetId()),
any(), held.capture());
assertTrue(held.getValue().containsAll(List.of("10.60.0.250", "10.60.0.224", "10.60.0.239")),
"the reservation sees the container's address and the prefixes leased before it as held");
for (String prefix : List.of("10.60.0.224/28", "10.60.0.208/28", "10.60.0.192/28")) {
service.releaseVpcPrefix("000000000000", "us-east-1", fixture.subnetId(), prefix);
}
assertEquals(before, service.describeSubnets("us-east-1", List.of(fixture.subnetId()), Map.of()).getFirst()
.getAvailableIpAddressCount());
verify(fixture.vpcNetworks()).releasePrivateIp("000000000000", "us-east-1", fixture.subnetId(), "10.60.0.230");
}
/** Without knowing which addresses Docker's containers hold, no prefix is leased or reserved. */
@Test
void noPrefixIsLeasedOrReservedWhenDockerCannotSayWhichAddressesItsContainersHold() {
MockedNetworkFixture fixture = mockedNetworkFixture("10.60.0.0/24");
when(fixture.vpcNetworks().networkEndpointAddresses("000000000000", "us-east-1", fixture.subnetId()))
.thenReturn(Optional.empty());
assertTrue(fixture.service().allocateVpcPrefixes("000000000000", "us-east-1", fixture.subnetId(), 1).isEmpty());
assertTrue(fixture.service().reserveVpcPrefixes("000000000000", "us-east-1", fixture.subnetId(),
List.of("10.60.0.224/28")).isEmpty());
verify(fixture.vpcNetworks(), never()).allocatePrefixes(any(), any(), any(), anyInt(), any());
verify(fixture.vpcNetworks(), never()).reservePrefix(any(), any(), any(), any(), any());
}
/** The same on a secondary-address update, which also leaves the gateway as it was. */
@Test
void aNatGatewayUpdateThatRunsOutOfAddressesGivesBackTheLeaseItTook() {
@@ -5,11 +5,14 @@ import com.github.dockerjava.api.command.ConnectToNetworkCmd;
import com.github.dockerjava.api.command.CreateNetworkCmd;
import com.github.dockerjava.api.command.CreateNetworkResponse;
import com.github.dockerjava.api.command.DisconnectFromNetworkCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectNetworkCmd;
import com.github.dockerjava.api.command.ListNetworksCmd;
import com.github.dockerjava.api.command.RemoveNetworkCmd;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Network;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
@@ -44,6 +47,8 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -428,6 +433,114 @@ class VpcNetworkManagerTest {
"a terminated instance's address must come back into circulation");
}
// ─── Prefixes: /28 blocks a container hands its own addresses out of ────
@Test
void prefixesAreTheHighestFreeSlashTwentyEightsOfTheSubnet() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
// .240/28 would hold .255, which AWS reserves; a block one of whose addresses something else holds is skipped.
assertEquals(List.of("10.0.1.224/28", "10.0.1.192/28"), manager.allocatePrefixes(ACCOUNT, REGION, "subnet-a",
2, Set.of("10.0.1.215")).stream().map(Cidr4::toString).toList());
// The prefixes' addresses are leased until they are released.
assertFalse(manager.reservePrivateIp(ACCOUNT, REGION, "subnet-a", "10.0.1.230"));
manager.releasePrefix(ACCOUNT, REGION, "subnet-a", Cidr4.parse("10.0.1.224/28").orElseThrow());
assertTrue(manager.reservePrivateIp(ACCOUNT, REGION, "subnet-a", "10.0.1.230"));
}
@Test
void aSubnetWithNoSlashTwentyEightClearOfReservedAddressesLeasesNoPrefix() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-small", "10.0.9.0/27");
assertTrue(manager.allocatePrefixes(ACCOUNT, REGION, "subnet-small", 1, Set.of()).isEmpty());
}
@Test
void theAddressesContainersHoldOnTheVpcNetworkAreReadFromDocker() {
Network.ContainerNetworkConfig endpoint = mock(Network.ContainerNetworkConfig.class);
when(endpoint.getIpv4Address()).thenReturn("10.0.1.231/16");
existingNetwork(manager.networkName(ACCOUNT, REGION, "vpc-1"), "10.0.0.0/16", ourLabels("vpc-1", "4650"),
Map.of("container-1", endpoint));
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertEquals(Optional.of(Set.of("10.0.1.231")),
manager.networkEndpointAddresses(ACCOUNT, REGION, "subnet-a"));
}
@Test
void aNetworkNotCreatedYetHoldsNoAddressAndOneDockerCannotDescribeHoldsUnknownOnes() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertEquals(Optional.of(Set.of()), manager.networkEndpointAddresses(ACCOUNT, REGION, "subnet-a"));
InspectNetworkCmd failing = mock(InspectNetworkCmd.class, RETURNS_SELF);
when(failing.exec()).thenThrow(new RuntimeException("daemon timed out"));
when(docker.inspectNetworkCmd()).thenReturn(failing);
assertEquals(Optional.empty(), manager.networkEndpointAddresses(ACCOUNT, REGION, "subnet-a"));
}
@Test
void aRestartReservesAPrefixOnlyWhenNoneOfItsAddressesIsLeasedOrHeld() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
Cidr4 held = Cidr4.parse("10.0.1.224/28").orElseThrow();
assertTrue(manager.reservePrivateIp(ACCOUNT, REGION, "subnet-a", "10.0.1.20"));
assertFalse(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", held, Set.of("10.0.1.233")),
"a container holds 10.0.1.233");
assertTrue(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", held, Set.of()));
assertFalse(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", held, Set.of()), "its addresses are leased now");
assertFalse(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", Cidr4.parse("10.0.1.16/28").orElseThrow(),
Set.of()), "10.0.1.20 is leased");
assertFalse(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", Cidr4.parse("10.0.2.0/28").orElseThrow(),
Set.of()), "outside the subnet");
assertFalse(manager.reservePrefix(ACCOUNT, REGION, "subnet-a", Cidr4.parse("10.0.1.64/27").orElseThrow(),
Set.of()), "not a /28");
}
@Test
void aContainerAttachedWithoutAnAddressTakesTheLowestOneNothingLeasesOrHolds() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-low", "10.0.0.0/24");
assertTrue(manager.reservePrivateIp(ACCOUNT, REGION, "subnet-low", "10.0.0.2"));
assertTrue(manager.reservePrivateIp(ACCOUNT, REGION, "subnet-low", "10.0.0.3"));
Network.ContainerNetworkConfig endpoint = mock(Network.ContainerNetworkConfig.class);
when(endpoint.getIpv4Address()).thenReturn("10.0.0.4/16");
String networkName = manager.networkName(ACCOUNT, REGION, "vpc-1");
existingNetwork(networkName, "10.0.0.0/16", ourLabels("vpc-1", "4650"), Map.of("container-1", endpoint));
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(inspect.exec()).thenReturn(mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS));
when(docker.inspectContainerCmd("node-1")).thenReturn(inspect);
ConnectToNetworkCmd connect = docker.connectToNetworkCmd();
assertTrue(manager.attachContainer(ACCOUNT, REGION, "vpc-1", "node-1"));
ArgumentCaptor<ContainerNetwork> placed = ArgumentCaptor.forClass(ContainerNetwork.class);
verify(connect).withContainerNetwork(placed.capture());
assertEquals("10.0.0.5", placed.getValue().getIpamConfig().getIpv4Address());
}
@Test
void aContainerDockerRefusesAtThePickedAddressIsAttachedWhereDockerPutsIt() {
manager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-low", "10.0.0.0/24");
existingNetwork(manager.networkName(ACCOUNT, REGION, "vpc-1"), "10.0.0.0/16", ourLabels("vpc-1", "4650"),
Map.of());
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(inspect.exec()).thenReturn(mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS));
when(docker.inspectContainerCmd("node-1")).thenReturn(inspect);
ConnectToNetworkCmd connect = docker.connectToNetworkCmd();
doThrow(new ConflictException("Address already in use")).doNothing().when(connect).exec();
assertTrue(manager.attachContainer(ACCOUNT, REGION, "vpc-1", "node-1"));
verify(connect, times(2)).exec();
verify(connect, times(1)).withContainerNetwork(any());
}
// ─── Restart: addresses persisted instances still hold ───────────────────
@Test
@@ -650,6 +763,27 @@ class VpcNetworkManagerTest {
verify(connect, times(2)).withNetworkId(networkName);
}
@Test
void theCurrentFlociContainerTakesTheLowestAddressNoOtherContainerOnTheNetworkHolds() {
CurrentContainerNetworkResolver currentContainerNetworkResolver = mock(CurrentContainerNetworkResolver.class);
when(currentContainerNetworkResolver.resolveContainerId()).thenReturn(Optional.of("floci-container"));
VpcNetworkManager dockerHostedManager = new VpcNetworkManager(config, docker, currentContainerNetworkResolver);
Network.ContainerNetworkConfig endpoint = mock(Network.ContainerNetworkConfig.class);
when(endpoint.getIpv4Address()).thenReturn("10.0.0.2/16");
existingNetwork(dockerHostedManager.networkName(ACCOUNT, REGION, "vpc-1"), "10.0.0.0/16",
ourLabels("vpc-1", "4650"), Map.of("instance-0", endpoint));
dockerHostedManager.declareVpc(ACCOUNT, REGION, "vpc-1", "10.0.0.0/16");
dockerHostedManager.declareSubnet(ACCOUNT, REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String address = dockerHostedManager.allocatePrivateIp(ACCOUNT, REGION, "subnet-a").orElseThrow();
assertTrue(dockerHostedManager.attach(ACCOUNT, REGION, "vpc-1", "subnet-a", "instance-1", address).isPresent());
ArgumentCaptor<ContainerNetwork> placed = ArgumentCaptor.forClass(ContainerNetwork.class);
verify(docker.connectToNetworkCmd(), times(2)).withContainerNetwork(placed.capture());
assertEquals(List.of("10.0.0.3", address), placed.getAllValues().stream()
.map(network -> network.getIpamConfig().getIpv4Address()).toList());
}
@Test
void doesNotReconnectCurrentFlociContainerAlreadyAttachedToVpcNetwork() {
CurrentContainerNetworkResolver currentContainerNetworkResolver =
@@ -121,6 +121,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
@@ -5448,6 +5449,29 @@ class EksClusterManagerTest {
assertEquals(firstLaunch.stream().filter(a -> !a.startsWith("--node-ip")).toList(), cmdCaptor.getValue());
}
@Test
void aFirstLaunchThatFallsBackToTheBridgeGivesItsPrefixesBackWithItsAddress() {
when(config.services().eks().vpcPodNetwork()).thenReturn(true);
when(config.services().eks().vpcPodPrefixes()).thenReturn(1);
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
when(lifecycleManager.create(any())).thenReturn("cid-vpc", "cid-bridge");
when(lifecycleManager.startCreated(eq("cid-bridge"), any()))
.thenReturn(new ContainerInfo("cid-bridge", Map.of()));
when(ec2Service.allocateVpcPrivateIp("000000000000", "us-east-1", "subnet-1"))
.thenReturn(Optional.of("10.0.1.25"));
when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 1))
.thenReturn(List.of("10.0.1.224/28"));
when(ec2Service.attachContainerToVpc("000000000000", "us-east-1", "vpc-1", "subnet-1", "cid-vpc", "10.0.1.25"))
.thenReturn(Optional.empty());
Cluster cluster = vpcCluster("prefix-fallback", "vpc-1", List.of("subnet-1"));
manager.startCluster(cluster);
assertNull(cluster.getNodePrivateIp());
assertNull(cluster.getNodePodPrefixes());
verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.224/28");
}
@Test
void restoreClusterFailsStartAndRetainsNodeIpWhenVpcAttachFails() {
when(lifecycleManager.findByName("floci-eks-restore-attach-fail")).thenReturn(Optional.empty());
@@ -5471,6 +5495,123 @@ class EksClusterManagerTest {
verify(lifecycleManager, never()).startCreated(anyString(), any());
}
@Test
void withVpcPodNetworkANodeLeasesItsPrefixesListsThemOnItsInterfaceAndReleasesThemOnStop() {
when(config.services().eks().vpcPodNetwork()).thenReturn(true);
when(config.services().eks().vpcPodPrefixes()).thenReturn(2);
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
when(lifecycleManager.create(any())).thenReturn("cid-1");
when(lifecycleManager.startCreated(eq("cid-1"), any())).thenReturn(new ContainerInfo("cid-1", Map.of()));
when(ec2Service.allocateVpcPrivateIp("000000000000", "us-east-1", "subnet-1"))
.thenReturn(Optional.of("10.0.1.25"));
when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 2))
.thenReturn(List.of("10.0.1.224/28", "10.0.1.208/28"));
Cluster cluster = vpcCluster("prefix-cluster", "vpc-1", List.of("subnet-1"));
manager.startCluster(cluster);
assertEquals(List.of("10.0.1.224/28", "10.0.1.208/28"), cluster.getNodePodPrefixes());
Instance node = manager.synthesizeClusterNodeInstance(cluster, "172.17.0.2", "us-east-1", "000000000000");
assertEquals(List.of("10.0.1.224/28", "10.0.1.208/28"),
node.getNetworkInterfaces().getFirst().getIpv4Prefixes());
manager.stopCluster(cluster);
verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.224/28");
verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.208/28");
// Kept with the cluster, as its address is, for the next start to reserve.
assertEquals(List.of("10.0.1.224/28", "10.0.1.208/28"), cluster.getNodePodPrefixes());
}
@Test
void aRestartReservesTheNodesPrefixesAndLeasesOnlyTheOnesItLost() {
when(config.services().eks().vpcPodNetwork()).thenReturn(true);
when(config.services().eks().vpcPodPrefixes()).thenReturn(2);
when(lifecycleManager.findByName("floci-eks-recreated")).thenReturn(Optional.empty());
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
when(lifecycleManager.create(any())).thenReturn("cid-recreated");
when(lifecycleManager.startCreated(eq("cid-recreated"), any()))
.thenReturn(new ContainerInfo("cid-recreated", Map.of()));
when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-1", "10.0.1.25")).thenReturn(true);
when(ec2Service.reserveVpcPrefixes("000000000000", "us-east-1", "subnet-1",
List.of("10.0.1.224/28", "10.0.1.208/28"))).thenReturn(List.of("10.0.1.224/28"));
when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 1))
.thenReturn(List.of("10.0.1.192/28"));
Cluster cluster = vpcCluster("recreated", "vpc-1", List.of("subnet-1"));
cluster.setNodePrivateIp("10.0.1.25");
cluster.setNodePodPrefixes(List.of("10.0.1.224/28", "10.0.1.208/28"));
manager.restoreCluster(cluster);
assertEquals(List.of("10.0.1.224/28", "10.0.1.192/28"), cluster.getNodePodPrefixes());
}
@Test
void anAdoptedNodeKeepsThePrefixesItCanReserveAndLeasesNoOthers() {
when(config.services().eks().vpcPodNetwork()).thenReturn(true);
when(config.services().eks().vpcPodPrefixes()).thenReturn(2);
when(lifecycleManager.findByName("floci-eks-survivor"))
.thenReturn(Optional.of(survivingContainer("cid-survivor")));
when(lifecycleManager.adopt(eq("cid-survivor"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-survivor", Map.of(), Map.of(6443, 6440)));
when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-1", "10.0.1.25")).thenReturn(true);
when(ec2Service.reserveVpcPrefixes("000000000000", "us-east-1", "subnet-1",
List.of("10.0.1.224/28", "10.0.1.208/28"))).thenReturn(List.of("10.0.1.224/28"));
Cluster cluster = vpcCluster("survivor", "vpc-1", List.of("subnet-1"));
cluster.setNodePrivateIp("10.0.1.25");
cluster.setNodePodPrefixes(List.of("10.0.1.224/28", "10.0.1.208/28"));
manager.restoreCluster(cluster);
// Its pods keep the addresses it handed out; a prefix it did not start with would not be in its config.
assertEquals(List.of("10.0.1.224/28"), cluster.getNodePodPrefixes());
verify(ec2Service, never()).allocateVpcPrefixes(anyString(), anyString(), anyString(), anyInt());
}
@Test
void aContainerReplacingAnAdoptedNodeLeasesThePrefixesTheNodeLacks() {
when(config.services().eks().vpcPodNetwork()).thenReturn(true);
when(config.services().eks().vpcPodPrefixes()).thenReturn(2);
when(lifecycleManager.findByName("floci-eks-survivor"))
.thenReturn(Optional.of(survivingContainer("cid-survivor")));
when(lifecycleManager.adopt(eq("cid-survivor"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-survivor", Map.of(), Map.of(6443, 6440)));
when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-1", "10.0.1.25")).thenReturn(true);
when(ec2Service.reserveVpcPrefixes("000000000000", "us-east-1", "subnet-1", List.of("10.0.1.224/28")))
.thenReturn(List.of("10.0.1.224/28"));
when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 1))
.thenReturn(List.of("10.0.1.192/28"));
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(eq("cid-new"), any())).thenReturn(new ContainerInfo("cid-new", Map.of()));
Cluster cluster = vpcCluster("survivor", "vpc-1", List.of("subnet-1"));
cluster.setDockerName("floci-eks-survivor");
cluster.setNodePrivateIp("10.0.1.25");
cluster.setNodePodPrefixes(List.of("10.0.1.224/28"));
manager.restoreCluster(cluster);
assertEquals(List.of("10.0.1.224/28"), cluster.getNodePodPrefixes());
assertTrue(manager.restartForNodeCapacity(cluster, "m5.large"));
assertEquals(List.of("10.0.1.224/28", "10.0.1.192/28"), cluster.getNodePodPrefixes());
verify(ec2Service, Mockito.times(1)).reserveVpcPrefixes(anyString(), anyString(), anyString(), anyList());
}
@Test
void withoutVpcPodNetworkANodeHoldsNoPrefixes() {
when(portAllocator.allocate(6440, 6499)).thenReturn(6440);
when(lifecycleManager.create(any())).thenReturn("cid-1");
when(lifecycleManager.startCreated(eq("cid-1"), any())).thenReturn(new ContainerInfo("cid-1", Map.of()));
when(ec2Service.allocateVpcPrivateIp("000000000000", "us-east-1", "subnet-1"))
.thenReturn(Optional.of("10.0.1.25"));
Cluster cluster = vpcCluster("plain-cluster", "vpc-1", List.of("subnet-1"));
cluster.setNodePodPrefixes(List.of("10.0.1.224/28"));
manager.startCluster(cluster);
assertNull(cluster.getNodePodPrefixes());
verify(ec2Service, never()).allocateVpcPrefixes(anyString(), anyString(), anyString(), anyInt());
verify(ec2Service, never()).reserveVpcPrefixes(anyString(), anyString(), anyString(), anyList());
}
@Test
void restoreClusterAdoptingSurvivingContainerReservesPersistedNodeIp() {
when(lifecycleManager.findByName("floci-eks-survivor"))
@@ -10,6 +10,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,6 +39,31 @@ class EksStartupValidatorTest {
assertDoesNotThrow(() -> mock.onStart(new StartupEvent()));
}
@ParameterizedTest
@ValueSource(ints = {0, -1, 17})
void aPodPrefixCountOutOfRangeIsRejectedWithTheVpcPodNetworkOn(int prefixes) {
EksStartupValidator validator = vpcPodNetworkValidator(true, prefixes);
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
() -> validator.onStart(new StartupEvent()));
assertTrue(refused.getMessage().contains("floci.services.eks.vpc-pod-prefixes"), refused.getMessage());
}
@Test
void aPodPrefixCountIsCheckedOnlyWithTheVpcPodNetworkOn() {
assertDoesNotThrow(() -> vpcPodNetworkValidator(true, 1).onStart(new StartupEvent()));
assertDoesNotThrow(() -> vpcPodNetworkValidator(true, 16).onStart(new StartupEvent()));
assertDoesNotThrow(() -> vpcPodNetworkValidator(false, 0).onStart(new StartupEvent()));
}
private static EksStartupValidator vpcPodNetworkValidator(boolean vpcPodNetwork, int prefixes) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().eks().endpointHost()).thenReturn(Optional.empty());
when(config.services().eks().enabled()).thenReturn(true);
when(config.services().eks().vpcPodNetwork()).thenReturn(vpcPodNetwork);
when(config.services().eks().vpcPodPrefixes()).thenReturn(prefixes);
return new EksStartupValidator(config);
}
private static EksStartupValidator validator(Optional<String> endpointHost) {
return validator(endpointHost, true, false);
}