feat(eks): remove EKS Auto Mode nodes left empty for their pool's consolidateAfter (#9465)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-26 12:09:54 -04:00
1 parent e8e6f0f306
commit 31befa5e92
7 files changed
+1081 -97

No files matched your search

+22 -2
View File
@@ -476,7 +476,9 @@ launches nodes on AWS. Floci checks every 10 seconds.
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
that fits all of the pool's waiting pods and the DaemonSet pods that would run on it (by their node selector,
required node affinity and tolerations, against its labels and region), or else the largest of them. A node still joining has room for its
DaemonSet pods taken too. 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
@@ -493,6 +495,24 @@ launches nodes on AWS. Floci checks every 10 seconds.
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.
- **Empty nodes.** A node that runs no workload (DaemonSet and static pods aside) and that no pending pod is counting
on is removed once it has been empty for its pool's `disruption.consolidateAfter`, as Auto Mode's consolidation
removes it: it is tainted `karpenter.sh/disrupted:NoSchedule`, as Karpenter marks a node it removes, and unless
the scheduler bound a pod to it meanwhile, it is drained (`kubectl drain`, so a pod that tolerates the taint and
arrived late is evicted, its disruption budget kept; on Floci's own Ready node, which has no kubelet to finish a
pod's shutdown, evicted pods go at once), its node is taken out and its instance terminated. A node a removal
that was called off or failed left with the taint, and that isn't being removed, has it taken off by the next pass. AWS removed an empty node within 90
seconds. A pool whose `consolidateAfter` is `Never` keeps its nodes. Each pass removes no more of a pool's nodes
than its disruption budgets that cover emptiness allow (a percentage is of its joined nodes, as Karpenter leaves
out nodes not yet initialized), less its nodes already not Ready or being deleted (a percentage rounded up, 10% without a budget; one whose
`reasons` leave out `Empty` doesn't count); a budget with a `schedule` is
left out, as Floci doesn't model its window. How long a node has been empty is kept in memory, so a restart starts
the wait again.
- **Deleted pools.** The nodes of a NodePool that is deleted, or that `UpdateClusterConfig` drops, are tainted,
drained and removed the same way, whatever they run, as Karpenter removes them.
The node of an Auto Mode instance that is terminated (one that registered while its instance was being
terminated, say), by its provider ID, is deleted by the next pass, while EC2 keeps the instance, an hour as on AWS, with compute on or
off.
- **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
@@ -500,7 +520,7 @@ launches nodes on AWS. Floci checks every 10 seconds.
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.
Floci makes no `NodeClaim` objects, and doesn't replace underutilized nodes with smaller ones.
### Auto Mode load balancing for Services
@@ -28,10 +28,12 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -75,6 +77,9 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
/** 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";
/** The taint Karpenter puts on a node it is removing, so nothing more is scheduled there. */
static final String DISRUPTED_KEY = "karpenter.sh/disrupted";
static final String DISRUPTED_TAINT = DISRUPTED_KEY + ":NoSchedule";
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";
@@ -90,18 +95,31 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
private final Ec2InstanceTypeCatalog instanceTypes;
private final EmulatorConfig config;
private Duration terminationWait = TERMINATION_WAIT;
private final Clock clock;
/**
* By cluster ARN, then instance ID: since when each Auto Mode node has run no workload and been counted on by
* no pending pod. Kept in memory, so a restart starts each node's wait again.
*/
private final Map<String, Map<String, Instant>> emptySince = new HashMap<>();
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, clusterManager, ec2, iam, instanceTypes, config, Clock.systemUTC());
}
/** As above; with the {@code clock} empty nodes are timed by. */
EksAutoModeCompute(EksService eksService, EksClusterManager clusterManager, Ec2Service ec2, IamService iam,
Ec2InstanceTypeCatalog instanceTypes, EmulatorConfig config, Clock clock) {
this.eksService = eksService;
this.clusterManager = clusterManager;
this.ec2 = ec2;
this.iam = iam;
this.instanceTypes = instanceTypes;
this.config = config;
this.clock = clock;
}
/** For tests: how long a deleted cluster waits for its instances to terminate. */
@@ -151,32 +169,44 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
List<Instance> launched = instancesOf(cluster, region, "pending", "running");
JsonNode podList = read(cluster, "pods");
List<EksAutoModeNodes.PendingPod> pods = EksAutoModeNodes.unschedulablePods(podList);
if (launched.isEmpty()) {
emptySince.remove(cluster.getArn());
}
Map<String, JsonNode> nodesByName = nodesByName(cluster);
removeStrayNodes(cluster, region, nodesByName);
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);
}
// The DaemonSet pods a node runs besides its workload, which room and sizing count; read only for pods to place.
List<EksAutoModeNodes.PendingPod> daemons = pods.isEmpty() ? List.of()
: EksAutoModeNodes.daemonPods(read(cluster, "daemonsets"));
Map<String, long[]> requests = EksAutoModeNodes.requestsByNode(podList);
Map<String, List<EksAutoModeNodes.BoundPod>> boundPods = EksAutoModeNodes.boundPodsByNode(podList);
Set<String> busy = EksAutoModeNodes.nodesWithWorkloads(podList);
List<EksAutoModeNodes.PoolNode> poolNodes = new ArrayList<>();
Map<String, Instance> idle = new HashMap<>();
List<Instance> neverRegistered = new ArrayList<>();
List<Instance> poolGone = 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());
|| instance.getLaunchTime().plus(REGISTRATION_WAIT).isAfter(clock.instant());
boolean joining = node == null && starting;
if (node == null && !joining) {
neverRegistered.add(instance);
continue;
}
if (pool == null || type.isEmpty()) {
if (pool == null) {
// Karpenter removes the nodes of a NodePool that was deleted, or that UpdateClusterConfig dropped.
poolGone.add(instance);
continue;
}
if (type.isEmpty()) {
continue;
}
if (node != null) {
@@ -208,9 +238,19 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
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 (node == null) {
// A node still joining runs none of its DaemonSet pods yet; they take its room once it does.
long[] daemon = EksAutoModeNodes.daemonRequests(daemons, EksAutoModeNodes.withRegion(
EksAutoModeNodes.labels(type.get(), pool, zone(instance)), region), pool.taints());
cpu -= daemon[0];
memory -= daemon[1];
}
poolNodes.add(new EksAutoModeNodes.PoolNode(instance.getInstanceId(), 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 (node != null && !busy.contains(nodeName)) {
idle.put(instance.getInstanceId(), instance);
}
}
if (!neverRegistered.isEmpty()) {
// A node that never joins would hold its pods' room for good; it goes, and they get another.
@@ -219,7 +259,25 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
neverRegistered.stream().map(Instance::getInstanceId).toList(), cluster.getName(),
REGISTRATION_WAIT);
}
List<EksAutoModeNodes.PendingPod> withoutRoom = EksAutoModeNodes.withoutRoom(pods, poolNodes);
EksAutoModeNodes.Room room = EksAutoModeNodes.withoutRoom(pods, poolNodes);
removeEmptyNodes(cluster, region, launched, nodesByName, idle, room.counted(), pools, poolGone);
for (Instance instance : poolGone) {
String nodeName = clusterManager.deriveInstanceNodeName(instance, region);
boolean joined = nodesByName.containsKey(nodeName);
try {
if (joined) {
exec(cluster, List.of("kubectl", "taint", "node", nodeName, DISRUPTED_TAINT, "--overwrite"),
"taint node " + nodeName);
}
retire(cluster, region, instance, nodeName, joined);
LOG.infov("EKS Auto Mode removed node {0} ({1}) of cluster {2}, whose pool {3} is gone", nodeName,
instance.getInstanceId(), cluster.getName(), tag(instance, POOL_TAG));
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode node {0} of cluster {1}, whose pool is gone, wasn''t removed: {2}", nodeName,
cluster.getName(), e.getMessage());
}
}
List<EksAutoModeNodes.PendingPod> withoutRoom = room.left();
if (withoutRoom.isEmpty()) {
return;
}
@@ -235,7 +293,7 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
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)) {
instanceTypes.instanceTypes(), zonesByNodeClass, daemons, region)) {
try {
launch(cluster, region, launch, nodeClasses.get(launch.pool().nodeClass()), subnetZones);
} catch (RuntimeException e) {
@@ -245,6 +303,98 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
}
}
/**
* Removes the pools' nodes that have been empty, running no workload and counted on by no pending pod, for
* their pool's {@code consolidateAfter}, as Auto Mode's consolidation does, within each pool's disruption
* budget: each is tainted {@code karpenter.sh/disrupted:NoSchedule}, as Karpenter marks a node it is removing,
* its node taken out of the cluster and its instance terminated. A pool whose {@code consolidateAfter} is
* {@code Never} keeps its nodes. A node left with the taint by a removal that was called off or failed, and that
* isn't being removed now, has it taken off again.
*/
private void removeEmptyNodes(Cluster cluster, String region, List<Instance> launched,
Map<String, JsonNode> nodesByName, Map<String, Instance> empty, Set<String> counted,
Map<String, NodePool> pools, List<Instance> poolGone) {
Instant now = clock.instant();
Map<String, Instant> since = emptySince.computeIfAbsent(cluster.getArn(), arn -> new HashMap<>());
// A node that runs a workload again, or that a pending pod counts on, waits from the start next time.
since.keySet().removeIf(id -> !empty.containsKey(id) || counted.contains(id));
// A budget's percentage is of the pool's joined nodes: one still joining isn't counted at all, as Karpenter
// leaves out nodes that aren't initialized yet.
Map<String, Integer> poolSizes = new HashMap<>();
for (Instance instance : launched) {
if (nodesByName.containsKey(clusterManager.deriveInstanceNodeName(instance, region))) {
poolSizes.merge(String.valueOf(tag(instance, POOL_TAG)), 1, Integer::sum);
}
}
// As Karpenter counts a budget: the pool's nodes already unavailable, not Ready or being deleted, use it up
// first. One this removal tainted before is the same removal tried again, not another.
Map<String, Integer> removed = new HashMap<>();
for (Instance instance : launched) {
if (unavailable(nodesByName.get(clusterManager.deriveInstanceNodeName(instance, region)))) {
removed.merge(String.valueOf(tag(instance, POOL_TAG)), 1, Integer::sum);
}
}
List<Instance> due = new ArrayList<>();
empty.values().stream()
.filter(instance -> !counted.contains(instance.getInstanceId()))
.sorted(Comparator.comparing(instance -> since.getOrDefault(instance.getInstanceId(), now)))
.forEach(instance -> {
Instant emptyAt = since.computeIfAbsent(instance.getInstanceId(), id -> now);
NodePool pool = pools.get(tag(instance, POOL_TAG));
if (pool == null || pool.consolidateAfter() == null
|| emptyAt.plus(pool.consolidateAfter()).isAfter(now)) {
return;
}
int done = removed.getOrDefault(pool.name(), 0);
if (done < pool.disruptable(poolSizes.getOrDefault(pool.name(), 0))) {
removed.put(pool.name(), done + 1);
due.add(instance);
}
});
for (Instance instance : launched) {
String nodeName = clusterManager.deriveInstanceNodeName(instance, region);
JsonNode node = nodesByName.get(nodeName);
if (node != null && !due.contains(instance) && !poolGone.contains(instance) && disrupted(node)) {
try {
// A drain that failed left it cordoned too; the taint comes off last, so it marks the node
// until both are undone.
if (node.path("spec").path("unschedulable").asBoolean(false)) {
exec(cluster, List.of("kubectl", "uncordon", nodeName), "uncordon node " + nodeName);
}
exec(cluster, List.of("kubectl", "taint", "node", nodeName, DISRUPTED_TAINT + "-"),
"untaint node " + nodeName);
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode node {0} of cluster {1} keeps its disrupted taint until the next "
+ "pass: {2}", nodeName, cluster.getName(), e.getMessage());
}
}
}
for (Instance instance : due) {
String nodeName = clusterManager.deriveInstanceNodeName(instance, region);
try {
exec(cluster, List.of("kubectl", "taint", "node", nodeName, DISRUPTED_TAINT, "--overwrite"),
"taint node " + nodeName);
// The scheduler may have bound a pod there since the pass read the pods; tainted, the node gets no
// more but those tolerating every taint, which the drain evicts. A workload there keeps the node.
JsonNode bound = readJson(cluster, List.of("kubectl", "get", "pods", "-A", "--field-selector",
"spec.nodeName=" + nodeName, "-o", "json"), "get pods of node " + nodeName);
if (EksAutoModeNodes.nodesWithWorkloads(bound).contains(nodeName)) {
since.remove(instance.getInstanceId());
exec(cluster, List.of("kubectl", "taint", "node", nodeName, DISRUPTED_TAINT + "-"),
"untaint node " + nodeName);
continue;
}
retire(cluster, region, instance, nodeName, true);
since.remove(instance.getInstanceId());
LOG.infov("EKS Auto Mode removed empty node {0} ({1}) of pool {2} of cluster {3}", nodeName,
instance.getInstanceId(), tag(instance, POOL_TAG), cluster.getName());
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode empty node {0} of cluster {1} wasn''t removed: {2}", nodeName,
cluster.getName(), e.getMessage());
}
}
}
private void launch(Cluster cluster, String region, Launch launch, JsonNode nodeClass,
Map<String, String> subnetZones) {
if (nodeClass == null) {
@@ -336,15 +486,109 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
}
}
/**
* Deletes the nodes of the cluster's Auto Mode instances that are shutting down or terminated: one that
* registered after a pass read the nodes, while that pass terminated its instance, or whose deletion failed
* after it. Only a node named after such an instance and whose provider ID is that instance's is touched, and
* not one a live Auto Mode instance's node shares the name of, so the cluster's own node and other workers stay
* whatever their labels, a worker that joined later under the same name included. A pass retries
* while EC2 keeps the terminated instance, an hour as on AWS.
*/
private void removeStrayNodes(Cluster cluster, String region, Map<String, JsonNode> nodesByName) {
if (nodesByName.isEmpty()) {
return;
}
Set<String> stray = new LinkedHashSet<>();
for (Instance instance : instancesOf(cluster, region, "shutting-down", "terminated")) {
String name = clusterManager.deriveInstanceNodeName(instance, region);
JsonNode node = nodesByName.get(name);
// Only the node that is this instance's, by its provider ID (aws:///<zone>/<instance>, as a kubelet and
// Floci's own Ready node set it): another worker may have joined since under the same name.
if (node != null && node.path("spec").path("providerID").asText("")
.endsWith("/" + instance.getInstanceId())) {
stray.add(name);
}
}
if (stray.isEmpty()) {
return;
}
for (Instance instance : instancesOf(cluster, region, "pending", "running", "stopping", "stopped")) {
stray.remove(clusterManager.deriveInstanceNodeName(instance, region));
}
for (String name : stray) {
try {
exec(cluster, List.of("kubectl", "delete", "node", name, "--ignore-not-found=true", "--wait=false"),
"delete node " + name);
nodesByName.remove(name);
LOG.infov("EKS Auto Mode deleted node {0} of cluster {1}, whose instance is gone", name,
cluster.getName());
} catch (RuntimeException e) {
LOG.warnv("EKS Auto Mode node {0} of cluster {1}, whose instance is gone, wasn''t deleted: {2}", name,
cluster.getName(), e.getMessage());
}
}
}
/**
* Takes a node already tainted as disrupted out as Karpenter's termination does: drained (its pods evicted, so
* one that tolerates the taint and arrived late goes elsewhere, its disruption budget kept, DaemonSet pods
* left), then deleted, and its instance terminated. A drain that fails leaves the node for the next pass.
*/
private void retire(Cluster cluster, String region, Instance instance, String nodeName, boolean joined) {
if (joined) {
List<String> drain = new ArrayList<>(List.of("kubectl", "drain", nodeName, "--ignore-daemonsets",
"--delete-emptydir-data", "--force", "--timeout=10s"));
if (!clusterManager.kubeletRegistersNode(instance)) {
// Floci's own Ready node has no kubelet to finish a pod's graceful shutdown, so its evicted pods
// would stay terminating for good: they go at once, their disruption budgets still kept.
drain.add("--grace-period=0");
}
exec(cluster, drain, "drain node " + nodeName);
clusterManager.removeJoinedNode(cluster, instance);
}
ec2.terminateInstances(region, List.of(instance.getInstanceId()));
}
/**
* Whether a joined node doesn't serve pods: being deleted, or with a Ready condition that isn't true. One still
* joining, or without a Ready condition yet, as Floci's own Ready node has none between its creation and its
* status, isn't counted.
*/
private static boolean unavailable(JsonNode node) {
if (node == null) {
return false;
}
if (!node.path("metadata").path("deletionTimestamp").isMissingNode()) {
return true;
}
for (JsonNode condition : node.path("status").path("conditions")) {
if ("Ready".equals(condition.path("type").asText())) {
return !"True".equals(condition.path("status").asText());
}
}
return false;
}
private static boolean disrupted(JsonNode node) {
for (JsonNode taint : node.path("spec").path("taints")) {
if (DISRUPTED_KEY.equals(taint.path("key").asText()) && "NoSchedule".equals(taint.path("effect").asText())) {
return true;
}
}
return false;
}
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.
* instance whose node can't be deleted is kept, so the next pass tries it again; the node of one that registered
* while it terminated is deleted by a later pass.
*/
synchronized void removeNodes(Cluster cluster, String region) {
emptySince.remove(cluster.getArn());
List<Instance> launched = instancesOf(cluster, region, "pending", "running", "stopping", "stopped");
List<String> removed = new ArrayList<>();
for (Instance instance : launched) {
@@ -356,16 +600,21 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
instance.getInstanceId(), cluster.getName(), e.getMessage());
}
}
if (removed.isEmpty()) {
return;
if (!removed.isEmpty()) {
ec2.terminateInstances(region, removed);
LOG.infov("EKS Auto Mode compute of cluster {0} is off: terminated {1}", cluster.getName(), removed);
}
// A worker that was joining can register while it terminates; its node goes on a later pass, as with compute
// on. The nodes are read only while EC2 still keeps such an instance.
if (!instancesOf(cluster, region, "shutting-down", "terminated").isEmpty()) {
removeStrayNodes(cluster, region, nodesByName(cluster));
}
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) {
emptySince.remove(cluster.getArn());
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
@@ -491,14 +740,27 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
return launch.pods().stream().map(p -> p.namespace() + "/" + p.name()).toList();
}
/** The cluster's nodes by name. */
private Map<String, JsonNode> nodesByName(Cluster cluster) {
Map<String, JsonNode> nodesByName = new HashMap<>();
for (JsonNode node : read(cluster, "nodes").path("items")) {
nodesByName.put(node.path("metadata").path("name").asText(), node);
}
return nodesByName;
}
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);
return readJson(cluster, command, "get " + kind);
}
private JsonNode readJson(Cluster cluster, List<String> command, String what) {
ContainerExec.Result result = exec(cluster, command, what);
try {
return MAPPER.readTree(result.stdout());
} catch (Exception e) {
throw new IllegalStateException("kubectl get " + kind + " returned no JSON: " + e.getMessage(), e);
throw new IllegalStateException("kubectl " + what + " returned no JSON: " + e.getMessage(), e);
}
}
@@ -5,12 +5,14 @@ import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
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.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -34,6 +36,8 @@ final class EksAutoModeNodes {
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";
/** The region label a joined node carries, which DaemonSets may select on. */
static final String REGION_LABEL = "topology.kubernetes.io/region";
/** 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]*)$");
@@ -78,7 +82,8 @@ final class EksAutoModeNodes {
}
try {
return Long.compare(Long.parseLong(value), Long.parseLong(values.getFirst()));
} catch (NumberFormatException e) {
} catch (NumberFormatException expected) {
// Gt and Lt compare integers; Kubernetes matches no node when either side isn't one, which 0 gives.
return 0;
}
}
@@ -104,9 +109,34 @@ final class EksAutoModeNodes {
}
}
/** A NodePool: its NodeClass, its requirements, the taints and labels its nodes get, and its weight. */
/**
* A NodePool: its NodeClass, its requirements, the taints and labels its nodes get, its weight, how long a node
* stays empty before it goes (null for {@code Never}), and its disruption budgets' {@code nodes} values.
*/
record NodePool(String name, String nodeClass, List<Requirement> requirements, List<Taint> taints,
Map<String, String> labels, int weight) {
Map<String, String> labels, int weight, Duration consolidateAfter, List<String> budgets) {
/**
* How many of the pool's {@code nodes} may be disrupted at once: the least its budgets allow, a percentage
* of them rounded up, as Karpenter counts it (AWS removed the only node of a pool budgeted at 10%). Without
* a budget Karpenter allows 10%.
*/
int disruptable(int nodes) {
List<String> values = budgets.isEmpty() ? List.of("10%") : budgets;
int allowed = Integer.MAX_VALUE;
for (String value : values) {
try {
allowed = Math.min(allowed, value.endsWith("%")
? (int) Math.ceil(nodes * Integer.parseInt(value.substring(0, value.length() - 1)) / 100.0)
: Integer.parseInt(value));
} catch (NumberFormatException expected) {
// The NodePool schema refuses such a value; one that got through allows no disruption, the safe
// reading.
allowed = 0;
}
}
return Math.max(0, allowed);
}
}
/** A pod the scheduler couldn't place, with what it asks of a node and the resources it requests. */
@@ -179,22 +209,24 @@ final class EksAutoModeNodes {
* 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) {
record PoolNode(String instanceId, 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());
PoolNode(String instanceId, NodePool pool, CatalogInstanceType instanceType, String zone, long freeCpuMillis,
long freeMemoryBytes, int freePods, boolean schedulable, List<Taint> nodeTaints) {
this(instanceId, 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,
PoolNode(String instanceId, NodePool pool, CatalogInstanceType instanceType, String zone, long usedCpuMillis,
long usedMemoryBytes) {
this(instanceId, pool, instanceType, zone, instanceType.vcpu * 1000L - usedCpuMillis,
instanceType.memoryMib * 1024L * 1024L - usedMemoryBytes, MAX_PODS, true, List.of());
}
@@ -206,6 +238,10 @@ final class EksAutoModeNodes {
}
}
/** The pending pods no pool node has room for, and the nodes whose room the others are counting on. */
record Room(List<PendingPod> left, Set<String> counted) {
}
/** 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) {
@@ -269,6 +305,21 @@ final class EksAutoModeNodes {
*/
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass) {
return plan(pools, pods, types, zonesByNodeClass, List.of());
}
/**
* As above; with the cluster's DaemonSet pods, as {@link #daemonPods} reads them: a node is sized for its
* waiting pods and the DaemonSet pods that would run on it too, as Karpenter sizes it.
*/
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass, List<PendingPod> daemons) {
return plan(pools, pods, types, zonesByNodeClass, daemons, null);
}
/** As above; with the region the nodes join in, whose label DaemonSets may select on. */
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass, List<PendingPod> daemons, String region) {
List<NodePool> ordered = pools.stream()
.sorted(Comparator.comparingInt(NodePool::weight).reversed().thenComparing(NodePool::name))
.toList();
@@ -280,7 +331,8 @@ final class EksAutoModeNodes {
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())
if (candidate(pool, sized, zonesOf(pool, zonesByNodeClass), pod, pod.cpuMillis(), pod.memoryBytes(),
daemons, region)
.isPresent()) {
byPool.computeIfAbsent(pool.name(), k -> new ArrayList<>()).add(pod);
break;
@@ -298,9 +350,10 @@ final class EksAutoModeNodes {
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)
Optional<Placement> placement = candidate(pool, sized, placesIn, largest, cpu, memory, daemons, region)
.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()));
.or(() -> candidate(pool, sized, placesIn, largest, largest.cpuMillis(), largest.memoryBytes(),
daemons, region));
placement.ifPresent(p -> launches.add(new Launch(pool, p.type(), p.zone(),
labels(p.type(), pool, p.zone()), List.copyOf(group))));
}
@@ -315,7 +368,7 @@ final class EksAutoModeNodes {
* 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) {
static Room 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()];
@@ -328,6 +381,7 @@ final class EksAutoModeNodes {
freePods[i] = node.freePods();
}
List<PendingPod> left = new ArrayList<>();
Set<String> counted = new HashSet<>();
for (PendingPod pod : pods) {
boolean placed = false;
for (int i = 0; i < nodes.size() && !placed; i++) {
@@ -340,6 +394,7 @@ final class EksAutoModeNodes {
freeMemory[i] -= pod.memoryBytes();
freePods[i]--;
onNode.get(i).add(pod.bound());
counted.add(node.instanceId());
placed = true;
}
}
@@ -347,7 +402,7 @@ final class EksAutoModeNodes {
left.add(pod);
}
}
return left;
return new Room(left, counted);
}
private static List<String> zonesOf(NodePool pool, Map<String, List<String>> zonesByNodeClass) {
@@ -356,13 +411,16 @@ final class EksAutoModeNodes {
}
private static Optional<Placement> candidate(NodePool pool, List<CatalogInstanceType> sized, List<String> zones,
PendingPod pod, long cpuMillis, long memoryBytes) {
PendingPod pod, long cpuMillis, long memoryBytes,
List<PendingPod> daemons, String region) {
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);
long[] daemon = daemonRequests(daemons, withRegion(labels, region), pool.taints());
if (type.vcpu * 1000L < cpuMillis + daemon[0]
|| type.memoryMib * 1024L * 1024L < memoryBytes + daemon[1]) {
continue;
}
if (poolAllows(pool, labels) && pod.fits(labels, pool.taints())) {
return Optional.of(new Placement(type, zone));
}
@@ -371,6 +429,89 @@ final class EksAutoModeNodes {
return Optional.empty();
}
/** A node's labels with the {@code topology.kubernetes.io/region} it joins with, when the region is known. */
static Map<String, String> withRegion(Map<String, String> labels, String region) {
if (region == null) {
return labels;
}
Map<String, String> all = new LinkedHashMap<>(labels);
all.put(REGION_LABEL, region);
return all;
}
/**
* The CPU (millicores) and memory (bytes) the DaemonSet pods that would run on a node of {@code labels} and
* {@code taints} request: those whose node selector, required node affinity and tolerations accept it.
*/
static long[] daemonRequests(List<PendingPod> daemons, Map<String, String> labels, List<Taint> taints) {
long[] total = new long[2];
for (PendingPod daemon : daemons) {
if (daemon.fits(labels, taints)) {
total[0] += daemon.cpuMillis();
total[1] += daemon.memoryBytes();
}
}
return total;
}
/**
* The pod each DaemonSet of {@code kubectl get daemonsets -A -o json} runs on a node, with its template's
* requests, node selector, required node affinity and tolerations, read as {@link #unschedulablePods} reads a
* pod's; one none of whose affinity terms a new node could match is left out. The DaemonSet controller lets its pods onto
* an unschedulable node, which Floci's nodes don't need.
*/
static List<PendingPod> daemonPods(JsonNode list) {
List<PendingPod> daemons = new ArrayList<>();
for (JsonNode item : list.path("items")) {
JsonNode spec = item.path("spec").path("template").path("spec");
Optional<NodeAsk> ask = nodeAsk(spec, false);
if (ask.isEmpty()) {
continue;
}
long[] requests = requests(spec);
daemons.add(new PendingPod(item.path("metadata").path("namespace").asText(),
item.path("metadata").path("name").asText(), requests[0], requests[1], ask.get().nodeSelector(),
ask.get().affinityTerms(), ask.get().tolerations()));
}
return daemons;
}
/** What a pod spec asks of its node: its node selector, required node affinity terms and tolerations. */
private record NodeAsk(Map<String, String> nodeSelector, List<List<Requirement>> affinityTerms,
List<Toleration> tolerations) {
}
/**
* What a pod spec asks of a node Auto Mode launches, or empty when no such node could take it. The required node
* affinity terms are alternatives: one with {@code matchFields}, which names nodes and so none Auto Mode
* launches, or with no expressions, which Kubernetes matches with no node, is no alternative for a new node, and
* a spec all of whose terms are such asks for none. With {@code refuseMatchFields}, a spec with any
* {@code matchFields} term asks for none, as Karpenter refuses a pending pod with one ("node selector term with
* matchFields is not supported") rather than read its other terms.
*/
private static Optional<NodeAsk> nodeAsk(JsonNode spec, boolean refuseMatchFields) {
JsonNode termList = spec.path("affinity").path("nodeAffinity")
.path("requiredDuringSchedulingIgnoredDuringExecution").path("nodeSelectorTerms");
List<List<Requirement>> terms = new ArrayList<>();
for (JsonNode term : termList) {
if (refuseMatchFields && !term.path("matchFields").isEmpty()) {
return Optional.empty();
}
if (term.path("matchFields").isEmpty() && !term.path("matchExpressions").isEmpty()) {
terms.add(requirements(term.path("matchExpressions")));
}
}
if (!termList.isEmpty() && terms.isEmpty()) {
return Optional.empty();
}
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(""))));
return Optional.of(new NodeAsk(selector, List.copyOf(terms), List.copyOf(tolerations)));
}
/** The NodePools of {@code kubectl get nodepools -o json}. */
static List<NodePool> nodePools(JsonNode list) {
List<NodePool> pools = new ArrayList<>();
@@ -382,18 +523,33 @@ final class EksAutoModeNodes {
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())));
JsonNode disruption = item.path("spec").path("disruption");
List<String> budgets = new ArrayList<>();
// A budget with a schedule applies only in its window, which Floci doesn't model; the others always do.
// A budget naming reasons covers only those; one without covers every reason, emptiness among them.
disruption.path("budgets").forEach(b -> {
boolean coversEmpty = !b.has("reasons") || b.path("reasons").isEmpty();
for (JsonNode reason : b.path("reasons")) {
coversEmpty |= "Empty".equals(reason.asText());
}
if (coversEmpty && b.path("schedule").asText("").isEmpty() && !b.path("nodes").asText("").isEmpty()) {
budgets.add(b.path("nodes").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)));
item.path("spec").path("weight").asInt(0), duration(disruption.path("consolidateAfter").asText("0s")),
List.copyOf(budgets)));
}
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).
* As Karpenter does, a DaemonSet's pods are left out, as are pods with a required node affinity term that pins
* named nodes ({@code matchFields}), which Karpenter refuses, and pods whose terms are all empty, which match no
* node (see {@link #nodeAsk}).
*/
static List<PendingPod> unschedulablePods(JsonNode list) {
List<PendingPod> pods = new ArrayList<>();
@@ -416,29 +572,15 @@ final class EksAutoModeNodes {
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())) {
Optional<NodeAsk> ask = nodeAsk(spec, true);
if (daemonSet || ask.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)));
ask.get().nodeSelector(), ask.get().affinityTerms(), ask.get().tolerations(), podLabels(item),
antiAffinity(item)));
}
return pods;
}
@@ -492,6 +634,29 @@ final class EksAutoModeNodes {
return List.copyOf(terms);
}
/**
* The nodes of {@code kubectl get pods -A -o json} that run a workload: a pod bound to them that hasn't finished
* and that isn't a DaemonSet's or a static pod's mirror, which Karpenter doesn't count either.
*/
static Set<String> nodesWithWorkloads(JsonNode list) {
Set<String> nodes = new HashSet<>();
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;
}
boolean daemon = false;
for (JsonNode owner : item.path("metadata").path("ownerReferences")) {
daemon |= "DaemonSet".equals(owner.path("kind").asText()) || "Node".equals(owner.path("kind").asText());
}
if (!daemon) {
nodes.add(node);
}
}
return nodes;
}
/**
* 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.
@@ -603,4 +768,18 @@ final class EksAutoModeNodes {
};
return value.setScale(0, RoundingMode.CEILING).longValue();
}
/** A Kubernetes duration such as {@code 30s}, {@code 5m} or {@code 1h30m}; null for {@code Never}. */
static Duration duration(String value) {
if ("Never".equals(value)) {
return null;
}
try {
return Duration.parse("PT" + value.toUpperCase(Locale.ROOT));
} catch (RuntimeException expected) {
// The NodePool schema refuses such a value (500ms, say, which the parse above doesn't read); one that got
// through waits the 30 seconds of Auto Mode's built-in pools.
return Duration.ofSeconds(30);
}
}
}
@@ -4437,9 +4437,14 @@ public class EksClusterManager
}
}
/** Whether the instance's image runs a kubelet that registers its node, rather than Floci registering it. */
boolean kubeletRegistersNode(Instance instance) {
return imageCatalog.findByIdOrAlias(instance.getImageId())
.map(image -> Boolean.TRUE.equals(image.kubeletRegistersNode)).orElse(false);
}
private void registerNodeInCluster(Cluster cluster, String containerId, Instance instance) {
if (imageCatalog.findByIdOrAlias(instance.getImageId())
.map(image -> Boolean.TRUE.equals(image.kubeletRegistersNode)).orElse(false)) {
if (kubeletRegistersNode(instance)) {
// Do not race the guest kubelet with a status-less Node or synthetic Ready status.
return;
}
@@ -16,9 +16,11 @@ 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 io.floci.aws.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.time.Duration;
import java.time.Instant;
@@ -40,14 +42,19 @@ 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.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EksAutoModeComputeTest {
private static final String REGION = "us-east-1";
/** The drain of Floci's own Ready node, which has no kubelet to finish a pod's graceful shutdown. */
private static final String[] DRAIN_NODE_1 = {"kubectl", "drain", "node-1", "--ignore-daemonsets",
"--delete-emptydir-data", "--force", "--timeout=10s", "--grace-period=0"};
private static final String PENDING_POD = """
{"items": [{"metadata": {"namespace": "default", "name": "web"},
"spec": {"nodeSelector": {"karpenter.sh/nodepool": "general-purpose"},
@@ -68,10 +75,12 @@ class EksAutoModeComputeTest {
private final IamService iam = mock(IamService.class);
private final Ec2InstanceTypeCatalog instanceTypes = mock(Ec2InstanceTypeCatalog.class);
private final EksService eksService = mock(EksService.class);
private final MutableClock clock = new MutableClock();
private final EksAutoModeCompute compute = new EksAutoModeCompute(eksService, clusterManager, ec2,
iam, instanceTypes, mock(EmulatorConfig.class));
iam, instanceTypes, mock(EmulatorConfig.class), clock);
private final Map<String, String> lists = new HashMap<>(Map.of("pods", PENDING_POD,
"nodepools", POOLS, "nodeclasses", NODE_CLASSES, "nodes", "{\"items\": []}"));
"nodepools", POOLS, "nodeclasses", NODE_CLASSES, "nodes", "{\"items\": []}", "daemonsets",
"{\"items\": []}"));
@BeforeEach
void cluster() {
@@ -80,6 +89,8 @@ class EksAutoModeComputeTest {
String[] cmd = inv.getArgument(1);
return new ContainerExec.Result(0, lists.get(cmd[2]), "", false);
});
when(clusterManager.execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 1 && !"get".equals(cmd[1])),
anyInt())).thenReturn(new ContainerExec.Result(0, "", "", 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<>(
@@ -184,7 +195,7 @@ class EksAutoModeComputeTest {
Instance stuck = new Instance();
stuck.setInstanceId("i-stuck");
stuck.setInstanceType("c7a.large");
stuck.setLaunchTime(Instant.now().minus(EksAutoModeCompute.REGISTRATION_WAIT).minusSeconds(1));
stuck.setLaunchTime(clock.instant().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));
@@ -199,6 +210,334 @@ class EksAutoModeComputeTest {
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
}
/**
* As Auto Mode consolidates: a node that runs no workload for its pool's consolidateAfter is tainted as
* disrupted, its node taken out and its instance terminated; a pod running on it again starts the wait over.
*/
@Test
void aNodeEmptyForItsPoolsConsolidateAfterIsRemoved() {
Instance node = joinedNode("i-node", "node-1");
lists.put("pods", "{\"items\": []}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"30s\"}, \"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
clock.advance(Duration.ofSeconds(20));
// A pod runs there for a while, which starts the wait over.
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"node-1\"}, "
+ "\"status\": {\"phase\": \"Running\"}}]}");
compute.reconcile(cluster, REGION);
lists.put("pods", "{\"items\": []}");
clock.advance(Duration.ofSeconds(20));
compute.reconcile(cluster, REGION);
clock.advance(Duration.ofSeconds(20));
compute.reconcile(cluster, REGION);
verify(ec2, never()).terminateInstances(REGION, List.of("i-node"));
clock.advance(Duration.ofSeconds(11));
compute.reconcile(cluster, REGION);
// Tainted as disrupted and drained, then its node goes before its instance does.
InOrder order = inOrder(clusterManager, ec2);
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node",
"node-1", "karpenter.sh/disrupted:NoSchedule", "--overwrite"}, 15);
order.verify(clusterManager).execInContainerForResult("k3s-1", DRAIN_NODE_1, 15);
order.verify(clusterManager).removeJoinedNode(cluster, node);
order.verify(ec2).terminateInstances(REGION, List.of("i-node"));
}
/**
* A pod the scheduler bound to the node after the pass read the pods, but before it was tainted, keeps it: the
* pass looks again once the node is tainted, and takes the taint off.
*/
@Test
void aPodBoundJustBeforeTheTaintKeepsTheNode() {
Instance node = joinedNode("i-node", "node-1");
lists.put("pods", "{\"items\": []}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"0s\"}, \"template\""));
when(clusterManager.execInContainerForResult(eq("k3s-1"),
argThat(cmd -> List.of(cmd).contains("--field-selector")), anyInt()))
.thenReturn(new ContainerExec.Result(0, "{\"items\": [{\"metadata\": {}, "
+ "\"spec\": {\"nodeName\": \"node-1\"}, \"status\": {\"phase\": \"Pending\"}}]}", "", false));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node", "node-1",
"karpenter.sh/disrupted:NoSchedule", "--overwrite"}, 15);
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node", "node-1",
"karpenter.sh/disrupted:NoSchedule-"}, 15);
verify(clusterManager, never()).removeJoinedNode(cluster, node);
verify(ec2, never()).terminateInstances(anyString(), anyList());
}
/**
* A node a removal left tainted as disrupted, because it was called off and taking the taint off failed or the
* pass failed after the taint, has it taken off by the next pass once it runs a workload again.
*/
@Test
void aBusyNodeLeftTaintedAsDisruptedHasTheTaintTakenOff() {
Instance node = joinedNode("i-node", "node-1");
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"node-1\"}, "
+ "\"status\": {\"phase\": \"Running\"}}]}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}, \"spec\": "
+ "{\"unschedulable\": true, "
+ "\"taints\": [{\"key\": \"karpenter.sh/disrupted\", \"effect\": \"NoSchedule\"}]}}]}");
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"0s\"}, \"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
// A drain that failed left it cordoned too: that is undone first, and the taint last.
InOrder order = inOrder(clusterManager);
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "uncordon", "node-1"}, 15);
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node",
"node-1", "karpenter.sh/disrupted:NoSchedule-"}, 15);
verify(clusterManager, never()).removeJoinedNode(cluster, node);
verify(ec2, never()).terminateInstances(anyString(), anyList());
}
/**
* The node of an Auto Mode instance that is terminated, one that registered while a pass terminated its
* instance, or whose deletion failed after it, is deleted by the next pass. A node no Auto Mode instance is
* named for stays, though it carries a pool's label and the Auto Mode compute label, as the cluster's own node
* can; so does one whose name a live instance's node has again.
*/
@Test
void theNodeOfATerminatedAutoModeInstanceIsDeleted() {
Instance live = joinedNode("i-node", "node-1");
Instance dead = new Instance();
dead.setInstanceId("i-dead");
Instance reused = new Instance();
reused.setInstanceId("i-old");
Instance replaced = new Instance();
replaced.setInstanceId("i-gone");
when(clusterManager.deriveInstanceNodeName(dead, REGION)).thenReturn("stray");
when(clusterManager.deriveInstanceNodeName(reused, REGION)).thenReturn("node-1");
when(clusterManager.deriveInstanceNodeName(replaced, REGION)).thenReturn("taken");
Reservation liveReservation = new Reservation();
liveReservation.setInstances(List.of(live));
Reservation deadReservation = new Reservation();
deadReservation.setInstances(List.of(dead, reused, replaced));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenAnswer(inv -> {
Map<String, List<String>> filters = inv.getArgument(2);
return filters.get("instance-state-name").contains("terminated") ? List.of(deadReservation)
: List.of(liveReservation);
});
lists.put("pods", "{\"items\": []}");
String autoLabels = "{\"karpenter.sh/nodepool\": \"general-purpose\", "
+ "\"eks.amazonaws.com/compute-type\": \"auto\"}";
// A node group's worker joined under the name of a terminated Auto Mode instance's node: its provider ID is
// its own.
lists.put("nodes", "{\"items\": ["
+ "{\"metadata\": {\"name\": \"node-1\", \"labels\": " + autoLabels + "}, "
+ "\"spec\": {\"providerID\": \"aws:///us-east-1a/i-node\"}},"
+ "{\"metadata\": {\"name\": \"stray\", \"labels\": " + autoLabels + "}, "
+ "\"spec\": {\"providerID\": \"aws:///us-east-1a/i-dead\"}},"
+ "{\"metadata\": {\"name\": \"taken\", \"labels\": {}}, "
+ "\"spec\": {\"providerID\": \"aws:///us-east-1a/i-worker\"}},"
+ "{\"metadata\": {\"name\": \"cluster-node\", \"labels\": " + autoLabels + "}}]}");
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"Never\"}, \"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "node", "stray",
"--ignore-not-found=true", "--wait=false"}, 15);
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "node",
"node-1", "--ignore-not-found=true", "--wait=false"}, 15);
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "node",
"cluster-node", "--ignore-not-found=true", "--wait=false"}, 15);
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "node",
"taken", "--ignore-not-found=true", "--wait=false"}, 15);
}
/**
* With compute off, a worker that was joining when it was terminated and registered while it shut down has its
* node deleted by the next pass too, as with compute on.
*/
@Test
void withComputeOffTheNodeOfAWorkerThatRegisteredWhileTerminatingIsDeleted() {
Instance late = new Instance();
late.setInstanceId("i-late");
when(clusterManager.deriveInstanceNodeName(late, REGION)).thenReturn("late-node");
Reservation dead = new Reservation();
dead.setInstances(List.of(late));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenAnswer(inv -> {
Map<String, List<String>> filters = inv.getArgument(2);
return filters.get("instance-state-name").contains("terminated") ? List.of(dead) : List.of();
});
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"late-node\", \"labels\": {}}, "
+ "\"spec\": {\"providerID\": \"aws:///us-east-1a/i-late\"}}]}");
Cluster cluster = cluster("prod");
cluster.setComputeConfig(new ComputeConfig(false, List.of(), null));
compute.removeNodes(cluster, REGION);
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "node",
"late-node", "--ignore-not-found=true", "--wait=false"}, 15);
verify(ec2, never()).terminateInstances(anyString(), anyList());
}
/** A node whose kubelet runs keeps its pods' graceful shutdown: the drain gives them their grace period. */
@Test
void aKubeletsNodeIsDrainedWithItsPodsGracePeriod() {
Instance node = joinedNode("i-node", "node-1");
when(clusterManager.kubeletRegistersNode(node)).thenReturn(true);
lists.put("pods", "{\"items\": []}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
lists.put("nodepools", "{\"items\": []}");
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "drain", "node-1",
"--ignore-daemonsets", "--delete-emptydir-data", "--force", "--timeout=10s"}, 15);
verify(clusterManager).removeJoinedNode(cluster, node);
}
/**
* The nodes of a NodePool that was deleted, or that UpdateClusterConfig dropped, go as Karpenter removes them:
* tainted as disrupted and drained, whatever they run, then deleted and terminated.
*/
@Test
void aDeletedPoolsNodeIsDrainedAndRemoved() {
Instance node = joinedNode("i-node", "node-1");
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"node-1\"}, "
+ "\"status\": {\"phase\": \"Running\"}}]}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
lists.put("nodepools", "{\"items\": []}");
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
InOrder order = inOrder(clusterManager, ec2);
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node",
"node-1", "karpenter.sh/disrupted:NoSchedule", "--overwrite"}, 15);
order.verify(clusterManager).execInContainerForResult("k3s-1", DRAIN_NODE_1, 15);
order.verify(clusterManager).removeJoinedNode(cluster, node);
order.verify(ec2).terminateInstances(REGION, List.of("i-node"));
}
/**
* A pool's nodes that are already unavailable use up its disruption budget first, as Karpenter counts it: of two
* nodes, at 10% one may go, and with one not Ready the empty other stays; once it is Ready again, the empty one
* goes.
*/
@Test
void aNotReadyNodeUsesUpThePoolsBudget() {
Instance empty = joinedNode("i-empty", "empty-node");
Instance sick = new Instance();
sick.setInstanceId("i-sick");
sick.setInstanceType("c7a.large");
sick.setLaunchTime(clock.instant());
sick.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
when(clusterManager.deriveInstanceNodeName(sick, REGION)).thenReturn("sick-node");
Reservation both = new Reservation();
both.setInstances(List.of(empty, sick));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(both));
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"sick-node\"}, "
+ "\"status\": {\"phase\": \"Running\"}}]}");
String nodes = "{\"items\": [{\"metadata\": {\"name\": \"empty-node\", \"labels\": {}}},"
+ "{\"metadata\": {\"name\": \"sick-node\", \"labels\": {}}, \"status\": {\"conditions\": "
+ "[{\"type\": \"Ready\", \"status\": \"%s\"}]}}]}";
lists.put("nodes", nodes.formatted("Unknown"));
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"0s\"}, \"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
verify(clusterManager, never()).removeJoinedNode(cluster, empty);
lists.put("nodes", nodes.formatted("True"));
compute.reconcile(cluster, REGION);
verify(clusterManager).removeJoinedNode(cluster, empty);
verify(clusterManager, never()).removeJoinedNode(cluster, sick);
}
/**
* A budget's percentage is of the pool's joined nodes: one still joining isn't counted, as Karpenter leaves out
* nodes that aren't initialized. Ten empty joined nodes and one joining, at 10%, lose one node a pass, not two.
*/
@Test
void aBudgetsPercentageLeavesOutNodesStillJoining() {
List<Instance> instances = new ArrayList<>();
StringBuilder nodes = new StringBuilder("{\"items\": [");
for (int i = 0; i < 11; i++) {
Instance instance = new Instance();
instance.setInstanceId("i-" + i);
instance.setInstanceType("c7a.large");
instance.setLaunchTime(clock.instant());
instance.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
when(clusterManager.deriveInstanceNodeName(instance, REGION)).thenReturn("node-" + i);
instances.add(instance);
if (i < 10) {
nodes.append(i == 0 ? "" : ",").append("{\"metadata\": {\"name\": \"node-").append(i)
.append("\", \"labels\": {}}}");
}
}
Reservation reservation = new Reservation();
reservation.setInstances(instances);
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
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));
lists.put("pods", "{\"items\": []}");
lists.put("nodes", nodes.append("]}").toString());
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"0s\", \"budgets\": [{\"nodes\": \"10%\"}]}, "
+ "\"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
verify(clusterManager, times(1)).removeJoinedNode(eq(cluster), any());
}
@Test
void aPoolThatNeverConsolidatesKeepsItsEmptyNode() {
joinedNode("i-node", "node-1");
lists.put("pods", "{\"items\": []}");
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
"\"spec\": {\"disruption\": {\"consolidateAfter\": \"Never\"}, \"template\""));
Cluster cluster = cluster("prod");
compute.reconcile(cluster, REGION);
clock.advance(Duration.ofHours(1));
compute.reconcile(cluster, REGION);
verify(ec2, never()).terminateInstances(anyString(), anyList());
}
private Instance joinedNode(String id, String nodeName) {
Instance node = new Instance();
node.setInstanceId(id);
node.setInstanceType("c7a.large");
node.setLaunchTime(clock.instant());
node.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(node));
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenReturn(List.of(reservation));
when(clusterManager.deriveInstanceNodeName(node, REGION)).thenReturn(nodeName);
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));
return node;
}
@Test
void aDeletedClustersInstancesAreTerminatedAndItsProfilesDeleted() {
Instance node = new Instance();
@@ -229,7 +568,7 @@ class EksAutoModeComputeTest {
Instance joined = new Instance();
joined.setInstanceId("i-joined");
joined.setInstanceType("c7a.large");
joined.setLaunchTime(Instant.now());
joined.setLaunchTime(clock.instant());
joined.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(joined));
@@ -269,7 +608,7 @@ class EksAutoModeComputeTest {
Instance joined = new Instance();
joined.setInstanceId("i-joined");
joined.setInstanceType("c7a.large");
joined.setLaunchTime(Instant.now());
joined.setLaunchTime(clock.instant());
joined.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
Reservation reservation = new Reservation();
reservation.setInstances(List.of(joined));
@@ -292,7 +631,7 @@ class EksAutoModeComputeTest {
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));
joined.setLaunchTime(clock.instant().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(),
@@ -38,7 +38,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* 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,
* the instance and takes its node out, and deleting the cluster deletes the profile. A node whose pod is gone is
* removed once it has been empty for its pool's consolidateAfter. 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.
*/
@@ -70,6 +71,8 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
EksService eksService;
private Cluster cluster;
private String role;
private String subnet;
@BeforeEach
void requireDocker() {
@@ -96,18 +99,21 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
}
}
@Test
void anUnschedulablePodGetsANodeOfItsPoolWhichGoesWithCompute() {
/**
* Starts a cluster in a VPC of {@code cidr} with compute on and the {@code general-purpose} pool, whose node
* role exists, and runs a pod selecting that pool, which the cluster's own node isn't, so it is unschedulable.
*/
private EksTestNode clusterWithAnUnschedulablePod(String cidr) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String role = "auto-node-" + suffix;
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, () -> {
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();
String vpc = ec2.createVpc(REGION, cidr + ".0.0/16", false).getVpcId();
return ec2.createSubnet(REGION, vpc, cidr + ".1.0/24", "us-east-1a").getSubnetId();
});
ResourcesVpcConfig network = new ResourcesVpcConfig();
network.setSubnetIds(List.of(subnet));
@@ -127,6 +133,13 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
.ignoreExceptions().until(() -> "Unschedulable".equals(node.kubectlOutput("get", "pod", "web",
"-o", "jsonpath={.status.conditions[?(@.type==\"PodScheduled\")].reason}")));
return node;
}
@Test
void anUnschedulablePodGetsANodeOfItsPoolWhichGoesWithCompute() {
EksTestNode node = clusterWithAnUnschedulablePod("10.71");
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
List<Instance> launched = RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running"));
@@ -173,4 +186,40 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
assertEquals(List.of(), RequestScopes.callAs(ACCOUNT, REGION, () -> iam.listInstanceProfiles(
"/eks/" + REGION + "/" + deleted.getName() + "/")));
}
/**
* As Auto Mode consolidates: once the pod is gone and its node has run no workload for the pool's
* consolidateAfter, the node is removed and its instance terminated.
*/
@Test
void aNodeLeftEmptyGoesAfterItsPoolsConsolidateAfter() {
EksTestNode node = clusterWithAnUnschedulablePod("10.72");
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
Instance instance = RequestScopes.callAs(ACCOUNT, REGION,
() -> compute.instancesOf(cluster, REGION, "pending", "running")).getFirst();
RequestScopes.runAs(ACCOUNT, REGION, () -> eksClusterManager.joinInstance(cluster, instance));
String nodeName = eksClusterManager.deriveInstanceNodeName(instance, REGION);
await("the pod is scheduled on the new node").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> {
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
return nodeName.equals(node.kubectlOutput("get", "pod", "web", "-o", "jsonpath={.spec.nodeName}"));
});
node.kubectl("patch", "nodepool", "general-purpose", "--type=merge",
"-p", "{\"spec\":{\"disruption\":{\"consolidateAfter\":\"2s\"}}}");
// Running its workload, the node stays.
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION,
() -> compute.instancesOf(cluster, REGION, "pending", "running")).size());
node.kubectl("delete", "pod", "web", "--grace-period=0", "--force");
await("the empty node is removed").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> {
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
return RequestScopes.callAs(ACCOUNT, REGION,
() -> compute.instancesOf(cluster, REGION, "pending", "running")).isEmpty();
});
await("the node is gone").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.ignoreExceptions().until(() -> node.kubectl("get", "node", nodeName).exitCode() != 0);
}
}
@@ -12,12 +12,15 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EksAutoModeNodesTest {
@@ -51,6 +54,77 @@ class EksAutoModeNodesTest {
type("c7g.large", 2, 4096, "arm64"),
type("m4.large", 2, 8192, "x86_64"));
/**
* A node is sized for the DaemonSet pods that would run on it as well, as Karpenter sizes it: 1900m of workload
* and 400m of daemons don't fit 2 vCPUs. A daemon whose node selector leaves the node out doesn't count, nor one
* pinned to a named node; one with another term a new node matches does.
*/
@Test
void aNodeIsSizedForTheDaemonSetPodsItWouldRunToo() throws Exception {
String daemonSets = """
{"items": [
{"metadata": {"namespace": "kube-system", "name": "agent"}, "spec": {"template": {"spec": {
"containers": [{"resources": {"requests": {"cpu": "300m", "memory": "64Mi"}}}]}}}},
{"metadata": {"namespace": "kube-system", "name": "arm-only"}, "spec": {"template": {"spec": {
"nodeSelector": {"kubernetes.io/arch": "arm64"},
"containers": [{"resources": {"requests": {"cpu": "1"}}}]}}}},
{"metadata": {"namespace": "kube-system", "name": "pinned"}, "spec": {"template": {"spec": {
"affinity": {"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [
{"matchFields": [{"key": "metadata.name", "operator": "In", "values": ["old-node"]}]}]}}},
"containers": [{"resources": {"requests": {"cpu": "1"}}}]}}}},
{"metadata": {"namespace": "kube-system", "name": "either"}, "spec": {"template": {"spec": {
"affinity": {"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [
{"matchFields": [{"key": "metadata.name", "operator": "In", "values": ["old-node"]}]},
{"matchExpressions": [{"key": "kubernetes.io/arch", "operator": "In", "values": ["amd64"]}]}]}}},
"containers": [{"resources": {"requests": {"cpu": "100m"}}}]}}}}
]}""";
List<PendingPod> daemons = EksAutoModeNodes.daemonPods(json(daemonSets));
// Terms are alternatives: "either" may run on any amd64 node, whatever its first term pins.
assertEquals(List.of("agent", "arm-only", "either"), daemons.stream().map(PendingPod::name).toList());
PendingPod big = pod("big", "1700m", "64Mi");
assertEquals("c7a.large", EksAutoModeNodes.plan(pools(), List.of(big), TYPES, Map.of())
.getFirst().instanceType().instanceType);
assertEquals("c7a.xlarge", EksAutoModeNodes.plan(pools(), List.of(big), TYPES, Map.of(), daemons)
.getFirst().instanceType().instanceType);
assertEquals(400, EksAutoModeNodes.daemonRequests(daemons,
EksAutoModeNodes.labels(TYPES.get(2), pools().getFirst(), null), List.of())[0]);
}
/** A DaemonSet selecting on the region, which a joined node carries, counts on a new node in that region. */
@Test
void aDaemonSetSelectingTheRegionCountsOnANodeThere() throws Exception {
String daemonSets = """
{"items": [{"metadata": {"namespace": "kube-system", "name": "regional"}, "spec": {"template": {"spec": {
"nodeSelector": {"topology.kubernetes.io/region": "us-east-1"},
"containers": [{"resources": {"requests": {"cpu": "300m"}}}]}}}}]}""";
List<PendingPod> daemons = EksAutoModeNodes.daemonPods(json(daemonSets));
PendingPod big = pod("big", "1900m", "64Mi");
assertEquals("c7a.xlarge", EksAutoModeNodes.plan(pools(), List.of(big), TYPES, Map.of(), daemons, "us-east-1")
.getFirst().instanceType().instanceType);
assertEquals("c7a.large", EksAutoModeNodes.plan(pools(), List.of(big), TYPES, Map.of(), daemons, "eu-west-1")
.getFirst().instanceType().instanceType);
}
/**
* A pending pod with a {@code matchFields} term is left out, whatever its other terms, as Karpenter refuses it
* ("node selector term with matchFields is not supported"); a DaemonSet reads its terms as alternatives instead.
*/
@Test
void aPodWithAMatchFieldsTermIsLeftOutWhateverItsOtherTerms() throws Exception {
String pods = """
{"items": [{"metadata": {"namespace": "default", "name": "either"},
"spec": {"affinity": {"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [
{"matchFields": [{"key": "metadata.name", "operator": "In", "values": ["old-node"]}]},
{"matchExpressions": [{"key": "kubernetes.io/arch", "operator": "In", "values": ["arm64"]}]}]}}},
"containers": [{"resources": {"requests": {"cpu": "100m"}}}]},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}]}""";
assertEquals(List.of(), EksAutoModeNodes.unschedulablePods(json(pods)));
}
@Test
void aSmallPodGetsTheSmallestTwoVcpuTypeOfTheGeneralPurposePool() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(pod("web", "100m", "64Mi")), TYPES, Map.of());
@@ -134,14 +208,17 @@ class EksAutoModeNodesTest {
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)));
EksAutoModeNodes.Room room = EksAutoModeNodes.withoutRoom(List.of(small, big),
List.of(new EksAutoModeNodes.PoolNode("i-1", 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)));
EksAutoModeNodes.Room untolerated = EksAutoModeNodes.withoutRoom(List.of(small),
List.of(new EksAutoModeNodes.PoolNode("i-2", pools().get(1), TYPES.get(3), null, 0, 0)));
assertEquals(List.of(big), left);
assertEquals(List.of(small), untolerated);
assertEquals(List.of(big), room.left());
// The node the small pod counts on isn't empty, whatever runs on it.
assertEquals(Set.of("i-1"), room.counted());
assertEquals(List.of(small), untolerated.left());
assertEquals(Set.of(), untolerated.counted());
}
/** A cordoned node, or one with a taint of its own the pod doesn't tolerate, has no room for it. */
@@ -151,13 +228,14 @@ class EksAutoModeNodesTest {
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 64_000, 1L << 40, 110, false,
List.of()))).left();
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")))));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 64_000, 1L << 40, 110, true,
List.of(new EksAutoModeNodes.Taint("maintenance", "", "NoSchedule"))))).left();
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")))));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 64_000, 1L << 40, 110, true,
List.of(new EksAutoModeNodes.Taint("busy", "", "PreferNoSchedule"))))).left();
assertEquals(List.of(small), cordoned);
assertEquals(List.of(small), tainted);
@@ -172,9 +250,11 @@ class EksAutoModeNodesTest {
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 64_000, 1L << 40, 0, true,
List.of()))).left();
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 64_000, 1L << 40, 1, true,
List.of()))).left();
assertEquals(List.of(first), full);
assertEquals(List.of(second), oneSlot);
@@ -215,24 +295,24 @@ class EksAutoModeNodesTest {
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,
EksAutoModeNodes.PoolNode withWeb1 = new EksAutoModeNodes.PoolNode("i-3", 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,
EksAutoModeNodes.PoolNode empty = new EksAutoModeNodes.PoolNode("i-3", 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)));
List.of(withWeb1)).left());
// 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)));
assertEquals(List.of(plain), EksAutoModeNodes.withoutRoom(List.of(plain), List.of(withWeb1)).left());
assertEquals(List.of(web3), EksAutoModeNodes.withoutRoom(List.of(pending.get("web-2"), web3), List.of(empty)).left());
}
/** A joined node's room is what it offers, its allocatable CPU and memory less its pods', not its type's size. */
@@ -242,11 +322,14 @@ class EksAutoModeNodesTest {
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 400, 1L << 30, 110, true,
List.of()))).left();
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 1000, 32L << 20, 110, true,
List.of()))).left();
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())));
new EksAutoModeNodes.PoolNode("i-3", general, TYPES.get(2), null, 500, 64L << 20, 110, true,
List.of()))).left();
assertEquals(List.of(pod), tooLittleCpu);
assertEquals(List.of(pod), tooLittleMemory);
@@ -306,6 +389,53 @@ class EksAutoModeNodesTest {
assertEquals("c7a.large", launches.getFirst().instanceType().instanceType);
}
/** Percentages round up, as AWS removed the only node of a pool budgeted at 10%; the least budget wins. */
@ParameterizedTest
@CsvSource({"'10%',1,1", "'10%',10,1", "'10%',11,2", "'0',5,0", "'20%;1',10,1", "'',3,1", "'x',3,0"})
void disruptionBudgets(String budgets, int nodes, int disruptable) {
NodePool pool = new NodePool("p", "default", List.of(), List.of(), Map.of(), 0, Duration.ofSeconds(30),
budgets.isEmpty() ? List.of() : List.of(budgets.split(";")));
assertEquals(disruptable, pool.disruptable(nodes));
}
@Test
void consolidateAfterAndBudgetsAreReadFromThePoolScheduledAndOtherReasonsBudgetsLeftOut() throws Exception {
String pools = """
{"items": [{"metadata": {"name": "batch"}, "spec": {
"disruption": {"consolidateAfter": "1m30s",
"budgets": [{"nodes": "50%"}, {"nodes": "0", "schedule": "@daily", "duration": "1h"},
{"nodes": "0", "reasons": ["Underutilized"]},
{"nodes": "2", "reasons": ["Drifted", "Empty"]}]},
"template": {"spec": {}}}},
{"metadata": {"name": "pinned"}, "spec": {"disruption": {"consolidateAfter": "Never"},
"template": {"spec": {}}}}]}""";
List<NodePool> read = EksAutoModeNodes.nodePools(json(pools));
assertEquals(Duration.ofSeconds(90), read.getFirst().consolidateAfter());
// A budget for other reasons than emptiness doesn't hold empty nodes back.
assertEquals(List.of("50%", "2"), read.getFirst().budgets());
assertNull(read.get(1).consolidateAfter());
}
/** DaemonSet pods and static pods' mirrors don't keep a node busy; finished pods don't either. */
@Test
void onlyAWorkloadKeepsANodeBusy() throws Exception {
String pods = """
{"items": [
{"metadata": {"ownerReferences": [{"kind": "ReplicaSet"}]}, "spec": {"nodeName": "busy"},
"status": {"phase": "Running"}},
{"metadata": {"ownerReferences": [{"kind": "DaemonSet"}]}, "spec": {"nodeName": "daemons"},
"status": {"phase": "Running"}},
{"metadata": {"ownerReferences": [{"kind": "Node"}]}, "spec": {"nodeName": "daemons"},
"status": {"phase": "Running"}},
{"metadata": {}, "spec": {"nodeName": "finished"}, "status": {"phase": "Succeeded"}}
]}""";
assertEquals(Set.of("busy"), EksAutoModeNodes.nodesWithWorkloads(json(pods)));
}
@Test
void requiredNodeAffinityTermsAreAlternatives() {
PendingPod pod = new PendingPod("default", "p", 0, 0, Map.of(), List.of(