mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): keep a NodeClaim for each EKS Auto Mode node, as Karpenter does (#9537)
Each EKS Auto Mode node now has a karpenter.sh/v1 NodeClaim, as Karpenter keeps one on AWS, so kubectl get nodeclaims and tools that watch claims see Auto Mode's nodes. The claim is named after its pool with a five-character suffix, chosen at launch so no other instance's claim has it and kept in the instance's karpenter.sh/nodeclaim tag. It is owned by its NodePool, held by the karpenter.sh/termination finalizer and labelled as its node is. Its spec carries the pool's requirements, its pods' requests, and expireAfter and terminationGracePeriod (336h and 24h0m0s when the pool doesn't say). Its status goes Launched, then Registered, Initialized and Ready once the node joins. A claim whose instance is gone loses Karpenter's finalizer and is deleted, and a missing one is made again without a new launch. Deleting a claim drains and removes its node and terminates its instance, as deleting a pool does. A NodePool being deleted launches nothing more. Only claims labelled app.kubernetes.io/managed-by: eks are touched.
This commit is contained in:
1 parent
58b0a476a7
commit
7db72767e3
9 files changed
+976
-47
No files matched your search
+17
-3
@@ -508,11 +508,24 @@ launches nodes on AWS. Floci checks every 10 seconds.
|
||||
`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.
|
||||
- **Deleted pools.** The nodes of a NodePool that is deleted (or being deleted, held by its NodeClaims), or that
|
||||
`UpdateClusterConfig` drops, are tainted, drained and removed the same way, whatever they run, as Karpenter removes
|
||||
them. A pool being deleted launches nothing more. So is the node of a NodeClaim that is deleted (`kubectl delete
|
||||
nodeclaim`), as deleting a claim is how Karpenter removes a node; the claim goes once its instance has.
|
||||
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.
|
||||
- **NodeClaim.** Each node has a `NodeClaim` (`karpenter.sh/v1`), as on AWS: named after its pool with five
|
||||
characters (`general-purpose-kw46r`) no other instance's claim has, kept in its instance's `karpenter.sh/nodeclaim`
|
||||
tag as Karpenter tags its instances, owned by its NodePool and held by the `karpenter.sh/termination` finalizer,
|
||||
labelled as its node, with the pool's requirements (plus the chosen instance type, the pool and the NodeClass), its
|
||||
pods' requests, and the pool's `expireAfter` and `terminationGracePeriod` (336h and 24h0m0s when the pool doesn't
|
||||
say, as on AWS). Its status says `Launched` once the instance is up, then, once the node joins, `Registered`,
|
||||
`Initialized` and `Ready`
|
||||
(as the node's own Ready), with the node's name, capacity and allocatable, kept in step as they change. It goes
|
||||
with its instance, Karpenter's finalizer taken off (other finalizers stay). A claim that couldn't be made is made
|
||||
on a later pass. Floci touches only the claims labelled `app.kubernetes.io/managed-by: eks`. `kubectl get
|
||||
nodeclaims` shows the type, capacity type, zone, node and readiness, as Karpenter's columns do.
|
||||
- **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
|
||||
@@ -520,7 +533,8 @@ 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 replace underutilized nodes with smaller ones.
|
||||
Floci doesn't replace underutilized nodes with smaller ones, and a NodeClaim's requirements name only the instance
|
||||
type chosen, where AWS lists every type that would do.
|
||||
|
||||
### Auto Mode load balancing for Services
|
||||
|
||||
|
||||
@@ -81,6 +81,8 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
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";
|
||||
/** The tag naming an instance's NodeClaim, as Karpenter tags the instances it launches. */
|
||||
static final String NODECLAIM_TAG = "karpenter.sh/nodeclaim";
|
||||
static final String MANAGED_LAUNCH_TAG = "aws:ec2:managed-launch";
|
||||
static final String MANAGED_LAUNCH = "eks-auto";
|
||||
/** How long a launched node may take to register before its pool may get another. */
|
||||
@@ -174,11 +176,14 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
}
|
||||
Map<String, JsonNode> nodesByName = nodesByName(cluster);
|
||||
removeStrayNodes(cluster, region, nodesByName);
|
||||
Set<String> claimsDeleted = syncNodeClaims(cluster, region, nodesByName, podList);
|
||||
removeStoppedOfDeletedClaims(cluster, region, claimsDeleted);
|
||||
if (launched.isEmpty() && pods.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, NodePool> pools = new HashMap<>();
|
||||
EksAutoModeNodes.nodePools(read(cluster, "nodepools")).forEach(pool -> pools.put(pool.name(), pool));
|
||||
Pools poolsRead = Pools.of(read(cluster, "nodepools"));
|
||||
Map<String, NodePool> pools = poolsRead.byName();
|
||||
Map<String, JsonNode> poolItems = poolsRead.items();
|
||||
// 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"));
|
||||
@@ -201,8 +206,9 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
neverRegistered.add(instance);
|
||||
continue;
|
||||
}
|
||||
if (pool == null) {
|
||||
// Karpenter removes the nodes of a NodePool that was deleted, or that UpdateClusterConfig dropped.
|
||||
if (pool == null || claimsDeleted.contains(claimName(instance))) {
|
||||
// Karpenter removes the nodes of a NodePool that was deleted, or that UpdateClusterConfig dropped,
|
||||
// and the node of a NodeClaim that was deleted, as deleting a claim is how a node is removed.
|
||||
poolGone.add(instance);
|
||||
continue;
|
||||
}
|
||||
@@ -270,11 +276,11 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
"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));
|
||||
LOG.infov("EKS Auto Mode removed node {0} ({1}) of cluster {2}, whose pool {3} or claim 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());
|
||||
LOG.warnv("EKS Auto Mode node {0} of cluster {1}, whose pool or claim is gone, wasn''t removed: {2}",
|
||||
nodeName, cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
List<EksAutoModeNodes.PendingPod> withoutRoom = room.left();
|
||||
@@ -295,7 +301,8 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
for (Launch launch : EksAutoModeNodes.plan(List.copyOf(pools.values()), withoutRoom,
|
||||
instanceTypes.instanceTypes(), zonesByNodeClass, daemons, region)) {
|
||||
try {
|
||||
launch(cluster, region, launch, nodeClasses.get(launch.pool().nodeClass()), subnetZones);
|
||||
launch(cluster, region, launch, nodeClasses.get(launch.pool().nodeClass()), subnetZones,
|
||||
poolItems.getOrDefault(launch.pool().name(), MAPPER.createObjectNode()));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EKS Auto Mode pool {0} of cluster {1} launched no node for {2}: {3}",
|
||||
launch.pool().name(), cluster.getName(), podNames(launch), e.getMessage());
|
||||
@@ -396,7 +403,7 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
}
|
||||
|
||||
private void launch(Cluster cluster, String region, Launch launch, JsonNode nodeClass,
|
||||
Map<String, String> subnetZones) {
|
||||
Map<String, String> subnetZones, JsonNode poolItem) {
|
||||
if (nodeClass == null) {
|
||||
throw new IllegalStateException("its NodeClass " + launch.pool().nodeClass() + " isn't there");
|
||||
}
|
||||
@@ -434,6 +441,195 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
}
|
||||
LOG.infov("EKS Auto Mode pool {0} of cluster {1} launched {2} ({3}) for {4}", launch.pool().name(),
|
||||
cluster.getName(), instanceId, launch.instanceType().instanceType, podNames(launch));
|
||||
Instance instance = reservation.getInstances().getFirst();
|
||||
String claim = uniqueClaimName(cluster, region, launch.pool().name(), instanceId);
|
||||
try {
|
||||
ec2.createTags(region, List.of(instanceId), List.of(new Tag(NODECLAIM_TAG, claim)));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EKS Auto Mode instance {0} of cluster {1} wasn''t tagged with its NodeClaim: {2}", instanceId,
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
makeNodeClaim(cluster, region, launch, instance, claim, imageId, poolItem,
|
||||
EksAutoModeNodeClaims.requests(launch));
|
||||
}
|
||||
|
||||
/**
|
||||
* A NodeClaim name for a new instance of {@code pool} that none of the cluster's other instances has, as
|
||||
* Karpenter's {@code generateName} gives a name not taken: two instances of a pool whose derived names are the
|
||||
* same would otherwise share one claim, and deleting it would remove both nodes.
|
||||
*/
|
||||
private String uniqueClaimName(Cluster cluster, String region, String pool, String instanceId) {
|
||||
Set<String> taken = new HashSet<>();
|
||||
for (Instance other : instancesOf(cluster, region, "pending", "running", "stopping", "stopped")) {
|
||||
if (!instanceId.equals(other.getInstanceId())) {
|
||||
taken.add(claimName(other));
|
||||
}
|
||||
}
|
||||
String name = EksAutoModeNodeClaims.name(pool, instanceId);
|
||||
for (int attempt = 1; taken.contains(name); attempt++) {
|
||||
name = EksAutoModeNodeClaims.name(pool, instanceId, attempt);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the NodeClaim of an instance, with {@code requests} in its spec ({@code null} for none), and marks it
|
||||
* launched. One that can't be made is logged, and a later pass makes it again.
|
||||
*/
|
||||
private void makeNodeClaim(Cluster cluster, String region, Launch launch, Instance instance, String claim,
|
||||
String imageId, JsonNode poolItem, long[] requests) {
|
||||
try {
|
||||
apply(cluster, EksAutoModeNodeClaims.claim(launch, claim, poolItem,
|
||||
EksAutoModeNodes.withRegion(launch.labels(), region), requests), "apply nodeclaim " + claim);
|
||||
exec(cluster, List.of("kubectl", "patch", "nodeclaim", claim, "--subresource=status", "--type=merge", "-p",
|
||||
EksAutoModeNodeClaims.launchedStatus(clusterManager.deriveInstanceNodeProviderId(instance, region),
|
||||
imageId, clock.instant().toString())), "patch nodeclaim " + claim);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EKS Auto Mode NodeClaim {0} of cluster {1} wasn''t made: {2}", claim, cluster.getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the NodeClaims in step with the instances: one whose node has joined is marked registered, initialized
|
||||
* and ready, as its node is; one whose instance is gone loses Karpenter's finalizer and is deleted, as Karpenter's
|
||||
* termination ends it. Only the claims Auto Mode manages ({@code app.kubernetes.io/managed-by: eks}) are touched.
|
||||
* With the cluster's pods ({@code podList}, {@code null} for none), a pending or running instance of a pool whose
|
||||
* claim is missing, as when making it failed, gets it again. Returns the names of the claims being deleted whose
|
||||
* instance still runs, whose nodes the pass then removes.
|
||||
*/
|
||||
private Set<String> syncNodeClaims(Cluster cluster, String region, Map<String, JsonNode> nodesByName,
|
||||
JsonNode podList) {
|
||||
JsonNode claims;
|
||||
try {
|
||||
claims = read(cluster, "nodeclaims");
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("EKS Auto Mode NodeClaims of cluster {0} unreadable: {1}", cluster.getName(), e.getMessage());
|
||||
return Set.of();
|
||||
}
|
||||
Set<String> deleted = new HashSet<>();
|
||||
Map<String, Instance> live = new HashMap<>();
|
||||
for (Instance instance : instancesOf(cluster, region, "pending", "running", "stopping", "stopped")) {
|
||||
live.put(claimName(instance), instance);
|
||||
}
|
||||
Set<String> listed = new HashSet<>();
|
||||
for (JsonNode claim : claims.path("items")) {
|
||||
String name = claim.path("metadata").path("name").asText();
|
||||
listed.add(name);
|
||||
if (!EksAutoModeNodeClaims.managed(claim)) {
|
||||
continue;
|
||||
}
|
||||
Instance instance = live.get(name);
|
||||
try {
|
||||
if (instance == null) {
|
||||
deleteNodeClaim(cluster, claim);
|
||||
continue;
|
||||
}
|
||||
if (claim.path("metadata").has("deletionTimestamp")) {
|
||||
// Karpenter's finalizer holds it while its node is drained and its instance ends.
|
||||
deleted.add(name);
|
||||
continue;
|
||||
}
|
||||
JsonNode node = nodesByName.get(clusterManager.deriveInstanceNodeName(instance, region));
|
||||
if (node != null && !EksAutoModeNodeClaims.saysJoined(claim, node)) {
|
||||
exec(cluster, List.of("kubectl", "patch", "nodeclaim", name, "--subresource=status",
|
||||
"--type=merge", "-p", EksAutoModeNodeClaims.joinedStatus(
|
||||
clusterManager.deriveInstanceNodeProviderId(instance, region),
|
||||
instance.getImageId(), node, clock.instant().toString())),
|
||||
"patch nodeclaim " + name);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EKS Auto Mode NodeClaim {0} of cluster {1} isn''t in step yet: {2}", name,
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
if (podList != null) {
|
||||
List<Instance> unclaimed = instancesOf(cluster, region, "pending", "running").stream()
|
||||
.filter(i -> !listed.contains(claimName(i))).toList();
|
||||
if (!unclaimed.isEmpty()) {
|
||||
remakeNodeClaims(cluster, region, unclaimed, EksAutoModeNodes.requestsByNode(podList));
|
||||
}
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the NodeClaims of instances of pools that are still there whose claims are missing. A joined node's claim
|
||||
* requests what the pods bound to it request; one whose node hasn't joined requests nothing it can't know.
|
||||
*/
|
||||
private void remakeNodeClaims(Cluster cluster, String region, List<Instance> unclaimed,
|
||||
Map<String, long[]> requestsByNode) {
|
||||
Pools pools;
|
||||
try {
|
||||
pools = Pools.of(read(cluster, "nodepools"));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("EKS Auto Mode NodePools of cluster {0} unreadable: {1}", cluster.getName(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
for (Instance instance : unclaimed) {
|
||||
NodePool pool = pools.byName().get(tag(instance, POOL_TAG));
|
||||
Optional<Ec2InstanceTypeCatalog.CatalogInstanceType> type = instanceTypes.find(instance.getInstanceType());
|
||||
if (pool == null || type.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String zone = zone(instance);
|
||||
makeNodeClaim(cluster, region, new Launch(pool, type.get(), zone,
|
||||
EksAutoModeNodes.labels(type.get(), pool, zone), List.of()), instance, claimName(instance),
|
||||
instance.getImageId(),
|
||||
pools.items().get(pool.name()),
|
||||
requestsByNode.get(clusterManager.deriveInstanceNodeName(instance, region)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The instances of deleted claims that are stopping or stopped, which the pass's pending and running ones leave
|
||||
* out, go too: a stopped node serves no pods, so its node is deleted without a drain and its instance terminated.
|
||||
* The next pass then ends the claim.
|
||||
*/
|
||||
private void removeStoppedOfDeletedClaims(Cluster cluster, String region, Set<String> claimsDeleted) {
|
||||
if (claimsDeleted.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (Instance instance : instancesOf(cluster, region, "stopping", "stopped")) {
|
||||
if (!claimsDeleted.contains(claimName(instance))) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
clusterManager.removeJoinedNode(cluster, instance);
|
||||
ec2.terminateInstances(region, List.of(instance.getInstanceId()));
|
||||
LOG.infov("EKS Auto Mode removed stopped instance {0} of cluster {1}, whose claim was deleted",
|
||||
instance.getInstanceId(), cluster.getName());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("EKS Auto Mode stopped instance {0} of cluster {1}, whose claim was deleted, wasn''t "
|
||||
+ "removed: {2}", instance.getInstanceId(), cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of an instance's NodeClaim: its {@code karpenter.sh/nodeclaim} tag, or, for an instance without one
|
||||
* (its tagging failed), the name derived from its pool and instance ID.
|
||||
*/
|
||||
private static String claimName(Instance instance) {
|
||||
String tagged = tag(instance, NODECLAIM_TAG);
|
||||
return tagged != null ? tagged
|
||||
: EksAutoModeNodeClaims.name(String.valueOf(tag(instance, POOL_TAG)), instance.getInstanceId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes Karpenter's finalizer off a NodeClaim, keeping any other, and deletes it, as Karpenter does once its
|
||||
* instance is gone.
|
||||
*/
|
||||
private void deleteNodeClaim(Cluster cluster, JsonNode claim) {
|
||||
String name = claim.path("metadata").path("name").asText();
|
||||
exec(cluster, List.of("kubectl", "patch", "nodeclaim", name, "--type=merge", "-p",
|
||||
EksAutoModeNodeClaims.withoutFinalizer(claim)), "patch nodeclaim " + name);
|
||||
exec(cluster, List.of("kubectl", "delete", "nodeclaim", name, "--ignore-not-found=true", "--wait=false"),
|
||||
"delete nodeclaim " + name);
|
||||
}
|
||||
|
||||
private void apply(Cluster cluster, String json, String what) {
|
||||
exec(cluster, List.of("sh", "-c", "echo '" + json.replace("'", "'\\''") + "' | kubectl apply -f -"), what);
|
||||
}
|
||||
|
||||
/** Whether the cluster is still among the running ones, not deleted or being deleted. */
|
||||
@@ -549,6 +745,20 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
ec2.terminateInstances(region, List.of(instance.getInstanceId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The NodePools of {@code kubectl get nodepools}, by name, as Auto Mode reads them and as they're listed (whose
|
||||
* UID and template a NodeClaim takes).
|
||||
*/
|
||||
private record Pools(Map<String, NodePool> byName, Map<String, JsonNode> items) {
|
||||
static Pools of(JsonNode list) {
|
||||
Map<String, NodePool> byName = new HashMap<>();
|
||||
EksAutoModeNodes.nodePools(list).forEach(pool -> byName.put(pool.name(), pool));
|
||||
Map<String, JsonNode> items = new HashMap<>();
|
||||
list.path("items").forEach(item -> items.put(item.path("metadata").path("name").asText(), item));
|
||||
return new Pools(byName, items);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -561,12 +771,8 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
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;
|
||||
String ready = EksAutoModeNodes.conditionStatus(node, "Ready");
|
||||
return ready != null && !"True".equals(ready);
|
||||
}
|
||||
|
||||
private static boolean disrupted(JsonNode node) {
|
||||
@@ -605,9 +811,12 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
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.
|
||||
// on, and so do the claims of the instances terminated, this pass or one whose claim deletion failed. The
|
||||
// nodes and claims are read only while EC2 still keeps such an instance.
|
||||
if (!instancesOf(cluster, region, "shutting-down", "terminated").isEmpty()) {
|
||||
removeStrayNodes(cluster, region, nodesByName(cluster));
|
||||
Map<String, JsonNode> nodesByName = nodesByName(cluster);
|
||||
removeStrayNodes(cluster, region, nodesByName);
|
||||
syncNodeClaims(cluster, region, nodesByName, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,6 +960,7 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
|
||||
private JsonNode read(Cluster cluster, String kind) {
|
||||
List<String> command = "nodes".equals(kind) || "nodepools".equals(kind) || "nodeclasses".equals(kind)
|
||||
|| "nodeclaims".equals(kind)
|
||||
? List.of("kubectl", "get", kind, "-o", "json") : List.of("kubectl", "get", kind, "-A", "-o", "json");
|
||||
return readJson(cluster, command, "get " + kind);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.services.eks.EksAutoModeNodes.Launch;
|
||||
import io.floci.aws.services.eks.EksAutoModeNodes.PendingPod;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The {@code NodeClaim} (karpenter.sh/v1) Auto Mode keeps for each node it launches, shaped as AWS shows it
|
||||
* (measured on an Auto Mode cluster in us-east-1): named after its pool with a five-character suffix, owned by its
|
||||
* NodePool, held by the {@code karpenter.sh/termination} finalizer, labelled as its node is, and with the pool's
|
||||
* requirements, its pods' requests, the pool's {@code expireAfter} and {@code terminationGracePeriod} (336h and 24h
|
||||
* when it doesn't say) in its spec. Its
|
||||
* status says it was launched, then, once its node has joined, registered, initialized and ready.
|
||||
*/
|
||||
final class EksAutoModeNodeClaims {
|
||||
|
||||
static final String FINALIZER = "karpenter.sh/termination";
|
||||
static final String NODECLASS_GROUP = "eks.amazonaws.com"; // partition-literal: a Kubernetes API group
|
||||
static final String NODECLASS_LABEL = NODECLASS_GROUP + "/nodeclass";
|
||||
/** What Auto Mode puts in {@code expireAfter} when the pool doesn't say: its built-in pools' 14 days. */
|
||||
static final String DEFAULT_EXPIRE_AFTER = "336h";
|
||||
/** What Auto Mode puts in {@code terminationGracePeriod} when the pool doesn't say: 24 hours. */
|
||||
static final String DEFAULT_TERMINATION_GRACE_PERIOD = "24h0m0s";
|
||||
static final String MANAGED_BY = "app.kubernetes.io/managed-by";
|
||||
static final String MANAGED_BY_VALUE = "eks";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SUFFIX_ALPHABET = "bcdfghjklmnpqrstvwxz2456789";
|
||||
|
||||
private EksAutoModeNodeClaims() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The NodeClaim's name for an instance of {@code pool}: the pool's name and five characters, as Karpenter's
|
||||
* {@code generateName} gives them, here derived from the instance ID.
|
||||
*/
|
||||
static String name(String pool, String instanceId) {
|
||||
return name(pool, instanceId, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above; {@code attempt} past 0 derives another name, for when the first is another instance's already. The
|
||||
* name chosen is kept in the instance's {@code karpenter.sh/nodeclaim} tag.
|
||||
*/
|
||||
static String name(String pool, String instanceId, int attempt) {
|
||||
String seed = attempt == 0 ? instanceId : instanceId + "#" + attempt;
|
||||
byte[] hash = Digests.sha256(seed.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder suffix = new StringBuilder();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
suffix.append(SUFFIX_ALPHABET.charAt(Math.floorMod(hash[i], SUFFIX_ALPHABET.length())));
|
||||
}
|
||||
return pool + "-" + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* The NodeClaim of a launch, as it is applied: metadata and spec. {@code poolItem} is the NodePool as
|
||||
* {@code kubectl get nodepools} lists it, whose UID owns the claim and whose template gives its requirements.
|
||||
*/
|
||||
static String claim(Launch launch, String name, JsonNode poolItem, Map<String, String> labels) {
|
||||
return claim(launch, name, poolItem, labels, requests(launch));
|
||||
}
|
||||
|
||||
/** What a launch's pods request: CPU millicores, memory bytes, and how many they are. */
|
||||
static long[] requests(Launch launch) {
|
||||
return new long[]{launch.pods().stream().mapToLong(PendingPod::cpuMillis).sum(),
|
||||
launch.pods().stream().mapToLong(PendingPod::memoryBytes).sum(), launch.pods().size()};
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, with the {@code requests} (CPU millicores, memory bytes, pods) its spec gives, or none when
|
||||
* {@code null}, as for a claim made again whose node's pods aren't known.
|
||||
*/
|
||||
static String claim(Launch launch, String name, JsonNode poolItem, Map<String, String> labels,
|
||||
long[] requests) {
|
||||
ObjectNode claim = MAPPER.createObjectNode();
|
||||
claim.put("apiVersion", "karpenter.sh/v1");
|
||||
claim.put("kind", "NodeClaim");
|
||||
ObjectNode metadata = claim.putObject("metadata");
|
||||
metadata.put("name", name);
|
||||
ObjectNode claimLabels = metadata.putObject("labels");
|
||||
labels.forEach(claimLabels::put);
|
||||
claimLabels.put(NODECLASS_LABEL, launch.pool().nodeClass());
|
||||
claimLabels.put(MANAGED_BY, MANAGED_BY_VALUE);
|
||||
metadata.putArray("finalizers").add(FINALIZER);
|
||||
String uid = poolItem.path("metadata").path("uid").asText("");
|
||||
if (!uid.isEmpty()) {
|
||||
ObjectNode owner = metadata.putArray("ownerReferences").addObject();
|
||||
owner.put("apiVersion", "karpenter.sh/v1");
|
||||
owner.put("kind", "NodePool");
|
||||
owner.put("name", launch.pool().name());
|
||||
owner.put("uid", uid);
|
||||
owner.put("blockOwnerDeletion", true);
|
||||
}
|
||||
JsonNode template = poolItem.path("spec").path("template").path("spec");
|
||||
ObjectNode spec = claim.putObject("spec");
|
||||
spec.put("expireAfter", template.path("expireAfter").asText(DEFAULT_EXPIRE_AFTER));
|
||||
spec.put("terminationGracePeriod", template.path("terminationGracePeriod")
|
||||
.asText(DEFAULT_TERMINATION_GRACE_PERIOD));
|
||||
ObjectNode classRef = spec.putObject("nodeClassRef");
|
||||
classRef.put("group", NODECLASS_GROUP);
|
||||
classRef.put("kind", "NodeClass");
|
||||
classRef.put("name", launch.pool().nodeClass());
|
||||
ArrayNode requirements = spec.putArray("requirements");
|
||||
template.path("requirements").forEach(requirements::add);
|
||||
// What Karpenter adds to the pool's: the type it chose (AWS lists every type that would do), the pool and
|
||||
// the NodeClass.
|
||||
requirement(requirements, "node.kubernetes.io/instance-type", launch.instanceType().instanceType);
|
||||
requirement(requirements, EksAutoModeNodes.NODEPOOL_LABEL, launch.pool().name());
|
||||
requirement(requirements, NODECLASS_LABEL, launch.pool().nodeClass());
|
||||
if (requests != null) {
|
||||
ObjectNode resources = spec.putObject("resources").putObject("requests");
|
||||
resources.put("cpu", requests[0] + "m");
|
||||
resources.put("memory", String.valueOf(requests[1]));
|
||||
resources.put("pods", String.valueOf(requests[2]));
|
||||
}
|
||||
return claim.toString();
|
||||
}
|
||||
|
||||
private static void requirement(ArrayNode requirements, String key, String value) {
|
||||
ObjectNode requirement = requirements.addObject();
|
||||
requirement.put("key", key);
|
||||
requirement.put("operator", "In");
|
||||
requirement.putArray("values").add(value);
|
||||
}
|
||||
|
||||
/** The status a NodeClaim gets once its instance is launched. */
|
||||
static String launchedStatus(String providerId, String imageId, String now) {
|
||||
ObjectNode status = MAPPER.createObjectNode().putObject("status");
|
||||
status.put("providerID", providerId);
|
||||
status.put("imageID", imageId);
|
||||
ArrayNode conditions = status.putArray("conditions");
|
||||
condition(conditions, "Launched", "True", now);
|
||||
condition(conditions, "Registered", "Unknown", now);
|
||||
condition(conditions, "Initialized", "Unknown", now);
|
||||
condition(conditions, "Ready", "Unknown", now);
|
||||
return wrap(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* The status a NodeClaim gets once its node has joined: the node's name, capacity and allocatable, and
|
||||
* registered, initialized and ready, Ready following the node's own Ready condition.
|
||||
*/
|
||||
static String joinedStatus(String providerId, String imageId, JsonNode node, String now) {
|
||||
ObjectNode status = MAPPER.createObjectNode().putObject("status");
|
||||
status.put("providerID", providerId);
|
||||
status.put("imageID", imageId);
|
||||
status.put("nodeName", node.path("metadata").path("name").asText());
|
||||
JsonNode nodeStatus = node.path("status");
|
||||
if (nodeStatus.has("capacity")) {
|
||||
status.set("capacity", nodeStatus.path("capacity"));
|
||||
}
|
||||
if (nodeStatus.has("allocatable")) {
|
||||
status.set("allocatable", nodeStatus.path("allocatable"));
|
||||
}
|
||||
ArrayNode conditions = status.putArray("conditions");
|
||||
condition(conditions, "Launched", "True", now);
|
||||
condition(conditions, "Registered", "True", now);
|
||||
condition(conditions, "Initialized", "True", now);
|
||||
condition(conditions, "Ready", nodeReady(node), now);
|
||||
return wrap(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a NodeClaim's status already says {@code node} joined: its name, capacity and allocatable, and its
|
||||
* Ready as the node's.
|
||||
*/
|
||||
static boolean saysJoined(JsonNode claim, JsonNode node) {
|
||||
JsonNode status = claim.path("status");
|
||||
JsonNode nodeStatus = node.path("status");
|
||||
if (!node.path("metadata").path("name").asText().equals(status.path("nodeName").asText())
|
||||
|| !nodeStatus.path("capacity").equals(status.path("capacity"))
|
||||
|| !nodeStatus.path("allocatable").equals(status.path("allocatable"))) {
|
||||
return false;
|
||||
}
|
||||
return nodeReady(node).equals(EksAutoModeNodes.conditionStatus(claim, "Ready"));
|
||||
}
|
||||
|
||||
/** Whether Auto Mode manages a NodeClaim, as its {@code app.kubernetes.io/managed-by: eks} label says. */
|
||||
static boolean managed(JsonNode claim) {
|
||||
return MANAGED_BY_VALUE.equals(claim.path("metadata").path("labels").path(MANAGED_BY).asText());
|
||||
}
|
||||
|
||||
/** The merge patch that takes Karpenter's finalizer off a NodeClaim and keeps its others. */
|
||||
static String withoutFinalizer(JsonNode claim) {
|
||||
ObjectNode patch = MAPPER.createObjectNode();
|
||||
ArrayNode kept = MAPPER.createArrayNode();
|
||||
claim.path("metadata").path("finalizers").forEach(f -> {
|
||||
if (!FINALIZER.equals(f.asText())) {
|
||||
kept.add(f);
|
||||
}
|
||||
});
|
||||
if (kept.isEmpty()) {
|
||||
patch.putObject("metadata").putNull("finalizers");
|
||||
} else {
|
||||
patch.putObject("metadata").set("finalizers", kept);
|
||||
}
|
||||
return patch.toString();
|
||||
}
|
||||
|
||||
/** A node's Ready condition status, {@code Unknown} when it has none. */
|
||||
static String nodeReady(JsonNode node) {
|
||||
return Objects.requireNonNullElse(EksAutoModeNodes.conditionStatus(node, "Ready"), "Unknown");
|
||||
}
|
||||
|
||||
private static void condition(ArrayNode conditions, String type, String status, String now) {
|
||||
ObjectNode condition = conditions.addObject();
|
||||
condition.put("type", type);
|
||||
condition.put("status", status);
|
||||
condition.put("reason", "True".equals(status) ? type : "AwaitingReconciliation");
|
||||
condition.put("message", "");
|
||||
condition.put("lastTransitionTime", now);
|
||||
}
|
||||
|
||||
private static String wrap(ObjectNode status) {
|
||||
ObjectNode patch = MAPPER.createObjectNode();
|
||||
patch.set("status", status);
|
||||
return patch.toString();
|
||||
}
|
||||
}
|
||||
@@ -516,6 +516,10 @@ final class EksAutoModeNodes {
|
||||
static List<NodePool> nodePools(JsonNode list) {
|
||||
List<NodePool> pools = new ArrayList<>();
|
||||
for (JsonNode item : list.path("items")) {
|
||||
// A pool being deleted launches nothing more and its nodes go, as Karpenter treats it.
|
||||
if (item.path("metadata").has("deletionTimestamp")) {
|
||||
continue;
|
||||
}
|
||||
JsonNode template = item.path("spec").path("template");
|
||||
Map<String, String> labels = new LinkedHashMap<>();
|
||||
template.path("metadata").path("labels").properties()
|
||||
@@ -657,6 +661,19 @@ final class EksAutoModeNodes {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status of an object's condition {@code type} (a node's or a NodeClaim's {@code status.conditions}),
|
||||
* {@code Unknown} when it says none, or {@code null} when it has no such condition.
|
||||
*/
|
||||
static String conditionStatus(JsonNode object, String type) {
|
||||
for (JsonNode condition : object.path("status").path("conditions")) {
|
||||
if (type.equals(condition.path("type").asText())) {
|
||||
return condition.path("status").asText("Unknown");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# EKS Auto Mode compute on a Floci cluster: the NodePool and NodeClass kinds Auto Mode installs, its default
|
||||
# NodeClass, and the built-in node pools the cluster's computeConfig.nodePools names (appended by Floci).
|
||||
# Floci launches no nodes for them; workloads run on the cluster's node.
|
||||
# EKS Auto Mode compute on a Floci cluster: the NodePool, NodeClass and NodeClaim kinds Auto Mode installs, its
|
||||
# default NodeClass, and the built-in node pools the cluster's computeConfig.nodePools names (appended by Floci).
|
||||
# Floci launches nodes for pods its pools' nodes could take and keeps a NodeClaim for each.
|
||||
apiVersion: apiextensions.k8s.io/v1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
@@ -62,6 +62,68 @@ spec:
|
||||
status:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: nodeclaims.karpenter.sh
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: floci
|
||||
spec:
|
||||
group: karpenter.sh
|
||||
scope: Cluster
|
||||
names:
|
||||
kind: NodeClaim
|
||||
listKind: NodeClaimList
|
||||
plural: nodeclaims
|
||||
singular: nodeclaim
|
||||
versions:
|
||||
- name: v1
|
||||
served: true
|
||||
storage: true
|
||||
subresources:
|
||||
status: {}
|
||||
additionalPrinterColumns:
|
||||
- name: Type
|
||||
type: string
|
||||
jsonPath: .metadata.labels.node\.kubernetes\.io/instance-type
|
||||
- name: Capacity
|
||||
type: string
|
||||
jsonPath: .metadata.labels.karpenter\.sh/capacity-type
|
||||
- name: Zone
|
||||
type: string
|
||||
jsonPath: .metadata.labels.topology\.kubernetes\.io/zone
|
||||
- name: Node
|
||||
type: string
|
||||
jsonPath: .status.nodeName
|
||||
- name: Ready
|
||||
type: string
|
||||
jsonPath: '.status.conditions[?(@.type=="Ready")].status'
|
||||
- name: Age
|
||||
type: date
|
||||
jsonPath: .metadata.creationTimestamp
|
||||
- name: ID
|
||||
type: string
|
||||
jsonPath: .status.providerID
|
||||
priority: 1
|
||||
- name: NodePool
|
||||
type: string
|
||||
jsonPath: .metadata.labels.karpenter\.sh/nodepool
|
||||
priority: 1
|
||||
- name: NodeClass
|
||||
type: string
|
||||
jsonPath: .spec.nodeClassRef.name
|
||||
priority: 1
|
||||
schema:
|
||||
openAPIV3Schema:
|
||||
type: object
|
||||
properties:
|
||||
spec:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
status:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
# The default NodeClass, which Floci leaves out without a node role.
|
||||
---
|
||||
apiVersion: eks.amazonaws.com/v1
|
||||
|
||||
@@ -80,7 +80,7 @@ class EksAutoModeComputeTest {
|
||||
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\": []}", "daemonsets",
|
||||
"{\"items\": []}"));
|
||||
"{\"items\": []}", "nodeclaims", "{\"items\": []}"));
|
||||
|
||||
@BeforeEach
|
||||
void cluster() {
|
||||
@@ -157,6 +157,172 @@ class EksAutoModeComputeTest {
|
||||
verify(iam).addRoleToInstanceProfile(profileName.getValue(), "auto-node");
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/eks/us-east-1/prod/" + profileName.getValue(),
|
||||
profile.getValue());
|
||||
// Its NodeClaim, named in the instance's tag, then the claim's launched status.
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-1");
|
||||
verifyTaggedWithClaim("i-1", claim);
|
||||
verify(clusterManager).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length == 3
|
||||
&& "sh".equals(cmd[0]) && cmd[2].contains("\"kind\":\"NodeClaim\"")
|
||||
&& cmd[2].contains("\"name\":\"" + claim + "\"")), anyInt());
|
||||
verifyClaimMarkedLaunched(claim);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each pass keeps the NodeClaims Auto Mode manages in step: one whose node has joined is marked registered,
|
||||
* initialized and ready; one whose instance is gone loses Karpenter's finalizer, keeping any other, and is deleted.
|
||||
* A claim Auto Mode doesn't manage is left alone.
|
||||
*/
|
||||
@Test
|
||||
void nodeClaimsFollowTheirInstancesAndNodes() {
|
||||
joinedNode("i-node", "node-1");
|
||||
String live = EksAutoModeNodeClaims.name("general-purpose", "i-node");
|
||||
String gone = EksAutoModeNodeClaims.name("general-purpose", "i-gone");
|
||||
aRunningPodOn("node-1", "");
|
||||
aReadyNode("node-1");
|
||||
lists.put("nodeclaims", "{\"items\": [" + managedClaim(live, "") + ", "
|
||||
+ managedClaim(gone, ", \"example.com/audit\"") + ", "
|
||||
+ "{\"metadata\": {\"name\": \"someone-elses\", "
|
||||
+ "\"finalizers\": [\"karpenter.sh/termination\"]}}]}");
|
||||
Cluster cluster = cluster("prod");
|
||||
|
||||
compute.reconcile(cluster, REGION);
|
||||
|
||||
verify(clusterManager).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 4
|
||||
&& "patch".equals(cmd[1]) && live.equals(cmd[3]) && "--subresource=status".equals(cmd[4])
|
||||
&& cmd[cmd.length - 1].contains("\"nodeName\":\"node-1\"")
|
||||
&& cmd[cmd.length - 1].contains("\"type\":\"Ready\",\"status\":\"True\"")), anyInt());
|
||||
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "patch", "nodeclaim", gone,
|
||||
"--type=merge", "-p", "{\"metadata\":{\"finalizers\":[\"example.com/audit\"]}}"}, 15);
|
||||
verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "nodeclaim", gone,
|
||||
"--ignore-not-found=true", "--wait=false"}, 15);
|
||||
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete",
|
||||
"nodeclaim", live, "--ignore-not-found=true", "--wait=false"}, 15);
|
||||
verify(clusterManager, never()).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 3
|
||||
&& "someone-elses".equals(cmd[3])), anyInt());
|
||||
}
|
||||
|
||||
/**
|
||||
* A launched instance whose derived claim name another instance of its pool has already gets another, so two
|
||||
* nodes never share one claim.
|
||||
*/
|
||||
@Test
|
||||
void aLaunchedInstanceWhoseClaimNameIsTakenGetsAnother() {
|
||||
Instance other = new Instance();
|
||||
other.setInstanceId("i-other");
|
||||
String taken = EksAutoModeNodeClaims.name("general-purpose", "i-1");
|
||||
other.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose"),
|
||||
new Tag(EksAutoModeCompute.NODECLAIM_TAG, taken)));
|
||||
instancesByState(List.of(), List.of(other), List.of());
|
||||
|
||||
compute.reconcile(cluster("prod"), REGION);
|
||||
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-1", 1);
|
||||
verifyTaggedWithClaim("i-1", claim);
|
||||
verifyClaimMarkedLaunched(claim);
|
||||
}
|
||||
|
||||
/** A running instance whose claim is missing, as when making it failed, gets it again without a new launch. */
|
||||
@Test
|
||||
void aMissingClaimIsMadeAgainWithoutANewLaunch() {
|
||||
joinedNode("i-node", "node-1");
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-node");
|
||||
aRunningPodOn("node-1", "{\"cpu\": \"250m\", \"memory\": \"64Mi\"}");
|
||||
aReadyNode("node-1");
|
||||
|
||||
compute.reconcile(cluster("prod"), REGION);
|
||||
|
||||
// It requests what the pods bound to its node request, not nothing.
|
||||
verify(clusterManager).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 2
|
||||
&& "sh".equals(cmd[0]) && cmd[2].contains("\"name\":\"" + claim + "\"")
|
||||
&& cmd[2].contains("\"requests\":{\"cpu\":\"250m\",\"memory\":\"" + (64L << 20)
|
||||
+ "\",\"pods\":\"1\"}") && cmd[2].contains("kubectl apply -f -")), anyInt());
|
||||
verifyClaimMarkedLaunched(claim);
|
||||
verify(ec2, never()).runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
|
||||
anyString(), anyString(), anyList(), anyString(), anyString(), any(), any(), anyInt(), any(), any(),
|
||||
any(), anyString(), anyBoolean(), any(), any(), any(), anyBoolean(), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* With compute off, a claim left by an earlier pass whose deletion failed is deleted once its instance is
|
||||
* terminating.
|
||||
*/
|
||||
@Test
|
||||
void withComputeOffALeftoverClaimOfATerminatedInstanceIsDeleted() {
|
||||
Instance late = new Instance();
|
||||
late.setInstanceId("i-late");
|
||||
late.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
|
||||
instancesByState(List.of(), List.of(), List.of(late));
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-late");
|
||||
lists.put("nodeclaims", "{\"items\": [" + managedClaim(claim, "") + "]}");
|
||||
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", "nodeclaim", claim,
|
||||
"--ignore-not-found=true", "--wait=false"}, 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* EC2 keeps {@code live} running, {@code stopped} stopped and {@code ended} terminated: each state filter
|
||||
* describes the instances in its states.
|
||||
*/
|
||||
private void instancesByState(List<Instance> live, List<Instance> stopped, List<Instance> ended) {
|
||||
Map<String, List<Instance>> byState = Map.of("running", live, "stopped", stopped, "terminated", ended);
|
||||
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenAnswer(inv -> {
|
||||
Map<String, List<String>> filters = inv.getArgument(2);
|
||||
List<Instance> found = new ArrayList<>();
|
||||
byState.forEach((state, instances) -> {
|
||||
if (filters.get("instance-state-name").contains(state)) {
|
||||
found.addAll(instances);
|
||||
}
|
||||
});
|
||||
if (found.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(found);
|
||||
return List.of(reservation);
|
||||
});
|
||||
}
|
||||
|
||||
/** A running pod bound to {@code nodeName}, requesting {@code requests} (a JSON object, or empty for none). */
|
||||
private void aRunningPodOn(String nodeName, String requests) {
|
||||
String resources = requests.isEmpty() ? ""
|
||||
: ", \"containers\": [{\"resources\": {\"requests\": " + requests + "}}]";
|
||||
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"" + nodeName + "\""
|
||||
+ resources + "}, \"status\": {\"phase\": \"Running\"}}]}");
|
||||
}
|
||||
|
||||
/** The cluster's one node, {@code nodeName}, Ready. */
|
||||
private void aReadyNode(String nodeName) {
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"" + nodeName + "\", \"labels\": {}}, "
|
||||
+ "\"status\": {\"conditions\": [{\"type\": \"Ready\", \"status\": \"True\"}]}}]}");
|
||||
}
|
||||
|
||||
/** That instance {@code instanceId} was tagged with its NodeClaim's name, {@code claim}. */
|
||||
private void verifyTaggedWithClaim(String instanceId, String claim) {
|
||||
verify(ec2).createTags(eq(REGION), eq(List.of(instanceId)), argThat(tags -> tags.size() == 1
|
||||
&& EksAutoModeCompute.NODECLAIM_TAG.equals(tags.getFirst().getKey())
|
||||
&& claim.equals(tags.getFirst().getValue())));
|
||||
}
|
||||
|
||||
/** That {@code claim}'s status was patched to say it was launched. */
|
||||
private void verifyClaimMarkedLaunched(String claim) {
|
||||
verify(clusterManager).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 4
|
||||
&& "patch".equals(cmd[1]) && claim.equals(cmd[3]) && "--subresource=status".equals(cmd[4])
|
||||
&& cmd[cmd.length - 1].contains("\"type\":\"Launched\",\"status\":\"True\"")), anyInt());
|
||||
}
|
||||
|
||||
/** A claim Auto Mode manages that is being deleted, held by Karpenter's finalizer. */
|
||||
private static String deletedClaim(String name) {
|
||||
return managedClaim(name, "").replace("\"metadata\": {",
|
||||
"\"metadata\": {\"deletionTimestamp\": \"2026-11-27T00:00:00Z\", ");
|
||||
}
|
||||
|
||||
private static String managedClaim(String name, String moreFinalizers) {
|
||||
return "{\"metadata\": {\"name\": \"" + name + "\", "
|
||||
+ "\"labels\": {\"app.kubernetes.io/managed-by\": \"eks\"}, "
|
||||
+ "\"finalizers\": [\"karpenter.sh/termination\"" + moreFinalizers + "]}, \"status\": {}}";
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -226,8 +392,7 @@ class EksAutoModeComputeTest {
|
||||
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\"}}]}");
|
||||
aRunningPodOn("node-1", "");
|
||||
compute.reconcile(cluster, REGION);
|
||||
lists.put("pods", "{\"items\": []}");
|
||||
clock.advance(Duration.ofSeconds(20));
|
||||
@@ -282,8 +447,7 @@ class EksAutoModeComputeTest {
|
||||
@Test
|
||||
void aBusyNodeLeftTaintedAsDisruptedHasTheTaintTakenOff() {
|
||||
Instance node = joinedNode("i-node", "node-1");
|
||||
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"node-1\"}, "
|
||||
+ "\"status\": {\"phase\": \"Running\"}}]}");
|
||||
aRunningPodOn("node-1", "");
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}, \"spec\": "
|
||||
+ "{\"unschedulable\": true, "
|
||||
+ "\"taints\": [{\"key\": \"karpenter.sh/disrupted\", \"effect\": \"NoSchedule\"}]}}]}");
|
||||
@@ -320,15 +484,7 @@ class EksAutoModeComputeTest {
|
||||
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);
|
||||
});
|
||||
instancesByState(List.of(live), List.of(), List.of(dead, reused, replaced));
|
||||
lists.put("pods", "{\"items\": []}");
|
||||
String autoLabels = "{\"karpenter.sh/nodepool\": \"general-purpose\", "
|
||||
+ "\"eks.amazonaws.com/compute-type\": \"auto\"}";
|
||||
@@ -367,12 +523,7 @@ class EksAutoModeComputeTest {
|
||||
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();
|
||||
});
|
||||
instancesByState(List.of(), List.of(), List.of(late));
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"late-node\", \"labels\": {}}, "
|
||||
+ "\"spec\": {\"providerID\": \"aws:///us-east-1a/i-late\"}}]}");
|
||||
Cluster cluster = cluster("prod");
|
||||
@@ -409,8 +560,7 @@ class EksAutoModeComputeTest {
|
||||
@Test
|
||||
void aDeletedPoolsNodeIsDrainedAndRemoved() {
|
||||
Instance node = joinedNode("i-node", "node-1");
|
||||
lists.put("pods", "{\"items\": [{\"metadata\": {}, \"spec\": {\"nodeName\": \"node-1\"}, "
|
||||
+ "\"status\": {\"phase\": \"Running\"}}]}");
|
||||
aRunningPodOn("node-1", "");
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
|
||||
lists.put("nodepools", "{\"items\": []}");
|
||||
Cluster cluster = cluster("prod");
|
||||
@@ -425,6 +575,53 @@ class EksAutoModeComputeTest {
|
||||
order.verify(ec2).terminateInstances(REGION, List.of("i-node"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A NodeClaim deleted while its instance runs, as {@code kubectl delete nodeclaim} does, has its node removed the
|
||||
* way a deleted pool's is; Karpenter's finalizer holds the claim until its instance has gone.
|
||||
*/
|
||||
@Test
|
||||
void aDeletedClaimsNodeIsDrainedAndRemoved() {
|
||||
Instance node = joinedNode("i-node", "node-1");
|
||||
aRunningPodOn("node-1", "");
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-node");
|
||||
lists.put("nodeclaims", "{\"items\": [" + deletedClaim(claim) + "]}");
|
||||
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"));
|
||||
// The claim keeps its finalizer this pass; the next one, with the instance gone, takes it off.
|
||||
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "patch",
|
||||
"nodeclaim", claim, "--type=merge", "-p", "{\"metadata\":{\"finalizers\":null}}"}, 15);
|
||||
}
|
||||
|
||||
/** A deleted claim whose instance was stopped has its node deleted, without a drain, and its instance ended. */
|
||||
@Test
|
||||
void aDeletedClaimsStoppedInstanceIsRemoved() {
|
||||
Instance stopped = new Instance();
|
||||
stopped.setInstanceId("i-stopped");
|
||||
stopped.setTags(List.of(new Tag(EksAutoModeCompute.POOL_TAG, "general-purpose")));
|
||||
instancesByState(List.of(), List.of(stopped), List.of());
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-stopped");
|
||||
lists.put("nodeclaims", "{\"items\": [" + deletedClaim(claim) + "]}");
|
||||
lists.put("pods", "{\"items\": []}");
|
||||
Cluster cluster = cluster("prod");
|
||||
|
||||
compute.reconcile(cluster, REGION);
|
||||
|
||||
InOrder order = inOrder(clusterManager, ec2);
|
||||
order.verify(clusterManager).removeJoinedNode(cluster, stopped);
|
||||
order.verify(ec2).terminateInstances(REGION, List.of("i-stopped"));
|
||||
verify(clusterManager, never()).execInContainerForResult(eq("k3s-1"), argThat(cmd -> cmd.length > 1
|
||||
&& "drain".equals(cmd[1])), anyInt());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
|
||||
import io.floci.aws.services.eks.EksAutoModeNodes.Launch;
|
||||
import io.floci.aws.services.eks.EksAutoModeNodes.NodePool;
|
||||
import io.floci.aws.services.eks.EksAutoModeNodes.PendingPod;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The NodeClaim Auto Mode keeps for each node, shaped as AWS shows it. */
|
||||
class EksAutoModeNodeClaimsTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** Named after the pool with five characters, as Karpenter's generateName gives them, stable for an instance. */
|
||||
@Test
|
||||
void aClaimIsNamedAfterItsPoolStablyForItsInstance() {
|
||||
String name = EksAutoModeNodeClaims.name("general-purpose", "i-0123456789abcdef0");
|
||||
|
||||
assertTrue(name.matches("general-purpose-[bcdfghjklmnpqrstvwxz2456789]{5}"), name);
|
||||
assertEquals(name, EksAutoModeNodeClaims.name("general-purpose", "i-0123456789abcdef0"));
|
||||
assertNotEquals(name, EksAutoModeNodeClaims.name("general-purpose", "i-0123456789abcdef1"));
|
||||
// Another attempt derives another name, for when the first is taken.
|
||||
String second = EksAutoModeNodeClaims.name("general-purpose", "i-0123456789abcdef0", 1);
|
||||
assertTrue(second.matches("general-purpose-[bcdfghjklmnpqrstvwxz2456789]{5}"), second);
|
||||
assertNotEquals(name, second);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owned by its NodePool, held by Karpenter's finalizer, labelled as its node, with the pool's requirements and
|
||||
* the chosen type, pool and NodeClass added, its pods' requests, and the pool's expireAfter and
|
||||
* terminationGracePeriod.
|
||||
*/
|
||||
@Test
|
||||
void aClaimCarriesItsPoolsOwnershipRequirementsAndItsPodsRequests() throws Exception {
|
||||
String poolItem = """
|
||||
{"metadata": {"name": "general-purpose", "uid": "b3a94e41"},
|
||||
"spec": {"template": {"spec": {"expireAfter": "336h", "terminationGracePeriod": "24h0m0s",
|
||||
"requirements": [{"key": "kubernetes.io/arch", "operator": "In", "values": ["amd64"]}]}}}}""";
|
||||
CatalogInstanceType large = new CatalogInstanceType();
|
||||
large.instanceType = "c6a.large";
|
||||
large.vcpu = 2;
|
||||
large.memoryMib = 4096;
|
||||
NodePool pool = new NodePool("general-purpose", "default", List.of(), List.of(), Map.of(), 0,
|
||||
Duration.ofSeconds(30), List.of());
|
||||
Launch launch = new Launch(pool, large, "us-east-1a", Map.of("karpenter.sh/nodepool", "general-purpose",
|
||||
"topology.kubernetes.io/zone", "us-east-1a"), List.of(
|
||||
new PendingPod("default", "a", 100, 64L << 20, Map.of(), List.of(), List.of()),
|
||||
new PendingPod("default", "b", 250, 32L << 20, Map.of(), List.of(), List.of())));
|
||||
|
||||
JsonNode claim = MAPPER.readTree(EksAutoModeNodeClaims.claim(launch, "general-purpose-kw46r",
|
||||
MAPPER.readTree(poolItem),
|
||||
launch.labels()));
|
||||
|
||||
assertEquals("karpenter.sh/v1", claim.path("apiVersion").asText());
|
||||
assertEquals("NodeClaim", claim.path("kind").asText());
|
||||
JsonNode metadata = claim.path("metadata");
|
||||
assertEquals("general-purpose-kw46r", metadata.path("name").asText());
|
||||
assertEquals("[\"karpenter.sh/termination\"]", metadata.path("finalizers").toString());
|
||||
assertEquals("NodePool", metadata.path("ownerReferences").get(0).path("kind").asText());
|
||||
assertEquals("b3a94e41", metadata.path("ownerReferences").get(0).path("uid").asText());
|
||||
assertTrue(metadata.path("ownerReferences").get(0).path("blockOwnerDeletion").asBoolean());
|
||||
assertEquals("default", metadata.path("labels").path("eks.amazonaws.com/nodeclass").asText());
|
||||
assertEquals("eks", metadata.path("labels").path("app.kubernetes.io/managed-by").asText());
|
||||
assertEquals("us-east-1a", metadata.path("labels").path("topology.kubernetes.io/zone").asText());
|
||||
JsonNode spec = claim.path("spec");
|
||||
assertEquals("336h", spec.path("expireAfter").asText());
|
||||
assertEquals("24h0m0s", spec.path("terminationGracePeriod").asText());
|
||||
assertEquals("default", spec.path("nodeClassRef").path("name").asText());
|
||||
assertEquals("eks.amazonaws.com", spec.path("nodeClassRef").path("group").asText());
|
||||
assertEquals(List.of("kubernetes.io/arch", "node.kubernetes.io/instance-type", "karpenter.sh/nodepool",
|
||||
"eks.amazonaws.com/nodeclass"), spec.path("requirements").findValuesAsText("key"));
|
||||
assertEquals("c6a.large", spec.path("requirements").get(1).path("values").get(0).asText());
|
||||
assertEquals("350m", spec.path("resources").path("requests").path("cpu").asText());
|
||||
assertEquals(String.valueOf(96L << 20), spec.path("resources").path("requests").path("memory").asText());
|
||||
assertEquals("2", spec.path("resources").path("requests").path("pods").asText());
|
||||
}
|
||||
|
||||
/** A pool without expireAfter or terminationGracePeriod gives Auto Mode's 336h and 24h. */
|
||||
@Test
|
||||
void aPoolWithoutExpireAfterOrGracePeriodGivesAutoModesDefaults() throws Exception {
|
||||
CatalogInstanceType large = new CatalogInstanceType();
|
||||
large.instanceType = "c6a.large";
|
||||
NodePool pool = new NodePool("batch", "default", List.of(), List.of(), Map.of(), 0, null, List.of());
|
||||
|
||||
JsonNode claim = MAPPER.readTree(EksAutoModeNodeClaims.claim(new Launch(pool, large, null, Map.of(),
|
||||
List.of()), "batch-kw46r", MAPPER.readTree("{\"metadata\": {\"name\": \"batch\"}}"), Map.of()));
|
||||
|
||||
assertEquals("336h", claim.path("spec").path("expireAfter").asText());
|
||||
assertEquals("24h0m0s", claim.path("spec").path("terminationGracePeriod").asText());
|
||||
assertFalse(claim.path("metadata").has("ownerReferences"));
|
||||
// A claim made again whose node's pods aren't known requests nothing rather than zero.
|
||||
assertFalse(MAPPER.readTree(EksAutoModeNodeClaims.claim(new Launch(pool, large, null, Map.of(), List.of()),
|
||||
"batch-kw46r", MAPPER.readTree("{\"metadata\": {\"name\": \"batch\"}}"), Map.of(), null))
|
||||
.path("spec").has("resources"));
|
||||
}
|
||||
|
||||
/** Launched first; once its node joins, registered, initialized, and ready as the node is. */
|
||||
@Test
|
||||
void theStatusSaysLaunchedThenJoinedWithTheNodesReadiness() throws Exception {
|
||||
JsonNode launched = MAPPER.readTree(EksAutoModeNodeClaims.launchedStatus("aws:///us-east-1a/i-1",
|
||||
"ami-1", "2026-11-26T00:00:00Z")).path("status");
|
||||
assertEquals("aws:///us-east-1a/i-1", launched.path("providerID").asText());
|
||||
assertEquals("ami-1", launched.path("imageID").asText());
|
||||
assertEquals("True", condition(launched, "Launched"));
|
||||
assertEquals("Unknown", condition(launched, "Registered"));
|
||||
assertEquals("Unknown", condition(launched, "Ready"));
|
||||
|
||||
JsonNode node = MAPPER.readTree("""
|
||||
{"metadata": {"name": "ip-10-0-1-10.ec2.internal"},
|
||||
"status": {"capacity": {"cpu": "2"}, "allocatable": {"cpu": "1780m"},
|
||||
"conditions": [{"type": "Ready", "status": "True"}]}}""");
|
||||
JsonNode joined = MAPPER.readTree(EksAutoModeNodeClaims.joinedStatus("aws:///us-east-1a/i-1", "ami-1",
|
||||
node, "2026-11-26T00:00:10Z")).path("status");
|
||||
assertEquals("ip-10-0-1-10.ec2.internal", joined.path("nodeName").asText());
|
||||
assertEquals("1780m", joined.path("allocatable").path("cpu").asText());
|
||||
assertEquals("2", joined.path("capacity").path("cpu").asText());
|
||||
assertEquals("True", condition(joined, "Registered"));
|
||||
assertEquals("True", condition(joined, "Initialized"));
|
||||
assertEquals("True", condition(joined, "Ready"));
|
||||
|
||||
JsonNode claim = MAPPER.createObjectNode().set("status", joined);
|
||||
assertTrue(EksAutoModeNodeClaims.saysJoined(claim, node));
|
||||
assertFalse(EksAutoModeNodeClaims.saysJoined(claim, MAPPER.readTree("""
|
||||
{"metadata": {"name": "ip-10-0-1-10.ec2.internal"},
|
||||
"status": {"capacity": {"cpu": "2"}, "allocatable": {"cpu": "1780m"},
|
||||
"conditions": [{"type": "Ready", "status": "False"}]}}""")));
|
||||
assertFalse(EksAutoModeNodeClaims.saysJoined(claim, MAPPER.readTree("""
|
||||
{"metadata": {"name": "another"},
|
||||
"status": {"capacity": {"cpu": "2"}, "allocatable": {"cpu": "1780m"},
|
||||
"conditions": [{"type": "Ready", "status": "True"}]}}""")));
|
||||
// A resource the node reports after it was ready, as a device plugin adds one, is written again.
|
||||
assertFalse(EksAutoModeNodeClaims.saysJoined(claim, MAPPER.readTree("""
|
||||
{"metadata": {"name": "ip-10-0-1-10.ec2.internal"},
|
||||
"status": {"capacity": {"cpu": "2", "nvidia.com/gpu": "1"},
|
||||
"allocatable": {"cpu": "1780m", "nvidia.com/gpu": "1"},
|
||||
"conditions": [{"type": "Ready", "status": "True"}]}}""")));
|
||||
}
|
||||
|
||||
/** Only the claims Auto Mode manages are its own; ending one takes Karpenter's finalizer off and keeps others. */
|
||||
@Test
|
||||
void onlyManagedClaimsAreOwnedAndEndingOneKeepsOtherFinalizers() throws Exception {
|
||||
assertTrue(EksAutoModeNodeClaims.managed(MAPPER.readTree(
|
||||
"{\"metadata\": {\"labels\": {\"app.kubernetes.io/managed-by\": \"eks\"}}}")));
|
||||
assertFalse(EksAutoModeNodeClaims.managed(MAPPER.readTree("{\"metadata\": {\"labels\": {}}}")));
|
||||
|
||||
assertEquals("{\"metadata\":{\"finalizers\":null}}", EksAutoModeNodeClaims.withoutFinalizer(
|
||||
MAPPER.readTree("{\"metadata\": {\"finalizers\": [\"karpenter.sh/termination\"]}}")));
|
||||
assertEquals("{\"metadata\":{\"finalizers\":[\"example.com/audit\"]}}",
|
||||
EksAutoModeNodeClaims.withoutFinalizer(MAPPER.readTree("{\"metadata\": {\"finalizers\": "
|
||||
+ "[\"karpenter.sh/termination\", \"example.com/audit\"]}}")));
|
||||
}
|
||||
|
||||
private static String condition(JsonNode status, String type) {
|
||||
for (JsonNode condition : status.path("conditions")) {
|
||||
if (type.equals(condition.path("type").asText())) {
|
||||
return condition.path("status").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+21
-1
@@ -124,6 +124,11 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
|
||||
await("the default NodeClass").atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(3))
|
||||
.ignoreExceptions().until(() -> subnet.equals(node.kubectlOutput("get", "nodeclass", "default",
|
||||
"-o", "jsonpath={.spec.subnetSelectorTerms[0].id}")));
|
||||
// k3s applies the built-in pools from the same manifest, maybe after the NodeClass: a pass before then has no
|
||||
// pool to launch from.
|
||||
await("the general-purpose NodePool").atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(3))
|
||||
.ignoreExceptions().until(() -> "general-purpose".equals(node.kubectlOutput("get", "nodepool",
|
||||
"general-purpose", "-o", "jsonpath={.metadata.name}")));
|
||||
|
||||
node.kubectl("run", "web", "--image=rancher/mirrored-pause:3.6", "--restart=Never", "--overrides="
|
||||
+ "{\"spec\":{\"nodeSelector\":{\"karpenter.sh/nodepool\":\"general-purpose\"},\"containers\":[{"
|
||||
@@ -147,13 +152,19 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
|
||||
Instance instance = launched.getFirst();
|
||||
assertEquals(subnet, instance.getSubnetId());
|
||||
Map<String, String> tags = instance.getTags().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue));
|
||||
// Tagged with its NodeClaim's name too, as Karpenter tags the instances it launches.
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", instance.getInstanceId());
|
||||
assertEquals(Map.of("eks:eks-cluster-name", cluster.getName(), "eks:kubernetes-node-pool-name", "general-purpose",
|
||||
"eks:kubernetes-node-class-name", "default", "kubernetes.io/cluster/" + cluster.getName(), "owned",
|
||||
"aws:ec2:managed-launch", "eks-auto"), tags);
|
||||
"aws:ec2:managed-launch", "eks-auto", EksAutoModeCompute.NODECLAIM_TAG, claim), tags);
|
||||
InstanceProfile profile = RequestScopes.callAs(ACCOUNT, REGION, () -> iam.listInstanceProfiles(
|
||||
"/eks/" + REGION + "/" + cluster.getName() + "/")).getFirst();
|
||||
assertEquals(List.of(role), profile.getRoleNames());
|
||||
assertEquals(profile.getArn(), instance.getIamInstanceProfileArn());
|
||||
// Its NodeClaim, launched, owned by the pool.
|
||||
assertEquals("True NodePool general-purpose", node.kubectlOutput("get", "nodeclaim", claim, "-o",
|
||||
"jsonpath={.status.conditions[?(@.type==\"Launched\")].status} "
|
||||
+ "{.metadata.ownerReferences[0].kind} {.metadata.labels.karpenter\\.sh/nodepool}"));
|
||||
// A second pass while the node hasn't joined launches no other.
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
|
||||
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running")).size());
|
||||
@@ -171,6 +182,13 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
|
||||
await("the pod is scheduled on the new node").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.ignoreExceptions().until(() -> nodeName.equals(node.kubectlOutput("get", "pod", "web",
|
||||
"-o", "jsonpath={.spec.nodeName}")));
|
||||
// The NodeClaim says its node joined, as its node is.
|
||||
await("the NodeClaim is ready").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.ignoreExceptions().until(() -> {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
|
||||
return (nodeName + " True").equals(node.kubectlOutput("get", "nodeclaim", claim, "-o",
|
||||
"jsonpath={.status.nodeName} {.status.conditions[?(@.type==\"Ready\")].status}"));
|
||||
});
|
||||
|
||||
cluster.setComputeConfig(new ComputeConfig(false, List.of(), null));
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.removeNodes(cluster, REGION));
|
||||
@@ -178,6 +196,8 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
|
||||
assertEquals(List.of(), RequestScopes.callAs(ACCOUNT, REGION, () -> compute.instancesOf(cluster, REGION, "pending", "running")));
|
||||
await("the node is gone").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.ignoreExceptions().until(() -> node.kubectl("get", "node", nodeName).exitCode() != 0);
|
||||
await("the NodeClaim is gone").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
|
||||
.ignoreExceptions().until(() -> node.kubectl("get", "nodeclaim", claim).exitCode() != 0);
|
||||
|
||||
// DeleteCluster runs the Auto Mode cleanups, compute's among them.
|
||||
Cluster deleted = cluster;
|
||||
|
||||
@@ -419,6 +419,17 @@ class EksAutoModeNodesTest {
|
||||
assertNull(read.get(1).consolidateAfter());
|
||||
}
|
||||
|
||||
/** A pool being deleted, held by its claims, launches nothing more and its nodes go, as Karpenter treats it. */
|
||||
@Test
|
||||
void aPoolBeingDeletedIsLeftOut() throws Exception {
|
||||
String pools = """
|
||||
{"items": [{"metadata": {"name": "leaving", "deletionTimestamp": "2026-11-26T00:00:00Z"},
|
||||
"spec": {"template": {"spec": {}}}},
|
||||
{"metadata": {"name": "staying"}, "spec": {"template": {"spec": {}}}}]}""";
|
||||
|
||||
assertEquals(List.of("staying"), EksAutoModeNodes.nodePools(json(pools)).stream().map(NodePool::name).toList());
|
||||
}
|
||||
|
||||
/** DaemonSet pods and static pods' mirrors don't keep a node busy; finished pods don't either. */
|
||||
@Test
|
||||
void onlyAWorkloadKeepsANodeBusy() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user