mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(eks): keep the nodes Floci registers for joined instances Ready, renewing their Lease as a kubelet does (#9759)
The node lifecycle controller marked every node Floci registers for a joined instance Unknown once node-monitor-grace-period had passed (40 seconds up to Kubernetes 1.31, 50 from 1.32), tainted it unreachable and evicted its pods, since no kubelet renewed its Lease. Every 10 seconds, as a kubelet does, Floci now renews each running instance's node Lease in kube-node-lease, owned by the node and 40 seconds long, and posts Ready again for a node the controller marked not Ready. A stopped instance's node is not renewed, so it goes not Ready as on EKS. The renewal runs on a scheduler of its own, apart from the readiness poller, with each cluster on its own thread, so a slow API server delays no other cluster's heartbeat, and a sweep that throws is logged without ending the schedule. The kubectl apply command is now built once, by EksClusterManager.kubectlApply.
This commit is contained in:
1 parent
6563e6a315
commit
a6b5d1b210
7 files changed
+333
-8
No files matched your search
@@ -493,8 +493,9 @@ launches nodes on AWS. Floci checks every 10 seconds.
|
||||
- **Image.** The EKS optimized Amazon Linux 2023 image of the cluster's Kubernetes version and the node's
|
||||
architecture, the one a managed node group of that version runs. AWS runs its own EKS Auto Mode image, which Floci
|
||||
doesn't have. When the [image catalog](ec2.md) maps that image to one whose `kubeletRegistersNode` is on, pods
|
||||
really run on the node. Otherwise the instance joins with the Ready node Floci registers for every joined
|
||||
instance, and pods are scheduled to it but don't start.
|
||||
really run on the node. Otherwise the instance joins with the Ready node Floci registers and keeps Ready for
|
||||
every joined instance (see [Node metadata](#node-metadata-and-aws-outcome-alignment)), and pods are scheduled to
|
||||
it but don't start.
|
||||
- **Node.** The instance joins the cluster through its EKS bootstrap user data (a nodeadm `NodeConfig`), as any
|
||||
instance does. Its kubelet flags (`--node-labels`, `--register-with-taints`) register the node with its pool's
|
||||
labels and taints, so no pod the taints keep off lands there first; Floci's own Ready node for a joined instance
|
||||
@@ -984,6 +985,12 @@ For simulated workers, Floci registers a Kubernetes `Node` matching AWS conventi
|
||||
- **Node name**: Uses the instance's private DNS name (`privateDnsName`), matching AWS EKS conventions.
|
||||
- **Provider ID**: Set to `spec.providerID: aws:///<availability-zone>/<instance-id>`.
|
||||
- **Labels & Status**: Includes topology and instance-type labels, ready status, internal IP, and catalog capacity.
|
||||
- **Heartbeat**: Every 10 seconds, as a kubelet does, Floci renews the node's Lease in `kube-node-lease` (owned by
|
||||
the node, 40 seconds long) while its instance is running, and posts Ready again if the node lifecycle controller
|
||||
marked it not Ready (as while Floci was down). Without it, the controller would mark the node `Unknown` once its
|
||||
`node-monitor-grace-period` had passed since it was registered (40 seconds up to Kubernetes 1.31, 50 from 1.32),
|
||||
taint it `node.kubernetes.io/unreachable` and evict its pods 5 minutes later. A node whose
|
||||
instance is stopped isn't renewed, so it goes not Ready, as a stopped instance's node does on EKS.
|
||||
- **EC2 persistence**: The instance remains an authentic EC2 instance reported by `DescribeInstances`.
|
||||
|
||||
### Guest kubelet registration
|
||||
|
||||
@@ -710,7 +710,7 @@ public class EksAutoModeCompute implements EksAutoModeCleanup {
|
||||
}
|
||||
|
||||
private void apply(Cluster cluster, String json, String what) {
|
||||
exec(cluster, List.of("sh", "-c", "echo '" + json.replace("'", "'\\''") + "' | kubectl apply -f -"), what);
|
||||
exec(cluster, List.of(EksClusterManager.kubectlApply(json)), what);
|
||||
}
|
||||
|
||||
/** Whether the cluster is still among the running ones, not deleted or being deleted. */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
@@ -96,6 +97,9 @@ import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -138,6 +142,8 @@ public class EksClusterManager
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
|
||||
private static final ObjectMapper NODE_MAPPER = new ObjectMapper();
|
||||
/** A kubelet's node Lease duration, its {@code nodeLeaseDurationSeconds} default. */
|
||||
static final int NODE_LEASE_DURATION_SECONDS = 40;
|
||||
private static final int K3S_API_SERVER_PORT = 6443;
|
||||
static final String DEFAULT_NODE_INSTANCE_TYPE = "m5.large";
|
||||
/** The tag naming the cluster, on the cluster's node and on its node groups' Auto Scaling groups. */
|
||||
@@ -4633,6 +4639,104 @@ public class EksClusterManager
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the nodes Floci registered for its running joined instances Ready, as their kubelet would: each one's
|
||||
* Lease in {@code kube-node-lease} is renewed, as a kubelet renews it every 10 seconds, and one the node lifecycle
|
||||
* controller marked not Ready (as while Floci was down) posts Ready again. Without it the controller marks such a
|
||||
* node {@code Unknown} once its {@code node-monitor-grace-period} has passed since it was registered (40 seconds
|
||||
* up to Kubernetes 1.31, 50 from 1.32), taints it
|
||||
* {@code node.kubernetes.io/unreachable} and evicts its pods 5 minutes later. A node whose instance isn't running
|
||||
* isn't renewed, so it goes not Ready as a stopped instance's node does on EKS; one whose image runs its own
|
||||
* kubelet is that kubelet's. A node not there (yet) is left to its registration.
|
||||
*/
|
||||
void renewRegisteredNodes(Cluster cluster) {
|
||||
String containerId = cluster.getContainerId();
|
||||
if (containerId == null || containerId.isBlank() || !guestReachable(containerId)) {
|
||||
return;
|
||||
}
|
||||
Map<String, Instance> renewed = new LinkedHashMap<>();
|
||||
for (Instance instance : getJoinedInstances(cluster)) {
|
||||
String region = instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster);
|
||||
if (!kubeletRegistersNode(instance) && running(cluster, region, instance)) {
|
||||
renewed.put(deriveInstanceNodeName(instance, region), instance);
|
||||
}
|
||||
}
|
||||
if (renewed.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ContainerExec.Result nodes = execInContainerForResult(containerId,
|
||||
new String[]{"kubectl", "get", "nodes", "-o", "json"}, 15);
|
||||
if (nodes.exitCode() != 0) {
|
||||
throw new IllegalStateException("kubectl get nodes failed: " + nodes.summary());
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
String renewTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", Locale.ROOT)
|
||||
.withZone(ZoneOffset.UTC).format(now);
|
||||
List<Map<String, Object>> leases = new ArrayList<>();
|
||||
List<String> notReady = new ArrayList<>();
|
||||
for (JsonNode node : NODE_MAPPER.readTree(nodes.stdout()).path("items")) {
|
||||
String name = node.path("metadata").path("name").asText();
|
||||
if (!renewed.containsKey(name)) {
|
||||
continue;
|
||||
}
|
||||
// Owned by its node, as a kubelet's Lease is, so it goes with the node.
|
||||
leases.add(Map.of("apiVersion", "coordination.k8s.io/v1", "kind", "Lease",
|
||||
"metadata", Map.of("name", name, "namespace", "kube-node-lease",
|
||||
"ownerReferences", List.of(Map.of("apiVersion", "v1", "kind", "Node", "name", name,
|
||||
"uid", node.path("metadata").path("uid").asText()))),
|
||||
"spec", Map.of("holderIdentity", name, "leaseDurationSeconds", NODE_LEASE_DURATION_SECONDS,
|
||||
"renewTime", renewTime)));
|
||||
if (!"True".equals(EksAutoModeNodes.conditionStatus(node, "Ready"))) {
|
||||
notReady.add(name);
|
||||
}
|
||||
}
|
||||
if (leases.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String list = NODE_MAPPER.writeValueAsString(Map.of("apiVersion", "v1", "kind", "List", "items", leases));
|
||||
ContainerExec.Result applied = execInContainerForResult(containerId, kubectlApply(list), 15);
|
||||
if (applied.exitCode() != 0) {
|
||||
throw new IllegalStateException("kubectl apply of the node leases failed: " + applied.summary());
|
||||
}
|
||||
for (String name : notReady) {
|
||||
ContainerExec.Result patched = execInContainerForResult(containerId, new String[]{"kubectl", "patch",
|
||||
"node", name, "--subresource=status", "--type=strategic",
|
||||
"-p", "{\"status\":{\"conditions\":[" + readyCondition(now) + "]}}"}, 15);
|
||||
if (patched.exitCode() != 0) {
|
||||
LOG.warnv("Could not post Ready again for node {0} of EKS cluster {1}: {2}", name,
|
||||
cluster.getName(), patched.summary());
|
||||
} else {
|
||||
LOG.infov("Posted Ready again for node {0} of EKS cluster {1}", name, cluster.getName());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not renew the registered nodes of EKS cluster {0}: {1}", cluster.getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** The command, run in a node, that applies {@code json} (one object or a List) as {@code kubectl apply} does. */
|
||||
static String[] kubectlApply(String json) {
|
||||
return new String[]{"sh", "-c", "echo '" + json.replace("'", "'\\''") + "' | kubectl apply -f -"};
|
||||
}
|
||||
|
||||
/** The Ready condition a kubelet posts, heartbeat at {@code now}. */
|
||||
private static String readyCondition(Instant now) {
|
||||
String time = DateTimeFormatter.ISO_INSTANT.format(now.truncatedTo(ChronoUnit.SECONDS));
|
||||
return "{\"type\":\"Ready\",\"status\":\"True\",\"reason\":\"KubeletReady\","
|
||||
+ "\"message\":\"kubelet is posting ready status\",\"lastHeartbeatTime\":\"" + time + "\","
|
||||
+ "\"lastTransitionTime\":\"" + time + "\"}";
|
||||
}
|
||||
|
||||
/** Whether the joined instance is running, as EC2 has it now. */
|
||||
private boolean running(Cluster cluster, String region, Instance instance) {
|
||||
Ec2Service ec2 = ec2Service();
|
||||
Instance current = ec2 == null ? instance : ec2.findInstanceForAccount(resolveClusterAccountId(cluster),
|
||||
region, instance.getInstanceId()).orElse(null);
|
||||
return current != null && current.getState() != null && "running".equals(current.getState().getName());
|
||||
}
|
||||
|
||||
/** Whether EKS Auto Mode launched the instance, as its {@code aws:ec2:managed-launch} tag says. */
|
||||
static boolean autoModeInstance(Instance instance) {
|
||||
return instance != null && instance.getTags() != null && instance.getTags().stream().anyMatch(t ->
|
||||
@@ -4685,8 +4789,7 @@ public class EksClusterManager
|
||||
String nodeJson = NODE_MAPPER.writeValueAsString(Map.of("apiVersion", "v1", "kind", "Node",
|
||||
"metadata", Map.of("name", nodeName, "labels", labels), "spec", spec));
|
||||
|
||||
ContainerExec.Result applyRes = execInContainerForResult(containerId,
|
||||
new String[]{"sh", "-c", "echo '" + nodeJson.replace("'", "'\\''") + "' | kubectl apply -f -"}, 15);
|
||||
ContainerExec.Result applyRes = execInContainerForResult(containerId, kubectlApply(nodeJson), 15);
|
||||
if (applyRes.exitCode() != 0) {
|
||||
throw new IllegalStateException("Failed to apply node " + nodeName + " to cluster "
|
||||
+ cluster.getName() + ": " + applyRes.stderr());
|
||||
@@ -4697,12 +4800,11 @@ public class EksClusterManager
|
||||
String internalDns = autoModeInstance(instance)
|
||||
? "{\"type\":\"InternalDNS\",\"address\":\"" + dnsName + "\"}," : "";
|
||||
String statusPatch = String.format(Locale.ROOT,
|
||||
"{\"status\":{\"conditions\":[{\"type\":\"Ready\",\"status\":\"True\","
|
||||
+ "\"reason\":\"KubeletReady\",\"message\":\"kubelet is posting ready status\"}],"
|
||||
"{\"status\":{\"conditions\":[%s],"
|
||||
+ "\"addresses\":[{\"type\":\"InternalIP\",\"address\":\"%s\"},%s{\"type\":\"Hostname\",\"address\":\"%s\"}],"
|
||||
+ "\"capacity\":{\"cpu\":\"%s\",\"memory\":\"%s\",\"pods\":\"110\"},"
|
||||
+ "\"allocatable\":{\"cpu\":\"%s\",\"memory\":\"%s\",\"pods\":\"110\"}}}",
|
||||
privateIp, internalDns, dnsName, cpu, memory, cpu, memory);
|
||||
readyCondition(Instant.now()), privateIp, internalDns, dnsName, cpu, memory, cpu, memory);
|
||||
|
||||
ContainerExec.Result patchRes = execInContainerForResult(containerId,
|
||||
new String[]{"kubectl", "patch", "node", nodeName, "--subresource=status", "--type=merge",
|
||||
|
||||
@@ -84,7 +84,9 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -134,6 +136,16 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
private final jakarta.enterprise.inject.Instance<EksAutoModeCleanup> autoModeCleanups;
|
||||
private final AutoScalingService autoScaling;
|
||||
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
|
||||
/**
|
||||
* Renews the nodes Floci registered, apart from the readiness poller, so a slow readiness check or finalize
|
||||
* doesn't delay a heartbeat; each cluster's renewal runs on a thread of its own ({@link #nodeRenewals}).
|
||||
*/
|
||||
private final ScheduledExecutorService nodeRenewer = Executors.newSingleThreadScheduledExecutor();
|
||||
private final ExecutorService nodeRenewals = Executors.newVirtualThreadPerTaskExecutor();
|
||||
/** The clusters, by ARN, whose renewal still runs: the next one is skipped, not queued behind it. */
|
||||
private final Set<String> renewingClusters = ConcurrentHashMap.newKeySet();
|
||||
/** How often the nodes Floci registered are renewed: a kubelet renews its node Lease every 10 seconds. */
|
||||
static final long NODE_LEASE_RENEW_SECONDS = 10;
|
||||
private final Map<String, UserDataClaim> appliedClusterUserData = new ConcurrentHashMap<>();
|
||||
private final Map<String, Object> nodeGroupCapacityLocks = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletableFuture<Boolean>> pendingFirstNodeGroups = new ConcurrentHashMap<>();
|
||||
@@ -790,6 +802,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
poller.shutdownNow();
|
||||
nodeRenewer.shutdownNow();
|
||||
nodeRenewals.shutdownNow();
|
||||
if (!config.services().eks().mock()) {
|
||||
boolean keepRunning = config.services().eks().keepRunningOnShutdown();
|
||||
for (Cluster cluster : allClusters()) {
|
||||
@@ -3031,6 +3045,44 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
|
||||
private void startReadinessPoller() {
|
||||
poller.scheduleAtFixedRate(this::pollClusterReadiness, 2, 3, TimeUnit.SECONDS);
|
||||
nodeRenewer.scheduleAtFixedRate(this::renewRegisteredNodes, NODE_LEASE_RENEW_SECONDS,
|
||||
NODE_LEASE_RENEW_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renews, every 10 seconds as a kubelet does, the nodes Floci registered in each active cluster, each cluster on
|
||||
* a thread of its own, so a cluster whose API server is slow delays no other's heartbeat. A cluster whose last
|
||||
* renewal still runs is skipped this time.
|
||||
*/
|
||||
void renewRegisteredNodes() {
|
||||
// Caught, as the readiness poller catches: a task that throws is never run again by its scheduler, and every
|
||||
// node Floci registered would then go Unknown.
|
||||
try {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
|
||||
Cluster cluster = entry.value();
|
||||
if (cluster == null || cluster.getStatus() != ClusterStatus.ACTIVE || cluster.getContainerId() == null
|
||||
|| cluster.getArn() == null || !renewingClusters.add(cluster.getArn())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
nodeRenewals.execute(() -> {
|
||||
try {
|
||||
clusterManager.renewRegisteredNodes(cluster);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Could not renew the registered nodes of EKS cluster {0}: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
} finally {
|
||||
renewingClusters.remove(cluster.getArn());
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException e) {
|
||||
// Shutting down.
|
||||
renewingClusters.remove(cluster.getArn());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error in EKS registered node renewal", e);
|
||||
}
|
||||
}
|
||||
|
||||
void pollClusterReadiness() {
|
||||
|
||||
+18
@@ -33,6 +33,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
/**
|
||||
* EKS Auto Mode compute on a real k3s node: a pod that asks for the {@code general-purpose} pool's nodes, which the
|
||||
@@ -285,6 +286,23 @@ class EksAutoModeNodesDockerNightlyIntegrationTest {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> compute.reconcile(cluster, REGION));
|
||||
return nodeName.equals(node.kubectlOutput("get", "pod", "web", "-o", "jsonpath={.spec.nodeName}"));
|
||||
});
|
||||
// Its Lease is renewed as a kubelet renews it, as EksService renews it every 10 seconds, so the node lifecycle
|
||||
// controller keeps it Ready: without it the node is marked Unknown once the controller's grace has passed,
|
||||
// its pod is evicted, and, not Ready, it uses up its pool's disruption budget, so the empty node below would
|
||||
// never go.
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> eksClusterManager.renewRegisteredNodes(cluster));
|
||||
String lease = "jsonpath={.spec.holderIdentity} {.spec.leaseDurationSeconds} "
|
||||
+ "{.metadata.ownerReferences[0].kind} {.metadata.ownerReferences[0].name}";
|
||||
assertEquals(nodeName + " 40 Node " + nodeName, node.kubectlOutput("get", "lease", "-n", "kube-node-lease",
|
||||
nodeName, "-o", lease));
|
||||
String renewed = node.kubectlOutput("get", "lease", "-n", "kube-node-lease", nodeName, "-o",
|
||||
"jsonpath={.spec.renewTime}");
|
||||
// Each renewal writes a renewTime of its own, to the microsecond.
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> eksClusterManager.renewRegisteredNodes(cluster));
|
||||
assertNotEquals(renewed, node.kubectlOutput("get", "lease", "-n", "kube-node-lease", nodeName, "-o",
|
||||
"jsonpath={.spec.renewTime}"));
|
||||
assertEquals("True", node.kubectlOutput("get", "node", nodeName, "-o",
|
||||
"jsonpath={.status.conditions[?(@.type==\"Ready\")].status}"));
|
||||
node.kubectl("patch", "nodepool", "general-purpose", "--type=merge",
|
||||
"-p", "{\"spec\":{\"disruption\":{\"consolidateAfter\":\"2s\"}}}");
|
||||
// Running its workload, the node stays.
|
||||
|
||||
@@ -53,6 +53,7 @@ import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.GroupIdentifier;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.model.LaunchTemplateData;
|
||||
import io.floci.aws.services.ec2.model.Placement;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
@@ -5971,6 +5972,94 @@ class EksClusterManagerTest {
|
||||
assertEquals(20, cluster.getJoinedInstanceIds().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* The nodes Floci registered are kept Ready as a kubelet keeps its node: a running instance's node has its
|
||||
* Lease renewed, owned by the node, and one the node lifecycle controller marked Unknown posts Ready again. A
|
||||
* stopped instance's node, a kubelet image's, and a node not there are left alone.
|
||||
*/
|
||||
@Test
|
||||
void registeredNodesAreRenewedAsAKubeletRenewsThem() throws Exception {
|
||||
Cluster cluster = clusterNamed("renew-cluster", "renew-container");
|
||||
Instance ready = createInstance("i-ready", "us-east-1a", "t3.medium", "x86_64", "10.0.1.60");
|
||||
Instance unknown = createInstance("i-unknown", "us-east-1a", "t3.medium", "x86_64", "10.0.1.61");
|
||||
Instance stopped = createInstance("i-stopped", "us-east-1a", "t3.medium", "x86_64", "10.0.1.62");
|
||||
Instance kubelet = createInstance("i-kubelet", "us-east-1a", "t3.medium", "x86_64", "10.0.1.63");
|
||||
Instance absent = createInstance("i-absent", "us-east-1a", "t3.medium", "x86_64", "10.0.1.64");
|
||||
kubelet.setImageId("ami-kubelet-worker");
|
||||
for (Instance instance : List.of(ready, unknown, stopped, kubelet, absent)) {
|
||||
instance.setState(instance == stopped ? InstanceState.stopped() : InstanceState.running());
|
||||
}
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
|
||||
.execInContainerForResult(anyString(), any(), anyInt());
|
||||
for (Instance instance : List.of(ready, unknown, stopped, kubelet, absent)) {
|
||||
manager.joinInstance(cluster, instance);
|
||||
}
|
||||
String readyNode = manager.deriveInstanceNodeName(ready, "us-east-1");
|
||||
String unknownNode = manager.deriveInstanceNodeName(unknown, "us-east-1");
|
||||
String nodes = "{\"items\":["
|
||||
+ node(readyNode, "uid-ready", "True") + "," + node(unknownNode, "uid-unknown", "Unknown") + ","
|
||||
+ node(manager.deriveInstanceNodeName(stopped, "us-east-1"), "uid-stopped", "True") + ","
|
||||
+ node(manager.deriveInstanceNodeName(kubelet, "us-east-1"), "uid-kubelet", "True") + "]}";
|
||||
ArgumentCaptor<String[]> commands = ArgumentCaptor.forClass(String[].class);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
|
||||
.execInContainerForResult(anyString(), commands.capture(), anyInt());
|
||||
doReturn(new ContainerExec.Result(0L, nodes, "", false)).when(manager).execInContainerForResult(
|
||||
"renew-container", new String[]{"kubectl", "get", "nodes", "-o", "json"}, 15);
|
||||
|
||||
manager.renewRegisteredNodes(cluster);
|
||||
|
||||
List<String[]> sent = commands.getAllValues();
|
||||
assertEquals(2, sent.size());
|
||||
String apply = sent.get(0)[2];
|
||||
JsonNode leases = new ObjectMapper().readTree(apply.substring(apply.indexOf('\'') + 1,
|
||||
apply.lastIndexOf("' | kubectl apply -f -")));
|
||||
assertEquals("List", leases.path("kind").asText());
|
||||
assertEquals(2, leases.path("items").size());
|
||||
for (int i = 0; i < 2; i++) {
|
||||
JsonNode lease = leases.path("items").get(i);
|
||||
String name = i == 0 ? readyNode : unknownNode;
|
||||
assertEquals("Lease", lease.path("kind").asText());
|
||||
assertEquals(name, lease.path("metadata").path("name").asText());
|
||||
assertEquals("kube-node-lease", lease.path("metadata").path("namespace").asText());
|
||||
JsonNode owner = lease.path("metadata").path("ownerReferences").get(0);
|
||||
assertEquals("Node " + name + " " + (i == 0 ? "uid-ready" : "uid-unknown"),
|
||||
owner.path("kind").asText() + " " + owner.path("name").asText() + " " + owner.path("uid").asText());
|
||||
assertEquals(name, lease.path("spec").path("holderIdentity").asText());
|
||||
assertEquals(40, lease.path("spec").path("leaseDurationSeconds").asInt());
|
||||
assertTrue(lease.path("spec").path("renewTime").asText().matches("\\d{4}-\\d{2}-\\d{2}T[0-9:]{8}\\.\\d{6}Z"));
|
||||
}
|
||||
String[] patch = sent.get(1);
|
||||
assertArrayEquals(new String[]{"kubectl", "patch", "node", unknownNode, "--subresource=status",
|
||||
"--type=strategic", "-p"}, Arrays.copyOf(patch, 7));
|
||||
JsonNode condition = new ObjectMapper().readTree(patch[7]).path("status").path("conditions").get(0);
|
||||
assertEquals("Ready True KubeletReady", condition.path("type").asText() + " "
|
||||
+ condition.path("status").asText() + " " + condition.path("reason").asText());
|
||||
assertTrue(condition.path("lastHeartbeatTime").isTextual());
|
||||
}
|
||||
|
||||
/** A cluster whose node's API hasn't answered yet, or with no joined instance to renew, isn't asked. */
|
||||
@Test
|
||||
void nothingIsRenewedWithoutARunningRegisteredNode() {
|
||||
Cluster cluster = clusterNamed("idle-cluster", "idle-container");
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager)
|
||||
.execInContainerForResult(anyString(), any(), anyInt());
|
||||
Instance stopped = createInstance("i-stopped", "us-east-1a", "t3.medium", "x86_64", "10.0.1.65");
|
||||
stopped.setState(InstanceState.stopped());
|
||||
manager.joinInstance(cluster, stopped);
|
||||
Mockito.clearInvocations(manager);
|
||||
|
||||
manager.renewRegisteredNodes(cluster);
|
||||
manager.renewRegisteredNodes(clusterNamed("empty-cluster", "empty-container"));
|
||||
|
||||
verify(manager, never()).execInContainerForResult(anyString(), any(), anyInt());
|
||||
}
|
||||
|
||||
private static String node(String name, String uid, String ready) {
|
||||
return "{\"metadata\":{\"name\":\"" + name + "\",\"uid\":\"" + uid + "\"},\"status\":{\"conditions\":["
|
||||
+ "{\"type\":\"MemoryPressure\",\"status\":\"False\"},{\"type\":\"Ready\",\"status\":\""
|
||||
+ ready + "\"}]}}";
|
||||
}
|
||||
|
||||
private Instance createInstance(String id, String zone, String type, String arch, String ip) {
|
||||
Instance inst = new Instance();
|
||||
inst.setInstanceId(id);
|
||||
|
||||
@@ -93,10 +93,12 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
@@ -110,6 +112,7 @@ import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -1728,6 +1731,60 @@ class EksServiceTest {
|
||||
verify(clusterManager, never()).restartExitedNode(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void registeredNodesAreRenewedInActiveClustersOnly() {
|
||||
EksClusterManager clusterManager = capacitySwapManager(true);
|
||||
EksService service = newService(clusterManager, false);
|
||||
Cluster active = activeClusterWithRunningNode(service, "renewed");
|
||||
Cluster failing = activeClusterWithRunningNode(service, "failing");
|
||||
Cluster creating = activeClusterWithRunningNode(service, "creating");
|
||||
creating.setStatus(ClusterStatus.CREATING);
|
||||
doThrow(new IllegalStateException("boom")).when(clusterManager).renewRegisteredNodes(failing);
|
||||
|
||||
service.renewRegisteredNodes();
|
||||
|
||||
// One cluster's failure doesn't stop the others, nor the next run.
|
||||
verify(clusterManager, timeout(5000)).renewRegisteredNodes(active);
|
||||
verify(clusterManager, timeout(5000)).renewRegisteredNodes(failing);
|
||||
verify(clusterManager, never()).renewRegisteredNodes(creating);
|
||||
}
|
||||
|
||||
/** A cluster whose renewal hangs delays no other cluster's, and isn't renewed again until its renewal is done. */
|
||||
@Test
|
||||
void aSlowClustersRenewalDelaysNoOtherAndIsNotQueuedBehindItself() throws Exception {
|
||||
EksClusterManager clusterManager = capacitySwapManager(true);
|
||||
EksService service = newService(clusterManager, false);
|
||||
Cluster slow = activeClusterWithRunningNode(service, "slow");
|
||||
Cluster fast = activeClusterWithRunningNode(service, "fast");
|
||||
CountDownLatch slowStarted = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicInteger slowRenewals = new AtomicInteger();
|
||||
AtomicInteger fastRenewals = new AtomicInteger();
|
||||
doAnswer(invocation -> {
|
||||
slowRenewals.incrementAndGet();
|
||||
slowStarted.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
return null;
|
||||
}).when(clusterManager).renewRegisteredNodes(slow);
|
||||
doAnswer(invocation -> fastRenewals.incrementAndGet()).when(clusterManager).renewRegisteredNodes(fast);
|
||||
try {
|
||||
service.renewRegisteredNodes();
|
||||
assertTrue(slowStarted.await(5, TimeUnit.SECONDS));
|
||||
// While the slow renewal hangs, the sweeps go on renewing the other cluster, each once its last is done.
|
||||
await().atMost(Duration.ofSeconds(5)).pollInterval(Duration.ofMillis(50)).untilAsserted(() -> {
|
||||
service.renewRegisteredNodes();
|
||||
assertTrue(fastRenewals.get() >= 3);
|
||||
});
|
||||
assertEquals(1, slowRenewals.get());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
await().atMost(Duration.ofSeconds(5)).pollInterval(Duration.ofMillis(50)).untilAsserted(() -> {
|
||||
service.renewRegisteredNodes();
|
||||
assertTrue(slowRenewals.get() >= 2);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedNodeReplacementStillHasThePreviousNodeVerified() {
|
||||
EksClusterManager clusterManager = capacitySwapManager(false);
|
||||
|
||||
Reference in new issue
Block a user