feat(eks): give EKS Auto Mode Ingresses of the ALB class an Application Load Balancer (#9413)

Step 7c of #8914: while a cluster has EKS Auto Mode load balancing on, an Ingress whose IngressClass names the eks.amazonaws.com/alb controller, or that names no class while such a class is the default, gets an Application Load Balancer.

- Floci installs the IngressClassParams kind (eks.amazonaws.com/v1) while load balancing is on, through the shared applyAutoModeManifest step, and removes it once it is off.
- The load balancer is named k8s-<namespace>-<name>-<hash>, with the scheme and subnets of the class's IngressClassParams, else the alb.ingress.kubernetes.io/scheme annotation and the cluster's subnets, internal by default. Ingress names hash their kind, so a Service and an Ingress of one name don't collide.
- An HTTP listener on port 80 answers a fixed 404 or forwards to the Ingress's defaultBackend. Each rule's paths become listener rules in the Load Balancer Controller's order: the rules as listed, and within each, Exact paths first, then Prefix paths longest first, then ImplementationSpecific ones.
- Target groups sit on each backend Service's TCP NodePort, with the cluster's node registered and an HTTP health check at the healthcheck-path annotation's path.
- A changed scheme replaces the load balancer, changed subnets and health-check paths are applied, and an Ingress whose class names missing IngressClassParams keeps its load balancer as it is.
- The Services reconciler's ELBv2 lookups, node registration and kubectl calls move to EksAutoModeElb and EksAutoModeKubectl, shared with Ingresses.
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-25 13:52:02 -04:00
1 parent f1c2c44883
commit 0dfa48e9fc
11 files changed
+1404 -144

No files matched your search

+60 -3
View File
@@ -454,7 +454,8 @@ Floci acts on the configuration as EKS does:
- **Block storage.** While it is on, claims of a StorageClass naming `ebs.csi.eks.amazonaws.com` are provisioned
(see [Storage classes](#storage-classes)).
- **Load balancing.** While it is on, Services get Network Load Balancers (see
[Auto Mode load balancing for Services](#auto-mode-load-balancing-for-services)).
[Auto Mode load balancing for Services](#auto-mode-load-balancing-for-services)) and Ingresses Application Load
Balancers (see [Auto Mode load balancing for Ingresses](#auto-mode-load-balancing-for-ingresses)).
Floci launches no nodes for the pools: workloads run on the cluster's k3s node.
[#8914](https://github.com/floci-io/floci/issues/8914) plans the rest.
@@ -503,8 +504,64 @@ restart, as they do on AWS, where [turning it off](https://docs.aws.amazon.com/e
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.
`service.k8s.aws/nlb`, is left to its controller.
### Auto Mode load balancing for Ingresses
While a cluster has the load balancing capability on, Floci installs the `IngressClassParams` kind
(`eks.amazonaws.com/v1`), as Auto Mode does, and an Ingress whose IngressClass names the `eks.amazonaws.com/alb`
controller, or that names no class while such a class is the default, gets an Application Load Balancer, as
[on AWS](https://docs.aws.amazon.com/eks/latest/userguide/auto-configure-alb.html). Auto Mode creates no
IngressClass; create one:
```yaml
apiVersion: eks.amazonaws.com/v1
kind: IngressClassParams
metadata:
name: alb
spec:
scheme: internet-facing # internal when left out
---
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: alb
spec:
controller: eks.amazonaws.com/alb
parameters:
apiGroup: eks.amazonaws.com
kind: IngressClassParams
name: alb
```
- **Load balancer.** Named `k8s-<namespace>-<name>-<hash>`, with the scheme and subnets (`subnets.ids`) of the class's
`IngressClassParams`, else the `alb.ingress.kubernetes.io/scheme` annotation and the cluster's subnets. As in
ELBv2, it needs two subnets in two Availability Zones; an Ingress that can't have one is logged and the others are
served. An Ingress whose class names `IngressClassParams` that aren't there is logged and its load balancer left as
it is, as the Load Balancer Controller fails it: the annotations don't stand in for the class's settings.
- **Listener and rules.** An HTTP listener on port 80, whose default answers a fixed 404 (`text/plain`), or forwards
to the Ingress's `defaultBackend`. Each path of each rule becomes a listener rule, in order: a `Prefix` path `/` is
the path pattern `/*`, as AWS makes it, another `Prefix` path `/p` is `/p` and `/p/*`, and an `Exact` path is itself;
a rule's `host` adds a host header condition. The rules are ordered as the AWS Load Balancer Controller orders them:
the Ingress's rules as listed, and within each, `Exact` paths first, then `Prefix` paths longest first, then
`ImplementationSpecific` ones as listed.
- **Target groups.** One per backend Service port, on the Service's NodePort, with the cluster's node registered by
instance ID, and an HTTP health check on the traffic port at the `alb.ingress.kubernetes.io/healthcheck-path`
annotation's path (`/` by default), every 15 seconds with a 5 second timeout.
- **Tags and status.** The tags Auto Mode sets: `eks:eks-cluster-name`, `ingress.eks.amazonaws.com/stack`
(`<namespace>/<name>`) and `ingress.eks.amazonaws.com/resource`. Once the node is registered, the load balancer's DNS
name is written to the Ingress's `status.loadBalancer.ingress[0].hostname`. Floci checks every 10 seconds, sets the
rules again when the Ingress changes, and deletes the load balancer with the Ingress, with the cluster, and when load
balancing is turned off.
Floci's load balancers reach the cluster's node, not the pods inside it, so a backend is served through its Service's
NodePort: a backend Service without one (a `ClusterIP` Service) is left out, and an Ingress whose target type is
`ip` (`IngressClassParams.targetType` or the `alb.ingress.kubernetes.io/target-type` annotation) gets no load
balancer. Only HTTP on port 80 is served: HTTPS listeners, certificates and the other `IngressClassParams` fields
are kept but not applied.
Floci's load balancers share one address, so a TCP listener needs its local port to itself
([Elastic Load Balancing](elb.md)): while a `LoadBalancer` Service of the cluster serves TCP port 80, an Ingress's
ALB is made and its address written, but its listener serves no traffic until that Service's listener is gone.
## Node group inputs
@@ -0,0 +1,130 @@
package io.floci.aws.services.eks;
import io.floci.aws.core.common.Digests;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.elbv2.ElbV2Service;
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 java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The ELBv2 resources EKS Auto Mode makes for a cluster's Services and Ingresses, found again without state of their
* own: each carries the cluster and its Kubernetes object, {@code namespace/name}, in the tags Auto Mode sets
* ({@code eks:eks-cluster-name} and a stack tag of the object's kind), and a name hashed from the cluster's ARN and
* the object. Only what has both is taken as Auto Mode's, so a load balancer that merely carries the tags is left
* alone.
*/
final class EksAutoModeElb {
static final String CLUSTER_TAG = "eks:eks-cluster-name";
/** A target group's name ends with what it serves, a port number, and the hash. */
private static final Pattern PORT_SUFFIX = Pattern.compile("-(\\d{1,5})-[0-9a-f]{10}$");
private final ElbV2Service elb;
EksAutoModeElb(ElbV2Service elb) {
this.elb = elb;
}
/**
* The load balancers of {@code type} made for {@code cluster}'s objects of {@code stackTag} and {@code kind}, by
* object.
*/
Map<String, LoadBalancer> loadBalancersOf(Cluster cluster, String region, String stackTag, String kind,
String type) {
Map<String, LoadBalancer> found = new LinkedHashMap<>();
List<LoadBalancer> all = elb.describeLoadBalancers(region, null, null, null, null);
if (all.isEmpty()) {
return found;
}
Map<String, Map<String, String>> tags = elb.describeTags(all.stream().map(LoadBalancer::getLoadBalancerArn).toList());
for (LoadBalancer lb : all) {
String stack = stackOf(cluster, tags.get(lb.getLoadBalancerArn()), stackTag);
if (stack != null && type.equals(lb.getType())
&& resourceName(cluster, kind, stack, "").equals(lb.getLoadBalancerName())) {
found.put(stack, lb);
}
}
return found;
}
/** The target groups made for the object {@code stack} of {@code cluster}, by name, wherever they are attached. */
Map<String, TargetGroup> targetGroupsOf(Cluster cluster, String region, String stackTag, String kind,
String stack) {
Map<String, TargetGroup> found = new HashMap<>();
List<TargetGroup> all = elb.describeTargetGroups(region, null, null, null);
if (all.isEmpty()) {
return found;
}
Map<String, Map<String, String>> 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()), stackTag)) && port.find()
&& resourceName(cluster, kind, stack, "-" + port.group(1)).equals(group.getTargetGroupName())) {
found.put(group.getTargetGroupName(), group);
}
}
return found;
}
/** Registers the cluster's node in {@code group} by instance ID, unless it is registered. */
void registerNode(String region, TargetGroup group, Instance node) {
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));
}
}
/** Deletes {@code lb} with its listeners, and every target group made for its object, attached or not. */
void delete(Cluster cluster, String region, String stackTag, String kind, 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, stackTag, kind, stack).values()
.forEach(group -> elb.deleteTargetGroup(region, group.getTargetGroupArn()));
}
/** The object, {@code namespace/name}, a resource's tags name, if they name {@code cluster}. */
private static String stackOf(Cluster cluster, Map<String, String> tags, String stackTag) {
if (tags == null || !cluster.getName().equals(tags.get(CLUSTER_TAG))) {
return null;
}
String stack = tags.get(stackTag);
return stack != null && stack.indexOf('/') > 0 ? stack : null;
}
/**
* A load balancer or target group name: {@code k8s-<namespace>-<name><suffix>-<hash>}, within ELBv2's 32
* characters, the namespace and name cut so the suffix, a target group's port, stays whole. The hash names the
* cluster's ARN and the object, so two clusters' objects of one name don't collide.
*/
static String resourceName(Cluster cluster, String stack, String suffix) {
return resourceName(cluster, "", stack, suffix);
}
/**
* {@link #resourceName(Cluster, String, String)} for an object of {@code kind}, which the hash names too, so a
* Service and an Ingress of one name get two names; a Service's kind is empty, which keeps its names as they were.
*/
static String resourceName(Cluster cluster, String kind, String stack, String suffix) {
String hash = Digests.sha256Hex(cluster.getArn() + "/" + kind + 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);
}
}
@@ -0,0 +1,490 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.Action;
import io.floci.aws.services.elbv2.model.AvailabilityZone;
import io.floci.aws.services.elbv2.model.Listener;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.Rule;
import io.floci.aws.services.elbv2.model.RuleCondition;
import io.floci.aws.services.elbv2.model.TargetGroup;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* EKS Auto Mode's load balancing capability for Ingresses: while a cluster has it on, an Ingress whose IngressClass
* names the {@code eks.amazonaws.com/alb} controller gets an Application Load Balancer, as on AWS (measured):
*
* <ul>
* <li>named {@code k8s-<namespace>-<name>-<hash>}, with the scheme and subnets of the class's
* {@code IngressClassParams}, else the {@code alb.ingress.kubernetes.io/scheme} annotation and the cluster's
* subnets, and {@code internal} by default;</li>
* <li>an HTTP listener on port 80 whose default answers a fixed 404 ({@code text/plain}), or forwards to the
* Ingress's default backend;</li>
* <li>a rule per host and path, in order, forwarding to a target group of the backend Service: {@code Prefix /} is
* the path pattern {@code /*}, as AWS makes it, another {@code Prefix} path {@code /p} is {@code /p} and
* {@code /p/*}, and an {@code Exact} one is itself;</li>
* <li>target groups on the Service's NodePort with the cluster's node registered, an HTTP health check on the
* traffic port at the {@code alb.ingress.kubernetes.io/healthcheck-path} annotation's path, {@code /} by default,
* every 15 seconds with a 5 second timeout;</li>
* <li>the tags Auto Mode sets, {@code eks:eks-cluster-name}, {@code ingress.eks.amazonaws.com/stack} and
* {@code ingress.eks.amazonaws.com/resource};</li>
* <li>its DNS name in the Ingress's {@code status.loadBalancer} once the node is registered.</li>
* </ul>
*
* <p>Floci's load balancers reach the node, not the pods inside it, so a backend is served through its Service's
* NodePort: an Ingress whose target type is {@code ip} gets no load balancer, and a route whose Service has no
* NodePort is left out. Only port 80 is served: HTTPS listeners and certificates aren't.
*/
final class EksAutoModeIngresses {
private static final Logger LOG = Logger.getLogger(EksAutoModeIngresses.class);
static final String ALB_CONTROLLER = "eks.amazonaws.com/alb"; // partition-literal: a Kubernetes controller name
static final String STACK_TAG = "ingress.eks.amazonaws.com/stack"; // partition-literal: a tag key, not a host
static final String RESOURCE_TAG = "ingress.eks.amazonaws.com/resource"; // partition-literal: a tag key
static final String SCHEME_ANNOTATION = "alb.ingress.kubernetes.io/scheme";
static final String TARGET_TYPE_ANNOTATION = "alb.ingress.kubernetes.io/target-type";
static final String HEALTH_CHECK_PATH_ANNOTATION = "alb.ingress.kubernetes.io/healthcheck-path";
private static final String PARAMS_GROUP = "eks.amazonaws.com"; // partition-literal: a Kubernetes API group
private static final String DEFAULT_CLASS_ANNOTATION = "ingressclass.kubernetes.io/is-default-class";
/** What Ingress names hash besides the Ingress, so a Service of the same name gets another name. */
static final String KIND = "ingress/";
private final ElbV2Service elb;
private final EksAutoModeElb resources;
private final EksAutoModeKubectl kubectl;
EksAutoModeIngresses(ElbV2Service elb, EksAutoModeElb resources, EksAutoModeKubectl kubectl) {
this.elb = elb;
this.resources = resources;
this.kubectl = kubectl;
}
/** A Service port an Ingress forwards to, and the NodePort the node serves it on. */
record Backend(String service, int port, int nodePort) {
String resource(AlbIngress ingress) {
return ingress.stack() + "-" + service + ":" + port;
}
}
/** A rule: the host it matches, if any, its path patterns, and the backend it forwards to. */
record Route(String host, List<String> paths, Backend backend) { }
/**
* An Ingress that gets an Application Load Balancer, as its class and annotations configure it. A held one's
* class names IngressClassParams that aren't there, so its load balancer is left as it is.
*/
record AlbIngress(String namespace, String name, String uid, String scheme, List<String> subnets,
String healthCheckPath, List<Route> routes, Backend defaultBackend, boolean held) {
AlbIngress(String namespace, String name, String uid, String scheme, List<String> subnets,
String healthCheckPath, List<Route> routes, Backend defaultBackend) {
this(namespace, name, uid, scheme, subnets, healthCheckPath, routes, defaultBackend, false);
}
static AlbIngress held(String namespace, String name, String uid) {
return new AlbIngress(namespace, name, uid, null, List.of(), null, List.of(), null, true);
}
String stack() {
return namespace + "/" + name;
}
/** Each backend once, the default one included. */
List<Backend> backends() {
Set<Backend> all = new LinkedHashSet<>();
routes.forEach(route -> all.add(route.backend()));
if (defaultBackend != null) {
all.add(defaultBackend);
}
return List.copyOf(all);
}
}
/** Makes and updates the load balancers of the cluster's ALB Ingresses, and deletes those of gone ones. */
void reconcile(Cluster cluster, String region, Instance node) {
JsonNode classes = kubectl.list(cluster, "ingressclasses");
boolean anyAlbClass = false;
for (JsonNode item : classes.path("items")) {
anyAlbClass |= ALB_CONTROLLER.equals(item.path("spec").path("controller").asText());
}
// Without an ALB class no Ingress gets a load balancer, so the other lists aren't read.
List<AlbIngress> ingresses = !anyAlbClass ? List.of() : albIngresses(kubectl.list(cluster, "ingresses"),
classes, ingressClassParams(cluster), kubectl.list(cluster, "services"));
Map<String, LoadBalancer> existing = resources.loadBalancersOf(cluster, region, STACK_TAG, KIND, "application");
for (AlbIngress ingress : ingresses) {
LoadBalancer lb = existing.remove(ingress.stack());
if (ingress.held()) {
continue;
}
// One Ingress ELBv2 refuses, for its subnets say, leaves the others served.
try {
if (lb != null && !ingress.scheme().equals(lb.getScheme())) {
// A load balancer's scheme can't change, so another scheme takes another load balancer.
delete(cluster, region, ingress.stack(), lb);
lb = null;
}
if (lb == null) {
lb = createLoadBalancer(cluster, region, ingress);
} else {
keepSubnets(cluster, region, ingress, lb);
}
if (ensureRouting(cluster, region, ingress, lb, node)) {
kubectl.writeHostname(cluster, "ingress", ingress.namespace(), ingress.name(), ingress.uid(),
lb.getDnsName());
}
} catch (RuntimeException e) {
LOG.warnv("Ingress {0} of EKS cluster {1} gets no load balancer: {2}", ingress.stack(),
cluster.getName(), e.getMessage());
}
}
existing.forEach((stack, lb) -> delete(cluster, region, stack, lb));
}
/**
* The cluster's IngressClassParams; none on a node started before Floci installed the kind. Any other failed read
* stops the pass, so no load balancer is made without the settings a class gives it.
*/
private JsonNode ingressClassParams(Cluster cluster) {
try {
return kubectl.list(cluster, "ingressclassparams");
} catch (IllegalStateException e) {
if (e.getMessage() != null && e.getMessage().contains("doesn't have a resource type")) {
return MissingNode.getInstance();
}
throw e;
}
}
/** Deletes every load balancer made for the cluster's Ingresses, with their listeners and target groups. */
void deleteLoadBalancers(Cluster cluster, String region) {
resources.loadBalancersOf(cluster, region, STACK_TAG, KIND, "application")
.forEach((stack, lb) -> delete(cluster, region, stack, lb));
}
/**
* The Ingresses of these {@code kubectl get ... -o json} lists that get an Application Load Balancer: those of
* an IngressClass naming the ALB controller, or of no class while such a class is the default, with a target type
* other than {@code ip}.
*/
static List<AlbIngress> albIngresses(JsonNode ingresses, JsonNode classes, JsonNode params, JsonNode services) {
Map<String, JsonNode> albClasses = new HashMap<>();
String defaultClass = null;
for (JsonNode item : classes.path("items")) {
if (ALB_CONTROLLER.equals(item.path("spec").path("controller").asText())) {
String name = item.path("metadata").path("name").asText();
albClasses.put(name, item);
if ("true".equals(item.path("metadata").path("annotations").path(DEFAULT_CLASS_ANNOTATION).asText())) {
defaultClass = name;
}
}
}
Map<String, JsonNode> paramsByName = new HashMap<>();
params.path("items").forEach(item -> paramsByName.put(item.path("metadata").path("name").asText(), item));
Map<String, JsonNode> servicesByStack = new HashMap<>();
services.path("items").forEach(item -> servicesByStack.put(item.path("metadata").path("namespace").asText()
+ "/" + item.path("metadata").path("name").asText(), item));
List<AlbIngress> found = new ArrayList<>();
for (JsonNode item : ingresses.path("items")) {
JsonNode metadata = item.path("metadata");
JsonNode spec = item.path("spec");
String className = spec.path("ingressClassName").asText(defaultClass == null ? "" : defaultClass);
JsonNode ingressClass = albClasses.get(className);
if (ingressClass == null) {
continue;
}
JsonNode classParams = paramsOf(ingressClass, paramsByName);
if (classParams == null) {
// As the Load Balancer Controller fails such an Ingress: the annotations don't stand in for the
// class's settings, so its load balancer keeps the ones it has.
LOG.warnv("Ingress {0}/{1} is left as it is: its IngressClass {2} names IngressClassParams {3}, "
+ "which aren't there", metadata.path("namespace").asText(), metadata.path("name").asText(),
className, ingressClass.path("spec").path("parameters").path("name").asText());
found.add(AlbIngress.held(metadata.path("namespace").asText(), metadata.path("name").asText(),
metadata.path("uid").asText("")));
continue;
}
JsonNode annotations = metadata.path("annotations");
String targetType = classParams.path("targetType").asText(annotations.path(TARGET_TYPE_ANNOTATION)
.asText("instance"));
if ("ip".equals(targetType)) {
LOG.warnv("Ingress {0}/{1} gets no load balancer: Floci reaches the node, not its pods, so it serves "
+ "target type instance only", metadata.path("namespace").asText(), metadata.path("name").asText());
continue;
}
String namespace = metadata.path("namespace").asText();
List<String> subnets = new ArrayList<>();
classParams.path("subnets").path("ids").forEach(id -> subnets.add(id.asText()));
List<Route> routes = new ArrayList<>();
// As the Load Balancer Controller builds them: the rules in the order the Ingress lists them, and each
// rule's paths in their precedence.
for (JsonNode rule : spec.path("rules")) {
List<JsonNode> paths = new ArrayList<>();
rule.path("http").path("paths").forEach(paths::add);
for (int i : precedence(paths)) {
Backend backend = backend(paths.get(i).path("backend"), namespace, servicesByStack);
if (backend != null) {
routes.add(new Route(rule.path("host").asText(null), pathPatterns(paths.get(i)), backend));
}
}
}
found.add(new AlbIngress(namespace, metadata.path("name").asText(), metadata.path("uid").asText(""),
classParams.path("scheme").asText(annotations.path(SCHEME_ANNOTATION).asText("internal")),
List.copyOf(subnets), annotations.path(HEALTH_CHECK_PATH_ANNOTATION).asText("/"),
List.copyOf(routes), backend(spec.path("defaultBackend"), namespace, servicesByStack)));
}
return found;
}
/**
* One Ingress rule's paths' indexes in the order they are matched, as the AWS Load Balancer Controller orders
* them: {@code Exact} paths first, then {@code Prefix} paths longest first, then {@code ImplementationSpecific}
* ones, each in the order the rule lists them otherwise.
*/
static List<Integer> precedence(List<JsonNode> paths) {
List<Integer> order = new ArrayList<>();
for (int i = 0; i < paths.size(); i++) {
order.add(i);
}
order.sort(Comparator.comparingInt((Integer i) -> pathRank(paths.get(i)))
.thenComparingInt(i -> "Prefix".equals(pathType(paths.get(i)))
? -paths.get(i).path("path").asText("/").length() : 0));
return order;
}
private static int pathRank(JsonNode path) {
return switch (pathType(path)) {
case "Exact" -> 0;
case "Prefix" -> 1;
default -> 2;
};
}
private static String pathType(JsonNode path) {
return path.path("pathType").asText("ImplementationSpecific");
}
/**
* The spec of the IngressClassParams a class names, missing when it names none, and null when it names ones that
* aren't there.
*/
private static JsonNode paramsOf(JsonNode ingressClass, Map<String, JsonNode> paramsByName) {
JsonNode reference = ingressClass.path("spec").path("parameters");
if (!"IngressClassParams".equals(reference.path("kind").asText())
|| !PARAMS_GROUP.equals(reference.path("apiGroup").asText())) {
return MissingNode.getInstance();
}
JsonNode found = paramsByName.get(reference.path("name").asText());
return found == null ? null : found.path("spec");
}
/** The Service port a backend names, by number or name, and its NodePort; null without one. */
private static Backend backend(JsonNode backend, String namespace, Map<String, JsonNode> servicesByStack) {
JsonNode service = backend.path("service");
String name = service.path("name").asText(null);
JsonNode found = name == null ? null : servicesByStack.get(namespace + "/" + name);
if (found == null) {
return null;
}
JsonNode wanted = service.path("port");
for (JsonNode port : found.path("spec").path("ports")) {
boolean matches = (wanted.has("number") ? wanted.path("number").asInt() == port.path("port").asInt()
: wanted.path("name").asText().equals(port.path("name").asText()))
// A port number a Service also serves over UDP takes its TCP NodePort.
&& "TCP".equals(port.path("protocol").asText("TCP"));
if (matches && port.path("nodePort").asInt() > 0) {
return new Backend(name, port.path("port").asInt(), port.path("nodePort").asInt());
}
}
return null;
}
/** The ALB path patterns of an Ingress path: {@code Prefix /} is {@code /*}, as AWS makes it (measured). */
static List<String> pathPatterns(JsonNode path) {
String value = path.path("path").asText("/");
String type = path.path("pathType").asText("ImplementationSpecific");
if (!"Prefix".equals(type)) {
return List.of(value);
}
if ("/".equals(value)) {
return List.of("/*");
}
String trimmed = value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
return List.of(trimmed, trimmed + "/*");
}
private LoadBalancer createLoadBalancer(Cluster cluster, String region, AlbIngress ingress) {
List<String> subnets = subnets(cluster, ingress);
LoadBalancer lb = elb.createLoadBalancer(region, EksAutoModeElb.resourceName(cluster, KIND, ingress.stack(), ""),
ingress.scheme(), "application", "ipv4", subnets, List.of(),
tags(cluster, ingress, "LoadBalancer"));
LOG.infov("Created Application Load Balancer {0} for Ingress {1} of EKS cluster {2}",
lb.getLoadBalancerName(), ingress.stack(), cluster.getName());
return lb;
}
/** The load balancer moves to the subnets the Ingress's class names now, when they differ. */
private void keepSubnets(Cluster cluster, String region, AlbIngress ingress, LoadBalancer lb) {
List<String> wanted = subnets(cluster, ingress);
List<String> have = lb.getAvailabilityZones() == null ? List.of()
: lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList();
if (!wanted.isEmpty() && !Set.copyOf(wanted).equals(Set.copyOf(have))) {
elb.setSubnets(region, lb.getLoadBalancerArn(), wanted);
}
}
private static List<String> subnets(Cluster cluster, AlbIngress ingress) {
return !ingress.subnets().isEmpty() ? ingress.subnets()
: cluster.getResourcesVpcConfig() == null ? List.of() : cluster.getResourcesVpcConfig().getSubnetIds();
}
/**
* Makes the Ingress's target groups, the node's registration and the listener where missing, sets its rules to
* the Ingress's routes when they differ, and removes the target groups no route forwards to any more. Answers
* whether the load balancer can serve: the node is registered.
*/
private boolean ensureRouting(Cluster cluster, String region, AlbIngress ingress, LoadBalancer lb, Instance node) {
Map<String, TargetGroup> groups = resources.targetGroupsOf(cluster, region, STACK_TAG, KIND, ingress.stack());
Map<Backend, String> groupArns = new HashMap<>();
Set<String> wanted = new LinkedHashSet<>();
for (Backend backend : ingress.backends()) {
String name = EksAutoModeElb.resourceName(cluster, KIND, ingress.stack(), "-" + backend.nodePort());
wanted.add(name);
TargetGroup group = groups.get(name);
if (group == null) {
String vpcId = cluster.getResourcesVpcConfig() == null ? null : cluster.getResourcesVpcConfig().getVpcId();
group = elb.createTargetGroup(region, name, "HTTP", null, backend.nodePort(), vpcId, "instance", "HTTP",
"traffic-port", true, ingress.healthCheckPath(), 15, 5, null, null, null, "ipv4",
tags(cluster, ingress, backend.resource(ingress)));
} else if (!ingress.healthCheckPath().equals(group.getHealthCheckPath())) {
elb.modifyTargetGroup(region, group.getTargetGroupArn(), null, null, null, ingress.healthCheckPath(),
null, null, null, null, null);
}
resources.registerNode(region, group, node);
groupArns.put(backend, group.getTargetGroupArn());
}
Action defaultAction = ingress.defaultBackend() == null ? notFound() : forward(groupArns.get(ingress.defaultBackend()));
List<Listener> listeners = elb.describeListeners(region, lb.getLoadBalancerArn(), null);
Listener listener = listeners.stream().filter(l -> Integer.valueOf(80).equals(l.getPort())).findFirst()
.orElseGet(() -> elb.createListener(region, lb.getLoadBalancerArn(), "HTTP", 80, null, null,
List.of(defaultAction), null, tags(cluster, ingress, "LoadBalancer")));
if (!sameAction(listener.getDefaultActions(), defaultAction)) {
// A default backend added, changed or dropped since the listener was made.
elb.modifyListener(region, listener.getListenerArn(), null, null, null, null, List.of(defaultAction), null);
}
setRules(region, listener, ingress, groupArns);
groups.forEach((name, group) -> {
if (!wanted.contains(name)) {
elb.deleteTargetGroup(region, group.getTargetGroupArn());
}
});
return node != null;
}
/** The listener's rules become the Ingress's routes, in order from priority 1, when they differ. */
private void setRules(String region, Listener listener, AlbIngress ingress, Map<Backend, String> groupArns) {
List<Rule> current = elb.describeRules(region, listener.getListenerArn(), null).stream()
.filter(rule -> !"default".equals(rule.getPriority())).toList();
List<String> desired = new ArrayList<>();
for (Route route : ingress.routes()) {
desired.add(route.host() + " " + route.paths() + " " + groupArns.get(route.backend()));
}
List<String> have = current.stream().map(EksAutoModeIngresses::describe).toList();
if (have.equals(desired)) {
return;
}
current.forEach(rule -> elb.deleteRule(region, rule.getRuleArn()));
int priority = 1;
for (Route route : ingress.routes()) {
List<RuleCondition> conditions = new ArrayList<>();
if (route.host() != null) {
conditions.add(condition("host-header", List.of(route.host())));
}
conditions.add(condition("path-pattern", route.paths()));
elb.createRule(region, listener.getListenerArn(), conditions, priority++,
List.of(forward(groupArns.get(route.backend()))), Map.of());
}
}
/** A rule as {@link #setRules} compares it: its host, its path patterns and the target group it forwards to. */
private static String describe(Rule rule) {
String host = null;
List<String> paths = List.of();
for (RuleCondition condition : rule.getConditions()) {
if ("host-header".equals(condition.getField())) {
host = condition.getValues().isEmpty() ? null : condition.getValues().getFirst();
} else if ("path-pattern".equals(condition.getField())) {
paths = condition.getValues();
}
}
String target = rule.getActions().isEmpty() ? null : rule.getActions().getFirst().getTargetGroupArn();
return host + " " + paths + " " + target;
}
private static RuleCondition condition(String field, List<String> values) {
RuleCondition condition = new RuleCondition();
condition.setField(field);
condition.setValues(new ArrayList<>(values));
if ("host-header".equals(field)) {
condition.setHostHeaderValues(new ArrayList<>(values));
} else {
condition.setPathPatternValues(new ArrayList<>(values));
}
return condition;
}
private static boolean sameAction(List<Action> actions, Action wanted) {
if (actions == null || actions.size() != 1) {
return false;
}
Action have = actions.getFirst();
return Objects.equals(have.getType(), wanted.getType())
&& Objects.equals(have.getTargetGroupArn(), wanted.getTargetGroupArn())
&& Objects.equals(have.getFixedResponseStatusCode(), wanted.getFixedResponseStatusCode());
}
private static Action forward(String targetGroupArn) {
Action action = new Action();
action.setType("forward");
action.setTargetGroupArn(Objects.requireNonNull(targetGroupArn));
return action;
}
/** The listener's default without a default backend: a fixed 404, as AWS makes it (measured). */
private static Action notFound() {
Action action = new Action();
action.setType("fixed-response");
action.setFixedResponseStatusCode("404");
action.setFixedResponseContentType("text/plain");
return action;
}
private static Map<String, String> tags(Cluster cluster, AlbIngress ingress, String resource) {
Map<String, String> tags = new LinkedHashMap<>();
tags.put(EksAutoModeElb.CLUSTER_TAG, cluster.getName());
tags.put(STACK_TAG, ingress.stack());
tags.put(RESOURCE_TAG, resource);
return tags;
}
private void delete(Cluster cluster, String region, String stack, LoadBalancer lb) {
resources.delete(cluster, region, STACK_TAG, KIND, stack, lb);
LOG.infov("Deleted Application Load Balancer {0} of Ingress {1} of EKS cluster {2}",
lb.getLoadBalancerName(), stack, cluster.getName());
}
}
@@ -0,0 +1,51 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.services.eks.model.Cluster;
import org.jboss.logging.Logger;
/** The Kubernetes objects EKS Auto Mode's load balancing reads and writes, through {@code kubectl} in the node. */
final class EksAutoModeKubectl {
private static final Logger LOG = Logger.getLogger(EksAutoModeKubectl.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final EksClusterManager clusterManager;
EksAutoModeKubectl(EksClusterManager clusterManager) {
this.clusterManager = clusterManager;
}
/** {@code kubectl get <kind> -A -o json}: every object of {@code kind} in the cluster. */
JsonNode list(Cluster cluster, String kind) {
ContainerExec.Result result = clusterManager.execInContainerForResult(cluster.getContainerId(),
new String[]{"kubectl", "get", kind, "-A", "-o", "json"}, 15);
if (result.exitCode() != 0) {
throw new IllegalStateException("kubectl get " + kind + " failed: " + result.summary());
}
try {
return MAPPER.readTree(result.stdout());
} catch (Exception e) {
throw new IllegalStateException("kubectl get " + kind + " returned no JSON: " + e.getMessage(), e);
}
}
/**
* Writes a load balancer's DNS name to an object's {@code status.loadBalancer}, as the controller on AWS does.
* The patch names the object's UID, so one made again under the same name meanwhile refuses it.
*/
void writeHostname(Cluster cluster, String kind, String namespace, String name, String uid, String dnsName) {
String identity = uid.isEmpty() ? "" : "\"metadata\":{\"uid\":\"" + uid + "\"},";
String patch = "{" + identity + "\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\"" + dnsName
+ "\"}]}}}";
ContainerExec.Result result = clusterManager.execInContainerForResult(cluster.getContainerId(),
new String[]{"kubectl", "patch", kind, name, "-n", namespace, "--subresource=status", "--type=merge",
"-p", patch}, 15);
if (result.exitCode() != 0) {
LOG.warnv("Could not write the load balancer of {0} {1}/{2} to its status: {3}", kind, namespace, name,
result.summary());
}
}
}
@@ -1,11 +1,8 @@
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;
@@ -14,7 +11,6 @@ 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;
@@ -27,18 +23,16 @@ 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
* EKS Auto Mode's load balancing capability, for Services here and for Ingresses through
* {@link EksAutoModeIngresses}: 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
@@ -65,16 +59,15 @@ 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 EksAutoModeElb resources;
private final EksAutoModeKubectl kubectl;
private final EksAutoModeIngresses ingresses;
private final EmulatorConfig config;
private final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "eks-auto-mode-load-balancers"));
@@ -85,6 +78,9 @@ public class EksAutoModeLoadBalancers {
this.eksService = eksService;
this.clusterManager = clusterManager;
this.elb = elb;
this.resources = new EksAutoModeElb(elb);
this.kubectl = new EksAutoModeKubectl(clusterManager);
this.ingresses = new EksAutoModeIngresses(elb, resources, kubectl);
this.config = config;
}
@@ -145,8 +141,9 @@ public class EksAutoModeLoadBalancers {
* Services that are gone.
*/
void reconcile(Cluster cluster, String region) {
List<NlbService> services = nlbServices(readServices(cluster), clusterManager.runsWithoutServiceLb(cluster));
Map<String, LoadBalancer> existing = loadBalancersOf(cluster, region);
List<NlbService> services = nlbServices(kubectl.list(cluster, "services"),
clusterManager.runsWithoutServiceLb(cluster));
Map<String, LoadBalancer> existing = resources.loadBalancersOf(cluster, region, STACK_TAG, "", "network");
Instance node = clusterManager.getRegisteredClusterNodeInstance(cluster);
for (NlbService service : services) {
LoadBalancer lb = existing.remove(service.stack());
@@ -154,15 +151,22 @@ public class EksAutoModeLoadBalancers {
lb = createLoadBalancer(cluster, region, service);
}
if (ensurePorts(cluster, region, service, lb, node)) {
writeStatus(cluster, service, lb.getDnsName());
kubectl.writeHostname(cluster, "service", service.namespace(), service.name(), service.uid(),
lb.getDnsName());
}
}
existing.forEach((stack, lb) -> delete(cluster, region, stack, lb));
ingresses.reconcile(cluster, region, node);
}
/** Deletes every load balancer made for {@code cluster}'s Services, with their listeners and target groups. */
/**
* Deletes every load balancer made for {@code cluster}'s Services and Ingresses, with their listeners and target
* groups.
*/
public void deleteLoadBalancers(Cluster cluster, String region) {
loadBalancersOf(cluster, region).forEach((stack, lb) -> delete(cluster, region, stack, lb));
resources.loadBalancersOf(cluster, region, STACK_TAG, "", "network")
.forEach((stack, lb) -> delete(cluster, region, stack, lb));
ingresses.deleteLoadBalancers(cluster, region);
}
/**
@@ -195,75 +199,15 @@ public class EksAutoModeLoadBalancers {
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<String, LoadBalancer> loadBalancersOf(Cluster cluster, String region) {
Map<String, LoadBalancer> found = new LinkedHashMap<>();
List<LoadBalancer> all = elb.describeLoadBalancers(region, null, null, null, null);
if (all.isEmpty()) {
return found;
}
Map<String, Map<String, String>> 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<String, TargetGroup> targetGroupsOf(Cluster cluster, String region, String stack) {
Map<String, TargetGroup> found = new HashMap<>();
List<TargetGroup> all = elb.describeTargetGroups(region, null, null, null);
if (all.isEmpty()) {
return found;
}
Map<String, Map<String, String>> 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<String, String> 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<String, String> tags(Cluster cluster, NlbService service) {
return Map.of(CLUSTER_TAG, cluster.getName(), STACK_TAG, service.stack());
return Map.of(EksAutoModeElb.CLUSTER_TAG, cluster.getName(), STACK_TAG, service.stack());
}
private LoadBalancer createLoadBalancer(Cluster cluster, String region, NlbService service) {
List<String> subnets = cluster.getResourcesVpcConfig() == null ? List.of()
: cluster.getResourcesVpcConfig().getSubnetIds();
LoadBalancer lb = elb.createLoadBalancer(region, resourceName(cluster, service.stack(), ""), service.scheme(),
LoadBalancer lb = elb.createLoadBalancer(region, EksAutoModeElb.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());
@@ -276,12 +220,12 @@ public class EksAutoModeLoadBalancers {
* 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<String, TargetGroup> groups = targetGroupsOf(cluster, region, service.stack());
Map<String, TargetGroup> groups = resources.targetGroupsOf(cluster, region, STACK_TAG, "", service.stack());
Map<Integer, Listener> listeners = new HashMap<>();
elb.describeListeners(region, lb.getLoadBalancerArn(), null).forEach(l -> listeners.put(l.getPort(), l));
Set<String> wanted = new HashSet<>();
for (ServicePort port : service.ports()) {
String name = resourceName(cluster, service.stack(), "-" + port.port());
String name = EksAutoModeElb.resourceName(cluster, service.stack(), "-" + port.port());
wanted.add(name);
TargetGroup group = groups.get(name);
Listener listener = listeners.remove(port.port());
@@ -298,12 +242,7 @@ public class EksAutoModeLoadBalancers {
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));
}
resources.registerNode(region, group, node);
if (listener == null) {
Action forward = new Action();
forward.setType("forward");
@@ -322,46 +261,8 @@ public class EksAutoModeLoadBalancers {
}
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()));
resources.delete(cluster, region, STACK_TAG, "", stack, lb);
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-<namespace>-<name><suffix>-<hash>}, 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);
}
}
@@ -197,6 +197,13 @@ public class EksClusterManager
/** The label EKS Auto Mode's nodes carry, given to the cluster's node while compute is on. */
static final String AUTO_COMPUTE_LABEL_KEY = "eks.amazonaws.com/compute-type"; // partition-literal: a label
static final String AUTO_COMPUTE_LABEL = AUTO_COMPUTE_LABEL_KEY + "=auto";
static final String LOAD_BALANCING_MANIFEST_FILE = "floci-eks-auto-mode-load-balancing.yaml";
static final String LOAD_BALANCING_MANIFEST_TAR_ENTRY = "server/manifests/" + LOAD_BALANCING_MANIFEST_FILE;
// The manifest once load balancing is off: no objects, so k3s deletes the IngressClassParams kind it held before.
static final String LOAD_BALANCING_MANIFEST_REMOVED = """
# EKS Auto Mode load balancing is off for this cluster.
# k3s deletes the IngressClassParams kind an earlier version of this file created.
""";
private static final String ENDPOINT_MODE_NETWORK = "network";
public static final String DEFAULT_POD_CIDR = "10.42.0.0/16";
@@ -1043,6 +1050,7 @@ public class EksClusterManager
registerPodIdentityWebhook(containerId, cluster);
applyBlockStorage(containerId, cluster);
applyCompute(containerId, cluster);
applyLoadBalancing(containerId, cluster);
if (signingKeyFiles != null) {
copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName());
}
@@ -1206,6 +1214,7 @@ public class EksClusterManager
() -> survivingNodeResolvesThroughFloci(info.containerId()));
applyBlockStorage(info.containerId(), cluster);
applyCompute(info.containerId(), cluster);
applyLoadBalancing(info.containerId(), cluster);
applyComputeLabel(cluster, info.containerId());
activeClusters.put(clusterResourceName(cluster), cluster);
attachClusterLogs(cluster, true, true, false);
@@ -3128,6 +3137,25 @@ public class EksClusterManager
}
}
/**
* Installs the {@code IngressClassParams} kind while the cluster's EKS Auto Mode load balancing is on, as Auto
* Mode does, so the IngressClass an Application Load Balancer is configured through can name its parameters;
* otherwise removes it, as {@link #applyBlockStorage} removes the provisioner.
*/
void applyLoadBalancing(String containerId, Cluster cluster) {
boolean enabled = cluster.getKubernetesNetworkConfig() != null
&& ElasticLoadBalancing.loadBalancingOn(cluster.getKubernetesNetworkConfig().getElasticLoadBalancing());
applyAutoModeManifest(containerId, cluster, enabled, LOAD_BALANCING_MANIFEST_FILE,
LOAD_BALANCING_MANIFEST_TAR_ENTRY, this::loadBalancingManifest, LOAD_BALANCING_MANIFEST_REMOVED,
"IngressClassParams kind");
}
/** The IngressClassParams kind EKS Auto Mode load balancing installs. */
String loadBalancingManifest() {
return resource(EksClusterManager.class.getResourceAsStream("/eks/auto-mode-load-balancing.yaml"),
"/eks/auto-mode-load-balancing.yaml");
}
/**
* Installs, while the cluster's EKS Auto Mode compute is on, the NodePool and NodeClass kinds, the {@code default}
* NodeClass and the built-in node pools its {@code computeConfig.nodePools} names, as Auto Mode does (measured), and
@@ -0,0 +1,44 @@
# EKS Auto Mode load balancing on a Floci cluster: the IngressClassParams kind an IngressClass for
# eks.amazonaws.com/alb names, as Auto Mode installs it. Floci reads scheme, subnets.ids and targetType;
# the other fields are kept as given.
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: ingressclassparams.eks.amazonaws.com
labels:
app.kubernetes.io/managed-by: floci
spec:
group: eks.amazonaws.com
scope: Cluster
names:
kind: IngressClassParams
listKind: IngressClassParamsList
plural: ingressclassparams
singular: ingressclassparams
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
x-kubernetes-preserve-unknown-fields: true
properties:
scheme:
type: string
enum: ["internal", "internet-facing"]
targetType:
type: string
enum: ["instance", "ip"]
subnets:
type: object
x-kubernetes-preserve-unknown-fields: true
properties:
ids:
type: array
items:
type: string
pattern: "^subnet-[0-9a-f]+$"
@@ -0,0 +1,449 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.services.ec2.model.Instance;
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.Action;
import io.floci.aws.services.elbv2.model.AvailabilityZone;
import io.floci.aws.services.elbv2.model.Listener;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.Rule;
import io.floci.aws.services.elbv2.model.RuleCondition;
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;
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.assertThrows;
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.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EksAutoModeIngressesTest {
private static final String REGION = "us-east-1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CLASSES = """
{"items": [
{"metadata": {"name": "alb"}, "spec": {"controller": "eks.amazonaws.com/alb",
"parameters": {"apiGroup": "eks.amazonaws.com", "kind": "IngressClassParams", "name": "public"}}},
{"metadata": {"name": "alb-default", "annotations": {"ingressclass.kubernetes.io/is-default-class": "true"}},
"spec": {"controller": "eks.amazonaws.com/alb"}},
{"metadata": {"name": "nginx"}, "spec": {"controller": "k8s.io/ingress-nginx"}}
]}""";
private static final String PARAMS = """
{"items": [{"metadata": {"name": "public"},
"spec": {"scheme": "internet-facing", "subnets": {"ids": ["subnet-pub1", "subnet-pub2"]}}}]}""";
private static final String SERVICES = """
{"items": [
{"metadata": {"namespace": "shop", "name": "web"},
"spec": {"type": "NodePort", "ports": [{"name": "http", "port": 80, "nodePort": 30080}]}},
{"metadata": {"namespace": "shop", "name": "api"},
"spec": {"type": "NodePort", "ports": [{"port": 8080, "nodePort": 30081}]}},
{"metadata": {"namespace": "shop", "name": "internal"},
"spec": {"type": "ClusterIP", "ports": [{"port": 80}]}}
]}""";
private static final String INGRESSES = """
{"items": [
{"metadata": {"namespace": "shop", "name": "front", "uid": "uid-front",
"annotations": {"alb.ingress.kubernetes.io/healthcheck-path": "/healthz"}},
"spec": {"ingressClassName": "alb", "rules": [
{"host": "shop.example.com", "http": {"paths": [
{"path": "/api", "pathType": "Prefix", "backend": {"service": {"name": "api", "port": {"number": 8080}}}},
{"path": "/", "pathType": "Prefix", "backend": {"service": {"name": "web", "port": {"name": "http"}}}},
{"path": "/hidden", "pathType": "Exact",
"backend": {"service": {"name": "internal", "port": {"number": 80}}}}]}}]}},
{"metadata": {"namespace": "shop", "name": "plain"},
"spec": {"defaultBackend": {"service": {"name": "web", "port": {"number": 80}}}}},
{"metadata": {"namespace": "shop", "name": "pods",
"annotations": {"alb.ingress.kubernetes.io/target-type": "ip"}},
"spec": {"ingressClassName": "alb-default", "defaultBackend":
{"service": {"name": "web", "port": {"number": 80}}}}},
{"metadata": {"namespace": "shop", "name": "other"},
"spec": {"ingressClassName": "nginx", "defaultBackend":
{"service": {"name": "web", "port": {"number": 80}}}}}
]}""";
private final EksClusterManager clusterManager = mock(EksClusterManager.class);
private final ElbV2Service elb = mock(ElbV2Service.class);
private final EksAutoModeIngresses ingresses = new EksAutoModeIngresses(elb, new EksAutoModeElb(elb),
new EksAutoModeKubectl(clusterManager));
private final List<LoadBalancer> lbs = new ArrayList<>();
private final List<TargetGroup> groups = new ArrayList<>();
private final List<Rule> rules = new ArrayList<>();
private final Map<String, Map<String, String>> tags = new HashMap<>();
@Test
void ingressesOfAnAlbClassGetOneAsTheirClassParamsAndAnnotationsSay() throws Exception {
List<EksAutoModeIngresses.AlbIngress> found = EksAutoModeIngresses.albIngresses(json(INGRESSES),
json(CLASSES), json(PARAMS), json(SERVICES));
EksAutoModeIngresses.Backend api = new EksAutoModeIngresses.Backend("api", 8080, 30081);
EksAutoModeIngresses.Backend web = new EksAutoModeIngresses.Backend("web", 80, 30080);
// The class's IngressClassParams give the scheme and subnets; the ClusterIP backend has no NodePort to
// serve; the class-less Ingress takes the default ALB class; target type ip and another controller get none.
assertEquals(List.of(
new EksAutoModeIngresses.AlbIngress("shop", "front", "uid-front", "internet-facing",
List.of("subnet-pub1", "subnet-pub2"), "/healthz", List.of(
new EksAutoModeIngresses.Route("shop.example.com", List.of("/api", "/api/*"), api),
new EksAutoModeIngresses.Route("shop.example.com", List.of("/*"), web)), null),
new EksAutoModeIngresses.AlbIngress("shop", "plain", "", "internal", List.of(), "/", List.of(), web)),
found);
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {"/|Prefix|/*", "/api|Prefix|/api,/api/*", "/api/|Prefix|/api,/api/*",
"/exact|Exact|/exact", "/x|ImplementationSpecific|/x"})
void pathsBecomeAlbPathPatterns(String path, String type, String patterns) throws Exception {
assertEquals(List.of(patterns.split(",")), EksAutoModeIngresses.pathPatterns(
json("{\"path\": \"" + path + "\", \"pathType\": \"" + type + "\"}")));
}
@Test
void anIngressGetsAnAlbWithAListenerRulesTargetGroupsOnNodePortsAndItsDnsName() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, node());
Map<String, String> lbTags = Map.of(EksAutoModeElb.CLUSTER_TAG, "prod",
EksAutoModeIngresses.STACK_TAG, "shop/front", EksAutoModeIngresses.RESOURCE_TAG, "LoadBalancer");
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/front", "")),
eq("internet-facing"), eq("application"), eq("ipv4"), eq(List.of("subnet-pub1", "subnet-pub2")),
eq(List.of()), eq(lbTags));
verify(elb).createTargetGroup(eq(REGION), eq(EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/front", "-30081")),
eq("HTTP"), isNull(), eq(30081), eq("vpc-1"), eq("instance"), eq("HTTP"), eq("traffic-port"), eq(true),
eq("/healthz"), eq(15), eq(5), isNull(), isNull(), isNull(), eq("ipv4"),
eq(Map.of(EksAutoModeElb.CLUSTER_TAG, "prod", EksAutoModeIngresses.STACK_TAG, "shop/front",
EksAutoModeIngresses.RESOURCE_TAG, "shop/front-api:8080")));
// front forwards to api and web, plain to web: three target groups, each with the node.
verify(elb, times(3)).registerTargets(eq(REGION), anyString(),
argThat(targets -> "i-0node".equals(targets.getFirst().getId())));
ArgumentCaptor<List<Action>> defaults = ArgumentCaptor.forClass(List.class);
verify(elb, times(2)).createListener(eq(REGION), anyString(), eq("HTTP"), eq(80), isNull(), isNull(),
defaults.capture(), isNull(), any());
Action notFound = defaults.getAllValues().getFirst().getFirst();
assertEquals(List.of("fixed-response", "404", "text/plain"), List.of(notFound.getType(),
notFound.getFixedResponseStatusCode(), notFound.getFixedResponseContentType()));
ArgumentCaptor<List<RuleCondition>> conditions = ArgumentCaptor.forClass(List.class);
verify(elb).createRule(eq(REGION), anyString(), conditions.capture(), eq(1), anyList(), any());
assertEquals(List.of("host-header", "path-pattern"),
conditions.getValue().stream().map(RuleCondition::getField).toList());
assertEquals(List.of("/api", "/api/*"), conditions.getValue().get(1).getValues());
verify(elb).createRule(eq(REGION), anyString(), anyList(), eq(2), anyList(), any());
verify(clusterManager).execInContainerForResult(eq("k3s-prod"), argThat(cmd -> List.of(cmd).equals(List.of(
"kubectl", "patch", "ingress", "front", "-n", "shop", "--subresource=status", "--type=merge", "-p",
"{\"metadata\":{\"uid\":\"uid-front\"},\"status\":{\"loadBalancer\":{\"ingress\":[{\"hostname\":\""
+ "lb-1.elb.test\"}]}}}"))), anyInt());
}
@Test
void aPassThatFindsTheRulesAsTheIngressWantsLeavesThem() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, node());
verify(elb, times(2)).createRule(any(), any(), any(), anyInt(), any(), any());
ingresses.reconcile(cluster, REGION, node());
verify(elb, times(2)).createRule(any(), any(), any(), anyInt(), any(), any());
verify(elb, never()).deleteRule(any(), any());
}
@Test
void aGoneIngressLosesItsLoadBalancerAndWithoutAnAlbClassNothingElseIsRead() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, node());
String frontLb = lbs.getFirst().getLoadBalancerArn();
objects(cluster, "{\"items\": []}");
when(clusterManager.execInContainerForResult(eq("k3s-prod"),
argThat(cmd -> cmd.length > 2 && "ingressclasses".equals(cmd[2])), anyInt()))
.thenReturn(new ContainerExec.Result(0, "{\"items\": []}", "", false));
ingresses.reconcile(cluster, REGION, node());
verify(elb).deleteLoadBalancer(REGION, frontLb);
verify(clusterManager, times(1)).execInContainerForResult(eq("k3s-prod"),
argThat(cmd -> cmd.length > 2 && "ingresses".equals(cmd[2])), anyInt());
}
/** As the Load Balancer Controller: the annotations don't stand in for IngressClassParams that are gone. */
@Test
void anIngressWhoseClassParamsAreGoneKeepsItsLoadBalancerAsItIs() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, node());
String frontName = EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/front", "");
String frontLb = lbs.stream().filter(lb -> frontName.equals(lb.getLoadBalancerName())).findFirst()
.orElseThrow().getLoadBalancerArn();
when(clusterManager.execInContainerForResult(eq("k3s-prod"),
argThat(cmd -> cmd.length > 2 && "ingressclassparams".equals(cmd[2])), anyInt()))
.thenReturn(new ContainerExec.Result(0, "{\"items\": []}", "", false));
ingresses.reconcile(cluster, REGION, node());
verify(elb, never()).deleteLoadBalancer(REGION, frontLb);
verify(elb, times(1)).createLoadBalancer(anyString(), eq(frontName), anyString(), anyString(), anyString(),
anyList(), anyList(), any());
assertEquals(1, EksAutoModeIngresses.albIngresses(json(INGRESSES), json(CLASSES), json("{\"items\": []}"),
json(SERVICES)).stream().filter(EksAutoModeIngresses.AlbIngress::held).count());
}
@Test
void anIngressElbV2RefusesLeavesTheOthersServed() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
when(elb.createLoadBalancer(anyString(), eq(EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/front", "")), anyString(),
anyString(), anyString(), anyList(), anyList(), any()))
.thenThrow(new AwsException("ValidationError", "At least two subnets in two different Availability "
+ "Zones must be specified", 400));
ingresses.reconcile(cluster, REGION, node());
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/plain", "")),
anyString(), eq("application"), anyString(), anyList(), anyList(), any());
}
@Test
void aServiceAndAnIngressOfOneNameGetTwoNames() {
Cluster cluster = cluster();
assertNotEquals(EksAutoModeElb.resourceName(cluster, "shop/web", ""),
EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND, "shop/web", ""));
}
/** As the Load Balancer Controller orders paths: Exact, then Prefix longest first, then ImplementationSpecific. */
@Test
void rulesFollowTheLoadBalancerControllersPathOrder() throws Exception {
List<JsonNode> paths = List.of(json("{\"path\": \"/long/implementation\", \"pathType\": \"ImplementationSpecific\"}"),
json("{\"path\": \"/\", \"pathType\": \"Prefix\"}"),
json("{\"path\": \"/api\", \"pathType\": \"Prefix\"}"),
json("{\"path\": \"/x\", \"pathType\": \"ImplementationSpecific\"}"),
json("{\"path\": \"/api/health\", \"pathType\": \"Exact\"}"),
json("{\"path\": \"/static\", \"pathType\": \"Prefix\"}"));
assertEquals(List.of(4, 5, 2, 1, 0, 3), EksAutoModeIngresses.precedence(paths));
}
/** Paths are ordered within each rule; the rules keep the order the Ingress lists them in. */
@Test
void eachRulesPathsAreOrderedAndTheRulesKeepTheirOrder() throws Exception {
String ingress = """
{"items": [{"metadata": {"namespace": "shop", "name": "store"},
"spec": {"ingressClassName": "alb", "rules": [
{"http": {"paths": [
{"path": "/", "pathType": "Prefix", "backend": {"service": {"name": "web", "port": {"number": 80}}}}]}},
{"host": "x.com", "http": {"paths": [
{"path": "/", "pathType": "Prefix", "backend": {"service": {"name": "web", "port": {"number": 80}}}},
{"path": "/api", "pathType": "Prefix", "backend": {"service": {"name": "api", "port": {"number": 8080}}}}]}}]}}]}""";
List<EksAutoModeIngresses.Route> routes = EksAutoModeIngresses.albIngresses(json(ingress), json(CLASSES),
json(PARAMS), json(SERVICES)).getFirst().routes();
assertEquals(List.of("null /* 30080", "x.com /api,/api/* 30081", "x.com /* 30080"), routes.stream()
.map(r -> r.host() + " " + String.join(",", r.paths()) + " " + r.backend().nodePort()).toList());
}
@Test
void aBackendPortServedOverUdpAndTcpTakesTheTcpNodePort() throws Exception {
String services = """
{"items": [{"metadata": {"namespace": "shop", "name": "dns"},
"spec": {"type": "NodePort", "ports": [{"protocol": "UDP", "port": 53, "nodePort": 30053},
{"protocol": "TCP", "port": 53, "nodePort": 31053}]}}]}""";
String ingress = """
{"items": [{"metadata": {"namespace": "shop", "name": "dns"},
"spec": {"ingressClassName": "alb", "defaultBackend": {"service": {"name": "dns", "port": {"number": 53}}}}}]}""";
List<EksAutoModeIngresses.AlbIngress> found = EksAutoModeIngresses.albIngresses(json(ingress), json(CLASSES),
json(PARAMS), json(services));
assertEquals(31053, found.getFirst().defaultBackend().nodePort());
}
@Test
void changedSettingsReachTheLoadBalancerItsListenerAndTargetGroups() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, node());
LoadBalancer plain = lbs.get(1);
// plain loses its default backend, front's health check path changes, and front turns internal.
objects(cluster, INGRESSES.replace(
"\"spec\": {\"defaultBackend\": {\"service\": {\"name\": \"web\", \"port\": {\"number\": 80}}}}}",
"\"spec\": {\"rules\": []}}")
.replace("/healthz", "/ready"));
when(clusterManager.execInContainerForResult(eq("k3s-prod"),
argThat(cmd -> cmd.length > 2 && "ingressclassparams".equals(cmd[2])), anyInt()))
.thenReturn(new ContainerExec.Result(0, PARAMS.replace("internet-facing", "internal"), "", false));
String frontLb = lbs.getFirst().getLoadBalancerArn();
ingresses.reconcile(cluster, REGION, node());
verify(elb).modifyListener(eq(REGION), eq("arn:listener-" + plain.getLoadBalancerArn()), isNull(), isNull(),
isNull(), isNull(), argThat(actions -> "fixed-response".equals(actions.getFirst().getType())), isNull());
// front's two target groups, api and web, both take the new health check path.
verify(elb, times(2)).modifyTargetGroup(eq(REGION), anyString(), isNull(), isNull(), isNull(), eq("/ready"), isNull(),
isNull(), isNull(), isNull(), isNull());
verify(elb).deleteLoadBalancer(REGION, frontLb);
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeElb.resourceName(cluster, EksAutoModeIngresses.KIND,
"shop/front", "")), eq("internal"), eq("application"), anyString(), anyList(), anyList(), any());
}
@Test
void aFailedParamsReadOtherThanAMissingKindStopsThePass() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
when(clusterManager.execInContainerForResult(eq("k3s-prod"),
argThat(cmd -> cmd.length > 2 && "ingressclassparams".equals(cmd[2])), anyInt()))
.thenReturn(new ContainerExec.Result(1, "", "Unable to connect to the server", false));
assertThrows(IllegalStateException.class, () -> ingresses.reconcile(cluster, REGION, node()));
verify(elb, never()).createLoadBalancer(any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void noAddressIsWrittenUntilTheNodeIsRegistered() throws Exception {
Cluster cluster = cluster();
objects(cluster, INGRESSES);
holdElb();
ingresses.reconcile(cluster, REGION, null);
verify(elb, never()).registerTargets(any(), any(), any());
verify(clusterManager, never()).execInContainerForResult(any(), argThat(cmd -> "patch".equals(cmd[1])), anyInt());
}
/** The cluster's objects, by the kind {@code kubectl get} asks for. */
private void objects(Cluster cluster, String ingressList) {
Map<String, String> lists = Map.of("ingresses", ingressList, "ingressclasses", CLASSES,
"ingressclassparams", PARAMS, "services", SERVICES);
when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
argThat(cmd -> cmd.length > 2 && "get".equals(cmd[1])), anyInt())).thenAnswer(inv -> {
String[] cmd = inv.getArgument(1);
return new ContainerExec.Result(0, lists.get(cmd[2]), "", false);
});
when(clusterManager.execInContainerForResult(eq(cluster.getContainerId()),
argThat(cmd -> cmd.length > 2 && "patch".equals(cmd[1])), anyInt()))
.thenReturn(new ContainerExec.Result(0, "patched", "", false));
}
/** The mocked ELBv2 lists and tags what the reconciler puts 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<String, Map<String, String>> found = new HashMap<>();
for (String arn : inv.<List<String>>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 -> {
LoadBalancer lb = new LoadBalancer();
lb.setLoadBalancerArn("arn:lb-" + (lbs.size() + 1));
lb.setLoadBalancerName(inv.getArgument(1));
lb.setType(inv.getArgument(3));
lb.setScheme(inv.getArgument(2));
List<AvailabilityZone> zones = new ArrayList<>();
for (String subnet : inv.<List<String>>getArgument(5)) {
AvailabilityZone zone = new AvailabilityZone();
zone.setSubnetId(subnet);
zones.add(zone);
}
lb.setAvailabilityZones(zones);
lb.setDnsName("lb-" + (lbs.size() + 1) + ".elb.test");
lbs.add(lb);
tags.put(lb.getLoadBalancerArn(), inv.getArgument(7));
return lb;
});
when(elb.createTargetGroup(anyString(), anyString(), anyString(), any(), anyInt(), any(), anyString(), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(inv -> {
TargetGroup group = new TargetGroup();
group.setTargetGroupArn("arn:tg-" + (groups.size() + 1));
group.setTargetGroupName(inv.getArgument(1));
group.setPort(inv.getArgument(4));
group.setHealthCheckPath(inv.getArgument(10));
group.setTargets(new ArrayList<TargetDescription>());
groups.add(group);
tags.put(group.getTargetGroupArn(), inv.getArgument(17));
return group;
});
Map<String, List<Listener>> listeners = new HashMap<>();
when(elb.createListener(anyString(), anyString(), anyString(), anyInt(), any(), any(), anyList(), any(), any()))
.thenAnswer(inv -> {
Listener listener = new Listener();
listener.setListenerArn("arn:listener-" + inv.getArgument(1));
listener.setPort(inv.getArgument(3));
listener.setDefaultActions(inv.getArgument(6));
listeners.computeIfAbsent(inv.getArgument(1), k -> new ArrayList<>()).add(listener);
return listener;
});
when(elb.describeListeners(anyString(), anyString(), isNull()))
.thenAnswer(inv -> List.copyOf(listeners.getOrDefault(inv.getArgument(1), List.of())));
when(elb.createRule(anyString(), anyString(), anyList(), anyInt(), anyList(), any())).thenAnswer(inv -> {
Rule rule = new Rule();
rule.setRuleArn("arn:rule-" + (rules.size() + 1));
rule.setListenerArn(inv.getArgument(1));
rule.setPriority(String.valueOf((int) inv.getArgument(3)));
rule.setConditions(inv.getArgument(2));
rule.setActions(inv.getArgument(4));
rules.add(rule);
return rule;
});
when(elb.describeRules(anyString(), anyString(), isNull())).thenAnswer(inv -> rules.stream()
.filter(rule -> rule.getListenerArn().equals(inv.getArgument(1))).toList());
}
private static Instance node() {
Instance node = new Instance();
node.setInstanceId("i-0node");
return node;
}
private static Cluster cluster() {
Cluster cluster = new Cluster();
cluster.setName("prod");
cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/prod");
cluster.setContainerId("k3s-prod");
ResourcesVpcConfig vpc = new ResourcesVpcConfig();
vpc.setSubnetIds(List.of("subnet-a", "subnet-b"));
vpc.setVpcId("vpc-1");
cluster.setResourcesVpcConfig(vpc);
return cluster;
}
private static JsonNode json(String text) throws Exception {
return MAPPER.readTree(text);
}
}
@@ -121,9 +121,9 @@ class EksAutoModeLoadBalancersTest {
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, "");
String name = EksAutoModeElb.resourceName(cluster("prod"), stack, "");
String port = EksAutoModeElb.resourceName(cluster("prod"), stack, "-65535");
String other = EksAutoModeElb.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);
@@ -142,13 +142,13 @@ class EksAutoModeLoadBalancersTest {
loadBalancers.reconcile(cluster, REGION);
Map<String, String> serviceTags = Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, "prod",
Map<String, String> serviceTags = Map.of(EksAutoModeElb.CLUSTER_TAG, "prod",
EksAutoModeLoadBalancers.STACK_TAG, "shop/web");
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeLoadBalancers.resourceName(cluster, "shop/web", "")),
verify(elb).createLoadBalancer(eq(REGION), eq(EksAutoModeElb.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")),
verify(elb).createTargetGroup(eq(REGION), eq(EksAutoModeElb.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()),
@@ -302,24 +302,24 @@ class EksAutoModeLoadBalancersTest {
anyList(), any())).thenAnswer(inv -> {
Map<String, String> 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));
made.get(EksAutoModeElb.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<String, String> 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));
made.get(EksAutoModeElb.CLUSTER_TAG), made.get(EksAutoModeLoadBalancers.STACK_TAG));
});
}
private LoadBalancer ownLoadBalancer(Cluster cluster, String stack) {
return loadBalancer("arn:own-" + stack, EksAutoModeLoadBalancers.resourceName(cluster, stack, ""), "network",
return loadBalancer("arn:own-" + stack, EksAutoModeElb.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);
EksAutoModeElb.resourceName(cluster, stack, "-" + servicePort), 31080, cluster.getName(), stack);
}
private LoadBalancer loadBalancer(String arn, String name, String type, String clusterName, String stack) {
@@ -330,7 +330,7 @@ class EksAutoModeLoadBalancersTest {
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,
tags.put(arn, Map.of(EksAutoModeElb.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
stack));
}
return lb;
@@ -343,7 +343,7 @@ class EksAutoModeLoadBalancersTest {
group.setPort(port);
group.setTargets(new ArrayList<TargetDescription>());
groups.add(group);
tags.put(arn, Map.of(EksAutoModeLoadBalancers.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
tags.put(arn, Map.of(EksAutoModeElb.CLUSTER_TAG, clusterName, EksAutoModeLoadBalancers.STACK_TAG,
stack));
return group;
}
@@ -168,15 +168,97 @@ class EksAutoModeNlbDockerNightlyIntegrationTest {
"-o", "name"));
}
@Test
void anIngressOfAnAlbClassGetsAnApplicationLoadBalancerRoutingToItsServicesNodePort() {
cluster = clusterInAVpc("alb-", "10.63", true);
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
// The IngressClassParams kind Floci installs with load balancing, as Auto Mode does.
await("IngressClassParams kind").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.until(() -> node.kubectl("get", "crd", "ingressclassparams.eks.amazonaws.com").exitCode() == 0);
node.apply("""
apiVersion: eks.amazonaws.com/v1
kind: IngressClassParams
metadata:
name: alb
spec:
scheme: internet-facing
---
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: alb
spec:
controller: eks.amazonaws.com/alb
parameters:
apiGroup: eks.amazonaws.com
kind: IngressClassParams
name: alb
---
apiVersion: v1
kind: Service
metadata:
name: shop
namespace: default
spec:
type: NodePort
selector:
app: shop
ports:
- port: 80
targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop
namespace: default
spec:
ingressClassName: alb
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: shop
port:
number: 80""");
int nodePort = Integer.parseInt(node.kubectlOutput("get", "service", "shop", "-n", "default",
"-o", "jsonpath={.spec.ports[0].nodePort}"));
RequestScopes.runAs(ACCOUNT, REGION, () -> loadBalancers.reconcile(cluster, REGION));
LoadBalancer lb = RequestScopes.callAs(ACCOUNT, REGION, () -> elb.describeLoadBalancers(REGION, null, null,
null, null)).stream().filter(found -> "application".equals(found.getType())).findFirst().orElseThrow();
assertEquals("internet-facing", lb.getScheme());
List<TargetGroup> groups = RequestScopes.callAs(ACCOUNT, REGION, () -> {
List<TargetGroup> all = elb.describeTargetGroups(REGION, null, null, null);
Map<String, Map<String, String>> tags = elb.describeTags(all.stream().map(TargetGroup::getTargetGroupArn).toList());
return all.stream().filter(group -> "default/shop".equals(tags.get(group.getTargetGroupArn())
.get(EksAutoModeIngresses.STACK_TAG))).toList();
});
assertEquals(List.of(nodePort), groups.stream().map(TargetGroup::getPort).toList());
String listener = RequestScopes.callAs(ACCOUNT, REGION,
() -> elb.describeListeners(REGION, lb.getLoadBalancerArn(), null)).getFirst().getListenerArn();
assertEquals(List.of("/*"), RequestScopes.callAs(ACCOUNT, REGION, () -> elb.describeRules(REGION, listener, null))
.stream().filter(rule -> !"default".equals(rule.getPriority())).findFirst().orElseThrow()
.getConditions().getFirst().getValues());
assertEquals(lb.getDnsName(), node.kubectlOutput("get", "ingress", "shop", "-n", "default",
"-o", "jsonpath={.status.loadBalancer.ingress[0].hostname}"));
}
/** 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();
// Two subnets in two zones, as an Application Load Balancer needs.
String subnet = ec2.createSubnet(REGION, vpc, cidr + ".1.0/24", "us-east-1a").getSubnetId();
String other = ec2.createSubnet(REGION, vpc, cidr + ".2.0/24", "us-east-1b").getSubnetId();
ResourcesVpcConfig network = new ResourcesVpcConfig();
network.setVpcId(vpc);
network.setSubnetIds(List.of(subnet));
network.setSubnetIds(List.of(subnet, other));
created.setResourcesVpcConfig(network);
});
if (loadBalancing) {
@@ -194,6 +276,6 @@ class EksAutoModeNlbDockerNightlyIntegrationTest {
}
Map<String, Map<String, String>> 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();
tags.getOrDefault(lb.getLoadBalancerArn(), Map.of()).get(EksAutoModeElb.CLUSTER_TAG))).toList();
}
}
@@ -4566,6 +4566,34 @@ class EksClusterManagerTest {
assertFalse(manifest.contains("kind: NodePool\nmetadata"));
}
@Test
void aClusterWithLoadBalancingGetsTheIngressClassParamsKindAndLosesItOnceItIsOff() throws Exception {
Cluster cluster = cluster();
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
network.setElasticLoadBalancing(new ElasticLoadBalancing(true));
cluster.setKubernetesNetworkConfig(network);
Path localCopy = tempDir.resolve("auto-mode/000000000000/us-east-1/demo")
.resolve(EksClusterManager.LOAD_BALANCING_MANIFEST_FILE);
manager.applyLoadBalancing("container-1", cluster);
assertEquals(manager.loadBalancingManifest(), Files.readString(localCopy));
assertTrue(manager.loadBalancingManifest().contains("name: ingressclassparams.eks.amazonaws.com"));
network.setElasticLoadBalancing(new ElasticLoadBalancing(false));
manager.applyLoadBalancing("container-1", cluster);
assertEquals(EksClusterManager.LOAD_BALANCING_MANIFEST_REMOVED, Files.readString(localCopy));
verify(dockerClient, Mockito.times(2)).copyArchiveToContainerCmd("container-1");
}
@Test
void aClusterThatNeverHadLoadBalancingGetsNoCopy() {
manager.applyLoadBalancing("container-1", cluster());
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
private Path blockStorageCopy() {
return tempDir.resolve("auto-mode/000000000000/us-east-1/demo")
.resolve(EksClusterManager.BLOCK_STORAGE_MANIFEST_FILE);