feat(eks): give EKS Auto Mode LoadBalancer Services of no class a Network Load Balancer (#9357)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-24 14:42:08 -04:00
1 parent 0b12f31467
commit 5b2fa9a30d
8 files changed
+323 -26

No files matched your search

+10 -2
View File
@@ -480,8 +480,16 @@ UDP and SCTP ports get no listener, as Floci's load balancers serve TCP and HTTP
NodePort, such as one with `allocateLoadBalancerNodePorts: false`, gets no load balancer.
On AWS, `eks.amazonaws.com/nlb` is the cluster's default class, so a Service that names no class gets one too. In
Floci such a Service stays with k3s's own ServiceLB, which answers it with the node's address; name the class to get
a load balancer. Ingresses (`eks.amazonaws.com/alb`) don't get one yet.
Floci it does once the cluster's node runs without k3s's own ServiceLB, which would otherwise answer it with the
node's address: a node started while load balancing is on, as one of a cluster created with it, runs without
ServiceLB. ServiceLB is a k3s server flag, so when `UpdateClusterConfig` turns load balancing on or off, Floci
replaces the cluster's node on the same data volume, to start without or with ServiceLB, and the cluster's pods
restart, as they do on AWS, where [turning it off](https://docs.aws.amazon.com/eks/latest/userguide/auto-disable.html)
terminates Auto Mode's instances. A restored node whose ServiceLB disagrees with the cluster is replaced the same way.
On a node without ServiceLB, a Service of no class with only UDP ports gets no load balancer, as Floci's load
balancers don't forward UDP. A Service of another class, such as the AWS Load Balancer Controller's
`service.k8s.aws/nlb`, is left to its controller. Ingresses
(`eks.amazonaws.com/alb`) don't get one yet.
## Node group inputs
@@ -53,9 +53,11 @@ import java.util.regex.Pattern;
* {@code service.eks.amazonaws.com/stack}, and a name hashed from the cluster's ARN and the Service, and is found
* again by both.
*
* <p>A Service with no {@code loadBalancerClass}, which Auto Mode also serves as its cluster default, stays with
* k3s's own ServiceLB here. UDP and SCTP ports get no listener, as Floci's load balancers serve TCP and HTTP only,
* and a Service with no TCP NodePort gets no load balancer.
* <p>A Service with no {@code loadBalancerClass} gets one too, as {@code eks.amazonaws.com/nlb} is then the cluster
* default, while the cluster's node runs without k3s's own ServiceLB: a node started with load balancing on does.
* A node whose load balancing was turned on after it started keeps ServiceLB, and with it those Services, until it
* is next replaced, so that no Service has two load balancers. UDP and SCTP ports get no listener, as Floci's load
* balancers serve TCP and HTTP only, and a Service with no TCP NodePort gets no load balancer.
*/
@ApplicationScoped
public class EksAutoModeLoadBalancers {
@@ -143,7 +145,7 @@ public class EksAutoModeLoadBalancers {
* Services that are gone.
*/
void reconcile(Cluster cluster, String region) {
List<NlbService> services = nlbServices(readServices(cluster));
List<NlbService> services = nlbServices(readServices(cluster), clusterManager.runsWithoutServiceLb(cluster));
Map<String, LoadBalancer> existing = loadBalancersOf(cluster, region);
Instance node = clusterManager.getRegisteredClusterNodeInstance(cluster);
for (NlbService service : services) {
@@ -165,13 +167,15 @@ public class EksAutoModeLoadBalancers {
/**
* The Services of {@code kubectl get services -A -o json} that get an Auto Mode Network Load Balancer: of type
* LoadBalancer, of its class, with a TCP port on a NodePort.
* LoadBalancer, of its class (and with {@code classless}, of no class), with a TCP port on a NodePort.
*/
static List<NlbService> nlbServices(JsonNode list) {
static List<NlbService> nlbServices(JsonNode list, boolean classless) {
List<NlbService> services = new ArrayList<>();
for (JsonNode item : list.path("items")) {
JsonNode spec = item.path("spec");
if (!"LoadBalancer".equals(spec.path("type").asText()) || !NLB_CLASS.equals(spec.path("loadBalancerClass").asText())) {
String lbClass = spec.path("loadBalancerClass").asText("");
if (!"LoadBalancer".equals(spec.path("type").asText())
|| !(NLB_CLASS.equals(lbClass) || classless && lbClass.isEmpty())) {
continue;
}
List<ServicePort> ports = new ArrayList<>();
@@ -61,6 +61,7 @@ import io.floci.aws.services.eks.model.CertificateAuthority;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.ClusterIdentity;
import io.floci.aws.services.eks.model.ClusterOidcKey;
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
import io.floci.aws.services.eks.model.LogSetup;
import io.floci.aws.services.eks.model.Nodegroup;
import io.floci.aws.services.eks.model.NodegroupStatus;
@@ -147,6 +148,8 @@ public class EksClusterManager
/** The k3s arguments that leave pod addresses to the VPC pod network's bridge configuration. */
static final List<String> VPC_POD_NETWORK_SERVER_ARGS = List.of("--flannel-backend=none",
"--disable-network-policy", "--kube-controller-manager-arg=allocate-node-cidrs=false");
/** Whether the node runs k3s's ServiceLB, which an EKS Auto Mode node with load balancing on runs without. */
static final String SERVICE_LB_LABEL = "io.floci.eks.service-lb";
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])?)*");
@@ -785,6 +788,7 @@ public class EksClusterManager
List<String> serverArgs;
String endpointHost;
boolean serviceLb = serviceLb(cluster);
ContainerBuilder.Builder specBuilder;
String webhookLocalFile = null;
SigningKeyFiles signingKeyFiles = null;
@@ -807,6 +811,9 @@ public class EksClusterManager
if (!"localhost".equals(endpointHost)) {
serverArgs.add("--tls-san=" + endpointHost);
}
if (!serviceLb) {
serverArgs.add("--disable=servicelb");
}
EksNodeCapacity.Limits nodeLimits = resolveNodeCapacity(cluster);
if (nodeLimits != null) {
@@ -859,6 +866,7 @@ public class EksClusterManager
if (registries != null) {
labels.put(REGISTRY_MIRROR_LABEL, registryMirrorLabel(registries));
}
labels.put(SERVICE_LB_LABEL, String.valueOf(serviceLb));
if (!"localhost".equals(endpointHost)) {
labels.put(ENDPOINT_HOST_LABEL, endpointHost);
}
@@ -1120,8 +1128,12 @@ 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 or registry mirror is replaced too.
if (capacityChanged || privateMounts || onAnotherNetwork(existing.get())
// One started with another pod network or registry mirror is replaced too. ServiceLB is a k3s server flag: a
// node started with it on while load balancing is on, or the reverse, is replaced too. A node from before the
// label ran ServiceLB.
boolean serviceLbChanged = serviceLb(cluster) != (existingLabels == null
|| !"false".equals(existingLabels.get(SERVICE_LB_LABEL)));
if (capacityChanged || privateMounts || serviceLbChanged || onAnotherNetwork(existing.get())
|| !endpointHost.equals(certificateHost(existingLabels)) || podNetworkChanged(cluster, existingLabels)
|| registryMirrorChanged(cluster, existingLabels)) {
replaceClusterContainer(cluster, null);
@@ -1631,6 +1643,39 @@ public class EksClusterManager
? cluster.getNodeInstanceType() : DEFAULT_NODE_INSTANCE_TYPE;
}
/**
* Whether the cluster's node gets k3s's ServiceLB: not while EKS Auto Mode load balancing is on, which serves
* the LoadBalancer Services of no class itself, as {@code eks.amazonaws.com/nlb} is then the cluster default.
*/
static boolean serviceLb(Cluster cluster) {
return cluster == null || cluster.getKubernetesNetworkConfig() == null
|| !ElasticLoadBalancing.loadBalancingOn(cluster.getKubernetesNetworkConfig().getElasticLoadBalancing());
}
/**
* Whether the cluster's running node was started without ServiceLB, leaving the LoadBalancer Services of no
* class to EKS Auto Mode. A node whose load balancing was turned on after it started keeps ServiceLB, and with
* it those Services, until it is next replaced.
*/
public boolean runsWithoutServiceLb(Cluster cluster) {
return cluster.getDockerName() != null && lifecycleManager.findByName(cluster.getDockerName())
.map(Container::getLabels)
.map(labels -> "false".equals(labels.get(SERVICE_LB_LABEL)))
.orElse(false);
}
/**
* Replaces the cluster's node on its data volume when it runs ServiceLB and load balancing is on, or runs
* without it and load balancing is off, so it starts as {@link #serviceLb} says; a node that already agrees is
* kept. Answers false when the replacement failed and the old node was restored.
*/
boolean replaceNodeForServiceLb(Cluster cluster) {
if (cluster.getContainerId() == null || runsWithoutServiceLb(cluster) != serviceLb(cluster)) {
return true;
}
return replaceClusterContainer(cluster, null);
}
/** Recreate the shared node with its named data volume intact, restoring its old type on failure. */
boolean restartForNodeCapacity(Cluster cluster, String previousType) {
if (cluster.getContainerId() == null) {
@@ -1250,6 +1250,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
AutoMode nextAutoMode = request.changesAutoMode() ? requireAutoModeChange(cluster, request) : null;
// Read before the write below, which may change this very object.
boolean blockStorageWasOn = StorageConfig.blockStorageOn(cluster.getStorageConfig());
boolean loadBalancingWasOn = ElasticLoadBalancing.loadBalancingOn(
elasticLoadBalancing(cluster.getKubernetesNetworkConfig()));
Boolean finalPublicAccess = publicAccess;
Boolean finalPrivateAccess = privateAccess;
@@ -1310,6 +1312,10 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
// The running node gets the block storage provisioner, or loses it, as it would when it next starts.
clusterManager.applyBlockStorage(cluster.getContainerId(), requireClusterInRequestRegion(name));
}
if (nextAutoMode != null && ElasticLoadBalancing.loadBalancingOn(nextAutoMode.loadBalancing()) != loadBalancingWasOn
&& !config.services().eks().mock() && clusterManager != null && cluster.getContainerId() != null) {
replaceNodeForServiceLb(requireClusterInRequestRegion(name));
}
LOG.infov("Updated the configuration of EKS cluster {0}: {1}", cluster.getName(),
updates.stream().map(Update::type).toList());
return updates;
@@ -1956,6 +1962,28 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return nodeGroup;
}
/**
* Load balancing turned on or off by UpdateClusterConfig takes effect at once, as on AWS: k3s's ServiceLB is a
* server flag, so the node is replaced on its data volume to start with ServiceLB off or on, and its pods restart,
* as they do on AWS, where turning it off terminates Auto Mode's instances. The readiness poller verifies the new
* node, as it does one replaced for capacity. A replacement that fails keeps the old node, logged.
*/
private void replaceNodeForServiceLb(Cluster cluster) {
try {
if (!clusterManager.replaceNodeForServiceLb(cluster)) {
LOG.warnv("EKS cluster {0} keeps its node, which still runs ServiceLB as before, until it is replaced",
cluster.getName());
}
// Set only now, as for a capacity change: before the swap the poller would verify the old container.
cluster.setFinalizePending(true);
} catch (RuntimeException e) {
cluster.setStatus(ClusterStatus.FAILED);
LOG.errorv("EKS cluster {0} could not recover after its load balancing changed: {1}", cluster.getName(),
e.getMessage());
}
storage.put(clusterKey(cluster), cluster);
}
private void applyFirstNodeGroupCapacity(String clusterName, String nodegroupName,
Cluster currentCluster, Nodegroup nodeGroup) {
String selectedType = selectedNodeInstanceType(nodeGroup);
@@ -17,6 +17,8 @@ import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.services.elbv2.model.TargetGroup;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
@@ -76,7 +78,7 @@ class EksAutoModeLoadBalancersTest {
@Test
void onlyLoadBalancerServicesOfTheAutoModeClassWithATcpNodePortGetOne() throws Exception {
List<EksAutoModeLoadBalancers.NlbService> services =
EksAutoModeLoadBalancers.nlbServices(new ObjectMapper().readTree(SERVICES));
EksAutoModeLoadBalancers.nlbServices(new ObjectMapper().readTree(SERVICES), false);
// UDP gets no listener, as Floci's load balancers serve TCP and HTTP only; a Service with no TCP NodePort
// (only UDP, or allocateLoadBalancerNodePorts false) gets no load balancer.
@@ -84,10 +86,33 @@ class EksAutoModeLoadBalancersTest {
List.of(new EksAutoModeLoadBalancers.ServicePort("TCP", 80, 31080)))), services);
}
@ParameterizedTest
@CsvSource({"true,shop/web shop/plain", "false,shop/web"})
void aServiceOfNoClassGetsOneOnlyWhileTheNodeRunsWithoutServiceLb(boolean classless, String expected)
throws Exception {
String classes = """
{"items": [
{"metadata": {"namespace": "shop", "name": "web"},
"spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
"ports": [{"protocol": "TCP", "port": 80, "nodePort": 31080}]}},
{"metadata": {"namespace": "shop", "name": "plain"},
"spec": {"type": "LoadBalancer", "ports": [{"protocol": "TCP", "port": 80, "nodePort": 32080}]}},
{"metadata": {"namespace": "shop", "name": "controller"},
"spec": {"type": "LoadBalancer", "loadBalancerClass": "service.k8s.aws/nlb",
"ports": [{"protocol": "TCP", "port": 80, "nodePort": 33080}]}}
]}""";
List<EksAutoModeLoadBalancers.NlbService> services =
EksAutoModeLoadBalancers.nlbServices(new ObjectMapper().readTree(classes), classless);
assertEquals(List.of(expected.split(" ")),
services.stream().map(EksAutoModeLoadBalancers.NlbService::stack).toList());
}
@Test
void aServiceWithoutASchemeAnnotationGetsAnInternalLoadBalancer() throws Exception {
List<EksAutoModeLoadBalancers.NlbService> services = EksAutoModeLoadBalancers.nlbServices(new ObjectMapper()
.readTree(SERVICES.replace(EksAutoModeLoadBalancers.SCHEME_ANNOTATION, "example.com/other")));
.readTree(SERVICES.replace(EksAutoModeLoadBalancers.SCHEME_ANNOTATION, "example.com/other")), false);
assertEquals("internal", services.getFirst().scheme());
}
@@ -5,6 +5,8 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
import io.floci.aws.services.eks.model.KubernetesNetworkConfig;
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.LoadBalancer;
@@ -33,7 +35,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* EKS Auto Mode load balancing on a real k3s node: a LoadBalancer Service of the {@code eks.amazonaws.com/nlb}
* class gets a Network Load Balancer with a target group on its NodePort, its DNS name is written to the
* Service's status, and the load balancer goes with the Service. The reconciler is called directly: EKS is mocked
* Service's status, and the load balancer goes with the Service; on a node started with load balancing on, a
* Service of no class gets one too, and k3s's ServiceLB doesn't take it. The reconciler is called directly: EKS is mocked
* in {@link RdsMockProfile}, which the other classes that run a real cluster use, so its interval doesn't run.
*/
@QuarkusTest
@@ -85,16 +88,7 @@ class EksAutoModeNlbDockerIntegrationTest {
@Test
void aServiceOfTheNlbClassGetsALoadBalancerOnItsNodePortWhichGoesWithIt() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
cluster = EksTestNode.cluster(ACCOUNT, "nlb-" + suffix);
RequestScopes.runAs(ACCOUNT, REGION, () -> {
String vpc = ec2.createVpc(REGION, "10.61.0.0/16", false).getVpcId();
String subnet = ec2.createSubnet(REGION, vpc, "10.61.1.0/24", "us-east-1a").getSubnetId();
ResourcesVpcConfig network = new ResourcesVpcConfig();
network.setVpcId(vpc);
network.setSubnetIds(List.of(subnet));
cluster.setResourcesVpcConfig(network);
});
cluster = clusterInAVpc("nlb-", "10.61", false);
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
node.apply("""
apiVersion: v1
@@ -141,6 +135,56 @@ class EksAutoModeNlbDockerIntegrationTest {
assertEquals("TargetGroupNotFound", gone.getErrorCode());
}
@Test
void aServiceOfNoClassGetsALoadBalancerOnANodeStartedWithLoadBalancingOn() {
cluster = clusterInAVpc("nlbd-", "10.62", true);
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
node.apply("""
apiVersion: v1
kind: Service
metadata:
name: plain
namespace: default
spec:
type: LoadBalancer
selector:
app: plain
ports:
- port: 18081
targetPort: 80
protocol: TCP""");
RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
List<LoadBalancer> created = RequestScopes.callAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName()));
assertEquals(1, created.size());
assertEquals("internal", created.getFirst().getScheme());
assertEquals(created.getFirst().getDnsName(), node.kubectlOutput("get", "service", "plain", "-n", "default",
"-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"));
// k3s's ServiceLB, which would take the Service too, doesn't run on the node.
assertEquals("", node.kubectlOutput("get", "pods", "-A", "-l", "svccontroller.k3s.cattle.io/svcname=plain",
"-o", "name"));
}
/** A cluster with a VPC and subnet of its own, with EKS Auto Mode load balancing on or not. */
private Cluster clusterInAVpc(String prefix, String cidr, boolean loadBalancing) {
Cluster created = EksTestNode.cluster(ACCOUNT, prefix + UUID.randomUUID().toString().substring(0, 8));
RequestScopes.runAs(ACCOUNT, REGION, () -> {
String vpc = ec2.createVpc(REGION, cidr + ".0.0/16", false).getVpcId();
String subnet = ec2.createSubnet(REGION, vpc, cidr + ".1.0/24", "us-east-1a").getSubnetId();
ResourcesVpcConfig network = new ResourcesVpcConfig();
network.setVpcId(vpc);
network.setSubnetIds(List.of(subnet));
created.setResourcesVpcConfig(network);
});
if (loadBalancing) {
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
network.setElasticLoadBalancing(new ElasticLoadBalancing(true));
created.setKubernetesNetworkConfig(network);
}
return created;
}
private List<LoadBalancer> loadBalancersOf(String clusterName) {
List<LoadBalancer> all = elb.describeLoadBalancers(REGION, null, null, null, null);
if (all.isEmpty()) {
@@ -60,6 +60,8 @@ import io.floci.aws.services.eks.model.CertificateAuthority;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.ClusterIdentity;
import io.floci.aws.services.eks.model.ClusterOidcKey;
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
import io.floci.aws.services.eks.model.KubernetesNetworkConfig;
import io.floci.aws.services.eks.model.LogSetup;
import io.floci.aws.services.eks.model.Logging;
import io.floci.aws.services.eks.model.Nodegroup;
@@ -78,6 +80,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
@@ -501,7 +504,8 @@ class EksClusterManagerTest {
"io.floci.eks.node-capacity", "m5.large:unbounded",
"io.floci.eks.default-storage-class", "false",
"io.floci.eks.shared-mounts", "true",
"io.floci.eks.pod-network", "flannel"));
"io.floci.eks.pod-network", "flannel",
"io.floci.eks.service-lb", "true"));
}
@ParameterizedTest
@@ -589,6 +593,39 @@ class EksClusterManagerTest {
assertFalse(manifest.contains("kind: StorageClass"), manifest);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void aNodeOfAClusterWithAutoModeLoadBalancingStartsWithoutServiceLb(boolean loadBalancing) {
EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
when(config.services().eks().defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class, Mockito.RETURNS_DEEP_STUBS);
when(lifecycleManager.create(any())).thenReturn("container-id");
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
EksClusterManager manager = EksClusterManagers.create(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, new RegionResolver("us-east-1", "000000000000"));
Cluster cluster = new Cluster();
cluster.setName("my-cluster");
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
network.setElasticLoadBalancing(new ElasticLoadBalancing(loadBalancing));
cluster.setKubernetesNetworkConfig(network);
manager.startCluster(cluster);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmd = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmd.capture());
assertEquals(loadBalancing, cmd.getValue().contains("--disable=servicelb"));
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> labels = ArgumentCaptor.forClass(Map.class);
verify(builder).withLabels(labels.capture());
assertEquals(String.valueOf(!loadBalancing), labels.getValue().get(EksClusterManager.SERVICE_LB_LABEL));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startClusterDefaultStorageClassFlag(boolean defaultStorageClass) {
@@ -735,6 +772,63 @@ class EksClusterManagerTest {
return cluster;
}
private Cluster loadBalancingCluster(boolean loadBalancing) {
Cluster cluster = cluster();
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
network.setElasticLoadBalancing(new ElasticLoadBalancing(loadBalancing));
cluster.setKubernetesNetworkConfig(network);
return cluster;
}
private Container survivorWithServiceLb(String id, String serviceLb) {
return containerFromJson("{\"Id\":\"" + id + "\",\"Labels\":{"
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\""
+ (serviceLb == null ? "" : ",\"io.floci.eks.service-lb\":\"" + serviceLb + "\"") + "}}");
}
/** A node runs ServiceLB unless load balancing is on: one started otherwise is replaced on its volume. */
@ParameterizedTest
@CsvSource(value = {"true,NULL", "true,true", "false,false"}, nullValues = "NULL")
void replacesASurvivorWhoseServiceLbDisagreesWithLoadBalancing(boolean loadBalancing, String serviceLb) {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(survivorWithServiceLb("cid-old", serviceLb)));
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
stubFreshStart("cid-new", 6440);
Cluster cluster = loadBalancingCluster(loadBalancing);
manager.restoreCluster(cluster);
assertEquals("cid-new", cluster.getContainerId());
verify(lifecycleManager, never()).removeVolume(anyString());
}
@ParameterizedTest
@CsvSource(value = {"true,false", "false,true", "false,NULL"}, nullValues = "NULL")
void keepsASurvivorWhoseServiceLbAgreesWithLoadBalancing(boolean loadBalancing, String serviceLb) {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(survivorWithServiceLb("cid-1", serviceLb)));
when(lifecycleManager.adopt(eq("cid-1"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6440)));
Cluster cluster = loadBalancingCluster(loadBalancing);
manager.restoreCluster(cluster);
assertEquals("cid-1", cluster.getContainerId());
verify(lifecycleManager, never()).create(any());
}
@ParameterizedTest
@CsvSource(value = {"false,true", "true,false", "NULL,false"}, nullValues = "NULL")
void aNodeRunsWithoutServiceLbOnlyWhenItsLabelSaysSo(String serviceLb, boolean without) {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(survivorWithServiceLb("cid-1", serviceLb)));
Cluster cluster = cluster();
cluster.setDockerName("floci-eks-demo");
assertEquals(without, manager.runsWithoutServiceLb(cluster));
}
private void stubFreshStart(String containerId, int allocatedPort) {
when(lifecycleManager.create(any())).thenReturn(containerId);
when(lifecycleManager.startCreated(any(), any()))
@@ -1155,6 +1249,43 @@ class EksClusterManagerTest {
verify(portAllocator, never()).allocate(6440, 6499);
}
/** UpdateClusterConfig's load balancing change: a node whose ServiceLB disagrees is replaced in place. */
@ParameterizedTest
@CsvSource({"true,true", "false,false"})
void aNodeWhoseServiceLbDisagreesWithLoadBalancingIsReplacedKeepingItsEndpoint(boolean loadBalancing,
String serviceLb) {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(survivorWithServiceLb("cid-old", serviceLb)));
when(lifecycleManager.create(any())).thenReturn("cid-new");
when(lifecycleManager.startCreated(any(), any())).thenReturn(new ContainerInfo("cid-new", Map.of()));
Cluster cluster = loadBalancingCluster(loadBalancing);
cluster.setDockerName("floci-eks-demo");
cluster.setContainerId("cid-old");
cluster.setHostPort(6441);
assertTrue(manager.replaceNodeForServiceLb(cluster));
assertEquals("cid-new", cluster.getContainerId());
assertEquals("https://localhost:6441", cluster.getEndpoint());
verify(dockerClient).stopContainerCmd("cid-old");
verify(lifecycleManager, never()).removeVolume(anyString());
}
@ParameterizedTest
@CsvSource({"true,false", "false,true"})
void aNodeWhoseServiceLbAgreesWithLoadBalancingIsKept(boolean loadBalancing, String serviceLb) {
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(survivorWithServiceLb("cid-1", serviceLb)));
Cluster cluster = loadBalancingCluster(loadBalancing);
cluster.setDockerName("floci-eks-demo");
cluster.setContainerId("cid-1");
assertTrue(manager.replaceNodeForServiceLb(cluster));
assertEquals("cid-1", cluster.getContainerId());
verify(lifecycleManager, never()).create(any());
}
@Test
void firstNodeGroupReplacementKeepsTheClusterEndpoint() {
when(lifecycleManager.create(any())).thenReturn("cid-new");
@@ -409,7 +409,7 @@ class EksServiceTest {
}
@Test
void turningAutoModeOnGivesTheRunningNodeBlockStorageAndAPoolChangeDoesNotReapplyIt() {
void turningAutoModeOnGivesTheRunningNodeBlockStorageAndReplacesItForLoadBalancingAndAPoolChangeDoesNeither() {
StorageBackend<String, Cluster> rawClusters = new InMemoryStorage<>();
AccountAwareStorageBackend<Cluster> clusterStore = new AccountAwareStorageBackend<>(rawClusters, null, "000000000000");
Cluster running = new Cluster();
@@ -420,6 +420,7 @@ class EksServiceTest {
running.setKubernetesNetworkConfig(new KubernetesNetworkConfig());
clusterStore.putForAccount("000000000000", EksService.clusterKey("us-east-1", "auto-running"), running);
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.replaceNodeForServiceLb(any())).thenReturn(true);
EksAddonService addons = mock(EksAddonService.class);
when(addons.recordUpdate(any(), anyString(), any(), any(), any()))
.thenReturn(new Update("u", "Successful", "AutoModeUpdate", List.of(), 0, List.of()));
@@ -439,12 +440,23 @@ class EksServiceTest {
ArgumentCaptor<Cluster> applied = ArgumentCaptor.forClass(Cluster.class);
verify(clusterManager).applyBlockStorage(eq("k3s-auto-running"), applied.capture());
assertEquals(Boolean.TRUE, applied.getValue().getStorageConfig().blockStorage().enabled());
// ServiceLB is a k3s server flag, so turning load balancing on replaces the node, which the poller verifies.
verify(clusterManager).replaceNodeForServiceLb(running);
assertTrue(running.isFinalizePending());
service.updateClusterConfig("auto-running", new UpdateClusterConfigRequest(null, null, null, null, null,
new ComputeConfig(true, List.of("general-purpose"), nodeRole),
new StorageConfig(new BlockStorage(true)), loadBalancing));
verify(clusterManager, times(1)).applyBlockStorage(anyString(), any());
verify(clusterManager, times(1)).replaceNodeForServiceLb(any());
KubernetesNetworkConfig off = new KubernetesNetworkConfig();
off.setElasticLoadBalancing(new ElasticLoadBalancing(false));
service.updateClusterConfig("auto-running", new UpdateClusterConfigRequest(null, null, null, null, null,
new ComputeConfig(false, List.of(), null), new StorageConfig(new BlockStorage(false)), off));
verify(clusterManager, times(2)).replaceNodeForServiceLb(running);
}
@Test