mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): give pods addresses from the VPC prefixes their node holds (#9288)
Pods got k3s's flannel addresses (10.42.0.0/16), which nothing outside the node reaches, so a target group with TargetType ip, which the AWS Load Balancer Controller registers, never saw a healthy target. With floci.services.eks.vpc-pod-network, pods now take their addresses from the /28 prefixes their node holds, as the VPC CNI's prefix delegation gives them. k3s starts without flannel and its network policy controller, with the VPC's range as its cluster CIDR, and the node's entrypoint sets up the rest before k3s starts: the CNI plugins the image ships, linked where containerd looks with flannel off, a bridge holding each prefix's gateway address, host-local handing out the prefixes, proxy ARP on the interface holding the node's VPC address, as the VPC delivers a prefix's traffic to its interface, and SNAT for traffic leaving the VPC only. Inside the VPC pods keep their own addresses, so Floci's health checks and load balancers reach them. The IMDS and Pod Identity rules for pod traffic match the prefixes instead of 10.42.0.0/16. A surviving node started with another pod network, or with prefixes it no longer holds all of, is replaced on its data volume, as one with another capacity is. disable-cni, or a node without an address or prefix in a Docker-backed subnet, keeps k3s's own network, with a warning. Closes #5929
This commit is contained in:
1 parent
374b5f5c8e
commit
e82be2c5f5
12 files changed
+831
-34
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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<String, String> startedLabels() {
|
||||
ArgumentCaptor<Map<String, String>> 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<List<String>> 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<List<String>> 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<List<String>> 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<String> 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<Map<String, String>> 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<String> prefixes) {
|
||||
Mockito.clearInvocations(lifecycleManager);
|
||||
String name = "survivor-" + (++survivors);
|
||||
Map<String, String> 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);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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<Integer> 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<String> containers = new ArrayList<>();
|
||||
private final List<String> 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<String> 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<String> 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<String> 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<String> serverArgs = EksClusterManager.buildServerArgs(false, false, null, podNetwork.vpcCidr(), nodeIp);
|
||||
serverArgs.addAll(EksClusterManager.VPC_POD_NETWORK_SERVER_ARGS);
|
||||
List<String> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user