diff --git a/docs/services/ec2.md b/docs/services/ec2.md index b14c5cc38a..5a7896a3e2 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -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/=owned`, `eks: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. 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. +- **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 the [EKS VPC pod network](eks.md#vpc-pod-network) on, the interface also lists the node's IPv4 `/28` prefixes in `ipv4PrefixSet`, whose addresses its pods hold. 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. diff --git a/docs/services/eks.md b/docs/services/eks.md index 649ccd6520..1f322b0786 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -768,31 +768,51 @@ 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_NETWORK` | `false` | Give pods addresses from IPv4 `/28` prefixes of the node's subnet, listed on its network interface, as the VPC CNI's prefix delegation does (see [VPC pod network](#vpc-pod-network)) | | `FLOCI_SERVICES_EKS_VPC_POD_PREFIXES` | `2` | How many `/28` prefixes a node holds with `FLOCI_SERVICES_EKS_VPC_POD_NETWORK` | -### VPC pod prefixes +### VPC pod network -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. +With `FLOCI_SERVICES_EKS_VPC_POD_NETWORK=true`, pods get addresses from the cluster's VPC, as the Amazon VPC CNI plugin +gives them with prefix delegation, instead of k3s's own pod network. A node holding an address in a Docker-backed subnet +leases IPv4 `/28` prefixes of that subnet, and its pods take their addresses from them. The node's interface lists the +prefixes in `ipv4PrefixSet`, on `DescribeInstances` and `DescribeNetworkInterfaces`, where the AWS Load Balancer +Controller finds the interface behind a pod address, so a target group with `TargetType ip` reaches the pods: Floci's +health checks and load balancers dial the pod addresses on the VPC's Docker network, as other instances in the VPC do. - **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 + 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`). +- **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. +- **On the node**: k3s starts without flannel and its network policy controller (the VPC CNI enforces no network + policy unless it is enabled), with the VPC's range as its cluster CIDR. A bridge, `cni0`, hands out the prefixes' + addresses, keeping the first host address of each for itself as the pods' gateway, so a prefix gives thirteen pods + their addresses. The node answers ARP for them on the VPC network, as the VPC delivers a prefix's traffic to the + interface it is delegated to, and traffic from a prefix leaving the VPC takes the node's address, as the VPC CNI's + SNAT gives it. Inside the VPC, pods keep their own addresses both ways. +- **Out of addresses**: pods beyond what the prefixes hold stay in `ContainerCreating`, as on EKS when a node runs out + of addresses. `FLOCI_SERVICES_EKS_VPC_POD_PREFIXES` gives the node more. +- **Link-local endpoints**: the rules that send pods' requests for IMDS (with `FLOCI_SERVICES_EKS_IMDS_POD_NETWORK`) and + for the Pod Identity address to Floci match the prefixes instead of `10.42.0.0/16`. +- **Changing the setting**: a node started with another pod network, or with prefixes it no longer holds all of, is + replaced on its data volume when Floci starts, as one with another capacity is. A node on k3s's network is replaced + only when its replacement would run the VPC's, so one that fell back stays as it is until its subnet has a free `/28`. + A replacement that fails leaves the node running as it was, with the prefixes it was started with. +- **Falls back to k3s's network** when `FLOCI_SERVICES_EKS_DISABLE_CNI` leaves the pod network to an external CNI, or + when the node holds no address or prefix in a Docker-backed subnet; a warning says which. On Docker Desktop for macOS + and Windows, as with any container address, the host cannot dial pod addresses; containers and Floci in a container + can. ### Kubernetes versions and network configuration diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index dbbb24178a..0d05a1b8ac 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -4315,8 +4315,9 @@ public interface EmulatorConfig { 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. + * When true, pods get addresses from IPv4 /28 prefixes of their node's subnet, which the node holds on its network + * interface, as the Amazon VPC CNI plugin's prefix delegation assigns them, instead of k3s's own pod network. A + * node needs an address in a Docker-backed subnet for it. */ @WithDefault("false") boolean vpcPodNetwork(); diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java index a03ca38920..0e30516f85 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerBuilder.java @@ -288,6 +288,15 @@ public class ContainerBuilder { return this; } + /** + * Removes the environment variable {@code key}, however many times it was added. + */ + public Builder withoutEnv(String key) { + String entry = key + "="; + this.env.removeIf(variable -> variable.startsWith(entry)); + return this; + } + /** * Sets the container command (overrides image CMD). */ diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 6239c10ccc..136ae6debe 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -539,6 +539,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab }); } + /** The IPv4 range the VPC's Docker network uses, which a substituted CIDR makes differ from the declared one. */ + public Optional effectiveVpcCidr(String accountId, String region, String vpcId) { + return vpcNetworkManager == null ? Optional.empty() + : vpcNetworkManager.effectiveVpcCidr(accountId, region, vpcId); + } + /** * 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 diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index 45a0786bca..f69262dae7 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -54,6 +54,7 @@ import io.floci.aws.services.ec2.model.LaunchTemplateData; import io.floci.aws.services.ec2.model.Placement; import io.floci.aws.services.ec2.model.RouteTable; import io.floci.aws.services.ec2.model.Tag; +import io.floci.aws.services.ec2.net.Cidr4; import io.floci.aws.services.ecr.registry.EcrRegistryManager; import io.floci.aws.services.eks.model.CertificateAuthority; import io.floci.aws.services.eks.model.Cluster; @@ -134,6 +135,13 @@ public class EksClusterManager private static final String ENDPOINT_HOST_LABEL = "io.floci.eks.endpoint-host"; /** Marks a node started behind {@link #RSHARE_ENTRYPOINT}, whose mounts are shared. */ private static final String SHARED_MOUNTS_LABEL = "io.floci.eks.shared-mounts"; + /** The pod network a node was started with: {@link #FLANNEL_POD_NETWORK}, or {@code vpc:} and its prefixes. */ + private static final String POD_NETWORK_LABEL = "io.floci.eks.pod-network"; + private static final String FLANNEL_POD_NETWORK = "flannel"; + private static final String VPC_POD_NETWORK_LABEL_PREFIX = "vpc:"; + /** The k3s arguments that leave pod addresses to the VPC pod network's bridge configuration. */ + static final List VPC_POD_NETWORK_SERVER_ARGS = List.of("--flannel-backend=none", + "--disable-network-policy", "--kube-controller-manager-arg=allocate-node-cidrs=false"); private static final Pattern HOSTNAME = Pattern.compile( "[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*"); @@ -759,6 +767,7 @@ public class EksClusterManager List previousPodPrefixes = cluster != null ? cluster.getNodePodPrefixes() : null; VpcLease vpcLease = acquireClusterVpcLease(cluster, labelAccountId, clusterRegion); String nodeIp = vpcLease != null ? vpcLease.address() : null; + VpcPodNetwork podNetwork = vpcPodNetwork(cluster, vpcLease, true); String restoredNodeIp = (previousNodeIp != null && !previousNodeIp.isBlank() && previousNodeIp.equals(nodeIp)) ? previousNodeIp : null; @@ -776,8 +785,11 @@ public class EksClusterManager config.services().eks().disableCni(), defaultStorageClass, serviceCidr, - clusterCidr, + podNetwork != null ? podNetwork.vpcCidr() : clusterCidr, nodeIp); + if (podNetwork != null) { + serverArgs.addAll(VPC_POD_NETWORK_SERVER_ARGS); + } endpointHost = endpointHost(); if (!"localhost".equals(endpointHost)) { serverArgs.add("--tls-san=" + endpointHost); @@ -829,6 +841,7 @@ public class EksClusterManager labels.put(NODE_CAPACITY_LABEL, capacityLabel(cluster, nodeLimits)); labels.put(DEFAULT_STORAGE_CLASS_LABEL, String.valueOf(defaultStorageClass)); labels.put(SHARED_MOUNTS_LABEL, "true"); + labels.put(POD_NETWORK_LABEL, podNetworkLabel(podNetwork)); if (!"localhost".equals(endpointHost)) { labels.put(ENDPOINT_HOST_LABEL, endpointHost); } @@ -921,7 +934,10 @@ public class EksClusterManager // `mount --make-rshared /` before k3s starts gives the node the same; kind's own node // image runs the same fix in its entrypoint. RSHARE_ENTRYPOINT is POSIX sh-compatible // (no bashisms): the k3s image has no bash, only busybox sh. - specBuilder.withEntrypoint(RSHARE_ENTRYPOINT); + if (podNetwork != null) { + podNetwork.env(nodeIp).forEach(specBuilder::withEnv); + } + specBuilder.withEntrypoint(podNetwork != null ? VPC_POD_NETWORK_ENTRYPOINT : RSHARE_ENTRYPOINT); specBuilder.withCmd(buildRshareWrappedCmd(serverArgs)); spec = specBuilder.build(); @@ -955,6 +971,11 @@ public class EksClusterManager throw new IllegalStateException("Failed to attach restored EKS container " + containerName + " to VPC " + vpcLease.vpcId()); } + if (podNetwork != null) { + LOG.warnv("EKS cluster {0} runs its pods on k3s''s own network: its node could not join VPC {1}", + cluster.getName(), vpcLease.vpcId()); + dropVpcPodNetwork(specBuilder, serverArgs, podNetwork, clusterCidr, nodeIp); + } releaseClusterVpcLease(cluster, resourceName); if (cluster != null) { cluster.setNodePrivateIp(null); @@ -1081,8 +1102,9 @@ public class EksClusterManager // A node started before its mounts were shared keeps private mounts, on which a CSI node plugin's // Bidirectional mounts fail: it is replaced on the same data volume, as one with another capacity is. boolean privateMounts = existingLabels == null || !"true".equals(existingLabels.get(SHARED_MOUNTS_LABEL)); + // One started with another pod network is replaced too. if (capacityChanged || privateMounts || onAnotherNetwork(existing.get()) - || !endpointHost.equals(certificateHost(existingLabels))) { + || !endpointHost.equals(certificateHost(existingLabels)) || podNetworkChanged(cluster, existingLabels)) { replaceClusterContainer(cluster, null); } } @@ -1147,8 +1169,9 @@ public class EksClusterManager int oldPort = cluster.getHostPort(); String containerName = cluster.getDockerName(); String backupName = capacityBackupName(cluster); - String oldCertificateHost = certificateHost(lifecycleManager.findByName(containerName) - .map(Container::getLabels).orElse(null)); + Map oldLabels = lifecycleManager.findByName(containerName).map(Container::getLabels).orElse(null); + String oldCertificateHost = certificateHost(oldLabels); + List oldPodPrefixes = labelPodPrefixes(startedPodNetwork(oldLabels)); DockerClient docker = lifecycleManager.getDockerClient(); try { lifecycleManager.removeIfExistsStrict(backupName, true); @@ -1178,6 +1201,7 @@ public class EksClusterManager LOG.warnv("Could not replace the k3s container of EKS cluster {0}: {1}; restoring surviving node", cluster.getName(), replacement.getMessage()); restorePreviousNodeType(cluster, previousType); + retainPodPrefixes(cluster, oldPodPrefixes); if (!renamed) { return false; } @@ -1981,6 +2005,197 @@ public class EksClusterManager "mount --make-rshared / || echo 'floci: WARN: mount --make-rshared / failed; " + "CSI drivers and an external CNI may not work' >&2; exec /bin/k3s \"$@\""); + /** + * {@link #RSHARE_ENTRYPOINT}, preceded by the node's side of the VPC pod network, from what + * {@link VpcPodNetwork#env} sets. With flannel off, k3s leaves containerd's CNI paths at their defaults, + * {@code /opt/cni/bin} and {@code /etc/cni/net.d}, so the plugins the image ships in its {@code /bin/cni} go there + * and the bridge configuration over the node's prefixes beside them. The bridge, {@code cni0}, is created here with + * each prefix's gateway address, as the bridge plugin gives a bridge the gateway of one subnet only. The interface + * holding the node's VPC address + * answers ARP for the pods' addresses, as the VPC delivers a prefix's traffic to the interface it is delegated to, + * and traffic from a prefix leaving the VPC takes the node's address, as the VPC CNI's SNAT gives it. It runs on + * every start of the container, whose network namespace a restart rebuilds. + */ + static final List VPC_POD_NETWORK_ENTRYPOINT = List.of("sh", "-c", String.join("\n", + "mkdir -p /opt/cni/bin /etc/cni/net.d", + "for plugin in bridge host-local loopback portmap; do ln -sf /bin/cni /opt/cni/bin/$plugin; done", + "printf '%s' \"$FLOCI_POD_CNI_CONFIG\" > /etc/cni/net.d/10-floci-vpc.conflist", + "ip link add cni0 type bridge 2>/dev/null || true", + "for gateway in $FLOCI_POD_GATEWAYS; do ip addr add \"$gateway\" dev cni0 2>/dev/null || true; done", + "ip link set cni0 up", + "iface=$(ip -o -4 addr show | awk -v ip=\"$FLOCI_NODE_IP\"" + + " '{ split($4, a, \"/\"); if (a[1] == ip) { print $2; exit } }')", + "if [ -n \"$iface\" ]; then echo 1 > \"/proc/sys/net/ipv4/conf/$iface/proxy_arp\"; else" + + " echo \"floci: WARN: no interface holds $FLOCI_NODE_IP, so pod addresses do not answer on the VPC\"" + + " >&2; fi", + "for prefix in $FLOCI_POD_PREFIXES; do", + " iptables -t nat -C POSTROUTING -s \"$prefix\" ! -d \"$FLOCI_VPC_CIDR\" -j MASQUERADE 2>/dev/null" + + " || iptables -t nat -A POSTROUTING -s \"$prefix\" ! -d \"$FLOCI_VPC_CIDR\" -j MASQUERADE", + "done", + RSHARE_ENTRYPOINT.get(2))); + + /** The VPC pod network a node runs: its VPC's range on the Docker network, and the prefixes its pods use. */ + record VpcPodNetwork(String vpcCidr, List prefixes) { + + /** What {@link #VPC_POD_NETWORK_ENTRYPOINT} reads, for a node at {@code nodeIp}. */ + Map env(String nodeIp) { + Map env = new LinkedHashMap<>(); + env.put("FLOCI_NODE_IP", nodeIp); + env.put("FLOCI_VPC_CIDR", vpcCidr); + env.put("FLOCI_POD_PREFIXES", String.join(" ", prefixes)); + env.put("FLOCI_POD_GATEWAYS", prefixes.stream().map(prefix -> podGateway(prefix) + "/" + prefixLength(prefix)) + .collect(Collectors.joining(" "))); + env.put("FLOCI_POD_CNI_CONFIG", podCniConfig(prefixes)); + return env; + } + + String label() { + return VPC_POD_NETWORK_LABEL_PREFIX + String.join(",", prefixes); + } + } + + /** + * The bridge CNI configuration over {@code prefixes}: one bridge, {@code cni0}, holding in each prefix the address + * its pods route through, which the node gives it, host-local handing out the rest of the prefixes in order, and no + * masquerade, which the node applies to traffic leaving the VPC only. + */ + static String podCniConfig(List prefixes) { + String ranges = prefixes.stream() + .map(prefix -> "{\"subnet\": \"" + prefix + "\", \"gateway\": \"" + podGateway(prefix) + "\"}") + .collect(Collectors.joining(", ")); + return "{\"cniVersion\": \"1.0.0\", \"name\": \"floci-vpc\", \"plugins\": [" + + "{\"type\": \"bridge\", \"bridge\": \"cni0\", \"isGateway\": false, \"ipMasq\": false," + + " \"hairpinMode\": true, \"ipam\": {\"type\": \"host-local\", \"ranges\": [[" + ranges + "]]," + + " \"routes\": [{\"dst\": \"0.0.0.0/0\"}]}}," + + " {\"type\": \"portmap\", \"capabilities\": {\"portMappings\": true}}]}"; + } + + /** The address the pods of {@code prefix} route through: its first host address, which the node holds. */ + static String podGateway(String prefix) { + return Cidr4.format(podPrefix(prefix).network() + 1); + } + + private static int prefixLength(String prefix) { + return podPrefix(prefix).prefix(); + } + + private static Cidr4 podPrefix(String prefix) { + return Cidr4.parse(prefix).orElseThrow(() -> new IllegalArgumentException("not a CIDR: " + prefix)); + } + + /** + * The VPC pod network a node holding {@code lease} runs, or null when it runs k3s's flannel network: the setting is + * off, {@code disable-cni} leaves the pod network to an external CNI, the node holds no address or prefix in a + * Docker-backed VPC, or the VPC has no Docker network range. {@code warn} logs why a node that asks for it does + * not get it. + */ + private VpcPodNetwork vpcPodNetwork(Cluster cluster, VpcLease lease, boolean warn) { + EmulatorConfig.EksServiceConfig eks = config.services().eks(); + if (!eks.vpcPodNetwork() || lease == null) { + return null; + } + String why = null; + Optional vpcCidr = Optional.empty(); + if (eks.disableCni()) { + why = "disable-cni leaves the pod network to an external CNI"; + } else if (cluster.getNodePodPrefixes() == null || cluster.getNodePodPrefixes().isEmpty()) { + why = "its node holds no VPC prefix"; + } else { + Ec2Service ec2 = ec2Service(); + vpcCidr = ec2 == null ? Optional.empty() : ec2.effectiveVpcCidr(lease.accountId(), lease.region(), lease.vpcId()); + if (vpcCidr.isEmpty()) { + why = "VPC " + lease.vpcId() + " has no Docker network range"; + } + } + if (why != null) { + if (warn) { + LOG.warnv("EKS cluster {0} runs its pods on k3s''s own network: {1}", cluster.getName(), why); + } + return null; + } + return new VpcPodNetwork(vpcCidr.get(), List.copyOf(cluster.getNodePodPrefixes())); + } + + private static String podNetworkLabel(VpcPodNetwork podNetwork) { + return podNetwork == null ? FLANNEL_POD_NETWORK : podNetwork.label(); + } + + /** + * Whether a surviving node runs another pod network than it should: k3s's flannel network while the VPC pod network + * is on, the VPC while it is off, or prefixes it no longer holds all of. A replacement leases the prefixes a node + * lacks. A node on k3s's network is replaced only when its replacement would run the VPC's: it leases the prefixes + * for it here, and gives them back when it cannot, so a node that falls back to k3s's network is not replaced again + * on every start. + */ + private boolean podNetworkChanged(Cluster cluster, Map existingLabels) { + String existing = startedPodNetwork(existingLabels); + VpcLease lease = resolveClusterVpcLease(cluster); + EmulatorConfig.EksServiceConfig eks = config.services().eks(); + if (!eks.vpcPodNetwork() || eks.disableCni() || lease == null) { + return !FLANNEL_POD_NETWORK.equals(existing); + } + VpcPodNetwork current = vpcPodNetwork(cluster, lease, false); + if (current == null && FLANNEL_POD_NETWORK.equals(existing)) { + leasePodPrefixes(cluster, lease, true); + if (vpcPodNetwork(cluster, lease, false) != null) { + return true; + } + retainPodPrefixes(cluster, List.of()); + return false; + } + return current == null || !current.label().equals(existing); + } + + /** The pod network a node was started with, by its label: k3s's own when it has none, as before the label. */ + private static String startedPodNetwork(Map labels) { + return labels == null ? FLANNEL_POD_NETWORK : labels.getOrDefault(POD_NETWORK_LABEL, FLANNEL_POD_NETWORK); + } + + /** The prefixes a node started with the pod network {@code label} hands out: none on k3s's own network. */ + private static List labelPodPrefixes(String label) { + return label.startsWith(VPC_POD_NETWORK_LABEL_PREFIX) + ? List.of(label.substring(VPC_POD_NETWORK_LABEL_PREFIX.length()).split(",")) : List.of(); + } + + /** + * Gives back the prefixes the node holds other than {@code kept}: a node that keeps running after its replacement + * failed hands out only the prefixes it was started with, not those leased for the replacement. + */ + private void retainPodPrefixes(Cluster cluster, List kept) { + String resourceName = clusterResourceName(cluster); + List held = clusterPodPrefixes.get(resourceName); + VpcLease lease = clusterVpcLeases.get(resourceName); + Ec2Service ec2 = ec2Service(); + if (held == null || lease == null || ec2 == null) { + return; + } + List released = held.stream().filter(prefix -> !kept.contains(prefix)).toList(); + released.forEach(prefix -> ec2.releaseVpcPrefix(lease.accountId(), lease.region(), lease.subnetId(), prefix)); + held.removeAll(released); + cluster.setNodePodPrefixes(held.isEmpty() ? null : new ArrayList<>(held)); + } + + /** Takes the VPC pod network off the spec of a node falling back to the bridge: it starts on k3s's own network. */ + private static void dropVpcPodNetwork(ContainerBuilder.Builder spec, List serverArgs, + VpcPodNetwork podNetwork, String clusterCidr, String nodeIp) { + VPC_POD_NETWORK_SERVER_ARGS.forEach(serverArgs::remove); + int cidrAt = serverArgs.indexOf("--cluster-cidr=" + podNetwork.vpcCidr()); + if (cidrAt >= 0 && clusterCidr != null && !clusterCidr.isBlank()) { + serverArgs.set(cidrAt, "--cluster-cidr=" + clusterCidr); + } else if (cidrAt >= 0) { + serverArgs.remove(cidrAt); + } + podNetwork.env(nodeIp).keySet().forEach(spec::withoutEnv); + spec.withEntrypoint(RSHARE_ENTRYPOINT); + spec.withLabels(Map.of(POD_NETWORK_LABEL, FLANNEL_POD_NETWORK)); + } + + /** Where pod traffic reaches the node from: its VPC prefixes on the VPC pod network, else k3s's pod CIDR. */ + private String podSourceCidrs(Cluster cluster) { + VpcPodNetwork podNetwork = vpcPodNetwork(cluster, resolveClusterVpcLease(cluster), false); + return podNetwork == null ? cluster.getPodCidr() : String.join(",", podNetwork.prefixes()); + } + /** * Builds the CMD to pair with {@link #RSHARE_ENTRYPOINT}: an unused $0 placeholder * followed by the real k3s server args, so the entrypoint's "$@" expands to exactly @@ -3010,7 +3225,7 @@ public class EksClusterManager } ContainerExec.Result forward = execInContainerForResult(containerId, - EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(), + EksPodNetworkRouting.buildImdsForwardCommand(podSourceCidrs(cluster), config.services().eks().imdsPodNetwork(), dockerHostResolver.resolve(), config.services().ec2().imdsPort()), 30); if (forward.exitCode() != 0) { @@ -3097,7 +3312,7 @@ public class EksClusterManager private void forwardPodIdentityAddress(Cluster cluster, String containerId) { try { ContainerExec.Result forward = execInContainerForResult(containerId, - EksPodNetworkRouting.buildPodIdentityForwardCommand(cluster.getPodCidr(), + EksPodNetworkRouting.buildPodIdentityForwardCommand(podSourceCidrs(cluster), dockerHostResolver.resolve(), config.port()), 30); if (forward.exitCode() != 0) { LOG.warnv("Could not forward the Pod Identity address for EKS cluster {0} to Floci: {1}", diff --git a/src/main/java/io/floci/aws/services/eks/EksPodNetworkRouting.java b/src/main/java/io/floci/aws/services/eks/EksPodNetworkRouting.java index 663cb906dd..d667ff5f78 100644 --- a/src/main/java/io/floci/aws/services/eks/EksPodNetworkRouting.java +++ b/src/main/java/io/floci/aws/services/eks/EksPodNetworkRouting.java @@ -91,13 +91,18 @@ public final class EksPodNetworkRouting { flociPort, hostsFile, podIdentityProbeCommand("http://" + POD_IDENTITY_ENDPOINT.ip())); } - /** {@code podCidr}, or {@link #DEFAULT_POD_CIDR} if null or blank, which must be an IPv4 CIDR. */ + /** + * {@code podCidr}, or {@link #DEFAULT_POD_CIDR} if null or blank: an IPv4 CIDR, or several separated by commas, as + * the VPC prefixes a node's pods take addresses from are, which {@code iptables -s} takes as one rule each. + */ private static String podCidrOf(String podCidr) { - String cidr = (podCidr != null && !podCidr.isBlank()) ? podCidr.trim() : DEFAULT_POD_CIDR; - if (!IPV4_CIDR.matcher(cidr).matches()) { - throw new IllegalArgumentException("podCidr must be an IPv4 CIDR: " + podCidr); + String cidrs = (podCidr != null && !podCidr.isBlank()) ? podCidr.trim() : DEFAULT_POD_CIDR; + for (String cidr : cidrs.split(",", -1)) { + if (!IPV4_CIDR.matcher(cidr).matches()) { + throw new IllegalArgumentException("podCidr must be IPv4 CIDRs separated by commas: " + podCidr); + } } - return cidr; + return cidrs; } /** diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8c23381754..7861108f25 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -969,7 +969,7 @@ 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-network: false # give pods addresses from /28 prefixes of the node's subnet, 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) diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java index 7fe9427fa8..d36b003605 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerBuilderTest.java @@ -29,6 +29,18 @@ import static org.mockito.Mockito.when; class ContainerBuilderTest { + @Test + void withoutEnvRemovesEveryEntryOfThatVariableAndNoOther() { + ContainerSpec spec = new TestFixture().builder.newContainer("alpine") + .withEnv("POD", "1") + .withEnv("POD_CIDR", "10.0.0.0/16") + .withEnv("POD", "2") + .withoutEnv("POD") + .build(); + + assertEquals(List.of("POD_CIDR=10.0.0.0/16"), spec.env()); + } + @Test void withHostDockerInternalOnLinux_omitsAutomaticAliasForPodmanDaemon() { TestFixture fixture = new TestFixture(); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 93ff0cdd83..88dc93e533 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -93,6 +93,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -480,7 +481,8 @@ class EksClusterManagerTest { "io.floci.region", "us-east-1", "io.floci.eks.node-capacity", "m5.large:unbounded", "io.floci.eks.default-storage-class", "false", - "io.floci.eks.shared-mounts", "true")); + "io.floci.eks.shared-mounts", "true", + "io.floci.eks.pod-network", "flannel")); } @ParameterizedTest @@ -587,11 +589,44 @@ class EksClusterManagerTest { } // Container's getters are final, so survivors are built from JSON instead of mocked. + @Test + void theVpcPodNetworkEntrypointSetsUpTheNodeBeforeStartingK3s() { + String script = EksClusterManager.VPC_POD_NETWORK_ENTRYPOINT.get(2); + + assertEquals(List.of("sh", "-c"), EksClusterManager.VPC_POD_NETWORK_ENTRYPOINT.subList(0, 2)); + assertTrue(script.contains("ln -sf /bin/cni /opt/cni/bin/$plugin"), script); + assertTrue(script.contains("> /etc/cni/net.d/10-floci-vpc.conflist"), script); + assertTrue(script.contains("ip addr add \"$gateway\" dev cni0"), script); + assertTrue(script.contains("echo 1 > \"/proc/sys/net/ipv4/conf/$iface/proxy_arp\""), script); + assertTrue(script.contains("-s \"$prefix\" ! -d \"$FLOCI_VPC_CIDR\" -j MASQUERADE"), script); + // It ends as every node's entrypoint does, sharing the mounts and starting k3s. + assertTrue(script.endsWith(EksClusterManager.RSHARE_ENTRYPOINT.get(2)), script); + } + + @Test + void thePodCniConfigurationGivesEachPrefixItsOwnGatewayOnTheBridge() { + // The bridge plugin gives a bridge one subnet's gateway, so the node puts each prefix's on cni0 itself. + assertEquals("{\"cniVersion\": \"1.0.0\", \"name\": \"floci-vpc\", \"plugins\": [{\"type\": \"bridge\"," + + " \"bridge\": \"cni0\", \"isGateway\": false, \"ipMasq\": false, \"hairpinMode\": true," + + " \"ipam\": {\"type\": \"host-local\", \"ranges\": [[{\"subnet\": \"10.0.1.224/28\"," + + " \"gateway\": \"10.0.1.225\"}, {\"subnet\": \"10.0.1.208/28\", \"gateway\": \"10.0.1.209\"}]]," + + " \"routes\": [{\"dst\": \"0.0.0.0/0\"}]}}, {\"type\": \"portmap\"," + + " \"capabilities\": {\"portMappings\": true}}]}", + EksClusterManager.podCniConfig(List.of("10.0.1.224/28", "10.0.1.208/28"))); + } + private static Container survivingContainer(String id) { return containerFromJson("{\"Id\":\"" + id + "\"," + "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}"); } + /** A surviving node started on the VPC pod network with {@code prefixes}. */ + private static Container survivingVpcPodNode(String id, String prefixes) { + return containerFromJson("{\"Id\":\"" + id + "\"," + + "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"," + + "\"io.floci.eks.pod-network\":\"vpc:" + prefixes + "\"}}"); + } + private static Container containerFromJson(String json) { try { return new ObjectMapper().readValue(json, Container.class); @@ -2120,6 +2155,28 @@ class EksClusterManagerTest { assertNotNull(manager.getRegisteredClusterNodeInstance(cluster)); } + @Test + void onTheVpcPodNetworkThePodRulesMatchTheNodesPrefixes() { + when(eks.imdsPodNetwork()).thenReturn(true); + when(eks.vpcPodNetwork()).thenReturn(true); + Ec2Service ec2 = Mockito.mock(Ec2Service.class); + when(ec2.effectiveVpcCidr(anyString(), anyString(), eq("vpc-1"))).thenReturn(Optional.of("10.0.0.0/16")); + manager.setEc2Service(ec2); + Cluster cluster = new Cluster(); + cluster.setName("test-cluster"); + ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig(); + vpcConfig.setVpcId("vpc-1"); + vpcConfig.setSubnetIds(List.of("subnet-1")); + cluster.setResourcesVpcConfig(vpcConfig); + cluster.setNodePrivateIp("10.0.1.25"); + cluster.setNodePodPrefixes(List.of("10.0.1.224/28", "10.0.1.208/28")); + + manager.configureLinkLocalMetadataEndpoint(cluster, "container-42"); + + assertArrayEquals(EksPodNetworkRouting.buildImdsForwardCommand("10.0.1.224/28,10.0.1.208/28", true, + "floci-host", 9169), capturedCmds.get(0)); + } + @Test void configuresPodNetworkRoutingWhenImdsPodNetworkEnabled() { when(eks.imdsPodNetwork()).thenReturn(true); @@ -5181,6 +5238,9 @@ class EksClusterManagerTest { @Nested class VpcNodePrivateIp { + /** Numbers the clusters {@link #survivorReplaced} restores, so each has its own name. */ + private int survivors; + private EmulatorConfig config; private ContainerLifecycleManager lifecycleManager; private ContainerBuilder containerBuilder; @@ -5549,16 +5609,17 @@ class EksClusterManagerTest { void anAdoptedNodeKeepsThePrefixesItCanReserveAndLeasesNoOthers() { when(config.services().eks().vpcPodNetwork()).thenReturn(true); when(config.services().eks().vpcPodPrefixes()).thenReturn(2); + when(ec2Service.effectiveVpcCidr("000000000000", "us-east-1", "vpc-1")).thenReturn(Optional.of("10.0.0.0/16")); when(lifecycleManager.findByName("floci-eks-survivor")) - .thenReturn(Optional.of(survivingContainer("cid-survivor"))); + .thenReturn(Optional.of(survivingVpcPodNode("cid-survivor", "10.0.1.224/28"))); 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")); + when(ec2Service.reserveVpcPrefixes("000000000000", "us-east-1", "subnet-1", List.of("10.0.1.224/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")); + cluster.setNodePodPrefixes(List.of("10.0.1.224/28")); manager.restoreCluster(cluster); @@ -5571,8 +5632,9 @@ class EksClusterManagerTest { void aContainerReplacingAnAdoptedNodeLeasesThePrefixesTheNodeLacks() { when(config.services().eks().vpcPodNetwork()).thenReturn(true); when(config.services().eks().vpcPodPrefixes()).thenReturn(2); + when(ec2Service.effectiveVpcCidr("000000000000", "us-east-1", "vpc-1")).thenReturn(Optional.of("10.0.0.0/16")); when(lifecycleManager.findByName("floci-eks-survivor")) - .thenReturn(Optional.of(survivingContainer("cid-survivor"))); + .thenReturn(Optional.of(survivingVpcPodNode("cid-survivor", "10.0.1.224/28"))); 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); @@ -5595,6 +5657,216 @@ class EksClusterManagerTest { verify(ec2Service, Mockito.times(1)).reserveVpcPrefixes(anyString(), anyString(), anyString(), anyList()); } + private void vpcPodNetworkOn() { + when(config.services().eks().vpcPodNetwork()).thenReturn(true); + when(config.services().eks().vpcPodPrefixes()).thenReturn(2); + when(ec2Service.effectiveVpcCidr("000000000000", "us-east-1", "vpc-1")).thenReturn(Optional.of("10.0.0.0/16")); + } + + @SuppressWarnings("unchecked") + private Map startedLabels() { + ArgumentCaptor> labels = ArgumentCaptor.forClass(Map.class); + verify(builder).withLabels(labels.capture()); + return labels.getValue(); + } + + @Test + void onTheVpcPodNetworkANodeStartsWithoutFlannelAndHandsOutItsPrefixes() { + vpcPodNetworkOn(); + 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")); + + manager.startCluster(vpcCluster("vpc-pods", "vpc-1", List.of("subnet-1"))); + + @SuppressWarnings("unchecked") + ArgumentCaptor> cmd = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(cmd.capture()); + assertTrue(cmd.getValue().containsAll(EksClusterManager.VPC_POD_NETWORK_SERVER_ARGS), cmd.getValue().toString()); + assertTrue(cmd.getValue().contains("--cluster-cidr=10.0.0.0/16"), cmd.getValue().toString()); + verify(builder).withEntrypoint(EksClusterManager.VPC_POD_NETWORK_ENTRYPOINT); + verify(builder).withEnv("FLOCI_NODE_IP", "10.0.1.25"); + verify(builder).withEnv("FLOCI_VPC_CIDR", "10.0.0.0/16"); + verify(builder).withEnv("FLOCI_POD_PREFIXES", "10.0.1.224/28 10.0.1.208/28"); + verify(builder).withEnv("FLOCI_POD_GATEWAYS", "10.0.1.225/28 10.0.1.209/28"); + verify(builder).withEnv("FLOCI_POD_CNI_CONFIG", + EksClusterManager.podCniConfig(List.of("10.0.1.224/28", "10.0.1.208/28"))); + assertEquals("vpc:10.0.1.224/28,10.0.1.208/28", startedLabels().get("io.floci.eks.pod-network")); + } + + @Test + void disableCniKeepsANodeOnK3sOwnNetworkEvenWithTheVpcPodNetworkOn() { + vpcPodNetworkOn(); + when(config.services().eks().disableCni()).thenReturn(true); + 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")); + + manager.startCluster(vpcCluster("own-cni", "vpc-1", List.of("subnet-1"))); + + verify(builder).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT); + verify(builder, never()).withEnv(eq("FLOCI_POD_PREFIXES"), anyString()); + assertEquals("flannel", startedLabels().get("io.floci.eks.pod-network")); + } + + @Test + void aNodeOnK3sOwnNetworkStartsAsBefore() { + 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())); + + manager.startCluster(vpcCluster("flannel-pods", "vpc-1", List.of("subnet-1"))); + + @SuppressWarnings("unchecked") + ArgumentCaptor> cmd = ArgumentCaptor.forClass(List.class); + verify(builder).withCmd(cmd.capture()); + assertTrue(cmd.getValue().stream().noneMatch(EksClusterManager.VPC_POD_NETWORK_SERVER_ARGS::contains)); + assertTrue(cmd.getValue().contains("--cluster-cidr=10.42.0.0/16"), cmd.getValue().toString()); + verify(builder).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT); + assertEquals("flannel", startedLabels().get("io.floci.eks.pod-network")); + } + + @Test + void aSurvivorKeepsRunningOnlyWhenItRunsThePodNetworkItShould() { + vpcPodNetworkOn(); + when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-1", "10.0.1.25")).thenReturn(true); + when(ec2Service.reserveVpcPrefixes(eq("000000000000"), eq("us-east-1"), eq("subnet-1"), anyList())) + .thenAnswer(call -> call.getArgument(3)); + + // Started with the prefixes it still holds: kept. + assertFalse(survivorReplaced("vpc:10.0.1.224/28,10.0.1.208/28", + List.of("10.0.1.224/28", "10.0.1.208/28"))); + // Started on k3s's own network while the VPC pod network is on: replaced. + assertTrue(survivorReplaced("flannel", List.of("10.0.1.224/28", "10.0.1.208/28"))); + // Started with a prefix it no longer holds: replaced. + assertTrue(survivorReplaced("vpc:10.0.1.192/28,10.0.1.208/28", List.of("10.0.1.224/28", "10.0.1.208/28"))); + when(config.services().eks().vpcPodNetwork()).thenReturn(false); + // Started on the VPC while it is off: replaced. + assertTrue(survivorReplaced("vpc:10.0.1.224/28,10.0.1.208/28", null)); + // A survivor from before the label runs k3s's network: kept. + assertFalse(survivorReplaced(null, null)); + } + + @Test + void aNodeOnK3sOwnNetworkIsReplacedOnlyWhenItsReplacementWouldRunTheVpcs() { + vpcPodNetworkOn(); + when(ec2Service.reserveVpcPrivateIp("000000000000", "us-east-1", "subnet-1", "10.0.1.25")).thenReturn(true); + when(ec2Service.reserveVpcPrefixes(eq("000000000000"), eq("us-east-1"), eq("subnet-1"), anyList())) + .thenAnswer(call -> call.getArgument(3)); + + // The setting was turned on: replaced, on the prefixes leased for it. + when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 2)) + .thenReturn(List.of("10.0.1.224/28", "10.0.1.208/28")); + assertTrue(survivorReplaced("flannel", null)); + // The subnet has no free /28, so a replacement would fall back again: kept. + when(ec2Service.allocateVpcPrefixes("000000000000", "us-east-1", "subnet-1", 2)).thenReturn(List.of()); + assertFalse(survivorReplaced("flannel", null)); + // The VPC has no Docker network range: kept, and it gives back the prefixes it holds. + when(ec2Service.effectiveVpcCidr("000000000000", "us-east-1", "vpc-1")).thenReturn(Optional.empty()); + assertFalse(survivorReplaced("flannel", List.of("10.0.1.192/28", "10.0.1.176/28"))); + verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.192/28"); + verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.176/28"); + } + + @Test + void aNodeThatFallsBackToTheBridgeStartsOnK3sOwnNetwork() { + vpcPodNetworkOn(); + 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", 2)) + .thenReturn(List.of("10.0.1.224/28", "10.0.1.208/28")); + when(ec2Service.attachContainerToVpc("000000000000", "us-east-1", "vpc-1", "subnet-1", "cid-vpc", "10.0.1.25")) + .thenReturn(Optional.empty()); + + manager.startCluster(vpcCluster("pods-fallback", "vpc-1", List.of("subnet-1"))); + + @SuppressWarnings("unchecked") + ArgumentCaptor> cmd = ArgumentCaptor.forClass(List.class); + verify(builder, Mockito.times(2)).withCmd(cmd.capture()); + assertTrue(cmd.getAllValues().getFirst().contains("--cluster-cidr=10.0.0.0/16"), cmd.getAllValues().toString()); + List bridge = cmd.getValue(); + assertTrue(bridge.contains("--cluster-cidr=10.42.0.0/16"), bridge.toString()); + assertFalse(bridge.contains("--cluster-cidr=10.0.0.0/16"), bridge.toString()); + assertTrue(EksClusterManager.VPC_POD_NETWORK_SERVER_ARGS.stream().noneMatch(bridge::contains), bridge.toString()); + InOrder order = Mockito.inOrder(builder); + order.verify(builder).withEntrypoint(EksClusterManager.VPC_POD_NETWORK_ENTRYPOINT); + order.verify(builder).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT); + for (String variable : List.of("FLOCI_NODE_IP", "FLOCI_VPC_CIDR", "FLOCI_POD_PREFIXES", "FLOCI_POD_GATEWAYS", + "FLOCI_POD_CNI_CONFIG")) { + verify(builder).withoutEnv(variable); + } + @SuppressWarnings("unchecked") + ArgumentCaptor> labels = ArgumentCaptor.forClass(Map.class); + verify(builder, Mockito.times(2)).withLabels(labels.capture()); + assertEquals("flannel", labels.getValue().get("io.floci.eks.pod-network")); + } + + @Test + void aFailedReplacementGivesBackThePrefixesLeasedForItAndTheSurvivorKeepsItsOwn() { + vpcPodNetworkOn(); + when(lifecycleManager.findByName("floci-eks-survivor")) + .thenReturn(Optional.of(survivingVpcPodNode("cid-survivor", "10.0.1.224/28"))); + 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())).thenThrow(new RuntimeException("replacement failed")); + 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); + + assertFalse(manager.restartForNodeCapacity(cluster, "m5.large")); + + assertEquals("cid-survivor", cluster.getContainerId()); + assertEquals(List.of("10.0.1.224/28"), cluster.getNodePodPrefixes()); + verify(ec2Service).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.192/28"); + verify(ec2Service, never()).releaseVpcPrefix("000000000000", "us-east-1", "subnet-1", "10.0.1.224/28"); + } + + /** Restores a cluster whose surviving node carries {@code podNetwork}; whether it was replaced. */ + private boolean survivorReplaced(String podNetwork, List prefixes) { + Mockito.clearInvocations(lifecycleManager); + String name = "survivor-" + (++survivors); + Map labels = new HashMap<>(survivingContainer("cid-" + name).getLabels()); + if (podNetwork != null) { + labels.put("io.floci.eks.pod-network", podNetwork); + } + Container survivor = Mockito.mock(Container.class); + when(survivor.getId()).thenReturn("cid-" + name); + when(survivor.getLabels()).thenReturn(labels); + when(lifecycleManager.findByName("floci-eks-" + name)).thenReturn(Optional.of(survivor)); + when(lifecycleManager.adopt(eq("cid-" + name), eq(List.of(6443)), any())) + .thenReturn(new ContainerInfo("cid-" + name, Map.of(), Map.of(6443, 6440))); + when(lifecycleManager.create(any())).thenReturn("cid-new-" + name); + when(lifecycleManager.startCreated(eq("cid-new-" + name), any())) + .thenReturn(new ContainerInfo("cid-new-" + name, Map.of())); + Cluster cluster = vpcCluster(name, "vpc-1", List.of("subnet-1")); + cluster.setDockerName("floci-eks-" + name); + cluster.setNodePrivateIp("10.0.1.25"); + cluster.setNodePodPrefixes(prefixes); + manager.restoreCluster(cluster); + return Mockito.mockingDetails(lifecycleManager).getInvocations().stream() + .anyMatch(invocation -> invocation.getMethod().getName().equals("create")); + } + @Test void withoutVpcPodNetworkANodeHoldsNoPrefixes() { when(portAllocator.allocate(6440, 6499)).thenReturn(6440); diff --git a/src/test/java/io/floci/aws/services/eks/EksPodNetworkRoutingTest.java b/src/test/java/io/floci/aws/services/eks/EksPodNetworkRoutingTest.java index e1d897ce5a..335d24faf2 100644 --- a/src/test/java/io/floci/aws/services/eks/EksPodNetworkRoutingTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksPodNetworkRoutingTest.java @@ -58,6 +58,18 @@ class EksPodNetworkRoutingTest { /** As {@link #RELAY_PID_FILE}, for IMDS. */ private static final Path IMDS_RELAY_PID_FILE = Path.of("/tmp/floci-imds-proxy.pid"); + @Test + void podRulesTakeSeveralSourceRangesSeparatedByCommas() { + String script = EksPodNetworkRouting.buildImdsForwardCommand("10.0.1.224/28,10.0.1.208/28", true, + "10.0.0.5", 9169)[2]; + + assertTrue(script.contains("-s 10.0.1.224/28,10.0.1.208/28 "), script); + assertThrows(IllegalArgumentException.class, () -> + EksPodNetworkRouting.buildImdsForwardCommand("10.0.1.224/28,bogus", true, "10.0.0.5", 9169)); + assertThrows(IllegalArgumentException.class, () -> + EksPodNetworkRouting.buildImdsForwardCommand("10.0.1.224/28,", true, "10.0.0.5", 9169)); + } + @Test void linkLocalEndpointValidatesInput() { assertThrows(NullPointerException.class, () -> new LinkLocalEndpoint(null, 80)); diff --git a/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java new file mode 100644 index 0000000000..cd0f5325e6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java @@ -0,0 +1,245 @@ +package io.floci.aws.services.eks; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.DockerException; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.HostConfig; +import com.github.dockerjava.api.model.Network; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.services.ec2.net.Cidr4; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.TestDockerClients; +import org.jboss.logging.Logger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A cluster node started as Floci starts one on the VPC pod network, from the same entrypoint, environment and k3s + * arguments, on a network standing in for Floci's and a second standing in for the VPC's: its pods take addresses from + * both of its prefixes, and those answer another container on the VPC network and, on Linux, this JVM, the way Floci's + * health checks and load balancers dial a {@code TargetType ip} target. It pulls k3s and busybox and runs fourteen pods, + * so it runs nightly rather than in the pull request shards. + */ +class EksVpcPodNetworkNightlyIntegrationTest { + + private static final Logger LOG = Logger.getLogger(EksVpcPodNetworkNightlyIntegrationTest.class); + private static final String LABEL = "floci.test"; + private static final String LABEL_VALUE = "eks-vpc-pod-network"; + /** Longer than a run takes, so leftovers this old belong to no run still going. */ + private static final Duration LEFTOVER_AGE = Duration.ofHours(1); + private static final String K3S_IMAGE = EksClusterManager.SUPPORTED_K8S_VERSIONS.get("1.31"); + private static final String PEER_IMAGE = "alpine:3.21"; + private static final int REPLICAS = 14; + /** Ranges for the two networks, tried in turn, since another network on the daemon may hold one. */ + private static final List SECOND_OCTETS = List.of(247, 246, 245, 244, 243, 242, 241, 240); + + /** Names this run's containers and networks, so runs sharing a daemon keep to their own. */ + private final String run = UUID.randomUUID().toString().substring(0, 8); + private DockerClient docker; + private final List containers = new ArrayList<>(); + private final List networks = new ArrayList<>(); + + @BeforeEach + void connect() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon is unavailable"); + docker = TestDockerClients.local(); + removeLeftovers(); + } + + @AfterEach + void tearDown() throws IOException { + if (docker == null) { + return; + } + try { + containers.forEach(this::removeContainerQuietly); + networks.forEach(this::removeNetworkQuietly); + } finally { + docker.close(); + } + } + + @Test + @Timeout(value = 12, unit = TimeUnit.MINUTES) + void podsTakeAddressesFromBothPrefixesAndAnswerOnTheVpcNetwork() throws Exception { + pull(K3S_IMAGE); + pull(PEER_IMAGE); + createNetwork("floci"); + Cidr4 vpc = createNetwork("vpc"); + String nodeIp = Cidr4.format(vpc.network() + 266); + List prefixes = List.of(Cidr4.format(vpc.network() + 480) + "/28", + Cidr4.format(vpc.network() + 464) + "/28"); + EksClusterManager.VpcPodNetwork podNetwork = new EksClusterManager.VpcPodNetwork(vpc.toString(), prefixes); + + String node = startNode(podNetwork, nodeIp, networks.get(0), networks.get(1)); + await().atMost(Duration.ofMinutes(4)).pollInterval(Duration.ofSeconds(3)) + .until(() -> kubectl(node, "get", "nodes", "--no-headers").contains(" Ready ")); + kubectl(node, "create", "deployment", "web", "--image=busybox:1.36", "--replicas=" + REPLICAS, "--", + "sh", "-c", "hostname > /tmp/index.html; exec httpd -f -p 8080 -h /tmp"); + await().atMost(Duration.ofMinutes(5)).pollInterval(Duration.ofSeconds(3)).until(() -> + kubectl(node, "get", "deployment", "web", "-o", "jsonpath={.status.readyReplicas}").trim() + .equals(String.valueOf(REPLICAS))); + + List podIps = Arrays.stream(kubectl(node, "get", "pods", "-l", "app=web", "-o", + "jsonpath={range .items[*]}{.status.podIP}{\"\\n\"}{end}").trim().split("\n")).toList(); + assertEquals(REPLICAS, podIps.size(), podIps.toString()); + for (String prefix : prefixes) { + assertTrue(podIps.stream().anyMatch(ip -> contains(prefix, ip)), + "no pod took an address from " + prefix + ": " + podIps); + } + assertTrue(podIps.stream().allMatch(ip -> prefixes.stream().anyMatch(prefix -> contains(prefix, ip))), + "a pod took an address outside the prefixes: " + podIps); + + String peer = startPeer(networks.get(1), Cidr4.format(vpc.network() + 532)); + HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + boolean linux = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("linux"); + for (String ip : podIps) { + ContainerExec.Result fromPeer = ContainerExec.run(docker, peer, + new String[]{"wget", "-q", "-O-", "-T", "5", "http://" + ip + ":8080/"}, 20); + assertEquals(0, fromPeer.exitCode(), ip + " from the VPC network: " + fromPeer.stderr()); + assertTrue(fromPeer.stdout().startsWith("web-"), ip + ": " + fromPeer.stdout()); + if (linux) { + // The host holds an address on the VPC network's bridge, as Floci running natively does. + HttpResponse fromHost = http.send(HttpRequest.newBuilder(URI.create("http://" + ip + ":8080/")) + .timeout(Duration.ofSeconds(5)).build(), HttpResponse.BodyHandlers.ofString()); + assertEquals(200, fromHost.statusCode(), ip + " from the host"); + } + } + } + + private void pull(String image) throws InterruptedException { + docker.pullImageCmd(image).start().awaitCompletion(5, TimeUnit.MINUTES); + } + + /** + * Creates a labelled network on the first free range of {@link #SECOND_OCTETS}; returns that range. Docker refuses a + * range another network overlaps with a 403; any other failure fails the test. + */ + private Cidr4 createNetwork(String role) { + for (int octet : SECOND_OCTETS) { + Cidr4 range = Cidr4.parse("10." + octet + ".0.0/16").orElseThrow(); + String name = name(role); + try { + docker.createNetworkCmd().withName(name).withLabels(Map.of(LABEL, LABEL_VALUE)) + .withIpam(new Network.Ipam().withConfig(new Network.Ipam.Config() + .withSubnet(range.toString()))).exec(); + networks.add(name); + return range; + } catch (DockerException refused) { + if (refused.getHttpStatus() != 403 || refused.getMessage() == null + || !refused.getMessage().contains("overlaps")) { + throw refused; + } + LOG.debugv("Range {0} is not free for the {1} network: {2}", range, role, refused.getMessage()); + } + } + Assumptions.abort("No free 10.x.0.0/16 range for the " + role + " network"); + throw new IllegalStateException("unreachable"); + } + + /** Creates the node on Floci's network, attaches it to the VPC's at {@code nodeIp}, then starts it, as Floci does. */ + private String startNode(EksClusterManager.VpcPodNetwork podNetwork, String nodeIp, String flociNetwork, + String vpcNetwork) { + List serverArgs = EksClusterManager.buildServerArgs(false, false, null, podNetwork.vpcCidr(), nodeIp); + serverArgs.addAll(EksClusterManager.VPC_POD_NETWORK_SERVER_ARGS); + List env = new ArrayList<>(List.of("K3S_KUBECONFIG_MODE=644")); + podNetwork.env(nodeIp).forEach((key, value) -> env.add(key + "=" + value)); + String id = docker.createContainerCmd(K3S_IMAGE) + .withName(name("node")) + .withLabels(Map.of(LABEL, LABEL_VALUE)) + .withEntrypoint(EksClusterManager.VPC_POD_NETWORK_ENTRYPOINT) + .withCmd(EksClusterManager.buildRshareWrappedCmd(serverArgs)) + .withEnv(env) + .withHostConfig(HostConfig.newHostConfig().withPrivileged(true).withNetworkMode(flociNetwork) + .withMemory(1536L * 1024 * 1024)) + .exec().getId(); + containers.add(id); + docker.connectToNetworkCmd().withContainerId(id).withNetworkId(vpcNetwork) + .withContainerNetwork(new ContainerNetwork().withIpamConfig( + new ContainerNetwork.Ipam().withIpv4Address(nodeIp))).exec(); + docker.startContainerCmd(id).exec(); + return id; + } + + private String startPeer(String vpcNetwork, String address) { + String id = docker.createContainerCmd(PEER_IMAGE) + .withName(name("peer")) + .withLabels(Map.of(LABEL, LABEL_VALUE)) + .withCmd("sleep", "600") + .withHostConfig(HostConfig.newHostConfig().withNetworkMode(vpcNetwork).withMemory(64L * 1024 * 1024)) + .withIpv4Address(address) + .exec().getId(); + containers.add(id); + docker.startContainerCmd(id).exec(); + return id; + } + + private String name(String role) { + return "floci-test-" + LABEL_VALUE + "-" + role + "-" + run; + } + + private String kubectl(String node, String... args) { + String[] cmd = new String[args.length + 1]; + cmd[0] = "kubectl"; + System.arraycopy(args, 0, cmd, 1, args.length); + ContainerExec.Result result = ContainerExec.run(docker, node, cmd, 30); + return result.exitCode() == 0 ? result.stdout() : ""; + } + + private static boolean contains(String prefix, String ip) { + return Cidr4.parse(prefix).orElseThrow().containsAddress(Cidr4.parse(ip + "/32").orElseThrow().network()); + } + + /** + * Containers and networks an interrupted run left, found by label: only those older than {@link #LEFTOVER_AGE}, as a + * run on the same daemon may still be using newer ones. + */ + private void removeLeftovers() { + Instant before = Instant.now().minus(LEFTOVER_AGE); + docker.listContainersCmd().withShowAll(true).withLabelFilter(Map.of(LABEL, LABEL_VALUE)).exec().stream() + .filter(container -> container.getCreated() != null + && Instant.ofEpochSecond(container.getCreated()).isBefore(before)) + .forEach(container -> removeContainerQuietly(container.getId())); + docker.listNetworksCmd().withFilter("label", List.of(LABEL + "=" + LABEL_VALUE)).exec().stream() + .filter(network -> network.getCreated() != null && network.getCreated().toInstant().isBefore(before)) + .forEach(network -> removeNetworkQuietly(network.getId())); + } + + private void removeContainerQuietly(String id) { + try { + docker.removeContainerCmd(id).withForce(true).exec(); + } catch (RuntimeException e) { + LOG.warnv("Could not remove test container {0}: {1}", id, e.getMessage()); + } + } + + private void removeNetworkQuietly(String id) { + try { + docker.removeNetworkCmd(id).exec(); + } catch (RuntimeException e) { + LOG.warnv("Could not remove test network {0}: {1}", id, e.getMessage()); + } + } +}