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

@@ -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);