feat(eks): honour pods' zone topology spread constraints in EKS Auto Mode's room and launches (#9894)

EKS Auto Mode ignored pods' zone topology spread constraints: withoutRoom
counted a node in any zone as room for a pod the scheduler then refused
for its skew, and a new node went to the first zone that fit, so pods
that must spread kept getting nodes in one zone.

Auto Mode now reads each DoNotSchedule zone constraint and checks the
skew as the scheduler does, counting only pods on nodes the pod's node
selector and required affinity accept, over the zones the pool can
launch in. Room counts only in a zone the spread allows, and a spreading
pod's node goes to the allowed zone with the fewest matching pods, a
group sharing one node of the type that holds it. Pods without a spread
are placed as before.

Part of #8914
This commit is contained in:
mrfelek authored and GitHub committed 2026-12-01 22:42:27 -04:00
1 parent 0a3188e744
commit 5bc31a1ef4
4 files changed
+594 -28

No files matched your search

+9 -2
View File
@@ -483,9 +483,16 @@ launches nodes on AWS. Floci checks every 10 seconds.
joining has what its instance type offers pods 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
key isn't modelled; a node in a zone the pod's zone spread constraint refuses has none either (see Zone spread); 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
- **Zone spread.** A pod's `topologySpreadConstraints` on `topology.kubernetes.io/zone` that the scheduler enforces
(`whenUnsatisfiable: DoNotSchedule`, the default) count the pods their `labelSelector` names in the pod's namespace,
in each zone where a node the pod could run on is, as the scheduler counts them. A node in a zone where the pod would
make that zone's count exceed the fewest by more than `maxSkew` has no room for it, and its new node goes to the
zone of the pool's NodeClass that keeps within `maxSkew` with the fewest such pods, as Karpenter spreads them, so
pods spread over zones get a node in each. `ScheduleAnyway` constraints, those on another key (`kubernetes.io/
hostname` among them), `minDomains`, `matchLabelKeys` and the node affinity and taint policies aren't modelled.
- **Instance.** One node a pool and pass (one a zone for pods that spread over zones), of the smallest type in the instance type catalog with at least 2 vCPUs
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
@@ -308,7 +308,9 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
neverRegistered.stream().map(Instance::getInstanceId).toList(), cluster.getName(),
REGISTRATION_WAIT);
}
EksAutoModeNodes.Room room = EksAutoModeNodes.withoutRoom(pods, poolNodes);
// Where the cluster's pods run by zone, for zone spread constraints; the room check adds the pods it places.
EksAutoModeNodes.Zones zones = EksAutoModeNodes.Zones.of(podList, nodesByName);
EksAutoModeNodes.Room room = EksAutoModeNodes.withoutRoom(pods, poolNodes, zones);
Map<String, String> replacing = consolidation.replacing(cluster.getArn());
// A replacement waiting for its pods is no empty node to remove.
Set<String> counted = new HashSet<>(room.counted());
@@ -351,7 +353,7 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
}
Placing placing = placing(cluster, region);
for (Launch launch : EksAutoModeNodes.plan(List.copyOf(pools.values()), withoutRoom,
instanceTypes.instanceTypes(), placing.zonesByNodeClass(), daemons, region, poolUsed)) {
instanceTypes.instanceTypes(), placing.zonesByNodeClass(), daemons, region, poolUsed, zones)) {
try {
launch(cluster, region, launch, claims, placing.nodeClasses().get(launch.pool().nodeClass()),
placing.subnetZones(), poolItems.getOrDefault(launch.pool().name(), MAPPER.createObjectNode()));
@@ -10,8 +10,11 @@ import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -196,7 +199,16 @@ final class EksAutoModeNodes {
/** 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) {
List<Toleration> tolerations, Map<String, String> labels, List<PodTerm> antiAffinity,
List<ZoneSpread> zoneSpread) {
/** A pod with no zone spread constraint. */
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) {
this(namespace, name, cpuMillis, memoryBytes, nodeSelector, affinityTerms, tolerations, labels,
antiAffinity, List.of());
}
/** A pod with no labels and no pod anti-affinity. */
PendingPod(String namespace, String name, long cpuMillis, long memoryBytes, Map<String, String> nodeSelector,
@@ -249,6 +261,162 @@ final class EksAutoModeNodes {
}
}
/**
* A pod's topology spread constraint on {@code topology.kubernetes.io/zone} that the scheduler enforces
* ({@code whenUnsatisfiable: DoNotSchedule}): the pods it counts, in the pod's own namespace, and how many more of
* them one zone may have than the zone with the fewest.
*/
record ZoneSpread(PodTerm selector, int maxSkew) {
}
/**
* Where the cluster's pods run by zone, as the scheduler counts them for zone spread constraints: each zone's
* pods, and its nodes' labels, which decide the zones a pod could run in. Placing a pod adds it to its zone.
*/
static final class Zones {
private final Map<String, List<CountedPod>> pods;
private final Map<String, List<Map<String, String>>> nodes;
/** By pod: the zones of the nodes it could run on, which don't change in a pass. */
private final Map<PendingPod, Set<String>> nodeZones = new IdentityHashMap<>();
/**
* By pod, then constraint, then zone: the matching pods on nodes the pod could run on; placing a pod clears
* it.
*/
private final Map<PendingPod, Map<ZoneSpread, Map<String, Long>>> counts = new IdentityHashMap<>();
/** A pod counted in a zone, with the labels of its node. */
private record CountedPod(BoundPod pod, Map<String, String> nodeLabels) {
}
private Zones(Map<String, List<CountedPod>> pods, Map<String, List<Map<String, String>>> nodes) {
this.pods = pods;
this.nodes = nodes;
}
/** No pod and no node known: a zone spread constraint allows any zone. */
static Zones none() {
return new Zones(new LinkedHashMap<>(), new LinkedHashMap<>());
}
/**
* The zones of {@code nodesByName} (the cluster's nodes, by name) and the pods of {@code kubectl get pods -A
* -o json} bound to them that haven't finished or begun to go.
*/
static Zones of(JsonNode podList, Map<String, JsonNode> nodesByName) {
Zones zones = none();
Map<String, Map<String, String>> labelsOfNode = new HashMap<>();
nodesByName.forEach((name, node) -> {
Map<String, String> labels = new LinkedHashMap<>();
node.path("metadata").path("labels").properties()
.forEach(e -> labels.put(e.getKey(), e.getValue().asText()));
String zone = labels.get(ZONE_LABEL);
if (zone != null) {
labelsOfNode.put(name, labels);
zones.nodes.computeIfAbsent(zone, z -> new ArrayList<>()).add(labels);
}
});
for (JsonNode item : podList.path("items")) {
Map<String, String> nodeLabels = labelsOfNode.get(item.path("spec").path("nodeName").asText(""));
String phase = item.path("status").path("phase").asText();
if (nodeLabels == null || "Succeeded".equals(phase) || "Failed".equals(phase)
|| !item.path("metadata").path("deletionTimestamp").isMissingNode()) {
continue;
}
zones.pods.computeIfAbsent(nodeLabels.get(ZONE_LABEL), z -> new ArrayList<>()).add(new CountedPod(
new BoundPod(item.path("metadata").path("namespace").asText(), podLabels(item), List.of()),
nodeLabels));
}
return zones;
}
/** A copy, which placing pods leaves this one as it was. */
Zones copy() {
Map<String, List<CountedPod>> podsCopy = new LinkedHashMap<>();
pods.forEach((zone, list) -> podsCopy.put(zone, new ArrayList<>(list)));
return new Zones(podsCopy, nodes);
}
/** Counts {@code pod} in {@code zone}, as placed on a node there with {@code nodeLabels}. */
void add(String zone, PendingPod pod, Map<String, String> nodeLabels) {
if (zone != null) {
pods.computeIfAbsent(zone, z -> new ArrayList<>()).add(new CountedPod(pod.bound(), nodeLabels));
counts.clear();
}
}
/**
* Whether {@code pod} may go to {@code zone} by its zone spread constraints, as the scheduler checks them:
* the zone's matching pods, with this one, may exceed those of the zone with the fewest by at most
* {@code maxSkew}, counting only pods on nodes the pod's node selector and required affinity accept (the
* default {@code nodeAffinityPolicy: Honor}), over the zones whose nodes the pod could run on, {@code launchable} ones (where a new node
* could go) and {@code zone} itself. A zone not known allows it.
*/
boolean allows(PendingPod pod, String zone, List<String> launchable) {
if (zone == null || pod.zoneSpread().isEmpty()) {
return true;
}
// The zones the pod could run in: those of nodes it could run on, and the launchable ones its own node
// selector and required affinity allow, as Kubernetes honours the pod's node affinity for its domains.
Set<String> domains = new LinkedHashSet<>(nodeZones.computeIfAbsent(pod, p -> {
Set<String> zones = new LinkedHashSet<>();
nodes.forEach((name, labels) -> {
if (labels.stream().anyMatch(node -> p.fits(node, List.of()))) {
zones.add(name);
}
});
return zones;
}));
launchable.stream().filter(Objects::nonNull).filter(z -> zoneAllowed(pod, z)).forEach(domains::add);
domains.add(zone);
for (ZoneSpread spread : pod.zoneSpread()) {
Map<String, Long> counts = new HashMap<>();
domains.forEach(d -> counts.put(d, matching(pod, spread, d)));
long fewest = counts.values().stream().mapToLong(Long::longValue).min().orElse(0);
// The pod counts in its zone only when the constraint's selector names it, as Kubernetes counts it.
long self = spread.selector().matches(pod.namespace(), pod.labels()) ? 1 : 0;
if (counts.get(zone) + self - fewest > spread.maxSkew()) {
return false;
}
}
return true;
}
/** Whether {@code pod}'s node selector and required node affinity allow a node in {@code zone}. */
private static boolean zoneAllowed(PendingPod pod, String zone) {
String wanted = pod.nodeSelector().get(ZONE_LABEL);
if (wanted != null && !wanted.equals(zone)) {
return false;
}
Map<String, String> zoneLabels = Map.of(ZONE_LABEL, zone);
return pod.affinityTerms().isEmpty() || pod.affinityTerms().stream().anyMatch(term -> term.stream()
.filter(r -> ZONE_LABEL.equals(r.key())).allMatch(r -> r.matches(zoneLabels)));
}
/**
* The zones of {@code zones} that {@code pod}'s zone spread constraints allow a new node in, those with the
* fewest matching pods first, as Karpenter places a node to keep the spread; all of them, as given, for a pod
* without such a constraint.
*/
List<String> preferred(PendingPod pod, List<String> zones) {
if (pod.zoneSpread().isEmpty()) {
return zones;
}
return zones.stream()
.filter(zone -> allows(pod, zone, zones))
.sorted(Comparator.comparingLong((String zone) -> pod.zoneSpread().stream()
.mapToLong(spread -> matching(pod, spread, zone)).sum()))
.toList();
}
/** The pods in {@code zone} that {@code spread} matches, on nodes {@code pod} could run on. */
private long matching(PendingPod pod, ZoneSpread spread, String zone) {
return counts.computeIfAbsent(pod, p -> new HashMap<>()).computeIfAbsent(spread, k -> new HashMap<>())
.computeIfAbsent(zone, z -> pods.getOrDefault(z, List.of()).stream()
.filter(other -> spread.selector().matches(other.pod().namespace(), other.pod().labels()))
.filter(other -> pod.fits(other.nodeLabels(), List.of())).count());
}
}
/** 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) {
@@ -388,6 +556,19 @@ final class EksAutoModeNodes {
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass, List<PendingPod> daemons, String region,
Map<String, Capacity> used) {
return plan(pools, pods, types, zonesByNodeClass, daemons, region, used, Zones.none());
}
/**
* As above; with where the cluster's pods run by zone: a pod with a zone spread constraint gets its node in a
* zone the constraint allows, the one with the fewest matching pods first, as Karpenter places one to keep the
* spread, and the pods of a pool that spread over zones get a node in each. A pod no zone of a pool allows goes to
* the next pool, or waits.
*/
static List<Launch> plan(List<NodePool> pools, List<PendingPod> pods, List<CatalogInstanceType> types,
Map<String, List<String>> zonesByNodeClass, List<PendingPod> daemons, String region,
Map<String, Capacity> used, Zones zones) {
Zones placed = zones.copy();
List<NodePool> ordered = pools.stream()
.sorted(Comparator.comparingInt(NodePool::weight).reversed().thenComparing(NodePool::name))
.toList();
@@ -396,39 +577,93 @@ final class EksAutoModeNodes {
.sorted(Comparator.comparingInt((CatalogInstanceType t) -> t.vcpu)
.thenComparingInt(t -> t.memoryMib).thenComparing(t -> t.instanceType))
.toList();
Map<String, List<PendingPod>> byPool = new LinkedHashMap<>();
// By pool, then by the zone a spreading pod was given (null for the pool's others), each group one node.
Map<String, Map<String, List<PendingPod>>> byPool = new LinkedHashMap<>();
// By pool, then zone: the labels of the node a spreading group gets, which its counted pods share, so they
// count on the type that holds the whole group as it grows.
Map<String, Map<String, Map<String, String>>> groupNodeLabels = new HashMap<>();
for (PendingPod pod : pods) {
for (NodePool pool : ordered) {
if (candidate(pool, sized, zonesOf(pool, zonesByNodeClass), pod, pod.cpuMillis(), pod.memoryBytes(),
daemons, region, used)
.isPresent()) {
byPool.computeIfAbsent(pool.name(), k -> new ArrayList<>()).add(pod);
List<String> placesIn = placed.preferred(pod, zonesOf(pool, zonesByNodeClass));
if (placesIn.isEmpty()) {
continue;
}
Optional<Placement> placement = candidate(pool, sized, placesIn, pod, pod.cpuMillis(),
pod.memoryBytes(), daemons, region, used);
if (placement.isPresent()) {
String zone = pod.zoneSpread().isEmpty() ? null : placement.get().zone();
List<PendingPod> group = byPool.computeIfAbsent(pool.name(), k -> new LinkedHashMap<>())
.computeIfAbsent(zone, k -> new ArrayList<>());
if (zone != null) {
// A spreading pod joins its zone's node only while one node holds them all: counted there, a
// pod the node couldn't take would send the next one to another zone for nothing. It waits
// for the next pass, which counts the pods placed by then.
Optional<Placement> whole = placeAll(pool, append(group, pod), List.of(zone), sized, daemons,
region, used);
if (!group.isEmpty() && whole.isEmpty()) {
break;
}
Map<String, String> nodeLabels = groupNodeLabels.computeIfAbsent(pool.name(),
k -> new HashMap<>()).computeIfAbsent(zone, k -> new HashMap<>());
nodeLabels.clear();
nodeLabels.putAll(labels(whole.orElse(placement.get()).type(), pool, zone));
placed.add(zone, pod, nodeLabels);
}
group.add(pod);
break;
}
}
}
List<Launch> launches = new ArrayList<>();
// Each node planned counts against its pool's limits before the next, as the pool's nodes already do.
Map<String, Capacity> planned = new HashMap<>(used);
for (NodePool pool : ordered) {
List<PendingPod> group = byPool.get(pool.name());
if (group == null) {
continue;
for (Map.Entry<String, List<PendingPod>> zoned : byPool.getOrDefault(pool.name(), Map.of()).entrySet()) {
for (Launch launch : launch(pool, zoned.getValue(), zoned.getKey() != null ? List.of(zoned.getKey())
: zonesOf(pool, zonesByNodeClass), sized, daemons, region, planned)) {
launches.add(launch);
planned.merge(pool.name(), Capacity.of(launch.instanceType()), Capacity::plus);
}
}
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, daemons, region,
used)
.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(),
daemons, region, used));
placement.ifPresent(p -> launches.add(new Launch(pool, p.type(), p.zone(),
labels(p.type(), pool, p.zone()), List.copyOf(group))));
}
return launches;
}
/**
* The type and zone of one node, in one of {@code placesIn}, for all of {@code group}: sized for the group's
* requests by its largest pod, every pod accepting the type. None when no type holds them all.
*/
private static Optional<Placement> placeAll(NodePool pool, List<PendingPod> group, List<String> placesIn,
List<CatalogInstanceType> sized, List<PendingPod> daemons,
String region, Map<String, Capacity> used) {
return candidate(pool, sized, placesIn, largest(group), group.stream().mapToLong(PendingPod::cpuMillis).sum(),
group.stream().mapToLong(PendingPod::memoryBytes).sum(), daemons, region, used)
.filter(p -> group.stream().allMatch(pod -> pod.fits(labels(p.type(), pool, p.zone()), pool.taints())));
}
private static PendingPod largest(List<PendingPod> group) {
return group.stream().max(Comparator.comparingLong(PendingPod::cpuMillis)
.thenComparingLong(PendingPod::memoryBytes)).orElseThrow();
}
private static List<PendingPod> append(List<PendingPod> group, PendingPod pod) {
List<PendingPod> all = new ArrayList<>(group);
all.add(pod);
return all;
}
/** A node for {@code group}, pods of {@code pool}, in one of {@code placesIn}: none when no type fits. */
private static List<Launch> launch(NodePool pool, List<PendingPod> group, List<String> placesIn,
List<CatalogInstanceType> sized, List<PendingPod> daemons, String region,
Map<String, Capacity> used) {
PendingPod largest = largest(group);
Optional<Placement> placement = placeAll(pool, group, placesIn, sized, daemons, region, used)
.or(() -> candidate(pool, sized, placesIn, largest, largest.cpuMillis(), largest.memoryBytes(),
daemons, region, used));
return placement.map(p -> List.of(new Launch(pool, p.type(), p.zone(),
labels(p.type(), pool, p.zone()), List.copyOf(group)))).orElse(List.of());
}
/**
* 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
@@ -438,6 +673,15 @@ final class EksAutoModeNodes {
* has no room.
*/
static Room withoutRoom(List<PendingPod> pods, List<PoolNode> nodes) {
return withoutRoom(pods, nodes, Zones.none());
}
/**
* As above; with where the cluster's pods run by zone: a node has room for a pod only in a zone its zone spread
* constraints allow, as the scheduler places it. Each pod placed is counted in {@code zones}, so a launch after
* this sees the pods counted on nodes still joining.
*/
static Room withoutRoom(List<PendingPod> pods, List<PoolNode> nodes, Zones zones) {
long[] freeCpu = new long[nodes.size()];
long[] freeMemory = new long[nodes.size()];
int[] freePods = new int[nodes.size()];
@@ -458,7 +702,9 @@ final class EksAutoModeNodes {
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))) {
&& onNode.get(i).stream().noneMatch(other -> other.conflicts(pod))
&& zones.allows(pod, node.zone(), List.of())) {
zones.add(node.zone(), pod, labels(node.instanceType(), node.pool(), node.zone()));
freeCpu[i] -= pod.cpuMillis();
freeMemory[i] -= pod.memoryBytes();
freePods[i]--;
@@ -474,9 +720,19 @@ final class EksAutoModeNodes {
return new Room(left, counted);
}
/**
* The zones {@code pool} can launch a node in: those of its NodeClass's subnets that its zone requirements allow,
* so a zone spread counts only zones a node can go to; a single null when the NodeClass's zones aren't known.
*/
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;
if (zones.isEmpty()) {
return Collections.singletonList(null);
}
List<Requirement> zoneRequirements = pool.requirements().stream()
.filter(r -> ZONE_LABEL.equals(r.key())).toList();
return zones.stream().filter(zone -> zoneRequirements.stream()
.allMatch(r -> r.matches(Map.of(ZONE_LABEL, zone)))).toList();
}
private static Optional<Placement> candidate(NodePool pool, List<CatalogInstanceType> sized, List<String> zones,
@@ -697,7 +953,32 @@ final class EksAutoModeNodes {
long[] requests = requests(spec);
return Optional.of(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(), podLabels(item), antiAffinity(item)));
ask.get().affinityTerms(), ask.get().tolerations(), podLabels(item), antiAffinity(item),
zoneSpread(item)));
}
/**
* A pod's topology spread constraints on {@code topology.kubernetes.io/zone} that the scheduler enforces
* ({@code whenUnsatisfiable: DoNotSchedule}, the default), counting pods of its own namespace; those that only
* prefer a spread ({@code ScheduleAnyway}), and those on another topology key, aren't modelled. One without a
* label selector counts no pod.
*/
private static List<ZoneSpread> zoneSpread(JsonNode item) {
List<ZoneSpread> spreads = new ArrayList<>();
String own = item.path("metadata").path("namespace").asText();
for (JsonNode constraint : item.path("spec").path("topologySpreadConstraints")) {
JsonNode selector = constraint.path("labelSelector");
if (!ZONE_LABEL.equals(constraint.path("topologyKey").asText())
|| !"DoNotSchedule".equals(constraint.path("whenUnsatisfiable").asText("DoNotSchedule"))
|| selector.isMissingNode() || selector.isNull()) {
continue;
}
Map<String, String> matchLabels = new LinkedHashMap<>();
selector.path("matchLabels").properties().forEach(e -> matchLabels.put(e.getKey(), e.getValue().asText()));
spreads.add(new ZoneSpread(new PodTerm(matchLabels, requirements(selector.path("matchExpressions")),
Set.of(own)), Math.max(1, constraint.path("maxSkew").asInt(1))));
}
return List.copyOf(spreads);
}
/**
@@ -6,6 +6,7 @@ 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.PoolNode;
import io.floci.aws.services.eks.EksAutoModeNodes.Requirement;
import io.floci.aws.services.eks.EksAutoModeNodes.Toleration;
import org.junit.jupiter.api.Test;
@@ -13,10 +14,12 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -116,6 +119,279 @@ class EksAutoModeNodesTest {
assertTrue(EksAutoModeConsolidation.holds(launch, List.of(pod("web", "1900m", "64Mi")), List.of(), null));
}
/**
* A pod's zone spread constraint the scheduler enforces ({@code DoNotSchedule}, the default) is read, counting the
* pods its selector names in its own namespace; one that only prefers a spread, or spreads over another key, isn't.
*/
@Test
void aPendingPodsEnforcedZoneSpreadIsRead() throws Exception {
String pods = """
{"items": [{"metadata": {"namespace": "shop", "name": "web-1", "labels": {"app": "web"}},
"spec": {"containers": [{"resources": {"requests": {"cpu": "100m"}}}],
"topologySpreadConstraints": [
{"maxSkew": 2, "topologyKey": "topology.kubernetes.io/zone",
"labelSelector": {"matchLabels": {"app": "web"}}},
{"maxSkew": 1, "topologyKey": "topology.kubernetes.io/zone",
"whenUnsatisfiable": "ScheduleAnyway", "labelSelector": {"matchLabels": {"app": "web"}}},
{"maxSkew": 1, "topologyKey": "kubernetes.io/hostname",
"whenUnsatisfiable": "DoNotSchedule", "labelSelector": {"matchLabels": {"app": "web"}}}]},
"status": {"phase": "Pending", "conditions": [{"type": "PodScheduled", "status": "False",
"reason": "Unschedulable"}]}}]}""";
PendingPod pod = EksAutoModeNodes.unschedulablePods(json(pods)).getFirst();
assertEquals(List.of(new EksAutoModeNodes.ZoneSpread(new EksAutoModeNodes.PodTerm(Map.of("app", "web"),
List.of(), Set.of("shop")), 2)), pod.zoneSpread());
}
/**
* A node in a zone a pod's spread refuses has no room for it, as the scheduler won't place it there: with a web
* pod in zone a already, the next goes to the node in zone b; with only zone a's node, it waits for a new one.
*/
@Test
void aNodeInAZoneTheSpreadRefusesHasNoRoom() throws Exception {
NodePool pool = pools().getFirst();
PoolNode inA = new PoolNode("i-a", pool, TYPES.get(2), "eu-a", 0, 0);
PoolNode inB = new PoolNode("i-b", pool, TYPES.get(2), "eu-b", 0, 0);
EksAutoModeNodes.Room both = EksAutoModeNodes.withoutRoom(List.of(spreadingPod("web-2")), List.of(inA, inB),
webPodInZoneA());
EksAutoModeNodes.Room onlyA = EksAutoModeNodes.withoutRoom(List.of(spreadingPod("web-2")), List.of(inA),
webPodInZoneA());
assertEquals(Set.of("i-b"), both.counted());
assertEquals(List.of("web-2"), onlyA.left().stream().map(PendingPod::name).toList());
}
/** A spreading pod's new node goes to the pool's zone with the fewest of the pods it counts. */
@Test
void aSpreadingPodsNodeGoesToTheZoneWithTheFewest() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(spreadingPod("web-2")), TYPES,
Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(), webPodInZoneA());
assertEquals(List.of("eu-b"), launches.stream().map(Launch::zone).toList());
}
/**
* Two spreading pods with none placed yet get a node in each zone, as Karpenter spreads them, where pods without
* a spread share one node.
*/
@Test
void twoSpreadingPodsGetANodeInEachZone() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(spreadingPod("web-1"), spreadingPod("web-2")),
TYPES, Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(),
EksAutoModeNodes.Zones.none());
List<Launch> unspread = EksAutoModeNodes.plan(pools(), List.of(pod("a", "100m", "64Mi"),
pod("b", "100m", "64Mi")), TYPES, Map.of("default", List.of("eu-a", "eu-b")));
assertEquals(List.of("eu-a", "eu-b"), launches.stream().map(Launch::zone).toList());
assertEquals(1, unspread.size());
}
/**
* Spreading pods join a zone's node only while one node holds them all: with zone b holding two of the pods they
* count, four 3-CPU pods put one in zone a, on the 4-vCPU node a pass can launch there, and the others wait for
* the next pass rather than count in zone a and send one to zone b for nothing.
*/
@Test
void spreadingPodsCountInAZoneOnlyAsFarAsItsNodeHoldsThem() throws Exception {
String node = "{\"metadata\": {\"name\": \"%s\", \"labels\": {\"topology.kubernetes.io/zone\": \"%s\", "
+ "\"karpenter.sh/nodepool\": \"general-purpose\"}}}";
String pod = "{\"metadata\": {\"namespace\": \"default\", \"name\": \"%s\", \"labels\": {\"app\": \"web\"}}, "
+ "\"spec\": {\"nodeName\": \"n-b\"}, \"status\": {\"phase\": \"Running\"}}";
EksAutoModeNodes.Zones twoInB = EksAutoModeNodes.Zones.of(json("{\"items\": [" + pod.formatted("web-1") + ", "
+ pod.formatted("web-2") + "]}"), Map.of("n-a", json(node.formatted("n-a", "eu-a")),
"n-b", json(node.formatted("n-b", "eu-b"))));
List<PendingPod> big = List.of(bigSpreadingPod("web-3"), bigSpreadingPod("web-4"), bigSpreadingPod("web-5"),
bigSpreadingPod("web-6"));
List<Launch> launches = EksAutoModeNodes.plan(pools(), big, TYPES, Map.of("default", List.of("eu-a", "eu-b")),
List.of(), null, Map.of(), twoInB);
assertEquals(List.of("eu-a"), launches.stream().map(Launch::zone).toList());
assertEquals(List.of("web-3"), launches.getFirst().pods().stream().map(PendingPod::name).toList());
}
/**
* A spreading pod joins a zone's group only when the node the group would get holds them all, as {@code launch}
* picks it: a 1500m pod would need the 4-vCPU type beside a 500m pod that selects the 2-vCPU one, which no single
* node is, so it waits for the next pass rather than count on a node it won't get.
*/
@Test
void aSpreadingPodThatCantShareItsZonesNodeWaits() throws Exception {
PendingPod pinned = spreadingPod("web-1", Map.of("node.kubernetes.io/instance-type", "c7a.large"),
Map.of("app", "web"));
PendingPod small = new PendingPod(pinned.namespace(), "web-1", 500, pinned.memoryBytes(),
pinned.nodeSelector(), pinned.affinityTerms(), pinned.tolerations(), pinned.labels(),
pinned.antiAffinity(), pinned.zoneSpread());
PendingPod flexible = spreadingPod("web-2");
PendingPod larger = new PendingPod(flexible.namespace(), "web-2", 1500, flexible.memoryBytes(),
flexible.nodeSelector(), flexible.affinityTerms(), flexible.tolerations(), flexible.labels(),
flexible.antiAffinity(), flexible.zoneSpread());
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(small, larger), TYPES,
Map.of("default", List.of("eu-a")), List.of(), null, Map.of(), EksAutoModeNodes.Zones.none());
assertEquals(List.of(List.of("web-1")), launches.stream()
.map(launch -> launch.pods().stream().map(PendingPod::name).toList()).toList());
}
/** A web pod spreading over zones, requesting 3 CPUs. */
private static PendingPod bigSpreadingPod(String name) {
PendingPod small = spreadingPod(name);
return new PendingPod(small.namespace(), name, 3000, small.memoryBytes(), small.nodeSelector(),
small.affinityTerms(), small.tolerations(), small.labels(), small.antiAffinity(), small.zoneSpread());
}
/** Pods that spread over zones get one node a zone, each counted against the pool's limits before the next. */
@Test
void aPoolLimitedToOneNodeGetsOneNodeForPodsThatSpread() throws Exception {
List<NodePool> limited = EksAutoModeNodes.nodePools(json(POOLS.replaceFirst("\"spec\": \\{\"template\"",
"\"spec\": {\"limits\": {\"nodes\": \"1\"}, \"template\"")));
List<Launch> launches = EksAutoModeNodes.plan(limited, List.of(spreadingPod("web-1"), spreadingPod("web-2")),
TYPES, Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(),
EksAutoModeNodes.Zones.none());
assertEquals(List.of("eu-a"), launches.stream().map(Launch::zone).toList());
}
/**
* The zones a pod's spread counts are those it could run in: a pod its node selector keeps to zone a gets a node
* there, though the NodeClass's zone b has none of the pods it counts.
*/
@Test
void aPodKeptToOneZoneGetsItsNodeThereWhateverTheOtherZonesHave() throws Exception {
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(spreadingPod("web-2",
Map.of("topology.kubernetes.io/zone", "eu-a"), Map.of("app", "web"))), TYPES,
Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(), webPodInZoneA());
assertEquals(List.of("eu-a"), launches.stream().map(Launch::zone).toList());
}
/**
* The zones a spread counts are those the pool can launch in: a pool kept to zone a, whose NodeClass also has
* subnets in zone b and whose only node is in zone a, gets its spreading pod a node in zone a, as zone b is no
* domain the pod could land in.
*/
@Test
void aSpreadCountsOnlyTheZonesThePoolAllows() throws Exception {
NodePool zoneA = new NodePool("general-purpose", "default",
List.of(new Requirement("topology.kubernetes.io/zone", "In", List.of("eu-a"))), List.of(), Map.of(),
0, null, List.of());
String node = "{\"metadata\": {\"name\": \"n-a\", \"labels\": {\"topology.kubernetes.io/zone\": \"eu-a\", "
+ "\"karpenter.sh/nodepool\": \"general-purpose\"}}}";
EksAutoModeNodes.Zones webOnItsOnlyNode = EksAutoModeNodes.Zones.of(json("{\"items\": [{\"metadata\": "
+ "{\"namespace\": \"default\", \"name\": \"web-1\", \"labels\": {\"app\": \"web\"}}, \"spec\": "
+ "{\"nodeName\": \"n-a\"}, \"status\": {\"phase\": \"Running\"}}]}"), Map.of("n-a", json(node)));
List<Launch> launches = EksAutoModeNodes.plan(List.of(zoneA), List.of(spreadingPod("web-2")), TYPES,
Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(), webOnItsOnlyNode);
assertEquals(List.of("eu-a"), launches.stream().map(Launch::zone).toList());
}
/**
* A spread counts only pods on nodes the pod's node selector and required affinity accept, as Kubernetes's default
* {@code nodeAffinityPolicy: Honor} does: an amd64 pod whose peers are one on an amd64 node in zone b and three on
* an arm64 node in zone a gets its node in zone a, where it counts none.
*/
@Test
void aSpreadCountsOnlyPodsOnNodesThePodCouldRunOn() throws Exception {
String node = "{\"metadata\": {\"name\": \"%s\", \"labels\": {\"topology.kubernetes.io/zone\": \"%s\", "
+ "\"kubernetes.io/arch\": \"%s\", \"karpenter.sh/nodepool\": \"general-purpose\"}}}";
String pod = "{\"metadata\": {\"namespace\": \"default\", \"name\": \"%s\", \"labels\": {\"app\": \"web\"}}, "
+ "\"spec\": {\"nodeName\": \"%s\"}, \"status\": {\"phase\": \"Running\"}}";
EksAutoModeNodes.Zones zones = EksAutoModeNodes.Zones.of(json("{\"items\": [" + String.join(", ",
pod.formatted("web-b", "n-b"), pod.formatted("web-arm-1", "n-a-arm"),
pod.formatted("web-arm-2", "n-a-arm"), pod.formatted("web-arm-3", "n-a-arm")) + "]}"),
Map.of("n-a", json(node.formatted("n-a", "eu-a", "amd64")),
"n-a-arm", json(node.formatted("n-a-arm", "eu-a", "arm64")),
"n-b", json(node.formatted("n-b", "eu-b", "amd64"))));
List<Launch> launches = EksAutoModeNodes.plan(pools(), List.of(spreadingPod("web-2",
Map.of("kubernetes.io/arch", "amd64"), Map.of("app", "web"))), TYPES,
Map.of("default", List.of("eu-a", "eu-b")), List.of(), null, Map.of(), zones);
assertEquals(List.of("eu-a"), launches.stream().map(Launch::zone).toList());
}
/**
* Spreading pods count on the type of the node their zone's group gets, as it grows: two 1000m pods in zone a need
* a c7a.xlarge, so a pod kept to that type counts both there and goes to zone b, keeping the spread.
*/
@Test
void aGroupsPodsCountOnTheTypeThatHoldsTheGroup() throws Exception {
List<PendingPod> pods = List.of(oneCpuSpreadingPod("web-1", Map.of()), oneCpuSpreadingPod("web-2", Map.of()),
oneCpuSpreadingPod("web-3", Map.of()),
oneCpuSpreadingPod("web-4", Map.of("node.kubernetes.io/instance-type", "c7a.xlarge")));
List<Launch> launches = EksAutoModeNodes.plan(pools(), pods, TYPES, Map.of("default", List.of("eu-a", "eu-b")),
List.of(), null, Map.of(), EksAutoModeNodes.Zones.none());
assertEquals(Map.of("eu-a", List.of("web-1", "web-3"), "eu-b", List.of("web-2", "web-4")),
launches.stream().collect(Collectors.toMap(Launch::zone,
launch -> launch.pods().stream().map(PendingPod::name).toList())));
}
private static PendingPod oneCpuSpreadingPod(String name, Map<String, String> nodeSelector) {
PendingPod small = spreadingPod(name, nodeSelector, Map.of("app", "web"));
return new PendingPod(small.namespace(), name, 1000, small.memoryBytes(), small.nodeSelector(),
small.affinityTerms(), small.tolerations(), small.labels(), small.antiAffinity(), small.zoneSpread());
}
/** A pod its own spread's selector doesn't name doesn't count in a zone, as Kubernetes counts it: zone a has room. */
@Test
void aPodItsSpreadDoesntNameMayUseRoomInTheFullerZone() throws Exception {
PoolNode inA = new PoolNode("i-a", pools().getFirst(), TYPES.get(2), "eu-a", 0, 0);
EksAutoModeNodes.Room room = EksAutoModeNodes.withoutRoom(List.of(spreadingPod("api-1", Map.of(),
Map.of("app", "api"))), List.of(inA), webPodInZoneA());
assertEquals(Set.of("i-a"), room.counted());
}
/** Every zone spread constraint a pod lists is read, as the scheduler enforces every one. */
@Test
void everyZoneSpreadAPodListsIsRead() throws Exception {
StringBuilder constraints = new StringBuilder();
for (int i = 0; i < 20; i++) {
constraints.append(i == 0 ? "" : ", ").append("{\"maxSkew\": 1, \"topologyKey\": "
+ "\"topology.kubernetes.io/zone\", \"labelSelector\": {\"matchLabels\": {\"n\": \"" + i + "\"}}}");
}
String pods = "{\"items\": [{\"metadata\": {\"namespace\": \"default\", \"name\": \"p\"}, \"spec\": "
+ "{\"containers\": [{\"resources\": {\"requests\": {\"cpu\": \"100m\"}}}], "
+ "\"topologySpreadConstraints\": [" + constraints + "]}, \"status\": {\"phase\": \"Pending\", "
+ "\"conditions\": [{\"type\": \"PodScheduled\", \"status\": \"False\", \"reason\": "
+ "\"Unschedulable\"}]}}]}";
assertEquals(20, EksAutoModeNodes.unschedulablePods(json(pods)).getFirst().zoneSpread().size());
}
/** A pod labelled {@code app: web} in {@code default} that the spread of web pods over zones keeps to a skew of 1. */
private static PendingPod spreadingPod(String name) {
return spreadingPod(name, Map.of(), Map.of("app", "web"));
}
/** As above, with {@code nodeSelector} besides its pool's, and {@code labels} of its own. */
private static PendingPod spreadingPod(String name, Map<String, String> nodeSelector, Map<String, String> labels) {
Map<String, String> selector = new HashMap<>(nodeSelector);
selector.put("karpenter.sh/nodepool", "general-purpose");
return new PendingPod("default", name, 100, 64L << 20, selector, List.of(), List.of(), labels, List.of(),
List.of(new EksAutoModeNodes.ZoneSpread(new EksAutoModeNodes.PodTerm(Map.of("app", "web"), List.of(),
Set.of("default")), 1)));
}
/** Nodes in zones eu-a and eu-b, and one web pod, on the node in eu-a. */
private static EksAutoModeNodes.Zones webPodInZoneA() throws Exception {
String node = "{\"metadata\": {\"name\": \"%s\", \"labels\": {\"topology.kubernetes.io/zone\": \"%s\", "
+ "\"karpenter.sh/nodepool\": \"general-purpose\"}}}";
return EksAutoModeNodes.Zones.of(json("{\"items\": [{\"metadata\": {\"namespace\": \"default\", \"name\": \"web-1\", "
+ "\"labels\": {\"app\": \"web\"}}, \"spec\": {\"nodeName\": \"n-a\"}, \"status\": {\"phase\": \"Running\"}}]}"),
Map.of("n-a", json(node.formatted("n-a", "eu-a")), "n-b", json(node.formatted("n-b", "eu-b"))));
}
/** A DaemonSet selecting on the region, which a joined node carries, counts on a new node in that region. */
@Test
void aDaemonSetSelectingTheRegionCountsOnANodeThere() throws Exception {