mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): expire EKS Auto Mode NodeClaims after their expireAfter, as Karpenter does (#9634)
This commit is contained in:
1 parent
daa6f35bb5
commit
f5457a2516
6 files changed
+140
-7
No files matched your search
@@ -528,7 +528,10 @@ launches nodes on AWS. Floci checks every 10 seconds.
|
||||
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
|
||||
with its instance, Karpenter's finalizer taken off (other finalizers stay). Once it has lived its `expireAfter`,
|
||||
counted from its creation, it is deleted, whatever the pool's disruption budgets, as AWS expired a `5m` pool's
|
||||
claims five minutes in, a `nodes: "0"` budget aside; its node then goes as a deleted claim's does, and its pods get
|
||||
another. 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.
|
||||
- **Pool status.** Each pool's `status.resources` (`cpu`, `memory`, `pods`, `nodes`) and `status.nodes` say what its
|
||||
|
||||
@@ -505,8 +505,9 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
* 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
|
||||
* With the cluster's pods ({@code podList}, {@code null} for none, as with compute off), a claim that has lived its
|
||||
* {@code expireAfter} is deleted, and 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,
|
||||
@@ -541,6 +542,16 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
deleted.add(name);
|
||||
continue;
|
||||
}
|
||||
if (podList != null && EksAutoModeNodeClaims.expired(claim, clock.instant())) {
|
||||
// As Karpenter expires a claim: deleted, its pool's disruption budgets aside, so its node goes
|
||||
// this pass as a deleted claim's does and its pods get a node again.
|
||||
exec(cluster, List.of("kubectl", "delete", "nodeclaim", name, "--wait=false"),
|
||||
"delete nodeclaim " + name);
|
||||
LOG.infov("EKS Auto Mode NodeClaim {0} of cluster {1} expired after {2}", name, cluster.getName(),
|
||||
claim.path("spec").path("expireAfter").asText());
|
||||
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",
|
||||
|
||||
@@ -7,8 +7,11 @@ 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 org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -31,6 +34,7 @@ final class EksAutoModeNodeClaims {
|
||||
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 Logger LOG = Logger.getLogger(EksAutoModeNodeClaims.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SUFFIX_ALPHABET = "bcdfghjklmnpqrstvwxz2456789";
|
||||
|
||||
@@ -182,6 +186,28 @@ final class EksAutoModeNodeClaims {
|
||||
return nodeReady(node).equals(EksAutoModeNodes.conditionStatus(claim, "Ready"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a NodeClaim has lived its {@code expireAfter}, counted from its creation, as Karpenter expires a claim
|
||||
* (deleting it, whatever the pool's disruption budgets). One whose {@code expireAfter} is {@code Never}, missing
|
||||
* or unreadable doesn't expire.
|
||||
*/
|
||||
static boolean expired(JsonNode claim, Instant now) {
|
||||
String after = claim.path("spec").path("expireAfter").asText("");
|
||||
String created = claim.path("metadata").path("creationTimestamp").asText("");
|
||||
if (after.isEmpty() || created.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Duration life = EksAutoModeNodes.duration(after);
|
||||
return life != null && !Instant.parse(created).plus(life).isAfter(now);
|
||||
} catch (RuntimeException unreadable) {
|
||||
LOG.warnv("EKS Auto Mode NodeClaim {0} has an expireAfter ({1}) or creationTimestamp ({2}) that can''t be "
|
||||
+ "read; it doesn''t expire: {3}", claim.path("metadata").path("name").asText(), after, created,
|
||||
unreadable.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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());
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Duration;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
@@ -610,7 +611,7 @@ final class EksAutoModeNodes {
|
||||
pools.add(new NodePool(item.path("metadata").path("name").asText(),
|
||||
template.path("spec").path("nodeClassRef").path("name").asText("default"),
|
||||
requirements(template.path("spec").path("requirements")), List.copyOf(taints), labels,
|
||||
item.path("spec").path("weight").asInt(0), duration(disruption.path("consolidateAfter").asText("0s")),
|
||||
item.path("spec").path("weight").asInt(0), consolidateAfter(disruption.path("consolidateAfter").asText("0s")),
|
||||
List.copyOf(budgets), limits(item.path("spec").path("limits"))));
|
||||
}
|
||||
return pools;
|
||||
@@ -866,15 +867,28 @@ final class EksAutoModeNodes {
|
||||
return up.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) >= 0 ? Long.MAX_VALUE : up.longValue();
|
||||
}
|
||||
|
||||
/** A Kubernetes duration such as {@code 30s}, {@code 5m} or {@code 1h30m}; null for {@code Never}. */
|
||||
/**
|
||||
* A Kubernetes duration such as {@code 30s}, {@code 5m} or {@code 1h30m}; null for {@code Never}.
|
||||
*
|
||||
* @throws IllegalArgumentException for a value it can't read, such as {@code 500ms}
|
||||
*/
|
||||
static Duration duration(String value) {
|
||||
if ("Never".equals(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Duration.parse("PT" + value.toUpperCase(Locale.ROOT));
|
||||
} catch (RuntimeException expected) {
|
||||
// The NodePool schema refuses such a value (500ms, say, which the parse above doesn't read); one that got
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException("Not a Kubernetes duration: " + value, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** A pool's {@code consolidateAfter}, as {@link #duration} reads it; null for {@code Never}. */
|
||||
static Duration consolidateAfter(String value) {
|
||||
try {
|
||||
return duration(value);
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// The NodePool schema refuses such a value (500ms, say, which duration doesn't read); one that got
|
||||
// through waits the 30 seconds of Auto Mode's built-in pools.
|
||||
return Duration.ofSeconds(30);
|
||||
}
|
||||
|
||||
@@ -324,6 +324,13 @@ class EksAutoModeComputeTest {
|
||||
"\"metadata\": {\"deletionTimestamp\": \"2026-11-27T00:00:00Z\", ");
|
||||
}
|
||||
|
||||
/** A claim Auto Mode manages, made {@code age} ago, with {@code expireAfter}. */
|
||||
private String claimOfAge(String name, String expireAfter, Duration age) {
|
||||
return managedClaim(name, "").replace("\"status\": {}",
|
||||
"\"spec\": {\"expireAfter\": \"" + expireAfter + "\"}, \"status\": {}").replace("\"metadata\": {",
|
||||
"\"metadata\": {\"creationTimestamp\": \"" + clock.instant().minus(age) + "\", ");
|
||||
}
|
||||
|
||||
private static String managedClaim(String name, String moreFinalizers) {
|
||||
return "{\"metadata\": {\"name\": \"" + name + "\", "
|
||||
+ "\"labels\": {\"app.kubernetes.io/managed-by\": \"eks\"}, "
|
||||
@@ -678,6 +685,54 @@ class EksAutoModeComputeTest {
|
||||
"nodeclaim", claim, "--type=merge", "-p", "{\"metadata\":{\"finalizers\":null}}"}, 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* A claim that has lived its expireAfter is deleted and its node goes in the same pass, as a deleted claim's
|
||||
* does, whatever the pool's disruption budgets, as AWS expired a 5m pool's claims, its 0-node budget aside; a
|
||||
* claim not yet that old stays.
|
||||
*/
|
||||
@Test
|
||||
void anExpiredClaimIsDeletedAndItsNodeGoes() {
|
||||
Instance node = joinedNode("i-node", "node-1");
|
||||
aRunningPodOn("node-1", "");
|
||||
lists.put("nodes", "{\"items\": [{\"metadata\": {\"name\": \"node-1\", \"labels\": {}}}]}");
|
||||
lists.put("nodepools", POOLS.replace("\"spec\": {\"template\"",
|
||||
"\"spec\": {\"disruption\": {\"budgets\": [{\"nodes\": \"0\"}]}, \"template\""));
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-node");
|
||||
lists.put("nodeclaims", "{\"items\": [" + claimOfAge(claim, "5m", Duration.ofMinutes(5)) + "]}");
|
||||
Cluster cluster = cluster("prod");
|
||||
|
||||
compute.reconcile(cluster, REGION);
|
||||
|
||||
InOrder order = inOrder(clusterManager, ec2);
|
||||
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete", "nodeclaim",
|
||||
claim, "--wait=false"}, 15);
|
||||
order.verify(clusterManager).execInContainerForResult("k3s-1", new String[]{"kubectl", "taint", "node",
|
||||
"node-1", "karpenter.sh/disrupted:NoSchedule", "--overwrite"}, 15);
|
||||
order.verify(clusterManager).execInContainerForResult("k3s-1", DRAIN_NODE_1, 15);
|
||||
order.verify(clusterManager).removeJoinedNode(cluster, node);
|
||||
order.verify(ec2).terminateInstances(REGION, List.of("i-node"));
|
||||
}
|
||||
|
||||
/** A claim younger than its expireAfter, or whose expireAfter is Never, isn't deleted. */
|
||||
@Test
|
||||
void aClaimNotYetExpiredStays() {
|
||||
joinedNode("i-node", "node-1");
|
||||
aRunningPodOn("node-1", "");
|
||||
aReadyNode("node-1");
|
||||
String claim = EksAutoModeNodeClaims.name("general-purpose", "i-node");
|
||||
lists.put("nodeclaims", "{\"items\": [" + claimOfAge(claim, "5m", Duration.ofMinutes(4)) + "]}");
|
||||
|
||||
compute.reconcile(cluster("prod"), REGION);
|
||||
|
||||
// A claim whose expireAfter is Never stays however old it is.
|
||||
lists.put("nodeclaims", "{\"items\": [" + claimOfAge(claim, "Never", Duration.ofDays(30)) + "]}");
|
||||
compute.reconcile(cluster("prod"), REGION);
|
||||
|
||||
verify(clusterManager, never()).execInContainerForResult("k3s-1", new String[]{"kubectl", "delete",
|
||||
"nodeclaim", claim, "--wait=false"}, 15);
|
||||
verify(ec2, never()).terminateInstances(anyString(), anyList());
|
||||
}
|
||||
|
||||
/** A deleted claim whose instance was stopped has its node deleted, without a drain, and its instance ended. */
|
||||
@Test
|
||||
void aDeletedClaimsStoppedInstanceIsRemoved() {
|
||||
|
||||
@@ -9,6 +9,7 @@ import io.floci.aws.services.eks.EksAutoModeNodes.PendingPod;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -147,6 +148,29 @@ class EksAutoModeNodeClaimsTest {
|
||||
"conditions": [{"type": "Ready", "status": "True"}]}}""")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A claim expires once it has lived its expireAfter from its creation, as AWS deleted claims of a 5m pool five
|
||||
* minutes after they were made; Never, none or one unreadable doesn't.
|
||||
*/
|
||||
@Test
|
||||
void aClaimExpiresAfterItsExpireAfter() throws Exception {
|
||||
JsonNode fiveMinutes = MAPPER.readTree("""
|
||||
{"metadata": {"creationTimestamp": "2026-11-27T23:37:20Z"}, "spec": {"expireAfter": "5m"}}""");
|
||||
assertFalse(EksAutoModeNodeClaims.expired(fiveMinutes, Instant.parse("2026-11-27T23:42:19Z")));
|
||||
assertTrue(EksAutoModeNodeClaims.expired(fiveMinutes, Instant.parse("2026-11-27T23:42:20Z")));
|
||||
JsonNode defaulted = MAPPER.readTree("""
|
||||
{"metadata": {"creationTimestamp": "2026-11-01T00:00:00Z"}, "spec": {"expireAfter": "336h"}}""");
|
||||
assertFalse(EksAutoModeNodeClaims.expired(defaulted, Instant.parse("2026-11-14T23:59:59Z")));
|
||||
assertTrue(EksAutoModeNodeClaims.expired(defaulted, Instant.parse("2026-11-15T00:00:00Z")));
|
||||
Instant later = Instant.parse("2027-01-01T00:00:00Z");
|
||||
for (String after : List.of("\"Never\"", "\"soon\"")) {
|
||||
assertFalse(EksAutoModeNodeClaims.expired(MAPPER.readTree("{\"metadata\": {\"creationTimestamp\": "
|
||||
+ "\"2026-11-01T00:00:00Z\"}, \"spec\": {\"expireAfter\": " + after + "}}"), later), after);
|
||||
}
|
||||
assertFalse(EksAutoModeNodeClaims.expired(MAPPER.readTree(
|
||||
"{\"metadata\": {\"creationTimestamp\": \"2026-11-01T00:00:00Z\"}, \"spec\": {}}"), later));
|
||||
}
|
||||
|
||||
/** Only the claims Auto Mode manages are its own; ending one takes Karpenter's finalizer off and keeps others. */
|
||||
@Test
|
||||
void onlyManagedClaimsAreOwnedAndEndingOneKeepsOtherFinalizers() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user