diff --git a/docs/services/eks.md b/docs/services/eks.md
index d7a3286bb7..810378116d 100644
--- a/docs/services/eks.md
+++ b/docs/services/eks.md
@@ -444,6 +444,45 @@ Floci records the configuration and does nothing more with it yet. It does not c
entry, install the built-in node pools, serve the EBS provisioner or create load balancers, and
`UpdateClusterConfig` refuses these members. [#8914](https://github.com/floci-io/floci/issues/8914) plans each.
+### Auto Mode load balancing for Services
+
+While a cluster has the load balancing capability on (`kubernetesNetworkConfig.elasticLoadBalancing.enabled`), a
+Service of type `LoadBalancer` whose `loadBalancerClass` is `eks.amazonaws.com/nlb` gets a Network Load Balancer in
+the cluster's subnets, as [on AWS](https://docs.aws.amazon.com/eks/latest/userguide/auto-configure-nlb.html):
+
+```yaml
+apiVersion: v1
+kind: Service
+metadata:
+ name: web
+ annotations:
+ service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing # internal when left out
+spec:
+ type: LoadBalancer
+ loadBalancerClass: eks.amazonaws.com/nlb
+ selector:
+ app: web
+ ports:
+ - port: 80
+ targetPort: 8080
+```
+
+Each TCP port gets a target group on the Service's NodePort, with the cluster's node registered by instance ID and a
+TCP health check, and a listener on the Service port. Once the node is registered, the load balancer's DNS name is
+written to the Service's `status.loadBalancer.ingress[0].hostname`. The load balancer, its listeners and target
+groups are deleted with the Service, with the cluster, and when the cluster's load balancing is turned off. Floci
+checks the cluster's Services every 10 seconds, and each check makes whatever a Service's ports are missing, so a
+port added later gets its listener and a changed NodePort its target group. The load balancers and target groups carry
+the tags Auto Mode sets, `eks:eks-cluster-name` and `service.eks.amazonaws.com/stack` (the only keys
+`AmazonEKSLoadBalancingPolicy` lets it set), and Floci takes as its own only those it named for the Service.
+
+UDP and SCTP ports get no listener, as Floci's load balancers serve TCP and HTTP only, and a Service with no TCP
+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.
+
## Node group inputs
`CreateNodegroup` accepts the full documented input set and stores every member, so `CreateNodegroup` and `DescribeNodegroup` both return exactly what was supplied.
diff --git a/src/main/java/io/floci/aws/services/eks/EksAutoModeLoadBalancers.java b/src/main/java/io/floci/aws/services/eks/EksAutoModeLoadBalancers.java
new file mode 100644
index 0000000000..44a4ef2938
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/eks/EksAutoModeLoadBalancers.java
@@ -0,0 +1,363 @@
+package io.floci.aws.services.eks;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.config.EmulatorConfig;
+import io.floci.aws.core.common.Digests;
+import io.floci.aws.core.common.RequestScopes;
+import io.floci.aws.core.common.docker.ContainerExec;
+import io.floci.aws.core.storage.AccountAwareStorageBackend;
+import io.floci.aws.services.ec2.model.Instance;
+import io.floci.aws.services.eks.model.Cluster;
+import io.floci.aws.services.eks.model.ElasticLoadBalancing;
+import io.floci.aws.services.elbv2.ElbV2Service;
+import io.floci.aws.services.elbv2.model.Action;
+import io.floci.aws.services.elbv2.model.Listener;
+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 io.quarkus.runtime.StartupEvent;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * EKS Auto Mode's load balancing capability for Services: while a cluster has it on, a Service of type
+ * LoadBalancer whose {@code loadBalancerClass} is {@code eks.amazonaws.com/nlb} gets a Network Load Balancer in the
+ * cluster's subnets, as on AWS. Each of the Service's TCP ports gets a target group on its NodePort, with the
+ * cluster's node registered by instance ID as node group target groups register it and a TCP health check, and a
+ * listener on the Service port. Once the node is registered, the load balancer's DNS name is written to the
+ * Service's {@code status.loadBalancer}. The load balancer is deleted with the Service, with the cluster, and when
+ * the cluster's load balancing is turned off.
+ *
+ *
Floci reads the cluster with {@code kubectl} in the node, so this reconciles on an interval rather than
+ * watching. It keeps no state of its own: each pass makes the load balancer, target groups, registration and
+ * listeners the Service needs, so a pass that failed halfway is finished by the next. What it made carries the
+ * cluster and the Service in the tags Auto Mode sets, {@code eks:eks-cluster-name} and
+ * {@code service.eks.amazonaws.com/stack}, and a name hashed from the cluster's ARN and the Service, and is found
+ * again by both.
+ *
+ *
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.
+ */
+@ApplicationScoped
+public class EksAutoModeLoadBalancers {
+
+ private static final Logger LOG = Logger.getLogger(EksAutoModeLoadBalancers.class);
+ static final String NLB_CLASS = "eks.amazonaws.com/nlb"; // partition-literal: a Kubernetes class name, not a host
+ /** The tag keys Auto Mode sets, the only ones {@code AmazonEKSLoadBalancingPolicy} lets it set on them. */
+ static final String CLUSTER_TAG = "eks:eks-cluster-name";
+ static final String STACK_TAG = "service.eks.amazonaws.com/stack"; // partition-literal: a tag key, not a host
+ static final String SCHEME_ANNOTATION = "service.beta.kubernetes.io/aws-load-balancer-scheme";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ /** A target group's name ends with the Service port it serves and the hash. */
+ private static final Pattern PORT_SUFFIX = Pattern.compile("-(\\d{1,5})-[0-9a-f]{10}$");
+
+ private final EksService eksService;
+ private final EksClusterManager clusterManager;
+ private final ElbV2Service elb;
+ private final EmulatorConfig config;
+ private final ScheduledExecutorService scheduler =
+ Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "eks-auto-mode-load-balancers"));
+
+ @Inject
+ public EksAutoModeLoadBalancers(EksService eksService, EksClusterManager clusterManager, ElbV2Service elb,
+ EmulatorConfig config) {
+ this.eksService = eksService;
+ this.clusterManager = clusterManager;
+ this.elb = elb;
+ this.config = config;
+ }
+
+ void onStart(@Observes StartupEvent event) {
+ // Observing the startup event creates the bean, which starts the reconciler.
+ }
+
+ @PostConstruct
+ void start() {
+ if (!config.services().eks().mock()) {
+ scheduler.scheduleAtFixedRate(this::reconcileAll, 10, 10, TimeUnit.SECONDS);
+ }
+ }
+
+ @PreDestroy
+ void stop() {
+ scheduler.shutdownNow();
+ }
+
+ void reconcileAll() {
+ for (AccountAwareStorageBackend.AccountEntry entry : eksService.runningClusters()) {
+ Cluster cluster = entry.value();
+ String region = eksService.clusterRegion(cluster);
+ try {
+ RequestScopes.runAs(entry.accountId(), region, () -> {
+ if (loadBalancingOn(cluster)) {
+ reconcile(cluster, region);
+ } else {
+ deleteLoadBalancers(cluster, region);
+ }
+ });
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "EKS Auto Mode load balancers of cluster {0} were not reconciled", cluster.getName());
+ }
+ }
+ }
+
+ private static boolean loadBalancingOn(Cluster cluster) {
+ return cluster.getKubernetesNetworkConfig() != null
+ && ElasticLoadBalancing.loadBalancingOn(cluster.getKubernetesNetworkConfig().getElasticLoadBalancing());
+ }
+
+ /** One Service port: its protocol, the port clients use and the NodePort the node serves it on. */
+ record ServicePort(String protocol, int port, int nodePort) { }
+
+ /**
+ * A Service that gets a load balancer: its namespace, name and UID, the scheme it asks for, and its TCP ports.
+ */
+ record NlbService(String namespace, String name, String uid, String scheme, List ports) {
+
+ String stack() {
+ return namespace + "/" + name;
+ }
+ }
+
+ /**
+ * Makes what each Service needs, writes its DNS name back once it can serve, and deletes the load balancers of
+ * Services that are gone.
+ */
+ void reconcile(Cluster cluster, String region) {
+ List services = nlbServices(readServices(cluster));
+ Map existing = loadBalancersOf(cluster, region);
+ Instance node = clusterManager.getRegisteredClusterNodeInstance(cluster);
+ for (NlbService service : services) {
+ LoadBalancer lb = existing.remove(service.stack());
+ if (lb == null) {
+ lb = createLoadBalancer(cluster, region, service);
+ }
+ if (ensurePorts(cluster, region, service, lb, node)) {
+ writeStatus(cluster, service, lb.getDnsName());
+ }
+ }
+ existing.forEach((stack, lb) -> delete(cluster, region, stack, lb));
+ }
+
+ /** Deletes every load balancer made for {@code cluster}'s Services, with their listeners and target groups. */
+ public void deleteLoadBalancers(Cluster cluster, String region) {
+ loadBalancersOf(cluster, region).forEach((stack, lb) -> delete(cluster, region, stack, lb));
+ }
+
+ /**
+ * 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.
+ */
+ static List nlbServices(JsonNode list) {
+ List 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())) {
+ continue;
+ }
+ List ports = new ArrayList<>();
+ for (JsonNode port : spec.path("ports")) {
+ if ("TCP".equals(port.path("protocol").asText("TCP")) && port.path("nodePort").asInt() > 0) {
+ ports.add(new ServicePort("TCP", port.path("port").asInt(), port.path("nodePort").asInt()));
+ }
+ }
+ if (ports.isEmpty()) {
+ continue;
+ }
+ JsonNode metadata = item.path("metadata");
+ services.add(new NlbService(metadata.path("namespace").asText(), metadata.path("name").asText(),
+ metadata.path("uid").asText(""), metadata.path("annotations").path(SCHEME_ANNOTATION).asText("internal"),
+ ports));
+ }
+ return services;
+ }
+
+ private JsonNode readServices(Cluster cluster) {
+ ContainerExec.Result result = clusterManager.execInContainerForResult(cluster.getContainerId(),
+ new String[]{"kubectl", "get", "services", "-A", "-o", "json"}, 15);
+ if (result.exitCode() != 0) {
+ throw new IllegalStateException("kubectl get services failed: " + result.summary());
+ }
+ try {
+ return MAPPER.readTree(result.stdout());
+ } catch (Exception e) {
+ throw new IllegalStateException("kubectl get services returned no JSON: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * The load balancers made for {@code cluster}'s Services, by the Service they were made for: network load
+ * balancers with the cluster's and a Service's tags, named as this names that Service's.
+ */
+ private Map loadBalancersOf(Cluster cluster, String region) {
+ Map found = new LinkedHashMap<>();
+ List all = elb.describeLoadBalancers(region, null, null, null, null);
+ if (all.isEmpty()) {
+ return found;
+ }
+ Map> tags = elb.describeTags(all.stream().map(LoadBalancer::getLoadBalancerArn).toList());
+ for (LoadBalancer lb : all) {
+ String stack = stackOf(cluster, tags.get(lb.getLoadBalancerArn()));
+ if (stack != null && "network".equals(lb.getType())
+ && resourceName(cluster, stack, "").equals(lb.getLoadBalancerName())) {
+ found.put(stack, lb);
+ }
+ }
+ return found;
+ }
+
+ /** The target groups made for the Service {@code stack} of {@code cluster}, by name, wherever they are attached. */
+ private Map targetGroupsOf(Cluster cluster, String region, String stack) {
+ Map found = new HashMap<>();
+ List all = elb.describeTargetGroups(region, null, null, null);
+ if (all.isEmpty()) {
+ return found;
+ }
+ Map> tags = elb.describeTags(all.stream().map(TargetGroup::getTargetGroupArn).toList());
+ for (TargetGroup group : all) {
+ Matcher port = PORT_SUFFIX.matcher(group.getTargetGroupName());
+ if (stack.equals(stackOf(cluster, tags.get(group.getTargetGroupArn()))) && port.find()
+ && resourceName(cluster, stack, "-" + port.group(1)).equals(group.getTargetGroupName())) {
+ found.put(group.getTargetGroupName(), group);
+ }
+ }
+ return found;
+ }
+
+ /** The Service, {@code namespace/name}, a resource's tags name, if they name {@code cluster}. */
+ private static String stackOf(Cluster cluster, Map tags) {
+ if (tags == null || !cluster.getName().equals(tags.get(CLUSTER_TAG))) {
+ return null;
+ }
+ String stack = tags.get(STACK_TAG);
+ return stack != null && stack.indexOf('/') > 0 ? stack : null;
+ }
+
+ private static Map tags(Cluster cluster, NlbService service) {
+ return Map.of(CLUSTER_TAG, cluster.getName(), STACK_TAG, service.stack());
+ }
+
+ private LoadBalancer createLoadBalancer(Cluster cluster, String region, NlbService service) {
+ List subnets = cluster.getResourcesVpcConfig() == null ? List.of()
+ : cluster.getResourcesVpcConfig().getSubnetIds();
+ LoadBalancer lb = elb.createLoadBalancer(region, resourceName(cluster, service.stack(), ""), service.scheme(),
+ "network", "ipv4", subnets, List.of(), tags(cluster, service));
+ LOG.infov("Created Network Load Balancer {0} for Service {1} of EKS cluster {2}",
+ lb.getLoadBalancerName(), service.stack(), cluster.getName());
+ return lb;
+ }
+
+ /**
+ * Makes each port's target group, the node's registration in it and the port's listener where missing, and
+ * removes those of ports the Service no longer has. A target group whose NodePort changed is made again, as its
+ * port can't change. Answers whether every port can serve: the node is registered.
+ */
+ private boolean ensurePorts(Cluster cluster, String region, NlbService service, LoadBalancer lb, Instance node) {
+ Map groups = targetGroupsOf(cluster, region, service.stack());
+ Map listeners = new HashMap<>();
+ elb.describeListeners(region, lb.getLoadBalancerArn(), null).forEach(l -> listeners.put(l.getPort(), l));
+ Set wanted = new HashSet<>();
+ for (ServicePort port : service.ports()) {
+ String name = resourceName(cluster, service.stack(), "-" + port.port());
+ wanted.add(name);
+ TargetGroup group = groups.get(name);
+ Listener listener = listeners.remove(port.port());
+ if (group != null && !Integer.valueOf(port.nodePort()).equals(group.getPort())) {
+ if (listener != null) {
+ elb.deleteListener(region, listener.getListenerArn());
+ listener = null;
+ }
+ elb.deleteTargetGroup(region, group.getTargetGroupArn());
+ group = null;
+ }
+ if (group == null) {
+ String vpcId = cluster.getResourcesVpcConfig() == null ? null : cluster.getResourcesVpcConfig().getVpcId();
+ group = elb.createTargetGroup(region, name, "TCP", null, port.nodePort(), vpcId, "instance", "TCP",
+ null, null, null, null, null, null, null, null, "ipv4", tags(cluster, service));
+ }
+ if (node != null && (group.getTargets() == null
+ || group.getTargets().stream().noneMatch(t -> node.getInstanceId().equals(t.getId())))) {
+ TargetDescription target = new TargetDescription();
+ target.setId(node.getInstanceId());
+ elb.registerTargets(region, group.getTargetGroupArn(), List.of(target));
+ }
+ if (listener == null) {
+ Action forward = new Action();
+ forward.setType("forward");
+ forward.setTargetGroupArn(group.getTargetGroupArn());
+ elb.createListener(region, lb.getLoadBalancerArn(), "TCP", port.port(), null, null, List.of(forward),
+ null, tags(cluster, service));
+ }
+ }
+ listeners.values().forEach(l -> elb.deleteListener(region, l.getListenerArn()));
+ groups.forEach((name, group) -> {
+ if (!wanted.contains(name)) {
+ elb.deleteTargetGroup(region, group.getTargetGroupArn());
+ }
+ });
+ return node != null;
+ }
+
+ private void delete(Cluster cluster, String region, String stack, LoadBalancer lb) {
+ elb.describeListeners(region, lb.getLoadBalancerArn(), null)
+ .forEach(listener -> elb.deleteListener(region, listener.getListenerArn()));
+ elb.deleteLoadBalancer(region, lb.getLoadBalancerArn());
+ targetGroupsOf(cluster, region, stack).values()
+ .forEach(group -> elb.deleteTargetGroup(region, group.getTargetGroupArn()));
+ LOG.infov("Deleted Network Load Balancer {0} of Service {1} of EKS cluster {2}", lb.getLoadBalancerName(),
+ stack, cluster.getName());
+ }
+
+ /**
+ * Writes the load balancer's DNS name to the Service's status, as the controller on AWS does. The patch names
+ * the Service's UID, so a Service made again under the same name meanwhile refuses it.
+ */
+ private void writeStatus(Cluster cluster, NlbService service, String dnsName) {
+ String identity = service.uid().isEmpty() ? "" : "\"metadata\":{\"uid\":\"" + service.uid() + "\"},";
+ String patch = "{" + identity + "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"" + dnsName
+ + "\"}]}}}";
+ ContainerExec.Result result = clusterManager.execInContainerForResult(cluster.getContainerId(),
+ new String[]{"kubectl", "patch", "service", service.name(), "-n", service.namespace(),
+ "--subresource=status", "--type=merge", "-p", patch}, 15);
+ if (result.exitCode() != 0) {
+ LOG.warnv("Could not write the load balancer of Service {0} to its status: {1}",
+ service.stack(), result.summary());
+ }
+ }
+
+ /**
+ * A load balancer or target group name: {@code k8s---}, within ELBv2's 32
+ * characters, the namespace and name cut so the suffix, a target group's Service port, stays whole. The hash
+ * names the cluster's ARN and the Service, so two clusters' Services of one name don't collide.
+ */
+ static String resourceName(Cluster cluster, String stack, String suffix) {
+ String hash = Digests.sha256Hex(cluster.getArn() + "/" + stack + suffix).substring(0, 10);
+ int slash = stack.indexOf('/');
+ String base = ("k8s-" + cut(stack.substring(0, slash), 7) + "-" + cut(stack.substring(slash + 1), 7))
+ .replaceAll("[^A-Za-z0-9-]", "-");
+ return (cut(base, 32 - 11 - suffix.length()) + suffix + "-" + hash).replaceAll("-+", "-");
+ }
+
+ private static String cut(String value, int max) {
+ return value.length() <= max ? value : value.substring(0, max);
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java
index 71a64d23b5..c779e49a5f 100644
--- a/src/main/java/io/floci/aws/services/eks/EksService.java
+++ b/src/main/java/io/floci/aws/services/eks/EksService.java
@@ -126,6 +126,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private final EksAccessEntryService accessEntries;
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
+ /** A field, not a constructor argument: the reconciler depends on this service, and gets its client proxy. */
+ @Inject
+ EksAutoModeLoadBalancers autoModeLoadBalancers;
private final AutoScalingService autoScaling;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
private final Map appliedClusterUserData = new ConcurrentHashMap<>();
@@ -290,6 +293,15 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
+ /**
+ * The ACTIVE clusters, in every account, that have EKS Auto Mode's load balancing capability on and a running
+ * node: the ones whose LoadBalancer Services get a load balancer.
+ */
+ List> runningClusters() {
+ return allClusterEntries().stream().filter(entry -> entry.value() != null
+ && entry.value().getStatus() == ClusterStatus.ACTIVE && entry.value().getContainerId() != null).toList();
+ }
+
private List> allClusterEntries() {
if (storage instanceof AccountAwareStorageBackend aware) {
return aware.scanAllAccountEntries(k -> true).stream().peek(entry -> {
@@ -796,7 +808,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
ElasticLoadBalancing loadBalancing) {
boolean computeEnabled = compute != null && Boolean.TRUE.equals(compute.enabled());
boolean blockStorageEnabled = StorageConfig.blockStorageOn(storage);
- boolean loadBalancingEnabled = loadBalancing != null && Boolean.TRUE.equals(loadBalancing.enabled());
+ boolean loadBalancingEnabled = ElasticLoadBalancing.loadBalancingOn(loadBalancing);
if (computeEnabled != blockStorageEnabled || computeEnabled != loadBalancingEnabled) {
throw new AwsException("InvalidParameterException", "For EKS Auto Mode, please ensure that all "
+ "required configs, including computeConfig, kubernetesNetworkConfig, and blockStorage are "
@@ -1254,7 +1266,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return List.of(true, compute.nodePools() == null ? Set.of() : Set.copyOf(compute.nodePools()),
String.valueOf(compute.nodeRoleArn()),
StorageConfig.blockStorageOn(storage),
- loadBalancing != null && Boolean.TRUE.equals(loadBalancing.enabled()));
+ ElasticLoadBalancing.loadBalancingOn(loadBalancing));
}
}
@@ -1633,6 +1645,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
endClusterNodeInstance(cluster);
deleteClusterSecurityGroup(cluster);
deleteNodeGroupAutoScalingGroups(cluster.getAccountId(), cluster);
+ deleteAutoModeLoadBalancers(cluster);
accessEntries.deleteClusterEntries(cluster);
if (podIdentityAssociations != null) {
podIdentityAssociations.deleteClusterAssociations(cluster);
@@ -1654,6 +1667,15 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
+ /** The cluster's EKS Auto Mode load balancers go with it, as the controller's go on AWS. */
+ private void deleteAutoModeLoadBalancers(Cluster cluster) {
+ if (autoModeLoadBalancers != null) {
+ String region = clusterRegion(cluster);
+ RequestScopes.runAs(cluster.getAccountId(), region,
+ () -> autoModeLoadBalancers.deleteLoadBalancers(cluster, region));
+ }
+ }
+
public Nodegroup createNodeGroup(String clusterName, CreateNodeGroupRequest request) {
Nodegroup nodegroup = new Nodegroup();
nodegroup.setNodegroupName(request.getNodegroupName());
diff --git a/src/main/java/io/floci/aws/services/eks/model/ElasticLoadBalancing.java b/src/main/java/io/floci/aws/services/eks/model/ElasticLoadBalancing.java
index 163c93c785..1d6574f9a4 100644
--- a/src/main/java/io/floci/aws/services/eks/model/ElasticLoadBalancing.java
+++ b/src/main/java/io/floci/aws/services/eks/model/ElasticLoadBalancing.java
@@ -6,4 +6,10 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
/** EKS Auto Mode's load balancing capability: whether it creates load balancers for the cluster. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
-public record ElasticLoadBalancing(Boolean enabled) {}
+public record ElasticLoadBalancing(Boolean enabled) {
+
+ /** Whether {@code loadBalancing} turns the load balancing capability on: absent, or not enabled, is off. */
+ public static boolean loadBalancingOn(ElasticLoadBalancing loadBalancing) {
+ return loadBalancing != null && Boolean.TRUE.equals(loadBalancing.enabled());
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/eks/EksAutoModeLoadBalancersTest.java b/src/test/java/io/floci/aws/services/eks/EksAutoModeLoadBalancersTest.java
new file mode 100644
index 0000000000..3817959d3d
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/eks/EksAutoModeLoadBalancersTest.java
@@ -0,0 +1,362 @@
+package io.floci.aws.services.eks;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.config.EmulatorConfig;
+import io.floci.aws.core.common.docker.ContainerExec;
+import io.floci.aws.core.storage.AccountAwareStorageBackend;
+import io.floci.aws.services.ec2.model.Instance;
+import io.floci.aws.services.eks.model.Cluster;
+import io.floci.aws.services.eks.model.ClusterStatus;
+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.Action;
+import io.floci.aws.services.elbv2.model.Listener;
+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.mockito.ArgumentCaptor;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class EksAutoModeLoadBalancersTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String SERVICES = """
+ {"items": [
+ {"metadata": {"namespace": "shop", "name": "web", "uid": "uid-web",
+ "annotations": {"service.beta.kubernetes.io/aws-load-balancer-scheme": "internet-facing"}},
+ "spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
+ "ports": [{"protocol": "TCP", "port": 80, "nodePort": 31080},
+ {"protocol": "UDP", "port": 53, "nodePort": 31053}]}},
+ {"metadata": {"namespace": "shop", "name": "klipper"},
+ "spec": {"type": "LoadBalancer", "ports": [{"protocol": "TCP", "port": 80, "nodePort": 32080}]}},
+ {"metadata": {"namespace": "shop", "name": "internal"},
+ "spec": {"type": "ClusterIP", "loadBalancerClass": "eks.amazonaws.com/nlb",
+ "ports": [{"protocol": "TCP", "port": 80}]}},
+ {"metadata": {"namespace": "shop", "name": "dns"},
+ "spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
+ "ports": [{"protocol": "UDP", "port": 53, "nodePort": 31054}]}},
+ {"metadata": {"namespace": "shop", "name": "unallocated"},
+ "spec": {"type": "LoadBalancer", "loadBalancerClass": "eks.amazonaws.com/nlb",
+ "allocateLoadBalancerNodePorts": false, "ports": [{"protocol": "TCP", "port": 80}]}}
+ ]}""";
+
+ private final EksService eksService = mock(EksService.class);
+ private final EksClusterManager clusterManager = mock(EksClusterManager.class);
+ private final ElbV2Service elb = mock(ElbV2Service.class);
+ private final EksAutoModeLoadBalancers loadBalancers = new EksAutoModeLoadBalancers(eksService, clusterManager, elb,
+ mock(EmulatorConfig.class, RETURNS_DEEP_STUBS));
+ /** What the mocked ELBv2 holds, by ARN. */
+ private final List lbs = new ArrayList<>();
+ private final List groups = new ArrayList<>();
+ private final Map> tags = new HashMap<>();
+
+ @Test
+ void onlyLoadBalancerServicesOfTheAutoModeClassWithATcpNodePortGetOne() throws Exception {
+ List services =
+ EksAutoModeLoadBalancers.nlbServices(new ObjectMapper().readTree(SERVICES));
+
+ // 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.
+ assertEquals(List.of(new EksAutoModeLoadBalancers.NlbService("shop", "web", "uid-web", "internet-facing",
+ List.of(new EksAutoModeLoadBalancers.ServicePort("TCP", 80, 31080)))), services);
+ }
+
+ @Test
+ void aServiceWithoutASchemeAnnotationGetsAnInternalLoadBalancer() throws Exception {
+ List services = EksAutoModeLoadBalancers.nlbServices(new ObjectMapper()
+ .readTree(SERVICES.replace(EksAutoModeLoadBalancers.SCHEME_ANNOTATION, "example.com/other")));
+
+ assertEquals("internal", services.getFirst().scheme());
+ }
+
+ @Test
+ void namesFitElbV2KeepTheirPortAndDifferBetweenClustersAndPorts() {
+ String stack = "a-very-long-namespace/a-very-long-service-name";
+
+ String name = EksAutoModeLoadBalancers.resourceName(cluster("prod"), stack, "");
+ String port = EksAutoModeLoadBalancers.resourceName(cluster("prod"), stack, "-65535");
+ String other = EksAutoModeLoadBalancers.resourceName(cluster("dev"), stack, "");
+
+ for (String each : List.of(name, port, other)) {
+ assertTrue(each.length() <= 32 && each.matches("[A-Za-z0-9-]+") && !each.endsWith("-"), each);
+ }
+ assertTrue(port.matches(".*-65535-[0-9a-f]{10}"), port);
+ assertNotEquals(name, port);
+ assertNotEquals(name, other);
+ }
+
+ @Test
+ void aNewServiceGetsALoadBalancerATcpTargetGroupWithItsNodeAListenerAndItsDnsName() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, SERVICES);
+ nodeIs(cluster, "i-0node");
+ holdElb();
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ Map serviceTags = Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, "prod",
+ EksAutoModeLoadBalancers.STACK_TAG, "shop/web");
+ verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeLoadBalancers.resourceName(cluster, "shop/web", "")),
+ eq("internet-facing"), eq("network"), eq("ipv4"), eq(List.of("subnet-a", "subnet-b")), eq(List.of()),
+ eq(serviceTags));
+ // A TCP health check: ELBv2's default would probe the NodePort with HTTP.
+ verify(elb).createTargetGroup(eq(REGION), eq(EksAutoModeLoadBalancers.resourceName(cluster, "shop/web", "-80")),
+ eq("TCP"), isNull(), eq(31080), eq("vpc-1"), eq("instance"), eq("TCP"), isNull(), isNull(), isNull(),
+ isNull(), isNull(), isNull(), isNull(), isNull(), eq("ipv4"), eq(serviceTags));
+ verify(elb).registerTargets(eq(REGION), eq(groups.getFirst().getTargetGroupArn()),
+ argThat(targets -> targets.size() == 1 && "i-0node".equals(targets.getFirst().getId())));
+ ArgumentCaptor> forward = ArgumentCaptor.forClass(List.class);
+ verify(elb).createListener(eq(REGION), eq("arn:lb-1"), eq("TCP"), eq(80), isNull(), isNull(),
+ forward.capture(), isNull(), eq(serviceTags));
+ assertEquals(groups.getFirst().getTargetGroupArn(), forward.getValue().getFirst().getTargetGroupArn());
+ verify(elb, never()).createListener(any(), any(), eq("UDP"), anyInt(), any(), any(), any(), any(), any());
+ verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
+ + "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"lb-1.elb.test\"}]}}}");
+ }
+
+ @Test
+ void aPassThatStoppedAfterTheLoadBalancerIsFinishedByTheNext() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, SERVICES);
+ nodeIs(cluster, "i-0node");
+ holdElb();
+ LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb, never()).createLoadBalancer(any(), any(), any(), any(), any(), any(), any(), any());
+ verify(elb).createTargetGroup(eq(REGION), anyString(), eq("TCP"), isNull(), eq(31080), any(), any(), any(),
+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
+ verify(elb).createListener(eq(REGION), eq(lb.getLoadBalancerArn()), eq("TCP"), eq(80), any(), any(), anyList(),
+ any(), any());
+ verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
+ + "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"" + lb.getDnsName() + "\"}]}}}");
+ }
+
+ @Test
+ void aServiceGetsNoAddressUntilTheNodeIsRegisteredAndTheNodeIsRegisteredOnceItIs() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, SERVICES);
+ holdElb();
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb, never()).registerTargets(any(), any(), any());
+ verify(clusterManager, never()).execInContainerForResult(any(), argThat(cmd -> "patch".equals(cmd[1])), anyInt());
+
+ nodeIs(cluster, "i-0node");
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb).registerTargets(eq(REGION), eq(groups.getFirst().getTargetGroupArn()),
+ argThat(targets -> "i-0node".equals(targets.getFirst().getId())));
+ verify(elb).createLoadBalancer(any(), any(), any(), any(), any(), any(), any(), any());
+ verifyStatus(cluster, "{\"metadata\":{\"uid\":\"uid-web\"},"
+ + "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"lb-1.elb.test\"}]}}}");
+ }
+
+ @Test
+ void aGoneServicesLoadBalancerGoesWithItsListenersAndEveryTargetGroupMadeForItAttachedOrNot() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, "{\"items\": []}");
+ holdElb();
+ LoadBalancer lb = ownLoadBalancer(cluster, "shop/gone");
+ Listener listener = new Listener();
+ listener.setListenerArn("arn:listener");
+ when(elb.describeListeners(REGION, lb.getLoadBalancerArn(), null)).thenReturn(List.of(listener));
+ // A target group whose listener was never made has no load balancer to be found through.
+ TargetGroup orphan = ownTargetGroup(cluster, "shop/gone", 8080);
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb).deleteListener(REGION, "arn:listener");
+ verify(elb).deleteLoadBalancer(REGION, lb.getLoadBalancerArn());
+ verify(elb).deleteTargetGroup(REGION, orphan.getTargetGroupArn());
+ }
+
+ @Test
+ void aLoadBalancerWithTheTagsButNotTheNameThisGivesIsLeftAlone() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, "{\"items\": []}");
+ holdElb();
+ LoadBalancer someoneElses = loadBalancer("arn:theirs", "theirs", "network", "prod", "shop/web");
+ TargetGroup theirGroup = targetGroup("arn:their-tg", "k8s-shop-web-80-0123456789", 31080, "prod", "shop/web");
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb, never()).deleteLoadBalancer(REGION, someoneElses.getLoadBalancerArn());
+ verify(elb, never()).deleteTargetGroup(REGION, theirGroup.getTargetGroupArn());
+ }
+
+ @Test
+ void anotherClustersLoadBalancerIsLeftAlone() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, "{\"items\": []}");
+ holdElb();
+ ownLoadBalancer(cluster("dev"), "shop/web");
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb, never()).deleteLoadBalancer(any(), any());
+ }
+
+ @Test
+ void aClusterWhoseLoadBalancingIsOffLosesItsLoadBalancers() {
+ Cluster cluster = cluster("prod");
+ cluster.getKubernetesNetworkConfig().setElasticLoadBalancing(new ElasticLoadBalancing(false));
+ when(eksService.runningClusters()).thenReturn(List.of(new AccountAwareStorageBackend.AccountEntry<>(
+ "000000000000", "prod", cluster)));
+ when(eksService.clusterRegion(cluster)).thenReturn(REGION);
+ holdElb();
+ LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
+
+ loadBalancers.reconcileAll();
+
+ verify(elb).deleteLoadBalancer(REGION, lb.getLoadBalancerArn());
+ verify(clusterManager, never()).execInContainerForResult(any(), any(), anyInt());
+ }
+
+ @Test
+ void aTargetGroupWhoseNodePortChangedIsMadeAgainWithItsListener() {
+ Cluster cluster = cluster("prod");
+ servicesAre(cluster, SERVICES);
+ nodeIs(cluster, "i-0node");
+ holdElb();
+ LoadBalancer lb = ownLoadBalancer(cluster, "shop/web");
+ TargetGroup stale = ownTargetGroup(cluster, "shop/web", 80);
+ stale.setPort(30999);
+ Listener listener = new Listener();
+ listener.setListenerArn("arn:listener-80");
+ listener.setPort(80);
+ when(elb.describeListeners(REGION, lb.getLoadBalancerArn(), null)).thenReturn(List.of(listener));
+
+ loadBalancers.reconcile(cluster, REGION);
+
+ verify(elb).deleteListener(REGION, "arn:listener-80");
+ verify(elb).deleteTargetGroup(REGION, stale.getTargetGroupArn());
+ verify(elb).createTargetGroup(eq(REGION), anyString(), eq("TCP"), isNull(), eq(31080), any(), any(), any(),
+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
+ verify(elb).createListener(eq(REGION), eq(lb.getLoadBalancerArn()), eq("TCP"), eq(80), any(), any(), anyList(),
+ any(), any());
+ }
+
+ /** The mocked ELBv2 lists and tags what the test and the reconciler put in it. */
+ private void holdElb() {
+ when(elb.describeLoadBalancers(REGION, null, null, null, null)).thenAnswer(inv -> List.copyOf(lbs));
+ when(elb.describeTargetGroups(REGION, null, null, null)).thenAnswer(inv -> List.copyOf(groups));
+ when(elb.describeTags(anyList())).thenAnswer(inv -> {
+ Map> found = new HashMap<>();
+ for (String arn : inv.>getArgument(0)) {
+ found.put(arn, tags.getOrDefault(arn, Map.of()));
+ }
+ return found;
+ });
+ when(elb.createLoadBalancer(anyString(), anyString(), anyString(), anyString(), anyString(), anyList(),
+ anyList(), any())).thenAnswer(inv -> {
+ Map made = inv.getArgument(7);
+ return loadBalancer("arn:lb-" + (lbs.size() + 1), inv.getArgument(1), "network",
+ made.get(EksAutoModeLoadBalancers.CLUSTER_TAG), made.get(EksAutoModeLoadBalancers.STACK_TAG));
+ });
+ when(elb.createTargetGroup(anyString(), anyString(), anyString(), any(), anyInt(), any(), anyString(), any(),
+ any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(inv -> {
+ Map made = inv.getArgument(17);
+ return targetGroup("arn:tg-" + (groups.size() + 1), inv.getArgument(1), inv.getArgument(4),
+ made.get(EksAutoModeLoadBalancers.CLUSTER_TAG), made.get(EksAutoModeLoadBalancers.STACK_TAG));
+ });
+ }
+
+ private LoadBalancer ownLoadBalancer(Cluster cluster, String stack) {
+ return loadBalancer("arn:own-" + stack, EksAutoModeLoadBalancers.resourceName(cluster, stack, ""), "network",
+ cluster.getName(), stack);
+ }
+
+ private TargetGroup ownTargetGroup(Cluster cluster, String stack, int servicePort) {
+ return targetGroup("arn:own-tg-" + stack + "-" + servicePort,
+ EksAutoModeLoadBalancers.resourceName(cluster, stack, "-" + servicePort), 31080, cluster.getName(), stack);
+ }
+
+ private LoadBalancer loadBalancer(String arn, String name, String type, String clusterName, String stack) {
+ LoadBalancer lb = new LoadBalancer();
+ lb.setLoadBalancerArn(arn);
+ lb.setLoadBalancerName(name);
+ lb.setType(type);
+ lb.setDnsName(arn.substring(arn.indexOf(':') + 1) + ".elb.test");
+ lbs.add(lb);
+ if (clusterName != null) {
+ tags.put(arn, Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
+ stack));
+ }
+ return lb;
+ }
+
+ private TargetGroup targetGroup(String arn, String name, int port, String clusterName, String stack) {
+ TargetGroup group = new TargetGroup();
+ group.setTargetGroupArn(arn);
+ group.setTargetGroupName(name);
+ group.setPort(port);
+ group.setTargets(new ArrayList());
+ groups.add(group);
+ tags.put(arn, Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
+ stack));
+ return group;
+ }
+
+ private void nodeIs(Cluster cluster, String instanceId) {
+ Instance node = new Instance();
+ node.setInstanceId(instanceId);
+ when(clusterManager.getRegisteredClusterNodeInstance(cluster)).thenReturn(node);
+ }
+
+ private void verifyStatus(Cluster cluster, String patch) {
+ verify(clusterManager).execInContainerForResult(eq(cluster.getContainerId()), argThat(cmd -> List.of(cmd).equals(
+ List.of("kubectl", "patch", "service", "web", "-n", "shop", "--subresource=status", "--type=merge", "-p",
+ patch))), anyInt());
+ }
+
+ private void servicesAre(Cluster cluster, String json) {
+ when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
+ argThat(cmd -> cmd.length > 2 && "get".equals(cmd[1])), anyInt()))
+ .thenReturn(new ContainerExec.Result(0, json, "", false));
+ when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
+ argThat(cmd -> cmd.length > 2 && "patch".equals(cmd[1])), anyInt()))
+ .thenReturn(new ContainerExec.Result(0, "patched", "", false));
+ }
+
+ private static Cluster cluster(String name) {
+ Cluster cluster = new Cluster();
+ cluster.setName(name);
+ cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/" + name);
+ cluster.setContainerId("k3s-" + name);
+ cluster.setStatus(ClusterStatus.ACTIVE);
+ ResourcesVpcConfig vpc = new ResourcesVpcConfig();
+ vpc.setSubnetIds(List.of("subnet-a", "subnet-b"));
+ vpc.setVpcId("vpc-1");
+ cluster.setResourcesVpcConfig(vpc);
+ KubernetesNetworkConfig network = new KubernetesNetworkConfig();
+ network.setElasticLoadBalancing(new ElasticLoadBalancing(true));
+ cluster.setKubernetesNetworkConfig(network);
+ return cluster;
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/eks/EksAutoModeNlbDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksAutoModeNlbDockerIntegrationTest.java
new file mode 100644
index 0000000000..767b0f42b4
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/eks/EksAutoModeNlbDockerIntegrationTest.java
@@ -0,0 +1,153 @@
+package io.floci.aws.services.eks;
+
+import com.github.dockerjava.api.DockerClient;
+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.ResourcesVpcConfig;
+import io.floci.aws.services.elbv2.ElbV2Service;
+import io.floci.aws.services.elbv2.model.LoadBalancer;
+import io.floci.aws.services.elbv2.model.TargetGroup;
+import io.floci.aws.testing.DockerAvailability;
+import io.floci.aws.testing.EksTestNode;
+import io.floci.aws.testing.RdsMockProfile;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import jakarta.inject.Inject;
+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 java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+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
+ * in {@link RdsMockProfile}, which the other classes that run a real cluster use, so its interval doesn't run.
+ */
+@QuarkusTest
+@TestProfile(RdsMockProfile.class)
+class EksAutoModeNlbDockerIntegrationTest {
+
+ private static final Logger LOG = Logger.getLogger(EksAutoModeNlbDockerIntegrationTest.class);
+ private static final String ACCOUNT = "000000000000";
+ private static final String REGION = "us-east-1";
+
+ @Inject
+ DockerClient dockerClient;
+
+ @Inject
+ EksClusterManager eksClusterManager;
+
+ @Inject
+ EksAutoModeLoadBalancers loadBalancers;
+
+ @Inject
+ ElbV2Service elb;
+
+ @Inject
+ Ec2Service ec2;
+
+ private Cluster cluster;
+
+ @BeforeEach
+ void requireDocker() {
+ boolean dockerAvailable = DockerAvailability.answers(dockerClient);
+ if (!dockerAvailable) {
+ LOG.warn("Docker daemon is not available; skipping EksAutoModeNlbDockerIntegrationTest");
+ }
+ Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for the Auto Mode NLB test");
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (cluster != null) {
+ RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName())
+ .forEach(lb -> elb.deleteLoadBalancer(REGION, lb.getLoadBalancerArn())));
+ try {
+ eksClusterManager.stopCluster(cluster);
+ } catch (Exception e) {
+ LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());
+ }
+ }
+ }
+
+ @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);
+ });
+ EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
+ node.apply("""
+ apiVersion: v1
+ kind: Service
+ metadata:
+ name: web
+ namespace: default
+ annotations:
+ service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing
+ spec:
+ type: LoadBalancer
+ loadBalancerClass: eks.amazonaws.com/nlb
+ selector:
+ app: web
+ ports:
+ - port: 18080
+ targetPort: 80
+ protocol: TCP""");
+ int nodePort = Integer.parseInt(node.kubectlOutput("get", "service", "web", "-n", "default",
+ "-o", "jsonpath={.spec.ports[0].nodePort}"));
+
+ RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
+
+ List created = RequestScopes.callAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName()));
+ assertEquals(1, created.size());
+ LoadBalancer lb = created.getFirst();
+ assertEquals("network", lb.getType());
+ assertEquals("internet-facing", lb.getScheme());
+ List groups = RequestScopes.callAs(ACCOUNT, REGION,
+ () -> elb.describeTargetGroups(REGION, lb.getLoadBalancerArn(), null, null));
+ assertEquals(1, groups.size());
+ assertEquals(nodePort, groups.getFirst().getPort());
+ assertEquals("instance", groups.getFirst().getTargetType());
+ assertEquals(lb.getDnsName(), node.kubectlOutput("get", "service", "web", "-n", "default",
+ "-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"));
+
+ node.kubectl("delete", "service", "web", "-n", "default");
+ RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
+
+ await("load balancer deleted").atMost(Duration.ofSeconds(10))
+ .until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> loadBalancersOf(cluster.getName())).isEmpty());
+ AwsException gone = assertThrows(AwsException.class, () -> RequestScopes.callAs(ACCOUNT, REGION,
+ () -> elb.describeTargetGroups(REGION, null, List.of(groups.getFirst().getTargetGroupArn()), null)));
+ assertEquals("TargetGroupNotFound", gone.getErrorCode());
+ }
+
+ private List loadBalancersOf(String clusterName) {
+ List all = elb.describeLoadBalancers(REGION, null, null, null, null);
+ if (all.isEmpty()) {
+ return List.of();
+ }
+ Map> tags = elb.describeTags(all.stream().map(LoadBalancer::getLoadBalancerArn).toList());
+ return all.stream().filter(lb -> clusterName.equals(
+ tags.getOrDefault(lb.getLoadBalancerArn(), Map.of()).get(EksAutoModeLoadBalancers.CLUSTER_TAG))).toList();
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java
index 613280f8b0..aa12d3927c 100644
--- a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java
+++ b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java
@@ -632,6 +632,18 @@ class EksServiceTest {
verify(clusterManager, never()).detachCluster(any(Cluster.class));
}
+ @Test
+ void aDeletedClustersAutoModeLoadBalancersGoWithIt() {
+ Cluster cluster = activeCluster();
+ EksService service = serviceWithCluster(cluster, mock(EksClusterManager.class), false);
+ EksAutoModeLoadBalancers loadBalancers = mock(EksAutoModeLoadBalancers.class);
+ service.autoModeLoadBalancers = loadBalancers;
+
+ service.deleteCluster("running-cluster");
+
+ verify(loadBalancers).deleteLoadBalancers(cluster, service.clusterRegion(cluster));
+ }
+
@Test
void aDeleteOverlappingOneStillInProgressIsRejectedAndCannotReviveTheCluster() {
Cluster cluster = activeCluster();
diff --git a/src/test/java/io/floci/aws/services/eks/model/ElasticLoadBalancingTest.java b/src/test/java/io/floci/aws/services/eks/model/ElasticLoadBalancingTest.java
new file mode 100644
index 0000000000..0c49d8a46a
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/eks/model/ElasticLoadBalancingTest.java
@@ -0,0 +1,17 @@
+package io.floci.aws.services.eks.model;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ElasticLoadBalancingTest {
+
+ @Test
+ void loadBalancingIsOnOnlyWhenEnabledIsTrue() {
+ assertTrue(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(true)));
+ assertFalse(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(false)));
+ assertFalse(ElasticLoadBalancing.loadBalancingOn(new ElasticLoadBalancing(null)));
+ assertFalse(ElasticLoadBalancing.loadBalancingOn(null));
+ }
+}