feat(eks): launch EKS Auto Mode nodes for pods no node can take (#9444)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-25 22:30:00 -04:00
1 parent fb658f01ee
commit 4b7d57f016
15 files changed
+2506 -67

No files matched your search

+44 -2
View File
@@ -450,16 +450,58 @@ Floci acts on the configuration as EKS does:
`computeConfig.nodePools` names, as Auto Mode makes them: on-demand c, m and r instances of generation 5 and later,
`amd64` (`system` also `arm64`, with a `CriticalAddonsOnly` `NoSchedule` taint), expiring after 336 hours. A pool
`UpdateClusterConfig` drops is removed. The cluster's node carries Auto Mode's `eks.amazonaws.com/compute-type: auto`
label, so workloads that select Auto Mode nodes run on it.
label, so workloads that select Auto Mode nodes run on it. Pods it can't take get nodes of their own (see
[Auto Mode nodes](#auto-mode-nodes)).
- **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)) 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.
### Auto Mode nodes
While compute is on, a pod the scheduler can't place on any node, the cluster's own included, gets one, as Auto Mode
launches nodes on AWS. Floci checks every 10 seconds.
- **Pool.** The pod goes to the first NodePool, by `weight` then name, with an instance type the pool's requirements
allow, whose node the pod's `nodeSelector`, required node affinity and tolerations accept, and that fits its CPU and
memory requests. A requirement on a label Floci doesn't give its nodes (a GPU count, say) is left out. A pod one of
the pool's schedulable nodes has room for, joined or still joining, waits for the scheduler instead. A joined
node's room is its `status.allocatable` CPU, memory and pods less its pods' requests (sidecars included); one still
joining has its instance type's whole size and 110 pods. A cordoned node, one with a taint of its own the pod
doesn't tolerate, or one with a pod that the pod's required anti-affinity on `kubernetes.io/hostname` keeps it
apart from (either pod's, counting pods placed on it in the same pass) has none; anti-affinity on another topology
key isn't modelled; the taints a node carries while it starts (`node.kubernetes.io/not-ready` and the
like) don't count in the 3 minutes after its launch, as Karpenter counts a starting node.
- **Instance.** One node a pool and pass, of the smallest type in the instance type catalog with at least 2 vCPUs
that fits all of the pool's waiting pods, or else the largest of them. AWS picked a 2-vCPU `c6a.large` for a pod of
100m CPU. It is launched in a subnet of the pool's NodeClass, in the zone the pods ask for if they do, with its
security groups, the instance
profile `eks-<region>-<cluster>-<number>` (path `/eks/<region>/<cluster>/`) holding the NodeClass's role, and the
tags Auto Mode sets: `eks:eks-cluster-name`, `eks:kubernetes-node-pool-name`, `eks:kubernetes-node-class-name`,
`kubernetes.io/cluster/<cluster>: owned` and `aws:ec2:managed-launch: eks-auto`.
- **Image.** The EKS optimized Amazon Linux 2023 image of the cluster's Kubernetes version and the node's
architecture, the one a managed node group of that version runs. AWS runs its own EKS Auto Mode image, which Floci
doesn't have. When the [image catalog](ec2.md) maps that image to one whose `kubeletRegistersNode` is on, pods
really run on the node. Otherwise the instance joins with the Ready node Floci registers for every joined
instance, and pods are scheduled to it but don't start.
- **Node.** The instance joins the cluster through its EKS bootstrap user data (a nodeadm `NodeConfig`), as any
instance does. Its kubelet flags (`--node-labels`, `--register-with-taints`) register the node with its pool's
labels and taints, so no pod the taints keep off lands there first; Floci's own Ready node for a joined instance
honours those flags too. The labels are: `karpenter.sh/nodepool`,
`eks.amazonaws.com/compute-type: auto`, `node.kubernetes.io/instance-type`, `karpenter.sh/capacity-type`, and the
`eks.amazonaws.com/instance-*` category, generation, family, size, CPU and memory labels.
- **Removal.** Turning compute off terminates the cluster's Auto Mode instances and takes their nodes out of it.
Deleting the cluster terminates them, waits up to a minute for them to finish terminating, as they hold the
cluster security group deleted next (one that doesn't fails the delete, which can be retried), and deletes the
instance profiles made for it.
On AWS, a node is named after its instance ID and is a managed instance a plain `DescribeInstances` doesn't list.
In Floci it is named as other joined instances are, after its private DNS name, and `DescribeInstances` lists it.
Floci makes no `NodeClaim` objects, and doesn't yet remove empty nodes.
### Auto Mode load balancing for Services
While a cluster has the load balancing capability on (`kubernetesNetworkConfig.elasticLoadBalancing.enabled`), a
@@ -0,0 +1,10 @@
package io.floci.aws.services.eks;
import io.floci.aws.services.eks.model.Cluster;
/** An EKS Auto Mode capability with resources of its own outside the cluster, which go when the cluster is deleted. */
interface EksAutoModeCleanup {
/** Deletes what the capability made for {@code cluster}, as the request deleting it runs. */
void clusterDeleted(Cluster cluster, String region);
}
@@ -0,0 +1,513 @@
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.Ec2InstanceTypeCatalog;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Reservation;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.eks.EksAutoModeNodes.Launch;
import io.floci.aws.services.eks.EksAutoModeNodes.NodePool;
import io.floci.aws.services.eks.EksAutoModeNodes.Taint;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.InstanceProfile;
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.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* EKS Auto Mode's compute capability: while a cluster has it on, pods the scheduler can't place on any node get one,
* as Auto Mode launches nodes for them on AWS. A pod goes to the first NodePool, by weight then name, whose
* requirements and taints allow a node it fits on; the pool's node is an EC2 instance of the smallest catalog type
* that fits its pods, launched in a subnet of the pool's NodeClass with its security groups and the node role's
* instance profile, and tagged as Auto Mode tags its instances (measured). It joins the cluster as any instance with
* EKS bootstrap user data does, then carries its pool's labels and taints. As Karpenter does, a pod that one of the
* pool's nodes has room for, joined or still joining, waits for the scheduler rather than getting another node.
*
* <p>The instance runs the EKS optimized Amazon Linux 2023 image of the cluster's Kubernetes version and the
* node's architecture, the one a managed node group of that version launches. When the image catalog maps that
* image to one whose kubelet registers its own node, pods really run on it; otherwise the instance joins with the
* Ready node Floci registers for every joined instance.
*
* <p>Like the load balancers, this reconciles on an interval and keeps no state of its own: the instances it
* launched are found again by their tags. A node that hasn't registered {@link #REGISTRATION_WAIT} after its launch
* is terminated. Passes and cleanups run one at a time, so a cluster's deletion waits for a pass that is launching
* for it, and the pass, checking again before and after each launch, makes nothing that outlives the cluster.
* Turning compute off terminates the cluster's Auto Mode
* instances, and deleting the cluster terminates them and deletes the instance profiles made for it.
*/
@ApplicationScoped
public class EksAutoModeCompute implements EksAutoModeCleanup {
private static final Logger LOG = Logger.getLogger(EksAutoModeCompute.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
/** The tags Auto Mode gives its instances (measured). */
static final String CLUSTER_TAG = "eks:eks-cluster-name";
static final String POOL_TAG = "eks:kubernetes-node-pool-name";
static final String NODE_CLASS_TAG = "eks:kubernetes-node-class-name";
static final String MANAGED_LAUNCH_TAG = "aws:ec2:managed-launch";
static final String MANAGED_LAUNCH = "eks-auto";
/** How long a launched node may take to register before its pool may get another. */
static final Duration REGISTRATION_WAIT = Duration.ofMinutes(3);
/** How long a deleted cluster waits for its Auto Mode instances to finish terminating, which EC2 does after. */
static final Duration TERMINATION_WAIT = Duration.ofMinutes(1);
private final EksService eksService;
private final EksClusterManager clusterManager;
private final Ec2Service ec2;
private final IamService iam;
private final Ec2InstanceTypeCatalog instanceTypes;
private final EmulatorConfig config;
private Duration terminationWait = TERMINATION_WAIT;
private final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "eks-auto-mode-compute"));
@Inject
public EksAutoModeCompute(EksService eksService, EksClusterManager clusterManager, Ec2Service ec2,
IamService iam, Ec2InstanceTypeCatalog instanceTypes, EmulatorConfig config) {
this.eksService = eksService;
this.clusterManager = clusterManager;
this.ec2 = ec2;
this.iam = iam;
this.instanceTypes = instanceTypes;
this.config = config;
}
/** For tests: how long a deleted cluster waits for its instances to terminate. */
void terminationWait(Duration wait) {
this.terminationWait = wait;
}
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<Cluster> entry : eksService.runningClusters()) {
Cluster cluster = entry.value();
String region = eksService.clusterRegion(cluster);
try {
RequestScopes.runAs(entry.accountId(), region, () -> {
if (EksClusterManager.computeOn(cluster)) {
reconcile(cluster, region);
} else {
removeNodes(cluster, region);
}
});
} catch (RuntimeException e) {
LOG.warnv(e, "EKS Auto Mode compute of cluster {0} was not reconciled", cluster.getName());
}
}
}
/**
* Gives the nodes launched before their pool's labels and taints, terminates those that never registered, then
* launches what the unschedulable pods no pool node has room for need.
*/
synchronized void reconcile(Cluster cluster, String region) {
List<Instance> launched = instancesOf(cluster, region, "pending", "running");
JsonNode podList = read(cluster, "pods");
List<EksAutoModeNodes.PendingPod> pods = EksAutoModeNodes.unschedulablePods(podList);
if (launched.isEmpty() && pods.isEmpty()) {
return;
}
Map<String, NodePool> pools = new HashMap<>();
EksAutoModeNodes.nodePools(read(cluster, "nodepools")).forEach(pool -> pools.put(pool.name(), pool));
Map<String, JsonNode> nodesByName = new HashMap<>();
for (JsonNode node : read(cluster, "nodes").path("items")) {
nodesByName.put(node.path("metadata").path("name").asText(), node);
}
Map<String, long[]> requests = EksAutoModeNodes.requestsByNode(podList);
Map<String, List<EksAutoModeNodes.BoundPod>> boundPods = EksAutoModeNodes.boundPodsByNode(podList);
List<EksAutoModeNodes.PoolNode> poolNodes = new ArrayList<>();
List<Instance> neverRegistered = new ArrayList<>();
for (Instance instance : launched) {
NodePool pool = pools.get(tag(instance, POOL_TAG));
Optional<Ec2InstanceTypeCatalog.CatalogInstanceType> type = instanceTypes.find(instance.getInstanceType());
String nodeName = clusterManager.deriveInstanceNodeName(instance, region);
JsonNode node = nodesByName.get(nodeName);
boolean starting = instance.getLaunchTime() == null
|| instance.getLaunchTime().plus(REGISTRATION_WAIT).isAfter(Instant.now());
boolean joining = node == null && starting;
if (node == null && !joining) {
neverRegistered.add(instance);
continue;
}
if (pool == null || type.isEmpty()) {
continue;
}
if (node != null) {
try {
markNode(cluster, nodeName, node, type.get(), pool);
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode node {0} of cluster {1} doesn''t carry its pool''s labels and taints "
+ "yet: {2}", nodeName, cluster.getName(), e.getMessage());
}
}
long[] used = requests.getOrDefault(nodeName, new long[3]);
List<Taint> nodeTaints = new ArrayList<>();
if (node != null) {
// A node just registered carries not-ready until its status says Ready; while it starts, within the
// registration wait, that doesn't take its room. One still not ready after it has none.
node.path("spec").path("taints").forEach(t -> {
if (!starting || !EksAutoModeNodes.STARTUP_TAINTS.contains(t.path("key").asText())) {
nodeTaints.add(new Taint(t.path("key").asText(), t.path("value").asText(""),
t.path("effect").asText()));
}
});
}
boolean schedulable = node == null || !node.path("spec").path("unschedulable").asBoolean(false);
// A joined node offers what its kubelet says is allocatable, less what it reserves; one joining, its
// instance type's whole size.
JsonNode allocatable = node == null ? MAPPER.createObjectNode() : node.path("status").path("allocatable");
long cpu = allocatable.hasNonNull("cpu") ? EksAutoModeNodes.cpuMillis(allocatable.path("cpu").asText())
: type.get().vcpu * 1000L;
long memory = allocatable.hasNonNull("memory") ? EksAutoModeNodes.bytes(allocatable.path("memory").asText())
: type.get().memoryMib * 1024L * 1024L;
int podSlots = allocatable.path("pods").asInt(EksAutoModeNodes.MAX_PODS);
poolNodes.add(new EksAutoModeNodes.PoolNode(pool, type.get(), zone(instance), cpu - used[0],
memory - used[1], (int) Math.max(0, podSlots - used[2]), schedulable, List.copyOf(nodeTaints),
boundPods.getOrDefault(nodeName, List.of())));
}
if (!neverRegistered.isEmpty()) {
// A node that never joins would hold its pods' room for good; it goes, and they get another.
ec2.terminateInstances(region, neverRegistered.stream().map(Instance::getInstanceId).toList());
LOG.warnv("EKS Auto Mode nodes {0} of cluster {1} didn''t register within {2}: terminated",
neverRegistered.stream().map(Instance::getInstanceId).toList(), cluster.getName(),
REGISTRATION_WAIT);
}
List<EksAutoModeNodes.PendingPod> withoutRoom = EksAutoModeNodes.withoutRoom(pods, poolNodes);
if (withoutRoom.isEmpty()) {
return;
}
Map<String, JsonNode> nodeClasses = new HashMap<>();
Set<String> subnetIds = new LinkedHashSet<>();
for (JsonNode nodeClass : read(cluster, "nodeclasses").path("items")) {
nodeClasses.put(nodeClass.path("metadata").path("name").asText(), nodeClass.path("spec"));
subnetIds.addAll(ids(nodeClass.path("spec").path("subnetSelectorTerms")));
}
Map<String, String> subnetZones = subnetZones(region, subnetIds);
// Each pool places its nodes in the zones of its own NodeClass's subnets.
Map<String, List<String>> zonesByNodeClass = new HashMap<>();
nodeClasses.forEach((name, spec) -> zonesByNodeClass.put(name, ids(spec.path("subnetSelectorTerms")).stream()
.map(subnetZones::get).filter(Objects::nonNull).distinct().toList()));
for (Launch launch : EksAutoModeNodes.plan(List.copyOf(pools.values()), withoutRoom,
instanceTypes.instanceTypes(), zonesByNodeClass)) {
try {
launch(cluster, region, launch, nodeClasses.get(launch.pool().nodeClass()), subnetZones);
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode pool {0} of cluster {1} launched no node for {2}: {3}",
launch.pool().name(), cluster.getName(), podNames(launch), e.getMessage());
}
}
}
private void launch(Cluster cluster, String region, Launch launch, JsonNode nodeClass,
Map<String, String> subnetZones) {
if (nodeClass == null) {
throw new IllegalStateException("its NodeClass " + launch.pool().nodeClass() + " isn't there");
}
String role = nodeClass.path("role").asText("");
List<String> subnets = ids(nodeClass.path("subnetSelectorTerms"));
if (role.isEmpty() || subnets.isEmpty()) {
throw new IllegalStateException("its NodeClass names no role or no subnet");
}
String subnet = subnets.stream().filter(id -> launch.zone() == null || launch.zone().equals(subnetZones.get(id)))
.findFirst().orElseThrow(() -> new IllegalStateException("its NodeClass has no subnet in "
+ launch.zone()));
String architecture = EksAutoModeNodes.architecture(launch.instanceType());
String imageId = EksAmiReleaseVersions.recommendedImage(clusterManager.imageCatalog(), cluster.getVersion(),
"arm64".equals(architecture) ? "AL2023_ARM_64_STANDARD" : "AL2023_x86_64_STANDARD")
.map(image -> image.imageId)
.orElseThrow(() -> new IllegalStateException("the image catalog has no EKS optimized Amazon Linux "
+ "2023 " + architecture + " image for Kubernetes " + cluster.getVersion()));
// A cluster deleted since the pass began keeps nothing this pass would make.
if (!stillRunning(cluster)) {
return;
}
String profileArn = instanceProfile(cluster, region, launch.pool().nodeClass(), role).getArn();
String userData = nodeConfig(cluster, launch);
Reservation reservation = ec2.runInstances(region, imageId, launch.instanceType().instanceType, 1, 1, null,
ids(nodeClass.path("securityGroupSelectorTerms")), subnet, UUID.randomUUID().toString(),
tags(cluster, launch.pool()), userData, profileArn, null, null, 0, null, null, null,
Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8)), false, null, null,
null, false, null, null);
String instanceId = reservation.getInstances().getFirst().getInstanceId();
if (!stillRunning(cluster)) {
// Deleted while this launch ran: what the deletion missed goes now. Its security group is gone already,
// so nothing waits for the instance to end.
removeAll(cluster, region);
return;
}
LOG.infov("EKS Auto Mode pool {0} of cluster {1} launched {2} ({3}) for {4}", launch.pool().name(),
cluster.getName(), instanceId, launch.instanceType().instanceType, podNames(launch));
}
/** Whether the cluster is still among the running ones, not deleted or being deleted. */
private boolean stillRunning(Cluster cluster) {
return eksService.runningClusters().stream().anyMatch(entry -> entry.value() != null
&& cluster.getArn().equals(entry.value().getArn()));
}
private Map<String, String> subnetZones(String region, Set<String> subnetIds) {
Map<String, String> zones = new LinkedHashMap<>();
if (!subnetIds.isEmpty()) {
for (Subnet subnet : ec2.describeSubnets(region, List.copyOf(subnetIds), Map.of())) {
zones.put(subnet.getSubnetId(), subnet.getAvailabilityZone());
}
}
return zones;
}
private static String zone(Instance instance) {
return instance.getPlacement() == null ? null : instance.getPlacement().getAvailabilityZone();
}
/**
* Gives a launched node its pool's labels and taints, the instance type's {@code eks.amazonaws.com/instance-*}
* labels among them, unless it has them.
*/
private void markNode(Cluster cluster, String nodeName, JsonNode node,
Ec2InstanceTypeCatalog.CatalogInstanceType type, NodePool pool) {
JsonNode current = node.path("metadata").path("labels");
List<String> labelArgs = new ArrayList<>();
EksAutoModeNodes.labels(type, pool, null).forEach((key, value) -> {
if (!value.equals(current.path(key).asText(null))) {
labelArgs.add(key + "=" + value);
}
});
if (!labelArgs.isEmpty()) {
List<String> command = new ArrayList<>(List.of("kubectl", "label", "node", nodeName, "--overwrite"));
command.addAll(labelArgs);
exec(cluster, command, "label node " + nodeName);
}
Set<String> taints = new HashSet<>();
node.path("spec").path("taints").forEach(t -> taints.add(taint(t.path("key").asText(),
t.path("value").asText(""), t.path("effect").asText())));
for (Taint taint : pool.taints()) {
String spec = taint(taint.key(), taint.value(), taint.effect());
if (!taints.contains(spec)) {
exec(cluster, List.of("kubectl", "taint", "node", nodeName, spec, "--overwrite"),
"taint node " + nodeName);
}
}
}
private static String taint(String key, String value, String effect) {
return key + (value == null || value.isEmpty() ? "" : "=" + value) + ":" + effect;
}
/**
* Takes the cluster's Auto Mode nodes out of it and terminates their instances, as turning compute off does. An
* instance whose node can't be deleted is kept, so the next pass tries it again.
*/
synchronized void removeNodes(Cluster cluster, String region) {
List<Instance> launched = instancesOf(cluster, region, "pending", "running", "stopping", "stopped");
List<String> removed = new ArrayList<>();
for (Instance instance : launched) {
try {
clusterManager.removeJoinedNode(cluster, instance);
removed.add(instance.getInstanceId());
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode node of instance {0} of cluster {1} wasn''t deleted: {2}",
instance.getInstanceId(), cluster.getName(), e.getMessage());
}
}
if (removed.isEmpty()) {
return;
}
ec2.terminateInstances(region, removed);
LOG.infov("EKS Auto Mode compute of cluster {0} is off: terminated {1}", cluster.getName(), removed);
}
/** The cluster's Auto Mode instances and the instance profiles made for it go with it, as on AWS. */
@Override
public synchronized void clusterDeleted(Cluster cluster, String region) {
removeAll(cluster, region);
// EC2 ends an instance after TerminateInstances answers, and one shutting down still holds the cluster
// security group, which EKS deletes next: wait until none is. One that doesn't end in time fails the
// delete, which keeps the cluster for a retry.
Instant deadline = Instant.now().plus(terminationWait);
while (!instancesOf(cluster, region, "pending", "running", "stopping", "stopped", "shutting-down").isEmpty()) {
if (Instant.now().isAfter(deadline)) {
throw new IllegalStateException("EKS Auto Mode instances of cluster " + cluster.getName()
+ " didn't finish terminating within " + terminationWait);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted waiting for the Auto Mode instances of cluster "
+ cluster.getName() + " to terminate", e);
}
}
}
/** Terminates the cluster's Auto Mode instances and deletes the instance profiles made for it. */
private void removeAll(Cluster cluster, String region) {
List<Instance> launched = instancesOf(cluster, region, "pending", "running", "stopping", "stopped");
if (!launched.isEmpty()) {
ec2.terminateInstances(region, launched.stream().map(Instance::getInstanceId).toList());
}
for (InstanceProfile profile : iam.listInstanceProfiles(profilePath(cluster, region))) {
for (String role : List.copyOf(profile.getRoleNames())) {
iam.removeRoleFromInstanceProfile(profile.getInstanceProfileName(), role);
}
iam.deleteInstanceProfile(profile.getInstanceProfileName());
}
}
/** The cluster's Auto Mode instances in one of {@code states}, found by the tags they were launched with. */
List<Instance> instancesOf(Cluster cluster, String region, String... states) {
Map<String, List<String>> filters = Map.of(
"tag:" + CLUSTER_TAG, List.of(cluster.getName()),
"tag:" + MANAGED_LAUNCH_TAG, List.of(MANAGED_LAUNCH),
"instance-state-name", List.of(states));
return ec2.describeInstances(region, List.of(), filters).stream()
.flatMap(reservation -> reservation.getInstances().stream())
.toList();
}
/**
* The instance profile of a NodeClass's nodes, holding its role: {@code eks-<region>-<cluster>-<number>} on the
* path {@code /eks/<region>/<cluster>/}, as Auto Mode names it (measured), made on first use.
*/
private InstanceProfile instanceProfile(Cluster cluster, String region, String nodeClass, String role) {
String number = Long.toUnsignedString(Long.parseUnsignedLong(
Digests.sha256Hex(cluster.getArn() + "/" + nodeClass).substring(0, 15), 16));
String name = "eks-" + region + "-" + cluster.getName() + "-" + number;
InstanceProfile profile = iam.listInstanceProfiles(profilePath(cluster, region)).stream()
.filter(p -> name.equals(p.getInstanceProfileName())).findFirst()
.orElseGet(() -> iam.createInstanceProfile(name, profilePath(cluster, region)));
if (!profile.getRoleNames().contains(role)) {
for (String other : List.copyOf(profile.getRoleNames())) {
iam.removeRoleFromInstanceProfile(name, other);
}
iam.addRoleToInstanceProfile(name, role);
}
return profile;
}
private static String profilePath(Cluster cluster, String region) {
return "/eks/" + region + "/" + cluster.getName() + "/";
}
private static List<Tag> tags(Cluster cluster, NodePool pool) {
return List.of(new Tag(CLUSTER_TAG, cluster.getName()), new Tag(POOL_TAG, pool.name()),
new Tag(NODE_CLASS_TAG, pool.nodeClass()), new Tag("kubernetes.io/cluster/" + cluster.getName(), "owned"),
new Tag(MANAGED_LAUNCH_TAG, MANAGED_LAUNCH));
}
/**
* nodeadm's {@code NodeConfig} for the cluster, the user data an instance joins it with, its kubelet registering
* the node with its pool's labels and taints, so a pod the pool's taints keep off never lands there first.
*/
static String nodeConfig(Cluster cluster, Launch launch) {
StringBuilder yaml = new StringBuilder("""
apiVersion: node.eks.aws/v1alpha1
kind: NodeConfig
spec:
cluster:
""");
yaml.append(" name: ").append(cluster.getName()).append('\n');
if (cluster.getEndpoint() != null) {
yaml.append(" apiServerEndpoint: ").append(cluster.getEndpoint()).append('\n');
}
if (cluster.getCertificateAuthority() != null && cluster.getCertificateAuthority().getData() != null) {
yaml.append(" certificateAuthority: ").append(cluster.getCertificateAuthority().getData()).append('\n');
}
if (cluster.getKubernetesNetworkConfig() != null && cluster.getKubernetesNetworkConfig().getServiceIpv4Cidr() != null) {
yaml.append(" cidr: ").append(cluster.getKubernetesNetworkConfig().getServiceIpv4Cidr()).append('\n');
}
yaml.append(" kubelet:\n flags:\n");
yaml.append(" - --node-labels=").append(String.join(",", launch.labels().entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue()).toList())).append('\n');
if (!launch.pool().taints().isEmpty()) {
yaml.append(" - --register-with-taints=").append(String.join(",", launch.pool().taints().stream()
.map(t -> taint(t.key(), t.value(), t.effect())).toList())).append('\n');
}
return yaml.toString();
}
private static List<String> ids(JsonNode terms) {
List<String> ids = new ArrayList<>();
terms.forEach(term -> {
if (!term.path("id").asText("").isEmpty()) {
ids.add(term.path("id").asText());
}
});
return ids;
}
private static String tag(Instance instance, String key) {
return instance.getTags() == null ? null : instance.getTags().stream()
.filter(t -> key.equals(t.getKey())).map(Tag::getValue).findFirst().orElse(null);
}
private static List<String> podNames(Launch launch) {
return launch.pods().stream().map(p -> p.namespace() + "/" + p.name()).toList();
}
private JsonNode read(Cluster cluster, String kind) {
List<String> command = "nodes".equals(kind) || "nodepools".equals(kind) || "nodeclasses".equals(kind)
? List.of("kubectl", "get", kind, "-o", "json") : List.of("kubectl", "get", kind, "-A", "-o", "json");
ContainerExec.Result result = exec(cluster, command, "get " + kind);
try {
return MAPPER.readTree(result.stdout());
} catch (Exception e) {
throw new IllegalStateException("kubectl get " + kind + " returned no JSON: " + e.getMessage(), e);
}
}
private ContainerExec.Result exec(Cluster cluster, List<String> command, String what) {
ContainerExec.Result result = clusterManager.execInContainerForResult(cluster.getContainerId(),
command.toArray(String[]::new), 15);
if (result.exitCode() != 0) {
throw new IllegalStateException("kubectl " + what + " failed: " + result.summary());
}
return result;
}
}
@@ -54,7 +54,7 @@ import java.util.concurrent.TimeUnit;
* balancers serve TCP and HTTP only, and a Service with no TCP NodePort gets no load balancer.
*/
@ApplicationScoped
public class EksAutoModeLoadBalancers {
public class EksAutoModeLoadBalancers implements EksAutoModeCleanup {
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
@@ -169,6 +169,12 @@ public class EksAutoModeLoadBalancers {
ingresses.deleteLoadBalancers(cluster, region);
}
/** The cluster's load balancers go with it, as the controller's go on AWS. */
@Override
public void clusterDeleted(Cluster cluster, String region) {
deleteLoadBalancers(cluster, region);
}
/**
* The Services of {@code kubectl get services -A -o json} that get an Auto Mode Network Load Balancer: of type
* LoadBalancer, of its class (and with {@code classless}, of no class), with a TCP port on a NodePort.
@@ -0,0 +1,606 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* What EKS Auto Mode decides for a node, without Kubernetes or EC2: the labels a node of an instance type carries,
* whether a pool's requirements and a pod's constraints allow it, and which pool and instance type a set of
* unschedulable pods gets. The reconciler reads the objects with {@code kubectl} and launches what this picks.
*/
final class EksAutoModeNodes {
static final String NODEPOOL_LABEL = "karpenter.sh/nodepool";
static final String COMPUTE_TYPE_LABEL = "eks.amazonaws.com/compute-type"; // partition-literal: a label
static final String LABEL_PREFIX = "eks.amazonaws.com/instance-"; // partition-literal: a label prefix
/** The smallest instance Floci picks, as AWS picked a 2-vCPU instance for a pod of 100m CPU (measured). */
static final int MIN_VCPUS = 2;
/** The pods a node takes when it doesn't say: the kubelet's default, which Floci's own Ready node advertises. */
static final int MAX_PODS = 110;
/** The topology key of the pod anti-affinity a node's own pods decide. */
static final String HOSTNAME_LABEL = "kubernetes.io/hostname";
/** Instance family names: category letters, generation digits, then attribute letters, as in {@code c7gd}. */
private static final Pattern FAMILY = Pattern.compile("^([a-z]+)(\\d+)([a-z-]*)$");
private static final Pattern QUANTITY = Pattern.compile("^([0-9]*\\.?[0-9]+(?:[eE][+-]?[0-9]+)?)([a-zA-Z]*)$");
static final String ZONE_LABEL = "topology.kubernetes.io/zone";
/** The labels Floci gives its nodes: a pool requirement on any other label is left out. */
/**
* The taints a node carries while it starts, which Kubernetes or the cloud provider take off once it is ready:
* Karpenter counts a starting node's room without them, so a pod waits for it rather than get another. Floci
* leaves them out within the registration wait of the node's launch only, so a node that stays unhealthy after
* it has no room.
*/
static final Set<String> STARTUP_TAINTS = Set.of("node.kubernetes.io/not-ready", "node.kubernetes.io/unreachable",
"node.cloudprovider.kubernetes.io/uninitialized", "karpenter.sh/unregistered");
private static final Set<String> MODELLED_LABELS = Set.of("kubernetes.io/arch", "kubernetes.io/os",
"node.kubernetes.io/instance-type", "karpenter.sh/capacity-type", NODEPOOL_LABEL, COMPUTE_TYPE_LABEL,
ZONE_LABEL, LABEL_PREFIX + "category", LABEL_PREFIX + "generation", LABEL_PREFIX + "family",
LABEL_PREFIX + "size", LABEL_PREFIX + "cpu", LABEL_PREFIX + "memory");
private EksAutoModeNodes() {
}
/** A requirement of a pool or a pod's node affinity: a label key, an operator and its values. */
record Requirement(String key, String operator, List<String> values) {
/** Whether a node with {@code labels} meets it, as Kubernetes evaluates a node selector requirement. */
boolean matches(Map<String, String> labels) {
String value = labels.get(key);
return switch (operator) {
case "In" -> value != null && values.contains(value);
case "NotIn" -> value == null || !values.contains(value);
case "Exists" -> value != null;
case "DoesNotExist" -> value == null;
case "Gt" -> compare(value) > 0;
case "Lt" -> compare(value) < 0;
default -> false;
};
}
private int compare(String value) {
if (value == null || values.size() != 1) {
return 0;
}
try {
return Long.compare(Long.parseLong(value), Long.parseLong(values.getFirst()));
} catch (NumberFormatException e) {
return 0;
}
}
}
/** A taint, or a pod's toleration of taints. */
record Taint(String key, String value, String effect) {
}
record Toleration(String key, String operator, String value, String effect) {
boolean tolerates(Taint taint) {
boolean effectMatches = effect == null || effect.isEmpty() || effect.equals(taint.effect());
if (!effectMatches) {
return false;
}
if (key == null || key.isEmpty()) {
return "Exists".equals(operator);
}
return key.equals(taint.key())
&& ("Exists".equals(operator) || Objects.equals(value == null ? "" : value,
taint.value() == null ? "" : taint.value()));
}
}
/** A NodePool: its NodeClass, its requirements, the taints and labels its nodes get, and its weight. */
record NodePool(String name, String nodeClass, List<Requirement> requirements, List<Taint> taints,
Map<String, String> labels, int weight) {
}
/** A pod the scheduler couldn't place, with what it asks of a node and the resources it requests. */
record PendingPod(String namespace, String name, long cpuMillis, long memoryBytes,
Map<String, String> nodeSelector, List<List<Requirement>> affinityTerms,
List<Toleration> tolerations, Map<String, String> labels, List<PodTerm> antiAffinity) {
/** A pod with no labels and no pod anti-affinity. */
PendingPod(String namespace, String name, long cpuMillis, long memoryBytes, Map<String, String> nodeSelector,
List<List<Requirement>> affinityTerms, List<Toleration> tolerations) {
this(namespace, name, cpuMillis, memoryBytes, nodeSelector, affinityTerms, tolerations, Map.of(), List.of());
}
/** The pod as one placed on a node, for the anti-affinity of the pods after it. */
BoundPod bound() {
return new BoundPod(namespace, labels, antiAffinity);
}
/** Whether a node with {@code labels} and {@code taints} could take it. */
boolean fits(Map<String, String> labels, List<Taint> taints) {
for (Map.Entry<String, String> wanted : nodeSelector.entrySet()) {
if (!wanted.getValue().equals(labels.get(wanted.getKey()))) {
return false;
}
}
if (!affinityTerms.isEmpty()
&& affinityTerms.stream().noneMatch(term -> term.stream().allMatch(r -> r.matches(labels)))) {
return false;
}
for (Taint taint : taints) {
boolean scheduling = "NoSchedule".equals(taint.effect()) || "NoExecute".equals(taint.effect());
if (scheduling && tolerations.stream().noneMatch(t -> t.tolerates(taint))) {
return false;
}
}
return true;
}
}
/**
* A required pod anti-affinity term on {@code kubernetes.io/hostname}: the pods it keeps a pod off the node of,
* by label selector and namespaces ({@code null} for every namespace, as a {@code namespaceSelector} reads).
*/
record PodTerm(Map<String, String> matchLabels, List<Requirement> matchExpressions, Set<String> namespaces) {
boolean matches(String namespace, Map<String, String> labels) {
if (namespaces != null && !namespaces.contains(namespace)) {
return false;
}
for (Map.Entry<String, String> wanted : matchLabels.entrySet()) {
if (!wanted.getValue().equals(labels.get(wanted.getKey()))) {
return false;
}
}
return matchExpressions.stream().allMatch(r -> r.matches(labels));
}
}
/** A pod on a node, with what its own anti-affinity keeps off that node. */
record BoundPod(String namespace, Map<String, String> labels, List<PodTerm> antiAffinity) {
/** Whether the pod and this one can't share a node, by either one's required anti-affinity. */
boolean conflicts(PendingPod pod) {
return pod.antiAffinity().stream().anyMatch(t -> t.matches(namespace, labels))
|| antiAffinity.stream().anyMatch(t -> t.matches(pod.namespace(), pod.labels()));
}
}
/**
* A node Auto Mode launched for a pool, joined or still joining, with the CPU and memory its pods request: a
* pending pod it has room for is left to the scheduler rather than given another node.
*/
record PoolNode(NodePool pool, CatalogInstanceType instanceType, String zone, long freeCpuMillis,
long freeMemoryBytes, int freePods, boolean schedulable, List<Taint> nodeTaints,
List<BoundPod> pods) {
/** A node whose pods carry no labels and no anti-affinity that could keep a pending pod off it. */
PoolNode(NodePool pool, CatalogInstanceType instanceType, String zone, long freeCpuMillis, long freeMemoryBytes,
int freePods, boolean schedulable, List<Taint> nodeTaints) {
this(pool, instanceType, zone, freeCpuMillis, freeMemoryBytes, freePods, schedulable, nodeTaints, List.of());
}
/**
* A node still joining, with its pods' requests: it has its instance type's whole CPU and memory, as no
* kubelet has said what it reserves yet, all its pod slots, and no taints but its pool's.
*/
PoolNode(NodePool pool, CatalogInstanceType instanceType, String zone, long usedCpuMillis, long usedMemoryBytes) {
this(pool, instanceType, zone, instanceType.vcpu * 1000L - usedCpuMillis,
instanceType.memoryMib * 1024L * 1024L - usedMemoryBytes, MAX_PODS, true, List.of());
}
/** The taints a pod must tolerate there: the pool's and any the node carries besides. */
List<Taint> taints() {
List<Taint> all = new ArrayList<>(pool.taints());
nodeTaints.stream().filter(t -> !all.contains(t)).forEach(all::add);
return all;
}
}
/** A node to launch: its pool, instance type, zone (null when no subnet's zone is known) and labels, and its pods. */
record Launch(NodePool pool, CatalogInstanceType instanceType, String zone, Map<String, String> labels,
List<PendingPod> pods) {
}
/** An instance type in a zone, the two things a launch picks for its pool. */
private record Placement(CatalogInstanceType type, String zone) {
}
/**
* The labels a node of {@code type} in {@code pool} carries, as Auto Mode's nodes do (measured): architecture,
* OS, instance type, capacity type, the {@code eks.amazonaws.com/instance-*} attributes, its pool, the compute
* type, its zone when known, and the pool's own labels.
*/
static Map<String, String> labels(CatalogInstanceType type, NodePool pool, String zone) {
Map<String, String> labels = new LinkedHashMap<>();
labels.put("kubernetes.io/arch", architecture(type));
labels.put("kubernetes.io/os", "linux");
labels.put("node.kubernetes.io/instance-type", type.instanceType);
labels.put("karpenter.sh/capacity-type", "on-demand");
String family = type.instanceType.substring(0, type.instanceType.indexOf('.'));
Matcher parts = FAMILY.matcher(family);
if (parts.matches()) {
labels.put(LABEL_PREFIX + "category", parts.group(1));
labels.put(LABEL_PREFIX + "generation", parts.group(2));
}
labels.put(LABEL_PREFIX + "family", family);
labels.put(LABEL_PREFIX + "size", type.instanceType.substring(type.instanceType.indexOf('.') + 1));
labels.put(LABEL_PREFIX + "cpu", String.valueOf(type.vcpu));
labels.put(LABEL_PREFIX + "memory", String.valueOf(type.memoryMib));
labels.put(NODEPOOL_LABEL, pool.name());
labels.put(COMPUTE_TYPE_LABEL, "auto");
if (zone != null) {
labels.put(ZONE_LABEL, zone);
}
labels.putAll(pool.labels());
return labels;
}
static String architecture(CatalogInstanceType type) {
return type.supportedArchitectures.contains("arm64") ? "arm64" : "amd64";
}
/**
* Whether a node with {@code labels} meets every requirement of {@code pool} that names a label Floci gives
* its nodes; a requirement on another label (an attribute Floci doesn't model, such as a CPU manufacturer or
* GPU count) is left out.
*/
static boolean poolAllows(NodePool pool, Map<String, String> labels) {
return pool.requirements().stream()
.filter(r -> labels.containsKey(r.key()) || MODELLED_LABELS.contains(r.key()))
.allMatch(r -> r.matches(labels));
}
/**
* The nodes to launch for {@code pods}: each pod goes to the first pool, by weight then name, that has an
* instance type, in a zone of its NodeClass's subnets ({@code zonesByNodeClass}), that its requirements allow,
* the pod's constraints accept and its requests fit. Each pool gets one node, of the smallest such type that
* fits all of its pods, or else the largest pod; those left over get one on a later pass. Pods no pool can take
* are left out. A pool whose NodeClass's zones aren't known launches nodes with no zone label.
*/
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass) {
List<NodePool> ordered = pools.stream()
.sorted(Comparator.comparingInt(NodePool::weight).reversed().thenComparing(NodePool::name))
.toList();
List<CatalogInstanceType> sized = types.stream()
.filter(t -> t.vcpu >= MIN_VCPUS && t.instanceType.contains("."))
.sorted(Comparator.comparingInt((CatalogInstanceType t) -> t.vcpu)
.thenComparingInt(t -> t.memoryMib).thenComparing(t -> t.instanceType))
.toList();
Map<String, List<PendingPod>> byPool = new LinkedHashMap<>();
for (PendingPod pod : pods) {
for (NodePool pool : ordered) {
if (candidate(pool, sized, zonesOf(pool, zonesByNodeClass), pod, pod.cpuMillis(), pod.memoryBytes())
.isPresent()) {
byPool.computeIfAbsent(pool.name(), k -> new ArrayList<>()).add(pod);
break;
}
}
}
List<Launch> launches = new ArrayList<>();
for (NodePool pool : ordered) {
List<PendingPod> group = byPool.get(pool.name());
if (group == null) {
continue;
}
long cpu = group.stream().mapToLong(PendingPod::cpuMillis).sum();
long memory = group.stream().mapToLong(PendingPod::memoryBytes).sum();
PendingPod largest = group.stream().max(Comparator.comparingLong(PendingPod::cpuMillis)
.thenComparingLong(PendingPod::memoryBytes)).orElseThrow();
List<String> placesIn = zonesOf(pool, zonesByNodeClass);
Optional<Placement> placement = candidate(pool, sized, placesIn, largest, cpu, memory)
.filter(p -> group.stream().allMatch(pod -> pod.fits(labels(p.type(), pool, p.zone()), pool.taints())))
.or(() -> candidate(pool, sized, placesIn, largest, largest.cpuMillis(), largest.memoryBytes()));
placement.ifPresent(p -> launches.add(new Launch(pool, p.type(), p.zone(),
labels(p.type(), pool, p.zone()), List.copyOf(group))));
}
return launches;
}
/**
* The pods none of the pools' nodes has room for: each pod takes room on the first schedulable node whose
* labels and taints, the pool's and the node's own, it accepts, that has a pod slot left, whose free CPU and
* memory fit its requests, and where no pod, one there or one counted on it before, shares it against either's
* required anti-affinity on {@code kubernetes.io/hostname},
* as Karpenter counts its nodes, those still joining among them, before it launches another. A cordoned node
* has no room.
*/
static List<PendingPod> withoutRoom(List<PendingPod> pods, List<PoolNode> nodes) {
long[] freeCpu = new long[nodes.size()];
long[] freeMemory = new long[nodes.size()];
int[] freePods = new int[nodes.size()];
List<List<BoundPod>> onNode = new ArrayList<>();
for (int i = 0; i < nodes.size(); i++) {
PoolNode node = nodes.get(i);
onNode.add(new ArrayList<>(node.pods()));
freeCpu[i] = node.freeCpuMillis();
freeMemory[i] = node.freeMemoryBytes();
freePods[i] = node.freePods();
}
List<PendingPod> left = new ArrayList<>();
for (PendingPod pod : pods) {
boolean placed = false;
for (int i = 0; i < nodes.size() && !placed; i++) {
PoolNode node = nodes.get(i);
if (node.schedulable() && freePods[i] > 0 && freeCpu[i] >= pod.cpuMillis()
&& freeMemory[i] >= pod.memoryBytes()
&& pod.fits(labels(node.instanceType(), node.pool(), node.zone()), node.taints())
&& onNode.get(i).stream().noneMatch(other -> other.conflicts(pod))) {
freeCpu[i] -= pod.cpuMillis();
freeMemory[i] -= pod.memoryBytes();
freePods[i]--;
onNode.get(i).add(pod.bound());
placed = true;
}
}
if (!placed) {
left.add(pod);
}
}
return left;
}
private static List<String> zonesOf(NodePool pool, Map<String, List<String>> zonesByNodeClass) {
List<String> zones = zonesByNodeClass.getOrDefault(pool.nodeClass(), List.of());
return zones.isEmpty() ? Collections.singletonList(null) : zones;
}
private static Optional<Placement> candidate(NodePool pool, List<CatalogInstanceType> sized, List<String> zones,
PendingPod pod, long cpuMillis, long memoryBytes) {
for (CatalogInstanceType type : sized) {
if (type.vcpu * 1000L < cpuMillis || type.memoryMib * 1024L * 1024L < memoryBytes) {
continue;
}
for (String zone : zones) {
Map<String, String> labels = labels(type, pool, zone);
if (poolAllows(pool, labels) && pod.fits(labels, pool.taints())) {
return Optional.of(new Placement(type, zone));
}
}
}
return Optional.empty();
}
/** The NodePools of {@code kubectl get nodepools -o json}. */
static List<NodePool> nodePools(JsonNode list) {
List<NodePool> pools = new ArrayList<>();
for (JsonNode item : list.path("items")) {
JsonNode template = item.path("spec").path("template");
Map<String, String> labels = new LinkedHashMap<>();
template.path("metadata").path("labels").properties()
.forEach(e -> labels.put(e.getKey(), e.getValue().asText()));
List<Taint> taints = new ArrayList<>();
template.path("spec").path("taints").forEach(t -> taints.add(new Taint(t.path("key").asText(),
t.path("value").asText(""), t.path("effect").asText())));
pools.add(new NodePool(item.path("metadata").path("name").asText(),
template.path("spec").path("nodeClassRef").path("name").asText("default"),
requirements(template.path("spec").path("requirements")), List.copyOf(taints), labels,
item.path("spec").path("weight").asInt(0)));
}
return pools;
}
/**
* The pods of {@code kubectl get pods -A -o json} the scheduler marked unschedulable and a new node could take.
* As Karpenter does, a DaemonSet's pods and pods pinned to a named node ({@code matchFields}) are left out, as
* are pods whose required node affinity can match no node (only empty terms).
*/
static List<PendingPod> unschedulablePods(JsonNode list) {
List<PendingPod> pods = new ArrayList<>();
for (JsonNode item : list.path("items")) {
if (!"Pending".equals(item.path("status").path("phase").asText())
|| !item.path("spec").path("nodeName").asText("").isEmpty()) {
continue;
}
boolean unschedulable = false;
for (JsonNode condition : item.path("status").path("conditions")) {
unschedulable |= "PodScheduled".equals(condition.path("type").asText())
&& "False".equals(condition.path("status").asText())
&& "Unschedulable".equals(condition.path("reason").asText());
}
if (!unschedulable) {
continue;
}
boolean daemonSet = false;
for (JsonNode owner : item.path("metadata").path("ownerReferences")) {
daemonSet |= "DaemonSet".equals(owner.path("kind").asText());
}
JsonNode spec = item.path("spec");
JsonNode termList = spec.path("affinity").path("nodeAffinity")
.path("requiredDuringSchedulingIgnoredDuringExecution").path("nodeSelectorTerms");
boolean pinned = false;
List<List<Requirement>> terms = new ArrayList<>();
for (JsonNode term : termList) {
pinned |= !term.path("matchFields").isEmpty();
// An empty term matches no node, as Kubernetes reads it, so it adds no alternative.
if (!term.path("matchExpressions").isEmpty()) {
terms.add(requirements(term.path("matchExpressions")));
}
}
if (daemonSet || pinned || (!termList.isEmpty() && terms.isEmpty())) {
continue;
}
long[] requests = requests(spec);
Map<String, String> selector = new LinkedHashMap<>();
spec.path("nodeSelector").properties().forEach(e -> selector.put(e.getKey(), e.getValue().asText()));
List<Toleration> tolerations = new ArrayList<>();
spec.path("tolerations").forEach(t -> tolerations.add(new Toleration(t.path("key").asText(""),
t.path("operator").asText("Equal"), t.path("value").asText(""), t.path("effect").asText(""))));
String namespace = item.path("metadata").path("namespace").asText();
pods.add(new PendingPod(namespace, item.path("metadata").path("name").asText(), requests[0], requests[1],
selector, List.copyOf(terms), List.copyOf(tolerations), podLabels(item), antiAffinity(item)));
}
return pods;
}
/** The pods of {@code kubectl get pods -A -o json} bound to each node that haven't finished. */
static Map<String, List<BoundPod>> boundPodsByNode(JsonNode list) {
Map<String, List<BoundPod>> byNode = new LinkedHashMap<>();
for (JsonNode item : list.path("items")) {
String node = item.path("spec").path("nodeName").asText("");
String phase = item.path("status").path("phase").asText();
if (node.isEmpty() || "Succeeded".equals(phase) || "Failed".equals(phase)) {
continue;
}
byNode.computeIfAbsent(node, k -> new ArrayList<>()).add(new BoundPod(
item.path("metadata").path("namespace").asText(), podLabels(item), antiAffinity(item)));
}
return byNode;
}
private static Map<String, String> podLabels(JsonNode item) {
Map<String, String> labels = new LinkedHashMap<>();
item.path("metadata").path("labels").properties().forEach(e -> labels.put(e.getKey(), e.getValue().asText()));
return labels;
}
/**
* A pod's required anti-affinity terms on {@code kubernetes.io/hostname}, the ones a node's pods decide; those on
* another topology key, a zone's say, aren't modelled. A term without a label selector matches no pod.
*/
private static List<PodTerm> antiAffinity(JsonNode item) {
List<PodTerm> terms = new ArrayList<>();
String own = item.path("metadata").path("namespace").asText();
for (JsonNode term : item.path("spec").path("affinity").path("podAntiAffinity")
.path("requiredDuringSchedulingIgnoredDuringExecution")) {
JsonNode selector = term.path("labelSelector");
if (!HOSTNAME_LABEL.equals(term.path("topologyKey").asText()) || selector.isMissingNode()
|| selector.isNull()) {
continue;
}
Map<String, String> matchLabels = new LinkedHashMap<>();
selector.path("matchLabels").properties().forEach(e -> matchLabels.put(e.getKey(), e.getValue().asText()));
Set<String> named = new HashSet<>();
term.path("namespaces").forEach(n -> named.add(n.asText()));
if (named.isEmpty()) {
named.add(own);
}
// A namespaceSelector, which Floci can't evaluate without the namespaces' labels, is read as all of them.
Set<String> namespaces = term.has("namespaceSelector") ? null : Set.copyOf(named);
terms.add(new PodTerm(matchLabels, requirements(selector.path("matchExpressions")), namespaces));
}
return List.copyOf(terms);
}
/**
* The CPU (millicores) and memory (bytes) the pods of {@code kubectl get pods -A -o json} bound to each node
* request, and how many they are, those that finished left out.
*/
static Map<String, long[]> requestsByNode(JsonNode list) {
Map<String, long[]> byNode = new LinkedHashMap<>();
for (JsonNode item : list.path("items")) {
String node = item.path("spec").path("nodeName").asText("");
String phase = item.path("status").path("phase").asText();
if (node.isEmpty() || "Succeeded".equals(phase) || "Failed".equals(phase)) {
continue;
}
long[] requests = requests(item.path("spec"));
long[] total = byNode.computeIfAbsent(node, k -> new long[3]);
total[0] += requests[0];
total[1] += requests[1];
total[2]++;
}
return byNode;
}
/**
* A pod spec's CPU (millicores) and memory (bytes) requests as the scheduler counts them: its containers' and
* sidecars' sum, or what its init containers need at once when that is larger, plus the pod's overhead.
*/
private static long[] requests(JsonNode spec) {
long[] total = new long[2];
for (JsonNode container : spec.path("containers")) {
JsonNode requests = container.path("resources").path("requests");
total[0] += cpuMillis(requests.path("cpu").asText(""));
total[1] += bytes(requests.path("memory").asText(""));
}
// Init containers run in order. A sidecar (restartPolicy Always) keeps running from its start, alongside the
// init containers after it and the app's; any other one runs alone with the sidecars started before it.
long[] sidecars = new long[2];
long[] init = new long[2];
for (JsonNode container : spec.path("initContainers")) {
JsonNode requests = container.path("resources").path("requests");
long cpu = cpuMillis(requests.path("cpu").asText(""));
long memory = bytes(requests.path("memory").asText(""));
boolean sidecar = "Always".equals(container.path("restartPolicy").asText());
init[0] = Math.max(init[0], sidecars[0] + cpu);
init[1] = Math.max(init[1], sidecars[1] + memory);
if (sidecar) {
sidecars[0] += cpu;
sidecars[1] += memory;
}
}
total[0] = Math.max(total[0] + sidecars[0], init[0]) + cpuMillis(spec.path("overhead").path("cpu").asText(""));
total[1] = Math.max(total[1] + sidecars[1], init[1]) + bytes(spec.path("overhead").path("memory").asText(""));
return total;
}
private static List<Requirement> requirements(JsonNode list) {
List<Requirement> requirements = new ArrayList<>();
for (JsonNode r : list) {
List<String> values = new ArrayList<>();
r.path("values").forEach(v -> values.add(v.asText()));
requirements.add(new Requirement(r.path("key").asText(), r.path("operator").asText(), List.copyOf(values)));
}
return List.copyOf(requirements);
}
/**
* A CPU quantity in millicores: {@code 100m}, {@code 1}, {@code 0.5}, {@code 2e3}; rounded up, as Kubernetes
* does; 0 for none or one Floci can't read.
*/
static long cpuMillis(String quantity) {
Matcher m = QUANTITY.matcher(quantity.trim());
if (!m.matches()) {
return 0;
}
BigDecimal number = new BigDecimal(m.group(1));
BigDecimal millis = switch (m.group(2)) {
case "m" -> number;
case "" -> number.movePointRight(3);
case "k" -> number.movePointRight(6);
default -> BigDecimal.ZERO;
};
return millis.setScale(0, RoundingMode.CEILING).longValue();
}
/**
* A memory quantity in bytes: {@code 64Mi}, {@code 1G}, {@code 128974848}, {@code 1e9}, {@code 1.5Gi}; rounded
* up; 0 for none or one Floci can't read.
*/
static long bytes(String quantity) {
Matcher m = QUANTITY.matcher(quantity.trim());
if (!m.matches()) {
return 0;
}
BigDecimal number = new BigDecimal(m.group(1));
BigDecimal value = switch (m.group(2)) {
case "" -> number;
case "m" -> number.movePointLeft(3);
case "k" -> number.movePointRight(3);
case "M" -> number.movePointRight(6);
case "G" -> number.movePointRight(9);
case "T" -> number.movePointRight(12);
case "P" -> number.movePointRight(15);
case "E" -> number.movePointRight(18);
case "Ki" -> number.multiply(BigDecimal.valueOf(1L << 10));
case "Mi" -> number.multiply(BigDecimal.valueOf(1L << 20));
case "Gi" -> number.multiply(BigDecimal.valueOf(1L << 30));
case "Ti" -> number.multiply(BigDecimal.valueOf(1L << 40));
case "Pi" -> number.multiply(BigDecimal.valueOf(1L << 50));
case "Ei" -> number.multiply(BigDecimal.valueOf(1L << 60));
default -> BigDecimal.ZERO;
};
return value.setScale(0, RoundingMode.CEILING).longValue();
}
}
@@ -14,7 +14,9 @@ import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -73,39 +75,100 @@ public final class EksBootstrapUserData {
}
private static Optional<String> extractFromNodeadm(String userData) {
if (!userData.contains("NodeConfig") && !userData.contains("node.eks.aws")) {
return Optional.empty();
}
if (userData.contains("Content-Type:") || userData.contains("MIME-Version:") || userData.contains("multipart/")) {
Optional<String> mimeExtracted = extractFromMime(userData);
if (mimeExtracted.isPresent()) {
return mimeExtracted;
return nodeConfigs(userData).stream()
.map(root -> root.path("spec").path("cluster").path("name").asText().strip())
.filter(name -> !name.isEmpty())
.findFirst();
}
/**
* The labels a nodeadm {@code NodeConfig} in the user data gives the node through its kubelet's
* {@code --node-labels} flag, as a kubelet registers them; empty without one.
*/
public static Map<String, String> nodeLabels(String userData) {
Map<String, String> labels = new LinkedHashMap<>();
for (String value : kubeletFlag(userData, "--node-labels")) {
for (String pair : value.split(",")) {
int eq = pair.indexOf('=');
if (eq > 0) {
labels.put(pair.substring(0, eq).strip(), pair.substring(eq + 1).strip());
}
}
}
return parseNodeConfigYaml(userData);
return labels;
}
private static Optional<String> extractFromMime(String userData) {
try {
Message message = new DefaultMessageBuilder().parseMessage(
new ByteArrayInputStream(userData.getBytes(StandardCharsets.UTF_8)));
return extractNodeConfigFromEntity(message);
} catch (Exception ignored) {
// Malformed MIME structure in user data is treated as non-multipart content.
return Optional.empty();
/**
* The taints a nodeadm {@code NodeConfig} in the user data registers the node with through its kubelet's
* {@code --register-with-taints} flag ({@code key[=value]:Effect}), as {@code key}, {@code value} and
* {@code effect}; empty without one.
*/
public static List<Map<String, String>> registerWithTaints(String userData) {
List<Map<String, String>> taints = new ArrayList<>();
for (String value : kubeletFlag(userData, "--register-with-taints")) {
for (String spec : value.split(",")) {
int colon = spec.lastIndexOf(':');
if (colon <= 0) {
continue;
}
String keyValue = spec.substring(0, colon).strip();
int eq = keyValue.indexOf('=');
Map<String, String> taint = new LinkedHashMap<>();
taint.put("key", eq < 0 ? keyValue : keyValue.substring(0, eq));
taint.put("value", eq < 0 ? "" : keyValue.substring(eq + 1));
taint.put("effect", spec.substring(colon + 1).strip());
taints.add(taint);
}
}
return taints;
}
private static Optional<String> extractNodeConfigFromEntity(Entity entity) {
/** The values of a kubelet flag in the {@code spec.kubelet.flags} of every NodeConfig in the user data. */
private static List<String> kubeletFlag(String userData, String flag) {
List<String> values = new ArrayList<>();
if (userData == null || userData.isBlank()) {
return values;
}
for (JsonNode root : nodeConfigs(userData)) {
for (JsonNode entry : root.path("spec").path("kubelet").path("flags")) {
String text = entry.asText().strip();
if (text.startsWith(flag + "=")) {
values.add(stripQuotes(text.substring(flag.length() + 1)));
}
}
}
return values;
}
/** Every nodeadm {@code NodeConfig} document in the user data, plain YAML or inside MIME multipart parts. */
private static List<JsonNode> nodeConfigs(String userData) {
if (!userData.contains("NodeConfig") && !userData.contains("node.eks.aws")) {
return List.of();
}
List<JsonNode> found = new ArrayList<>();
if (userData.contains("Content-Type:") || userData.contains("MIME-Version:") || userData.contains("multipart/")) {
try {
Message message = new DefaultMessageBuilder().parseMessage(
new ByteArrayInputStream(userData.getBytes(StandardCharsets.UTF_8)));
collectNodeConfigs(message, found);
} catch (Exception ignored) {
// Malformed MIME structure in user data is treated as non-multipart content.
}
if (!found.isEmpty()) {
return found;
}
}
parseNodeConfigYaml(userData, found);
return found;
}
private static void collectNodeConfigs(Entity entity, List<JsonNode> found) {
if (entity == null) {
return Optional.empty();
return;
}
if (entity.getBody() instanceof Multipart multipart) {
for (Entity part : multipart.getBodyParts()) {
Optional<String> found = extractNodeConfigFromEntity(part);
if (found.isPresent()) {
return found;
}
collectNodeConfigs(part, found);
}
} else if (entity.getBody() instanceof SingleBody singleBody) {
try {
@@ -113,32 +176,27 @@ public final class EksBootstrapUserData {
singleBody.writeTo(out);
String content = out.toString(StandardCharsets.UTF_8);
if (content.contains("NodeConfig") || (entity.getMimeType() != null && entity.getMimeType().contains("node.eks.aws"))) {
return parseNodeConfigYaml(content);
parseNodeConfigYaml(content, found);
}
} catch (Exception ignored) {
// Ignore unreadable or malformed MIME body parts and continue scanning.
}
}
return Optional.empty();
}
private static Optional<String> parseNodeConfigYaml(String yaml) {
private static void parseNodeConfigYaml(String yaml, List<JsonNode> found) {
try {
Iterator<JsonNode> it = YAML_MAPPER.readValues(
YAML_MAPPER.getFactory().createParser(yaml), JsonNode.class);
while (it.hasNext()) {
JsonNode root = it.next();
if (root != null && "NodeConfig".equals(root.path("kind").asText())) {
String name = root.path("spec").path("cluster").path("name").asText();
if (name != null && !name.isBlank()) {
return Optional.of(name.strip());
}
found.add(root);
}
}
} catch (Exception ignored) {
// Non-YAML or invalid NodeConfig user data is safely ignored.
}
return Optional.empty();
}
private static String stripQuotes(String s) {
@@ -1,6 +1,7 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
@@ -131,6 +132,7 @@ public class EksClusterManager
DnsRecordSource, DnsForwardingRuleSource {
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final ObjectMapper NODE_MAPPER = new ObjectMapper();
private static final int K3S_API_SERVER_PORT = 6443;
static final String DEFAULT_NODE_INSTANCE_TYPE = "m5.large";
/** The tag naming the cluster, on the cluster's node and on its node groups' Auto Scaling groups. */
@@ -266,6 +268,9 @@ public class EksClusterManager
private final Map<String, Set<String>> programmedClusterRoutes = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> clusterRouteLocks = new ConcurrentHashMap<>();
private final StripedLocks podIdentityForwardLocks = new StripedLocks(256);
private final StripedLocks joinLocks = new StripedLocks(256);
/** Instances whose node was removed, never joined again: they are being terminated. */
private final Set<String> removedInstanceIds = ConcurrentHashMap.newKeySet();
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
@@ -4277,6 +4282,27 @@ public class EksClusterManager
if (cluster == null || instance == null) {
return;
}
// One instance's join and removal run one at a time, so a join that was waiting doesn't bring back a node
// just removed.
boolean joined;
synchronized (joinLocks.lockFor(instance.getInstanceId())) {
joined = !removedInstanceIds.contains(instance.getInstanceId()) && joinHoldingLock(cluster, instance);
}
if (!joined) {
return;
}
for (Consumer<Instance> listener : nodeRegistrationListeners) {
try {
listener.accept(instance);
} catch (Exception e) {
LOG.warnv("Node registration listener failed for joined instance {0} on cluster {1}: {2}",
instance.getInstanceId(), cluster.getName(), e.getMessage());
}
}
}
/** Joins the instance, holding its join lock; false when it was joined already. */
private boolean joinHoldingLock(Cluster cluster, Instance instance) {
String clusterKey = clusterResourceName(cluster);
synchronized (joinedClusterInstances) {
for (Map.Entry<String, Map<String, Instance>> entry : joinedClusterInstances.entrySet()) {
@@ -4287,7 +4313,7 @@ public class EksClusterManager
}
Map<String, Instance> current = joinedClusterInstances.get(clusterKey);
if (current != null && current.containsKey(instance.getInstanceId())) {
return;
return false;
}
}
@@ -4315,15 +4341,40 @@ public class EksClusterManager
.put(instance.getInstanceId(), instance);
}
recordJoinedInstanceId(cluster, instance);
return true;
}
for (Consumer<Instance> listener : nodeRegistrationListeners) {
try {
listener.accept(instance);
} catch (Exception e) {
LOG.warnv("Node registration listener failed for joined instance {0} on cluster {1}: {2}",
instance.getInstanceId(), cluster.getName(), e.getMessage());
/**
* Takes a joined instance out of the cluster before it is terminated: its node is deleted and it is no longer
* joined, and the cluster no longer records it. A node that can't be deleted throws and leaves the instance
* joined, so the caller keeps it and can try again.
*/
void removeJoinedNode(Cluster cluster, Instance instance) {
synchronized (joinLocks.lockFor(instance.getInstanceId())) {
removeJoinedNodeHoldingLock(cluster, instance);
removedInstanceIds.add(instance.getInstanceId());
}
}
private void removeJoinedNodeHoldingLock(Cluster cluster, Instance instance) {
String region = instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster);
String containerId = cluster.getContainerId();
if (containerId != null && !containerId.isBlank()) {
String nodeName = deriveInstanceNodeName(instance, region);
ContainerExec.Result result = execInContainerForResult(containerId, new String[]{"kubectl", "delete",
"node", nodeName, "--ignore-not-found=true", "--wait=false"}, 15);
if (result.exitCode() != 0) {
throw new IllegalStateException("kubectl delete node " + nodeName + " failed: " + result.summary());
}
}
Map<String, Instance> joined = joinedClusterInstances.get(clusterResourceName(cluster));
if (joined != null) {
joined.remove(instance.getInstanceId());
}
// Forgotten as well, so the readiness poller doesn't join it again while its instance is shutting down.
if (cluster.getJoinedInstanceIds() != null) {
cluster.getJoinedInstanceIds().remove(instance.getInstanceId());
}
}
void recordJoinedInstanceId(Cluster cluster, Instance instance) {
@@ -4409,12 +4460,22 @@ public class EksClusterManager
String k8sArch = (rawArch != null && (rawArch.toLowerCase(Locale.ROOT).contains("arm64")
|| rawArch.toLowerCase(Locale.ROOT).contains("aarch64"))) ? "arm64" : "amd64";
String nodeJson = String.format(Locale.ROOT,
"{\"apiVersion\":\"v1\",\"kind\":\"Node\",\"metadata\":{\"name\":\"%s\","
+ "\"labels\":{\"topology.kubernetes.io/zone\":\"%s\",\"topology.kubernetes.io/region\":\"%s\","
+ "\"node.kubernetes.io/instance-type\":\"%s\",\"kubernetes.io/hostname\":\"%s\","
+ "\"kubernetes.io/os\":\"linux\",\"kubernetes.io/arch\":\"%s\"}},\"spec\":{\"providerID\":\"%s\"}}",
nodeName, az, region, instanceType, nodeName, k8sArch, providerId);
// As a kubelet registers: the labels and taints its NodeConfig's flags name, under the node's own labels.
Map<String, String> labels = new LinkedHashMap<>(EksBootstrapUserData.nodeLabels(instance.getUserData()));
labels.put("topology.kubernetes.io/zone", az);
labels.put("topology.kubernetes.io/region", region);
labels.put("node.kubernetes.io/instance-type", instanceType);
labels.put("kubernetes.io/hostname", nodeName);
labels.put("kubernetes.io/os", "linux");
labels.put("kubernetes.io/arch", k8sArch);
Map<String, Object> spec = new LinkedHashMap<>();
spec.put("providerID", providerId);
List<Map<String, String>> taints = EksBootstrapUserData.registerWithTaints(instance.getUserData());
if (!taints.isEmpty()) {
spec.put("taints", taints);
}
String nodeJson = NODE_MAPPER.writeValueAsString(Map.of("apiVersion", "v1", "kind", "Node",
"metadata", Map.of("name", nodeName, "labels", labels), "spec", spec));
ContainerExec.Result applyRes = execInContainerForResult(containerId,
new String[]{"sh", "-c", "echo '" + nodeJson.replace("'", "'\\''") + "' | kubectl apply -f -"}, 15);
@@ -131,7 +131,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
/** Looked up when used: the reconciler depends on this service. */
private final jakarta.enterprise.inject.Instance<EksAutoModeLoadBalancers> autoModeLoadBalancers;
private final jakarta.enterprise.inject.Instance<EksAutoModeCleanup> autoModeCleanups;
private final AutoScalingService autoScaling;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
private final Map<String, UserDataClaim> appliedClusterUserData = new ConcurrentHashMap<>();
@@ -152,7 +152,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
EksOidcService oidcService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons, AutoScalingService autoScaling,
jakarta.enterprise.inject.Instance<EksAutoModeLoadBalancers> autoModeLoadBalancers) {
jakarta.enterprise.inject.Instance<EksAutoModeCleanup> autoModeCleanups) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {
});
@@ -173,7 +173,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
this.podIdentityAssociations = podIdentityAssociations;
this.addons = addons;
this.autoScaling = autoScaling;
this.autoModeLoadBalancers = autoModeLoadBalancers;
this.autoModeCleanups = autoModeCleanups;
if (this.clusterManager != null) {
this.clusterManager.setEc2Service(this.ec2Service);
}
@@ -378,7 +378,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
String reg = instEntry.getValue();
RequestScopes.runAs(accountId, reg, () -> {
Instance inst = ec2Service.getInstance(reg, instId).orElse(null);
if (inst == null || (inst.getState() != null && "terminated".equals(inst.getState().getName()))) {
// One shutting down is on its way out too: joining it again would bring back the node it took away.
if (inst == null || (inst.getState() != null && ("terminated".equals(inst.getState().getName())
|| "shutting-down".equals(inst.getState().getName())))) {
cluster.getJoinedInstanceIds().remove(instId);
prunedInstanceIds.add(instId);
} else {
@@ -1798,9 +1800,10 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
endClusterNodeInstance(cluster);
// Auto Mode's instances hold the cluster security group, so they go before it does.
deleteAutoModeResources(cluster);
deleteClusterSecurityGroup(cluster);
deleteNodeGroupAutoScalingGroups(cluster.getAccountId(), cluster);
deleteAutoModeLoadBalancers(cluster);
if (podIdentityAssociations != null) {
podIdentityAssociations.deleteClusterAssociations(cluster);
}
@@ -1824,12 +1827,33 @@ 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 && autoModeLoadBalancers.isResolvable()) {
String region = clusterRegion(cluster);
RequestScopes.runAs(cluster.getAccountId(), region,
() -> autoModeLoadBalancers.get().deleteLoadBalancers(cluster, region));
/**
* What the cluster's EKS Auto Mode capabilities made outside it go with it, as on AWS: the load balancers, and
* the compute capability's instances and instance profiles. Each cleanup runs even when another fails; a
* failure is then thrown, so the cluster record stays and a retried delete finishes the cleanup, as a cluster
* security group that can't be deleted keeps it.
*/
private void deleteAutoModeResources(Cluster cluster) {
if (autoModeCleanups == null) {
return;
}
String region = clusterRegion(cluster);
RuntimeException failure = null;
for (EksAutoModeCleanup cleanup : autoModeCleanups) {
try {
RequestScopes.runAs(cluster.getAccountId(), region, () -> cleanup.clusterDeleted(cluster, region));
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode resources of cluster {0} were not all deleted: {1}", cluster.getName(),
e.getMessage());
if (failure == null) {
failure = e;
} else {
failure.addSuppressed(e);
}
}
}
if (failure != null) {
throw failure;
}
}
@@ -18,6 +18,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.time.Duration;
import java.util.List;
@@ -34,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
class EksAutoModeComputeDockerNightlyIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksAutoModeComputeDockerNightlyIntegrationTest.class);
@@ -0,0 +1,369 @@
package io.floci.aws.services.eks;
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.Ec2ImageCatalog;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Reservation;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.eks.model.CertificateAuthority;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.ComputeConfig;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.InstanceProfile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
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.doThrow;
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 EksAutoModeComputeTest {
private static final String REGION = "us-east-1";
private static final String PENDING_POD = """
{"items": [{"metadata": {"namespace": "default", "name": "web"},
"spec": {"nodeSelector": {"karpenter.sh/nodepool": "general-purpose"},
"containers": [{"resources": {"requests": {"cpu": "100m", "memory": "64Mi"}}}]},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}]}""";
private static final String POOLS = """
{"items": [{"metadata": {"name": "general-purpose"}, "spec": {"template": {"spec": {
"nodeClassRef": {"name": "default"},
"requirements": [{"key": "kubernetes.io/arch", "operator": "In", "values": ["amd64"]}]}}}}]}""";
private static final String NODE_CLASSES = """
{"items": [{"metadata": {"name": "default"}, "spec": {"role": "auto-node",
"subnetSelectorTerms": [{"id": "subnet-a"}, {"id": "subnet-b"}],
"securityGroupSelectorTerms": [{"id": "sg-cluster"}]}}]}""";
private final EksClusterManager clusterManager = mock(EksClusterManager.class);
private final Ec2Service ec2 = mock(Ec2Service.class);
private final IamService iam = mock(IamService.class);
private final Ec2InstanceTypeCatalog instanceTypes = mock(Ec2InstanceTypeCatalog.class);
private final EksService eksService = mock(EksService.class);
private final EksAutoModeCompute compute = new EksAutoModeCompute(eksService, clusterManager, ec2,
iam, instanceTypes, mock(EmulatorConfig.class));
private final Map<String, String> lists = new HashMap<>(Map.of("pods", PENDING_POD,
"nodepools", POOLS, "nodeclasses", NODE_CLASSES, "nodes", "{\"items\": []}"));
@BeforeEach
void cluster() {
when(clusterManager.execInContainerForResult(eq("k3s-1"), 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.imageCatalog()).thenReturn(new Ec2ImageCatalog());
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of());
when(eksService.runningClusters()).thenReturn(List.of(new AccountAwareStorageBackend.AccountEntry<>(
"000000000000", "prod", cluster("prod"))));
when(ec2.describeSubnets(eq(REGION), anyList(), any())).thenReturn(List.of(subnet("subnet-a", "us-east-1a"),
subnet("subnet-b", "us-east-1b")));
CatalogInstanceType large = new CatalogInstanceType();
large.instanceType = "c7a.large";
large.vcpu = 2;
large.memoryMib = 4096;
large.supportedArchitectures = List.of("x86_64");
when(instanceTypes.instanceTypes()).thenReturn(List.of(large));
when(iam.listInstanceProfiles(anyString())).thenReturn(List.of());
when(iam.createInstanceProfile(anyString(), anyString())).thenAnswer(inv -> new InstanceProfile("AIPA1",
inv.getArgument(0), inv.getArgument(1), "arn:aws:iam::000000000000:instance-profile"
+ inv.getArgument(1) + inv.getArgument(0)));
Instance launched = new Instance();
launched.setInstanceId("i-1");
Reservation reservation = new Reservation();
reservation.setInstances(List.of(launched));
when(ec2.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(), anyString(),
anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(), any(),
anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any())).thenReturn(reservation);
}
@Test
void anUnschedulablePodGetsAnInstanceOfItsPoolInTheNodeClassesSubnetWithItsProfileTagsAndBootstrap() {
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
ArgumentCaptor<List<String>> groups = ArgumentCaptor.forClass(List.class);
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
ArgumentCaptor<String> userData = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> profile = ArgumentCaptor.forClass(String.class);
// The EKS optimized AL2023 x86_64 image of the cluster's version, from the bundled catalog.
verify(ec2).runInstances(eq(REGION), eq("ami-0abcdef1234567891"), eq("c7a.large"), eq(1), eq(1), isNull(),
groups.capture(), eq("subnet-a"), anyString(), tags.capture(), userData.capture(), profile.capture(),
isNull(), isNull(), eq(0), isNull(), isNull(), isNull(), anyString(), eq(false), isNull(), isNull(),
isNull(), eq(false), isNull(), isNull());
assertEquals(List.of("sg-cluster"), groups.getValue());
assertEquals(List.of("eks:eks-cluster-name=prod", "eks:kubernetes-node-pool-name=general-purpose",
"eks:kubernetes-node-class-name=default", "kubernetes.io/cluster/prod=owned",
"aws:ec2:managed-launch=eks-auto"),
tags.getValue().stream().map(t -> t.getKey() + "=" + t.getValue()).toList());
assertEquals("""
apiVersion: node.eks.aws/v1alpha1
kind: NodeConfig
spec:
cluster:
name: prod
apiServerEndpoint: https://prod.example
certificateAuthority: Q0E=
kubelet:
flags:
- --node-labels=kubernetes.io/arch=amd64,kubernetes.io/os=linux,node.kubernetes.io/instance-type=c7a.large,karpenter.sh/capacity-type=on-demand,eks.amazonaws.com/instance-category=c,eks.amazonaws.com/instance-generation=7,eks.amazonaws.com/instance-family=c7a,eks.amazonaws.com/instance-size=large,eks.amazonaws.com/instance-cpu=2,eks.amazonaws.com/instance-memory=4096,karpenter.sh/nodepool=general-purpose,eks.amazonaws.com/compute-type=auto,topology.kubernetes.io/zone=us-east-1a
""", userData.getValue());
// The node registers with those labels, as a kubelet given the flag does.
assertEquals("general-purpose", EksBootstrapUserData.nodeLabels(userData.getValue()).get("karpenter.sh/nodepool"));
assertEquals("prod", EksBootstrapUserData.extractClusterName(userData.getValue()).orElseThrow());
ArgumentCaptor<String> profileName = ArgumentCaptor.forClass(String.class);
verify(iam).createInstanceProfile(profileName.capture(), eq("/eks/us-east-1/prod/"));
assertTrue(profileName.getValue().matches("eks-us-east-1-prod-\\d+"));
verify(iam).addRoleToInstanceProfile(profileName.getValue(), "auto-node");
assertEquals("arn:aws:iam::000000000000:instance-profile/eks/us-east-1/prod/" + profileName.getValue(),
profile.getValue());
}
@Test
void aPoolWhoseNodeClassIsMissingOrWhoseImageTheCatalogLacksLaunchesNothing() {
lists.put("nodeclasses", "{\"items\": []}");
compute.reconcile(cluster("prod"), REGION);
lists.put("nodeclasses", NODE_CLASSES);
Cluster unsupported = cluster("prod");
unsupported.setVersion("1.0");
compute.reconcile(unsupported, REGION);
verify(ec2, never()).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
}
@Test
void aLaunchWhoseClusterWasDeletedMeanwhileIsUndone() {
// Running when the launch starts, gone once the instance is up.
when(eksService.runningClusters()).thenReturn(List.of(new AccountAwareStorageBackend.AccountEntry<>(
"000000000000", "prod", cluster("prod"))), List.of());
Instance launched = new Instance();
launched.setInstanceId("i-1");
Reservation reservation = new Reservation();
reservation.setInstances(List.of(launched));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(), List.of(reservation));
compute.reconcile(cluster("prod"), REGION);
verify(ec2).terminateInstances(REGION, List.of("i-1"));
}
@Test
void aNodeThatNeverRegisteredIsTerminatedAndItsPodsGetAnother() {
Instance stuck = new Instance();
stuck.setInstanceId("i-stuck");
stuck.setInstanceType("c7a.large");
stuck.setLaunchTime(Instant.now().minus(EksAutoModeCompute.REGISTRATION_WAIT).minusSeconds(1));
stuck.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(stuck));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
when(clusterManager.deriveInstanceNodeName(any(), eq(REGION))).thenReturn("never-joined");
compute.reconcile(cluster("prod"), REGION);
verify(ec2).terminateInstances(REGION, List.of("i-stuck"));
verify(ec2).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
}
@Test
void aDeletedClustersInstancesAreTerminatedAndItsProfilesDeleted() {
Instance node = new Instance();
node.setInstanceId("i-node");
Reservation reservation = new Reservation();
reservation.setInstances(List.of(node));
// Running, then still shutting down once after TerminateInstances, then gone.
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation),
List.of(reservation), List.of());
InstanceProfile profile = new InstanceProfile("AIPA1", "eks-us-east-1-prod-1", "/eks/us-east-1/prod/",
"arn:aws:iam::000000000000:instance-profile/eks/us-east-1/prod/eks-us-east-1-prod-1");
profile.getRoleNames().add("auto-node");
when(iam.listInstanceProfiles("/eks/us-east-1/prod/")).thenReturn(new ArrayList<>(List.of(profile)));
compute.clusterDeleted(cluster("prod"), REGION);
verify(ec2).terminateInstances(REGION, List.of("i-node"));
verify(iam).removeRoleFromInstanceProfile("eks-us-east-1-prod-1", "auto-node");
verify(iam).deleteInstanceProfile("eks-us-east-1-prod-1");
}
/**
* A joined node has the room its kubelet says is allocatable, which is less than its instance type when the
* kubelet reserves some: a pod that fits the type but not what the node offers gets another node.
*/
@Test
void aJoinedNodeHasTheRoomItsKubeletSaysIsAllocatable() {
Instance joined = new Instance();
joined.setInstanceId("i-joined");
joined.setInstanceType("c7a.large");
joined.setLaunchTime(Instant.now());
joined.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(joined));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
when(clusterManager.deriveInstanceNodeName(any(), eq(REGION))).thenReturn("node-1");
CatalogInstanceType large = new CatalogInstanceType();
large.instanceType = "c7a.large";
large.vcpu = 2;
large.memoryMib = 4096;
large.supportedArchitectures = List.of("x86_64");
when(instanceTypes.find("c7a.large")).thenReturn(Optional.of(large));
Cluster cluster = cluster("prod");
String node = "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}, "
+ "\"status\": {\"allocatable\": {\"cpu\": \"%s\", \"memory\": \"3Gi\", \"pods\": \"110\"}}}]}";
lists.put("nodes", node.formatted("1900m"));
compute.reconcile(cluster, REGION);
verify(ec2, never()).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
lists.put("nodes", node.formatted("50m"));
compute.reconcile(cluster, REGION);
verify(ec2).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
}
/**
* A node that just registered carries {@code node.kubernetes.io/not-ready} until Kubernetes sees it Ready, as
* Floci's own Ready node does between its creation and its status: while it starts, that doesn't take its room,
* as Karpenter counts it, so its pending pod waits for it rather than get another node. A node still not ready
* after the registration wait has no room, so an unhealthy node doesn't hold pods for good.
*/
@Test
void aStartingNodesNotReadyTaintDoesntTakeItsRoom() {
Instance joined = new Instance();
joined.setInstanceId("i-joined");
joined.setInstanceType("c7a.large");
joined.setLaunchTime(Instant.now());
joined.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(joined));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
when(clusterManager.deriveInstanceNodeName(any(), eq(REGION))).thenReturn("node-1");
CatalogInstanceType large = new CatalogInstanceType();
large.instanceType = "c7a.large";
large.vcpu = 2;
large.memoryMib = 4096;
large.supportedArchitectures = List.of("x86_64");
when(instanceTypes.find("c7a.large")).thenReturn(Optional.of(large));
Cluster cluster = cluster("prod");
String node = "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}, "
+ "\"spec\": {\"taints\": [{\"key\": \"%s\", \"effect\": \"NoSchedule\"}]}}]}";
lists.put("nodes", node.formatted("node.kubernetes.io/not-ready"));
compute.reconcile(cluster, REGION);
verify(ec2, never()).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
// Still not ready once the registration wait is over, it has no room.
joined.setLaunchTime(Instant.now().minus(EksAutoModeCompute.REGISTRATION_WAIT).minusSeconds(1));
compute.reconcile(cluster, REGION);
verify(ec2).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
}
/**
* Turning compute off deletes each node before its instance is terminated: an instance whose node can't be
* deleted is kept running, so the next pass, finding it still there, tries again.
*/
@Test
void aNodeThatCantBeDeletedKeepsItsInstanceForTheNextPass() {
Cluster cluster = cluster("prod");
Instance stuck = new Instance();
stuck.setInstanceId("i-stuck");
Instance gone = new Instance();
gone.setInstanceId("i-gone");
Reservation reservation = new Reservation();
reservation.setInstances(List.of(stuck, gone));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
doThrow(new IllegalStateException("kubectl delete node failed")).doNothing()
.when(clusterManager).removeJoinedNode(cluster, stuck);
compute.removeNodes(cluster, REGION);
verify(ec2).terminateInstances(REGION, List.of("i-gone"));
verify(ec2, never()).terminateInstances(REGION, List.of("i-stuck", "i-gone"));
reservation.setInstances(List.of(stuck));
compute.removeNodes(cluster, REGION);
verify(ec2).terminateInstances(REGION, List.of("i-stuck"));
}
/**
* An instance shutting down still holds the cluster security group EKS deletes next, so the cleanup waits for it;
* one that doesn't finish in time fails the delete, which keeps the cluster for a retry.
*/
@Test
void aDeletedClustersInstanceThatDoesntFinishTerminatingFailsTheCleanup() {
Instance node = new Instance();
node.setInstanceId("i-node");
Reservation reservation = new Reservation();
reservation.setInstances(List.of(node));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
compute.terminationWait(Duration.ofMillis(300));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> compute.clusterDeleted(cluster("prod"), REGION));
assertEquals("EKS Auto Mode instances of cluster prod didn't finish terminating within PT0.3S",
failure.getMessage());
verify(ec2).terminateInstances(REGION, List.of("i-node"));
}
private static Subnet subnet(String id, String zone) {
Subnet subnet = new Subnet();
subnet.setSubnetId(id);
subnet.setAvailabilityZone(zone);
return subnet;
}
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.setVersion(EksService.DEFAULT_K8S_VERSION);
cluster.setContainerId("k3s-1");
cluster.setEndpoint("https://" + name + ".example");
cluster.setCertificateAuthority(new CertificateAuthority("Q0E="));
cluster.setComputeConfig(new ComputeConfig(true, List.of("general-purpose"), "arn:aws:iam::000000000000:role/auto-node"));
return cluster;
}
}
@@ -0,0 +1,176 @@
package io.floci.aws.services.eks;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.ClusterStatus;
import io.floci.aws.services.eks.model.ComputeConfig;
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.InstanceProfile;
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 org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* EKS Auto Mode compute on a real k3s node: a pod that asks for the {@code general-purpose} pool's nodes, which the
* cluster's own node isn't, is unschedulable, so a pass launches an instance for it, tagged as Auto Mode tags its
* instances, with the node role's instance profile. Once it has joined, as an instance launched with EKS bootstrap
* user data does, its node gets the pool's labels and the pod is scheduled on it. Turning compute off terminates
* the instance and takes its node out, and deleting the cluster deletes the profile. Each pass is called directly,
* one at a time with the reconciler's own interval, which makes the same choices; the join EKS makes on the
* instance's launch, from its user data, is made here, as the instance isn't launched through a request.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
class EksAutoModeNodesDockerNightlyIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksAutoModeNodesDockerNightlyIntegrationTest.class);
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
@Inject
DockerClient dockerClient;
@Inject
EksClusterManager eksClusterManager;
@Inject
EksAutoModeCompute compute;
@Inject
Ec2Service ec2;
@Inject
IamService iam;
@Inject
EksService eksService;
private Cluster cluster;
@BeforeEach
void requireDocker() {
boolean dockerAvailable = DockerAvailability.answers(dockerClient);
if (!dockerAvailable) {
LOG.warn("Docker daemon is not available; skipping EksAutoModeNodesDockerNightlyIntegrationTest");
}
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for the Auto Mode nodes test");
}
@AfterEach
void tearDown() {
if (cluster != null) {
try {
eksClusterManager.stopCluster(cluster);
} catch (Exception e) {
LOG.warnv("Failed to stop the test cluster: {0}", e.getMessage());
}
try {
eksService.deleteClusterForAccount(ACCOUNT, cluster.getName());
} catch (Exception e) {
LOG.warnv("Failed to delete the test cluster: {0}", e.getMessage());
}
}
}
@Test
void anUnschedulablePodGetsANodeOfItsPoolWhichGoesWithCompute() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String role = "auto-node-" + suffix;
cluster = EksTestNode.cluster(ACCOUNT, "nodes-" + suffix);
cluster.setVersion(EksService.DEFAULT_K8S_VERSION);
cluster.setComputeConfig(new ComputeConfig(true, List.of("general-purpose"),
"arn:aws:iam::" + ACCOUNT + ":role/" + role));
String subnet = RequestScopes.callAs(ACCOUNT, REGION, () -> {
iam.createRole(role, "/", "{\"Version\":\"2012-10-17\",\"Statement\":[]}", null, 3600, Map.of());
String vpc = ec2.createVpc(REGION, "10.71.0.0/16", false).getVpcId();
return ec2.createSubnet(REGION, vpc, "10.71.1.0/24", "us-east-1a").getSubnetId();
});
ResourcesVpcConfig network = new ResourcesVpcConfig();
network.setSubnetIds(List.of(subnet));
cluster.setResourcesVpcConfig(network);
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
cluster.setStatus(ClusterStatus.ACTIVE);
eksService.putClusterForAccount(ACCOUNT, cluster);
await("the default NodeClass").atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(3))
.ignoreExceptions().until(() -> subnet.equals(node.kubectlOutput("get", "nodeclass", "default",
"-o", "jsonpath={.spec.subnetSelectorTerms[0].id}")));
node.kubectl("run", "web", "--image=rancher/mirrored-pause:3.6", "--restart=Never", "--overrides="
+ "{\"spec\":{\"nodeSelector\":{\"karpenter.sh/nodepool\":\"general-purpose\"},\"containers\":[{"
+ "\"name\":\"web\",\"image\":\"rancher/mirrored-pause:3.6\",\"resources\":{\"requests\":"
+ "{\"cpu\":\"100m\",\"memory\":\"64Mi\"}}}]}}");
await("the pod is unschedulable").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> "Unschedulable".equals(node.kubectlOutput("get", "pod", "web",
"-o", "jsonpath={.status.conditions[?(@.type==\"PodScheduled\")].reason}")));
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
List<Instance> launched = RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running"));
assertEquals(1, launched.size());
Instance instance = launched.getFirst();
assertEquals(subnet, instance.getSubnetId());
Map<String, String> tags = instance.getTags().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue));
assertEquals(Map.of("eks:eks-cluster-name", cluster.getName(), "eks:kubernetes-node-pool-name", "general-purpose",
"eks:kubernetes-node-class-name", "default", "kubernetes.io/cluster/" + cluster.getName(), "owned",
"aws:ec2:managed-launch", "eks-auto"), tags);
InstanceProfile profile = RequestScopes.callAs(ACCOUNT, REGION, () -> iam.listInstanceProfiles(
"/eks/" + REGION + "/" + cluster.getName() + "/")).getFirst();
assertEquals(List.of(role), profile.getRoleNames());
assertEquals(profile.getArn(), instance.getIamInstanceProfileArn());
// A second pass while the node hasn't joined launches no other.
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running")).size());
RequestScopes.runAs(ACCOUNT, REGION, () -> eksClusterManager.joinInstance(cluster, instance));
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
// The pod is still unschedulable until the scheduler tries it again, but the joined node has room for it.
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running")).size());
String nodeName = eksClusterManager.deriveInstanceNodeName(instance, REGION);
assertEquals("general-purpose auto " + instance.getInstanceType(), node.kubectlOutput("get", "node", nodeName,
"-o", "jsonpath={.metadata.labels.karpenter\\.sh/nodepool} "
+ "{.metadata.labels.eks\\.amazonaws\\.com/compute-type} "
+ "{.metadata.labels.node\\.kubernetes\\.io/instance-type}"));
await("the pod is scheduled on the new node").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> nodeName.equals(node.kubectlOutput("get", "pod", "web",
"-o", "jsonpath={.spec.nodeName}")));
cluster.setComputeConfig(new ComputeConfig(false, List.of(), null));
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.removeNodes(cluster, REGION));
assertEquals(List.of(), RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running")));
await("the node is gone").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> node.kubectl("get", "node", nodeName).exitCode() != 0);
// DeleteCluster runs the Auto Mode cleanups, compute's among them.
Cluster deleted = cluster;
cluster = null;
RequestScopes.runAs(ACCOUNT, REGION, () -> eksService.deleteCluster(deleted.getName()));
assertEquals(List.of(), RequestScopes.callAs(ACCOUNT, REGION, () -> iam.listInstanceProfiles(
"/eks/" + REGION + "/" + deleted.getName() + "/")));
}
}
@@ -0,0 +1,455 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.floci.aws.services.eks.EksAutoModeNodes.Launch;
import io.floci.aws.services.eks.EksAutoModeNodes.NodePool;
import io.floci.aws.services.eks.EksAutoModeNodes.PendingPod;
import io.floci.aws.services.eks.EksAutoModeNodes.Requirement;
import io.floci.aws.services.eks.EksAutoModeNodes.Toleration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EksAutoModeNodesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
/** The built-in pools as Floci installs them, with only the fields the planner reads. */
private static final String POOLS = """
{"items": [
{"metadata": {"name": "general-purpose"}, "spec": {"template": {"spec": {
"nodeClassRef": {"name": "default"},
"requirements": [
{"key": "karpenter.sh/capacity-type", "operator": "In", "values": ["on-demand"]},
{"key": "eks.amazonaws.com/instance-category", "operator": "In", "values": ["c", "m", "r"]},
{"key": "eks.amazonaws.com/instance-generation", "operator": "Gt", "values": ["4"]},
{"key": "kubernetes.io/arch", "operator": "In", "values": ["amd64"]},
{"key": "kubernetes.io/os", "operator": "In", "values": ["linux"]}]}}}},
{"metadata": {"name": "system"}, "spec": {"template": {"spec": {
"nodeClassRef": {"name": "default"},
"requirements": [
{"key": "eks.amazonaws.com/instance-category", "operator": "In", "values": ["c", "m", "r"]},
{"key": "eks.amazonaws.com/instance-generation", "operator": "Gt", "values": ["4"]},
{"key": "kubernetes.io/arch", "operator": "In", "values": ["amd64", "arm64"]}],
"taints": [{"key": "CriticalAddonsOnly", "effect": "NoSchedule"}]}}}}
]}""";
private static final List<CatalogInstanceType> TYPES = List.of(
type("t3.medium", 2, 4096, "x86_64"),
type("c7a.medium", 1, 2048, "x86_64"),
type("c7a.large", 2, 4096, "x86_64"),
type("c7a.xlarge", 4, 8192, "x86_64"),
type("m7a.large", 2, 8192, "x86_64"),
type("c7g.large", 2, 4096, "arm64"),
type("m4.large", 2, 8192, "x86_64"));
@Test
void aSmallPodGetsTheSmallestTwoVcpuTypeOfTheGeneralPurposePool() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(pod("web", "100m", "64Mi")), TYPES, Map.of());
assertEquals(1, launches.size());
assertEquals("general-purpose", launches.getFirst().pool().name());
// c7a.medium has 1 vCPU, t3 is not of category c, m or r, and m4 is of generation 4.
assertEquals("c7a.large", launches.getFirst().instanceType().instanceType);
Map<String, String> expected = Map.of("kubernetes.io/arch", "amd64", "kubernetes.io/os", "linux",
"node.kubernetes.io/instance-type", "c7a.large", "karpenter.sh/capacity-type", "on-demand",
"eks.amazonaws.com/instance-category", "c", "eks.amazonaws.com/instance-generation", "7",
"eks.amazonaws.com/instance-family", "c7a", "eks.amazonaws.com/instance-size", "large",
"karpenter.sh/nodepool", "general-purpose", "eks.amazonaws.com/compute-type", "auto");
expected.forEach((key, value) -> assertEquals(value, launches.getFirst().labels().get(key), key));
assertEquals("2", launches.getFirst().labels().get("eks.amazonaws.com/instance-cpu"));
assertEquals("4096", launches.getFirst().labels().get("eks.amazonaws.com/instance-memory"));
}
@Test
void podsOfOnePoolShareANodeSizedForAllOfThem() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(),
List.of(pod("a", "1500m", "1Gi"), pod("b", "1", "1Gi")), TYPES, Map.of());
assertEquals(1, launches.size());
assertEquals("c7a.xlarge", launches.getFirst().instanceType().instanceType);
assertEquals(2, launches.getFirst().pods().size());
}
@Test
void podsThatDontFitOneNodeTogetherGetANodeForTheLargestNow() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(),
List.of(pod("a", "3", "1Gi"), pod("b", "3", "1Gi")), TYPES, Map.of());
assertEquals("c7a.xlarge", launches.getFirst().instanceType().instanceType);
}
@Test
void onlyAPodToleratingTheSystemTaintGoesToTheSystemPoolAndItMayRunOnArm() throws Exception {
PendingPod critical = new PendingPod("kube-system", "addon", 100, 64L << 20,
Map.of("karpenter.sh/nodepool", "system", "kubernetes.io/arch", "arm64"), List.of(),
List.of(new Toleration("CriticalAddonsOnly", "Exists", "", "")));
PendingPod plain = new PendingPod("default", "plain", 100, 64L << 20,
Map.of("karpenter.sh/nodepool", "system"), List.of(), List.of());
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(critical, plain), TYPES, Map.of());
assertEquals(1, launches.size());
assertEquals("system", launches.getFirst().pool().name());
assertEquals("c7g.large", launches.getFirst().instanceType().instanceType);
assertEquals(List.of("addon"), launches.getFirst().pods().stream().map(PendingPod::name).toList());
}
@Test
void aHeavierPoolIsTriedFirst() throws Exception {
String weighted = POOLS.replace("{\"metadata\": {\"name\": \"system\"}, \"spec\": {",
"{\"metadata\": {\"name\": \"system\"}, \"spec\": {\"weight\": 10, ");
PendingPod tolerant = new PendingPod("default", "any", 100, 64L << 20, Map.of(), List.of(),
List.of(new Toleration("", "Exists", "", "")));
List<Launch> launches = EksAutoModeNodes.plan(EksAutoModeNodes.nodePools(json(weighted)),
List.of(tolerant), TYPES, Map.of());
assertEquals("system", launches.getFirst().pool().name());
}
@Test
void aPodNoPoolCanTakeGetsNoNode() throws Exception {
PendingPod huge = pod("huge", "64", "1Gi");
PendingPod gpu = new PendingPod("default", "gpu", 100, 0, Map.of("eks.amazonaws.com/instance-gpu-count", "1"),
List.of(), List.of());
assertEquals(List.of(), EksAutoModeNodes.plan(pools(), List.of(huge, gpu), TYPES, Map.of()));
}
/** As Karpenter counts its nodes: a pod a pool's node has room for gets no other node. */
@Test
void aPodANodeOfItsPoolHasRoomForGetsNoOther() throws Exception {
NodePool general = pools().getFirst();
CatalogInstanceType large = TYPES.get(2);
PendingPod small = pod("small", "500m", "512Mi");
PendingPod big = pod("big", "1500m", "512Mi");
// 1 vCPU of 2 in use: room for the small pod, not for the big one.
List<PendingPod> left = EksAutoModeNodes.withoutRoom(List.of(small, big),
List.of(new EksAutoModeNodes.PoolNode(general, large, null, 1000, 1L << 30)));
// A system pool node doesn't take pods that don't tolerate its taint, however much room it has.
List<PendingPod> untolerated = EksAutoModeNodes.withoutRoom(List.of(small),
List.of(new EksAutoModeNodes.PoolNode(pools().get(1), TYPES.get(3), null, 0, 0)));
assertEquals(List.of(big), left);
assertEquals(List.of(small), untolerated);
}
/** A cordoned node, or one with a taint of its own the pod doesn't tolerate, has no room for it. */
@Test
void aCordonedOrForeignTaintedNodeHasNoRoom() throws Exception {
NodePool general = pools().getFirst();
PendingPod small = pod("small", "100m", "64Mi");
List<PendingPod> cordoned = EksAutoModeNodes.withoutRoom(List.of(small), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000, 1L << 40, 110, false, List.of())));
List<PendingPod> tainted = EksAutoModeNodes.withoutRoom(List.of(small), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000, 1L << 40, 110, true,
List.of(new EksAutoModeNodes.Taint("maintenance", "", "NoSchedule")))));
List<PendingPod> preferOnly = EksAutoModeNodes.withoutRoom(List.of(small), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000, 1L << 40, 110, true,
List.of(new EksAutoModeNodes.Taint("busy", "", "PreferNoSchedule")))));
assertEquals(List.of(small), cordoned);
assertEquals(List.of(small), tainted);
assertEquals(List.of(), preferOnly);
}
/** A node whose pod slots are all taken has no room, however much CPU and memory it has left. */
@Test
void aNodeWithNoPodSlotLeftHasNoRoom() throws Exception {
NodePool general = pools().getFirst();
PendingPod first = pod("first", "100m", "64Mi");
PendingPod second = pod("second", "100m", "64Mi");
List<PendingPod> full = EksAutoModeNodes.withoutRoom(List.of(first), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000, 1L << 40, 0, true, List.of())));
List<PendingPod> oneSlot = EksAutoModeNodes.withoutRoom(List.of(first, second), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000, 1L << 40, 1, true, List.of())));
assertEquals(List.of(first), full);
assertEquals(List.of(second), oneSlot);
}
/**
* A replica whose required anti-affinity on {@code kubernetes.io/hostname} keeps it off its siblings' nodes has
* no room on the node of one, whether that one runs there or was counted on it in the same pass; either pod's
* anti-affinity counts. A term on another topology key isn't modelled, and one for another namespace doesn't
* match.
*/
@Test
void requiredPodAntiAffinityOnTheHostnameKeepsReplicasOnNodesOfTheirOwn() throws Exception {
NodePool general = pools().getFirst();
String pods = """
{"items": [
{"metadata": {"namespace": "shop", "name": "web-1", "labels": {"app": "web"}},
"spec": {"nodeName": "n1", "affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [
{"labelSelector": {"matchLabels": {"app": "web"}}, "topologyKey": "kubernetes.io/hostname"}]}}},
"status": {"phase": "Running"}},
{"metadata": {"namespace": "shop", "name": "web-2", "labels": {"app": "web"}},
"spec": {"affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [
{"labelSelector": {"matchExpressions": [{"key": "app", "operator": "In", "values": ["web"]}]},
"topologyKey": "kubernetes.io/hostname"}]}}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}},
{"metadata": {"namespace": "shop", "name": "zonal", "labels": {"app": "zonal"}},
"spec": {"affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [
{"labelSelector": {"matchLabels": {"app": "other"}}, "topologyKey": "topology.kubernetes.io/zone"}]}}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}},
{"metadata": {"namespace": "elsewhere", "name": "free", "labels": {"app": "api"}},
"spec": {"affinity": {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [
{"labelSelector": {"matchLabels": {"app": "web"}}, "topologyKey": "kubernetes.io/hostname"}]}}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}
]}""";
JsonNode list = json(pods);
Map<String, PendingPod> pending = new LinkedHashMap<>();
EksAutoModeNodes.unschedulablePods(list).forEach(p -> pending.put(p.name(), p));
EksAutoModeNodes.PoolNode withWeb1 = new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000,
1L << 40, 110, true, List.of(), EksAutoModeNodes.boundPodsByNode(list).get("n1"));
EksAutoModeNodes.PoolNode empty = new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 64_000,
1L << 40, 110, true, List.of());
// web-2 can't join web-1, by its own anti-affinity; zonal's term isn't on the hostname, and web-1's doesn't
// match it; free is in another namespace than web-1's term reads, and its own term reads its namespace, which
// has no web pod.
assertEquals(List.of(pending.get("web-2")), EksAutoModeNodes.withoutRoom(List.copyOf(pending.values()),
List.of(withWeb1)));
// Two replicas counted on one empty node in the same pass: the second has no room there.
PendingPod web3 = new PendingPod("shop", "web-3", 100, 64L << 20, Map.of(), List.of(), List.of(),
Map.of("app", "web"), pending.get("web-2").antiAffinity());
// A pod with no anti-affinity of its own is still kept off the node of one whose anti-affinity matches it.
PendingPod plain = new PendingPod("shop", "plain", 100, 64L << 20, Map.of(), List.of(), List.of(),
Map.of("app", "web"), List.of());
assertEquals(List.of(plain), EksAutoModeNodes.withoutRoom(List.of(plain), List.of(withWeb1)));
assertEquals(List.of(web3), EksAutoModeNodes.withoutRoom(List.of(pending.get("web-2"), web3), List.of(empty)));
}
/** A joined node's room is what it offers, its allocatable CPU and memory less its pods', not its type's size. */
@Test
void aNodeHasOnlyTheRoomItOffers() throws Exception {
NodePool general = pools().getFirst();
PendingPod pod = pod("web", "500m", "64Mi");
List<PendingPod> tooLittleCpu = EksAutoModeNodes.withoutRoom(List.of(pod), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 400, 1L << 30, 110, true, List.of())));
List<PendingPod> tooLittleMemory = EksAutoModeNodes.withoutRoom(List.of(pod), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 1000, 32L << 20, 110, true, List.of())));
List<PendingPod> enough = EksAutoModeNodes.withoutRoom(List.of(pod), List.of(
new EksAutoModeNodes.PoolNode(general, TYPES.get(2), null, 500, 64L << 20, 110, true, List.of())));
assertEquals(List.of(pod), tooLittleCpu);
assertEquals(List.of(pod), tooLittleMemory);
assertEquals(List.of(), enough);
}
@Test
void theRequestsOfThePodsBoundToEachNodeAreSummedThoseThatFinishedLeftOut() throws Exception {
String pods = """
{"items": [
{"spec": {"nodeName": "n1", "containers": [{"resources": {"requests": {"cpu": "200m", "memory": "64Mi"}}}]},
"status": {"phase": "Running"}},
{"spec": {"nodeName": "n1", "containers": [{"resources": {"requests": {"cpu": "300m"}}}]},
"status": {"phase": "Pending"}},
{"spec": {"nodeName": "n1", "containers": [{"resources": {"requests": {"cpu": "1"}}}]},
"status": {"phase": "Succeeded"}},
{"spec": {"containers": [{"resources": {"requests": {"cpu": "1"}}}]}, "status": {"phase": "Pending"}}
]}""";
Map<String, long[]> byNode = EksAutoModeNodes.requestsByNode(json(pods));
assertEquals(List.of("n1"), List.copyOf(byNode.keySet()));
assertEquals(500, byNode.get("n1")[0]);
assertEquals(64L << 20, byNode.get("n1")[1]);
assertEquals(2, byNode.get("n1")[2]);
}
/** A pod constrained to a zone gets a node in it, and the node carries the zone's label. */
@Test
void aPodAskingForAZoneGetsANodeThere() throws Exception {
PendingPod zonal = new PendingPod("default", "zonal", 100, 64L << 20,
Map.of("karpenter.sh/nodepool", "general-purpose", "topology.kubernetes.io/zone", "us-east-1b"),
List.of(), List.of());
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(zonal), TYPES,
Map.of("default", List.of("us-east-1a", "us-east-1b")));
// Another NodeClass's zone is no use to this pool, whose NodeClass has a subnet in us-east-1a only.
List<Launch> none = EksAutoModeNodes.plan(pools(), List.of(zonal), TYPES,
Map.of("default", List.of("us-east-1a"), "other", List.of("us-east-1b")));
assertEquals("us-east-1b", launches.getFirst().zone());
assertEquals("us-east-1b", launches.getFirst().labels().get("topology.kubernetes.io/zone"));
assertEquals(List.of(), none);
}
/** A pool requirement on an attribute Floci doesn't model is left out rather than blocking the pool. */
@Test
void aRequirementOnAnUnmodelledInstanceAttributeDoesntBlockThePool() throws Exception {
String strict = POOLS.replace(
"{\"key\": \"kubernetes.io/os\", \"operator\": \"In\", \"values\": [\"linux\"]}",
"{\"key\": \"kubernetes.io/os\", \"operator\": \"In\", \"values\": [\"linux\"]},"
+ "{\"key\": \"eks.amazonaws.com/instance-cpu-manufacturer\", \"operator\": \"In\", \"values\": [\"amd\"]}");
List<Launch> launches = EksAutoModeNodes.plan(EksAutoModeNodes.nodePools(json(strict)),
List.of(pod("web", "100m", "64Mi")), TYPES, Map.of());
assertEquals("c7a.large", launches.getFirst().instanceType().instanceType);
}
@Test
void requiredNodeAffinityTermsAreAlternatives() {
PendingPod pod = new PendingPod("default", "p", 0, 0, Map.of(), List.of(
List.of(new Requirement("kubernetes.io/arch", "In", List.of("arm64"))),
List.of(new Requirement("eks.amazonaws.com/instance-cpu", "Gt", List.of("3")),
new Requirement("eks.amazonaws.com/instance-family", "NotIn", List.of("m7a")))), List.of());
assertTrue(pod.fits(Map.of("kubernetes.io/arch", "arm64"), List.of()));
assertTrue(pod.fits(Map.of("kubernetes.io/arch", "amd64", "eks.amazonaws.com/instance-cpu", "4",
"eks.amazonaws.com/instance-family", "c7a"), List.of()));
assertFalse(pod.fits(Map.of("kubernetes.io/arch", "amd64", "eks.amazonaws.com/instance-cpu", "2"), List.of()));
}
@ParameterizedTest
@CsvSource({"In,a,true", "In,c,false", "NotIn,c,true", "NotIn,a,false", "Exists,a,true", "DoesNotExist,a,false",
"Gt,5,true", "Gt,1,false", "Lt,1,true"})
void requirementOperatorsMatchAsKubernetesDoes(String operator, String value, boolean matches) {
List<String> values = switch (operator) {
case "Gt", "Lt" -> List.of("2");
case "Exists", "DoesNotExist" -> List.of();
default -> List.of("a", "b");
};
assertEquals(matches, new Requirement("k", operator, values).matches(Map.of("k", value)));
}
@ParameterizedTest
@CsvSource({"100m,100", "1,1000", "0.5,500", "2500m,2500", "2e3,2000000", "0.1m,1", ",0", "x,0"})
void cpuQuantities(String quantity, long millis) {
assertEquals(millis, EksAutoModeNodes.cpuMillis(quantity == null ? "" : quantity));
}
@ParameterizedTest
@CsvSource({"64Mi,67108864", "1Gi,1073741824", "1.5Gi,1610612736", "1G,1000000000", "1e9,1000000000",
"128974848,128974848", "500M,500000000", "1Pi,1125899906842624", "1500m,2", ",0"})
void memoryQuantities(String quantity, long bytes) {
assertEquals(bytes, EksAutoModeNodes.bytes(quantity == null ? "" : quantity));
}
/** The largest init container counts when it asks for more than the containers together, and overhead adds. */
@Test
void initContainersAndOverheadCountAsTheSchedulerCountsThem() throws Exception {
String pods = """
{"items": [{"metadata": {"namespace": "default", "name": "p"},
"spec": {"containers": [{"resources": {"requests": {"cpu": "100m", "memory": "64Mi"}}},
{"resources": {"requests": {"cpu": "100m", "memory": "64Mi"}}}],
"initContainers": [{"resources": {"requests": {"cpu": "1", "memory": "32Mi"}}}],
"overhead": {"cpu": "50m", "memory": "16Mi"}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}]}""";
PendingPod pod = EksAutoModeNodes.unschedulablePods(json(pods)).getFirst();
assertEquals(1050, pod.cpuMillis());
assertEquals(144L << 20, pod.memoryBytes());
}
/**
* A sidecar, an init container with {@code restartPolicy: Always}, keeps running: its requests add to the app's,
* and to those of each init container after it, as the scheduler counts them.
*/
@Test
void sidecarsAddToTheContainersAndToTheInitContainersAfterThem() throws Exception {
String pods = """
{"items": [{"metadata": {"namespace": "default", "name": "p"},
"spec": {"containers": [{"resources": {"requests": {"cpu": "1500m", "memory": "64Mi"}}}],
"initContainers": [
{"restartPolicy": "Always", "resources": {"requests": {"cpu": "1", "memory": "32Mi"}}},
{"resources": {"requests": {"cpu": "100m", "memory": "512Mi"}}}]},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}]}""";
PendingPod pod = EksAutoModeNodes.unschedulablePods(json(pods)).getFirst();
// CPU: the app and the sidecar, 1500m + 1. Memory: the second init container beside the sidecar, 512Mi + 32Mi.
assertEquals(2500, pod.cpuMillis());
assertEquals(544L << 20, pod.memoryBytes());
}
/**
* Only pods the scheduler marked unschedulable and a new node could take: not a DaemonSet's, not one pinned to
* a named node, not one whose only affinity term is empty, which matches no node.
*/
@Test
void onlyPendingPodsTheSchedulerMarkedUnschedulableAreRead() throws Exception {
String pods = """
{"items": [
{"metadata": {"namespace": "default", "name": "waiting"},
"spec": {"nodeSelector": {"karpenter.sh/nodepool": "general-purpose"},
"containers": [{"resources": {"requests": {"cpu": "250m", "memory": "128Mi"}}},
{"resources": {"requests": {"cpu": "250m"}}}],
"tolerations": [{"key": "CriticalAddonsOnly", "operator": "Exists"}]},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}},
{"metadata": {"namespace": "default", "name": "pulling"}, "spec": {"nodeName": "n1"},
"status": {"phase": "Pending"}},
{"metadata": {"namespace": "default", "name": "fresh"}, "spec": {},
"status": {"phase": "Pending"}},
{"metadata": {"namespace": "default", "name": "running"}, "spec": {"nodeName": "n1"},
"status": {"phase": "Running"}},
{"metadata": {"namespace": "kube-system", "name": "agent",
"ownerReferences": [{"kind": "DaemonSet", "name": "agent"}]}, "spec": {},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}},
{"metadata": {"namespace": "default", "name": "pinned"}, "spec": {"affinity": {"nodeAffinity": {
"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [{"matchFields": [
{"key": "metadata.name", "operator": "In", "values": ["n1"]}]}]}}}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}},
{"metadata": {"namespace": "default", "name": "nowhere"}, "spec": {"affinity": {"nodeAffinity": {
"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [{}]}}}},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}
]}""";
List<PendingPod> pending = EksAutoModeNodes.unschedulablePods(json(pods));
assertEquals(1, pending.size());
assertEquals("waiting", pending.getFirst().name());
assertEquals(500, pending.getFirst().cpuMillis());
assertEquals(128L << 20, pending.getFirst().memoryBytes());
assertEquals(Map.of("karpenter.sh/nodepool", "general-purpose"), pending.getFirst().nodeSelector());
assertEquals(List.of(new Toleration("CriticalAddonsOnly", "Exists", "", "")), pending.getFirst().tolerations());
}
private static List<NodePool> pools() throws Exception {
return EksAutoModeNodes.nodePools(json(POOLS));
}
private static PendingPod pod(String name, String cpu, String memory) {
return new PendingPod("default", name, EksAutoModeNodes.cpuMillis(cpu), EksAutoModeNodes.bytes(memory),
Map.of("karpenter.sh/nodepool", "general-purpose"), List.of(), List.of());
}
private static CatalogInstanceType type(String name, int vcpu, int memoryMib, String architecture) {
CatalogInstanceType type = new CatalogInstanceType();
type.instanceType = name;
type.vcpu = vcpu;
type.memoryMib = memoryMib;
type.supportedArchitectures = List.of(architecture);
return type;
}
private static JsonNode json(String text) throws Exception {
return MAPPER.readTree(text);
}
}
@@ -2,6 +2,9 @@ package io.floci.aws.services.eks;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -31,6 +34,25 @@ class EksBootstrapUserDataTest {
assertEquals("mime-nodeadm-cluster", EksBootstrapUserData.extractClusterName(mime).orElse(null));
}
/** A kubelet's --node-labels and --register-with-taints flags, merged over every NodeConfig, MIME parts included. */
@Test
void readsTheKubeletLabelAndTaintFlagsOfEveryNodeConfig() {
String mime = "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"//\"\r\n\r\n"
+ "--//\r\nContent-Type: application/node.eks.aws\r\n\r\n---\r\n"
+ "apiVersion: node.eks.aws/v1alpha1\r\nkind: NodeConfig\r\nspec:\r\n cluster:\r\n name: c\r\n"
+ " kubelet:\r\n flags:\r\n - --node-labels=a=1,b=2\r\n"
+ " - --register-with-taints=CriticalAddonsOnly:NoSchedule,team=x:NoExecute\r\n"
+ "--//\r\nContent-Type: application/node.eks.aws\r\n\r\n---\r\n"
+ "apiVersion: node.eks.aws/v1alpha1\r\nkind: NodeConfig\r\nspec:\r\n"
+ " kubelet:\r\n flags:\r\n - \"--node-labels=c=3\"\r\n--//--\r\n";
assertEquals(Map.of("a", "1", "b", "2", "c", "3"), EksBootstrapUserData.nodeLabels(mime));
assertEquals(List.of(Map.of("key", "CriticalAddonsOnly", "value", "", "effect", "NoSchedule"),
Map.of("key", "team", "value", "x", "effect", "NoExecute")), EksBootstrapUserData.registerWithTaints(mime));
assertEquals(Map.of(), EksBootstrapUserData.nodeLabels("#!/bin/bash\necho hello"));
assertEquals(List.of(), EksBootstrapUserData.registerWithTaints(null));
}
@Test
void returnsEmptyForUnrelatedUserData() {
assertTrue(EksBootstrapUserData.extractClusterName(null).isEmpty());
@@ -5653,6 +5653,61 @@ class EksClusterManagerTest {
assertTrue(patchCmd[7].contains("10.0.1.50") && patchCmd[7].contains("KubeletReady"));
}
/** As a kubelet does: the node registers with the labels and taints its NodeConfig's kubelet flags name. */
@Test
void aSyntheticNodeRegistersWithItsNodeConfigsLabelsAndTaints() {
Cluster cluster = clusterNamed("flags-cluster", "flags-container");
Instance inst = createInstance("i-0flags1234567890a", "us-east-1a", "t3.medium", "x86_64", "10.0.1.70");
inst.setUserData("apiVersion: node.eks.aws/v1alpha1\nkind: NodeConfig\nspec:\n cluster:\n"
+ " name: flags-cluster\n kubelet:\n flags:\n"
+ " - --node-labels=karpenter.sh/nodepool=system,kubernetes.io/arch=arm64\n"
+ " - --register-with-taints=CriticalAddonsOnly:NoSchedule\n");
ArgumentCaptor<String[]> cmdCaptor = ArgumentCaptor.forClass(String[].class);
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
.execInContainerForResult(eq("flags-container"), cmdCaptor.capture(), anyInt());
manager.joinInstance(cluster, inst);
String applyScript = cmdCaptor.getAllValues().getFirst()[2];
assertTrue(applyScript.contains("\"karpenter.sh/nodepool\":\"system\""), applyScript);
assertTrue(applyScript.contains(
"\"taints\":[{\"key\":\"CriticalAddonsOnly\",\"value\":\"\",\"effect\":\"NoSchedule\"}]"), applyScript);
// The node's own labels stay what the instance is, whatever the flags say.
assertTrue(applyScript.contains("\"kubernetes.io/arch\":\"amd64\""), applyScript);
}
/**
* A removed node's instance is forgotten by the cluster too, and isn't joined again, so neither the readiness
* poller nor a join that waited for the removal brings its node back while it shuts down; a node that can't
* be deleted keeps both.
*/
@Test
void aRemovedNodesInstanceIsForgottenByTheCluster() {
Cluster cluster = clusterNamed("remove-cluster", "remove-container");
Instance inst = createInstance("i-0remove123456789a", "us-east-1a", "t3.medium", "x86_64", "10.0.1.71");
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
.execInContainerForResult(eq("remove-container"), any(), anyInt());
manager.joinInstance(cluster, inst);
manager.recordJoinedInstanceId(cluster, inst);
doReturn(new ContainerExec.Result(1L, "", "refused", false)).when(manager)
.execInContainerForResult(eq("remove-container"), any(), anyInt());
assertThrows(IllegalStateException.class, () -> manager.removeJoinedNode(cluster, inst));
assertEquals(Map.of(inst.getInstanceId(), "us-east-1"), cluster.getJoinedInstanceIds());
assertTrue(manager.isInstanceJoined(cluster, inst.getInstanceId()));
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
.execInContainerForResult(eq("remove-container"), any(), anyInt());
manager.removeJoinedNode(cluster, inst);
assertEquals(Map.of(), cluster.getJoinedInstanceIds());
assertFalse(manager.isInstanceJoined(cluster, inst.getInstanceId()));
// A join that was waiting while it was removed doesn't bring its node back.
manager.joinInstance(cluster, inst);
assertFalse(manager.isInstanceJoined(cluster, inst.getInstanceId()));
assertEquals(Map.of(), cluster.getJoinedInstanceIds());
}
@Test
void joinArmInstanceRegistersWithArm64Label() {
Cluster cluster = clusterNamed("arm-cluster", "arm-container-123");
@@ -806,20 +806,53 @@ class EksServiceTest {
verify(clusterManager, never()).detachCluster(any(Cluster.class));
}
/** Each Auto Mode capability's own resources go with the cluster, even when another's cleanup fails. */
@Test
void aDeletedClustersAutoModeLoadBalancersGoWithIt() {
void aDeletedClustersAutoModeResourcesGoWithIt() {
Cluster cluster = activeCluster();
EksAutoModeLoadBalancers loadBalancers = mock(EksAutoModeLoadBalancers.class);
EksAutoModeCleanup loadBalancers = mock(EksAutoModeCleanup.class);
EksAutoModeCleanup compute = mock(EksAutoModeCleanup.class);
doThrow(new IllegalStateException("ELBv2 refused")).doNothing().when(loadBalancers).clusterDeleted(any(), any());
// Fully qualified: the CDI lookup's Instance clashes with the EC2 Instance this class imports.
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<EksAutoModeLoadBalancers> lookup =
mock(jakarta.enterprise.inject.Instance.class);
when(lookup.isResolvable()).thenReturn(true);
when(lookup.get()).thenReturn(loadBalancers);
jakarta.enterprise.inject.Instance<EksAutoModeCleanup> lookup = mock(jakarta.enterprise.inject.Instance.class);
when(lookup.iterator()).thenAnswer(inv -> List.of(loadBalancers, compute).iterator());
EksService service = serviceWithCluster(cluster, mock(EksClusterManager.class), false, lookup);
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> service.deleteCluster("running-cluster"));
assertEquals("ELBv2 refused", failure.getMessage());
verify(compute).clusterDeleted(cluster, service.clusterRegion(cluster));
// The record stays, so a retried delete finishes the cleanup and deletes the cluster.
assertEquals("running-cluster", service.describeCluster("running-cluster").getName());
service.deleteCluster("running-cluster");
verify(loadBalancers).deleteLoadBalancers(cluster, service.clusterRegion(cluster));
verify(loadBalancers, times(2)).clusterDeleted(cluster, service.clusterRegion(cluster));
assertThrows(AwsException.class, () -> service.describeCluster("running-cluster"));
}
/** Auto Mode's instances hold the cluster security group, so they go before EC2 is asked to delete it. */
@Test
void aDeletedClustersAutoModeInstancesGoBeforeItsSecurityGroup() {
Cluster cluster = activeCluster();
ResourcesVpcConfig vpc = new ResourcesVpcConfig();
vpc.setClusterSecurityGroupId("sg-cluster");
cluster.setResourcesVpcConfig(vpc);
EksAutoModeCleanup compute = mock(EksAutoModeCleanup.class);
// Fully qualified: the CDI lookup's Instance clashes with the EC2 Instance this class imports.
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<EksAutoModeCleanup> lookup = mock(jakarta.enterprise.inject.Instance.class);
when(lookup.iterator()).thenAnswer(inv -> List.of(compute).iterator());
Ec2Service ec2 = mock(Ec2Service.class);
EksService service = serviceWithCluster(cluster, mock(EksClusterManager.class), false, lookup, ec2);
service.deleteCluster("running-cluster");
InOrder order = inOrder(compute, ec2);
order.verify(compute).clusterDeleted(cluster, service.clusterRegion(cluster));
order.verify(ec2).deleteSecurityGroup(service.clusterRegion(cluster), "sg-cluster");
}
@Test
@@ -916,18 +949,25 @@ class EksServiceTest {
return serviceWithCluster(cluster, clusterManager, keepRunningOnShutdown, null);
}
// The overloads below name the CDI lookup's Instance fully qualified: it clashes with the EC2 Instance imported here.
private EksService serviceWithCluster(Cluster cluster, EksClusterManager clusterManager,
boolean keepRunningOnShutdown,
jakarta.enterprise.inject.Instance<EksAutoModeLoadBalancers> autoModeLoadBalancers) {
jakarta.enterprise.inject.Instance<EksAutoModeCleanup> autoModeCleanups) {
return serviceWithCluster(cluster, clusterManager, keepRunningOnShutdown, autoModeCleanups, null);
}
private EksService serviceWithCluster(Cluster cluster, EksClusterManager clusterManager,
boolean keepRunningOnShutdown,
jakarta.enterprise.inject.Instance<EksAutoModeCleanup> autoModeCleanups, Ec2Service ec2) {
AccountAwareStorageBackend<Cluster> clusterStore =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000");
clusterStore.putForAccount("000000000000", EksService.clusterKey(
AwsArnUtils.regionOrDefault(cluster.getArn(), "us-east-1"), cluster.getName()), cluster);
return new EksService(fixedStorageFactory(clusterStore), testConfig(false, keepRunningOnShutdown),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new RegionResolver("us-east-1", "000000000000"), clusterManager, ec2,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()), mock(EksAccessEntryService.class), null, null, null,
autoModeLoadBalancers);
autoModeCleanups);
}
private StorageFactory fixedStorageFactory(StorageBackend<String, ?> backend) {