fix(eks): execute nothing in a k3s container until its API server answers (#8810)

On a cgroup v2 host, k3s moves the root cgroup's processes into /init
and then enables the cgroup controllers, which the kernel allows only
while the root cgroup is empty, and k3s does not retry. Floci executed
in the container right after starting it, and an exec landing in
between made kubelet exit with "cgroup ["kubepods"] has some missing
controllers", so the cluster never became ACTIVE.

k3s serves its API only after that step, so a started container now
waits for its API to answer before anything is executed in it:

- The guest setup that ran right after start (the link-local metadata
  endpoint, the Pod Identity forward, the VPC routes, the audit log
  follower and the node registration listeners, of which a volume
  restore makes a device node in the container) is registered before
  the container starts and runs once isReady sees the API answer, on a
  virtual thread of its own, so neither the CreateCluster request nor
  the readiness poller waits on it. A cluster is ready only once its
  node is set up. This covers create, restore, an adopted container
  and a node capacity swap, all of which the poller checks.
- Node group user data waits for that setup, following a node replaced
  meanwhile, since it executes in the container and may read the
  metadata endpoint. If the API does not answer within 10 minutes, the
  user data fails the node group.
- A route table update, an EC2 instance joining and an
  eks-pod-identity-agent add-on change before the API answers leave the
  node to its setup and to finalizeCluster, which now registers each
  joined node on its own and leaves one that fails to be joined again.
- A delete waits for a setup already running, so it releases the log
  follower that setup attached. The control plane log stream, read
  through Docker's log API, is still attached at start.

Closes #5389
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 23:02:14 -04:00
1 parent 5b9709677e
commit 98c0a50ab5
3 files changed
+708 -44

No files matched your search

@@ -96,8 +96,14 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.regex.Pattern;
@@ -205,6 +211,42 @@ public class EksClusterManager
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
/**
* The k3s containers whose guest setup waits for their API server to answer, by container ID. On a cgroup v2
* host, k3s moves the root cgroup's processes into {@code /init} and then enables the cgroup controllers, which
* the kernel allows only while the root cgroup is empty, and k3s does not retry. A {@code docker exec} landing in
* between keeps the root cgroup busy, and kubelet exits with {@code cgroup ["kubepods"] has some missing
* controllers}. k3s serves its API only after that step, so nothing is executed in a started container until the
* API has answered.
*/
private final Map<String, GuestSetup> pendingGuestSetups = new ConcurrentHashMap<>();
/** How long node group user data waits for its node's guest setup before the node group fails. */
private Duration guestSetupTimeout = Duration.ofMinutes(10);
/**
* Runs each node's guest setup off the readiness poller, which checks every cluster from one thread: a node whose
* setup is slow must not hold back the others' readiness.
*/
private final ExecutorService guestSetupExecutor = Executors.newVirtualThreadPerTaskExecutor();
/**
* The setup a k3s container waits for, run once its API server answers. Its monitor is held for the whole setup,
* so a delete abandoning it waits for one already running and then finds everything it attached.
*/
private static final class GuestSetup {
private final CompletableFuture<Void> done = new CompletableFuture<>();
private final boolean logsFromNow;
/** Set once the API server has answered, from when the container may be executed in. */
private volatile boolean apiAnswered;
/** Whether the setup was handed to {@link #guestSetupExecutor}; guarded by the monitor. */
private boolean started;
private GuestSetup(boolean logsFromNow) {
this.logsFromNow = logsFromNow;
}
}
/** The container a node runs in once it is set up, or why user data cannot run in it. */
record SetUpNode(String containerId, UserDataPipeline.ExecutionResult failure) {}
private Object routeLockFor(String clusterKey) {
return clusterRouteLocks.computeIfAbsent(clusterKey, k -> new Object());
@@ -996,10 +1038,13 @@ public class EksClusterManager
if (signingKeyFiles != null) {
copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName());
}
// Registered before the container starts, so no readiness check can see it started without its setup.
deferGuestSetup(containerId, false);
ContainerInfo info;
try {
info = lifecycleManager.startCreated(containerId, spec);
} catch (Exception e) {
abandonGuestSetup(containerId, "its container could not be started");
try {
lifecycleManager.removeIfExistsStrict(containerName, true);
} catch (RuntimeException cleanup) {
@@ -1024,12 +1069,9 @@ public class EksClusterManager
}
applyEndpoints(cluster, containerName, hostPort, info, endpointHost);
registerClusterNodeInstance(cluster, containerId);
configureLinkLocalMetadataEndpoint(cluster, containerId);
configurePodIdentityForward(cluster, containerId);
recordClusterNodeInstance(cluster, containerId);
activeClusters.put(clusterResourceName(cluster), cluster);
configureVpcRoutes(cluster, containerId);
attachClusterLogs(cluster);
attachClusterLogs(cluster, false, true, false);
LOG.infov("k3s container {0} started for cluster {1} on port {2} (internal: {3})",
containerId, cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
@@ -1107,11 +1149,14 @@ public class EksClusterManager
reinjectSigningKeys(containerId, cluster);
}
// adopt() starts a container a Docker daemon reboot stopped, which boots k3s again, cgroup step included.
deferGuestSetup(containerId, true);
ContainerInfo info;
try {
info = lifecycleManager.adopt(containerId, List.of(K3S_API_SERVER_PORT),
containerBuilder.resolveDockerNetwork(config.services().eks().dockerNetwork()));
} catch (Exception e) {
abandonGuestSetup(containerId, "its container could not be adopted");
LOG.warnv("Could not adopt surviving k3s container {0} for EKS cluster {1} ({2}); recreating it",
cluster.getDockerName(), cluster.getName(), e.getMessage());
return false;
@@ -1119,6 +1164,7 @@ public class EksClusterManager
var publishedPort = info.publishedHostPort(K3S_API_SERVER_PORT);
if (publishedPort.isEmpty()) {
abandonGuestSetup(containerId, "its container publishes no API server port");
LOG.warnv("Surviving k3s container {0} publishes no API server port; recreating it",
cluster.getDockerName());
return false;
@@ -1133,12 +1179,9 @@ public class EksClusterManager
if (cluster.getNodePrivateIp() != null && !cluster.getNodePrivateIp().isBlank()) {
acquireClusterVpcLease(cluster, resolveClusterAccountId(cluster), clusterRegion(cluster), false);
}
registerClusterNodeInstance(cluster, info.containerId());
configureLinkLocalMetadataEndpoint(cluster, info.containerId());
configurePodIdentityForward(cluster, info.containerId());
recordClusterNodeInstance(cluster, info.containerId());
activeClusters.put(clusterResourceName(cluster), cluster);
configureVpcRoutes(cluster, info.containerId());
attachClusterLogsFromNow(cluster);
attachClusterLogs(cluster, true, true, false);
LOG.infov("Adopted surviving k3s container {0} for EKS cluster {1} on port {2} (internal: {3})",
info.containerId(), cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());
@@ -1174,6 +1217,7 @@ public class EksClusterManager
}
unregisterMetadataEndpoint(cluster);
closeQuietly(clusterLogHandles.remove(clusterResourceName(cluster)));
abandonGuestSetup(oldId, "its container was replaced");
cluster.setContainerId(null);
startCluster(cluster, oldPort);
LOG.infov("Replaced the k3s container of EKS cluster {0}", cluster.getName());
@@ -1252,7 +1296,9 @@ public class EksClusterManager
}
/**
* Checks whether the k3s API server is ready by polling its /readyz endpoint.
* Checks whether the k3s API server is ready: it answers on {@code /livez} and k3s has deployed its addons. The
* first time the API answers after the container started, this also runs the guest setup the start deferred
* (see {@link #pendingGuestSetups}), so a cluster is only reported ready once its node is set up.
*/
public boolean isReady(Cluster cluster) {
// Prefer internalEndpoint (IP-based) for connectivity — works on both user-defined
@@ -1260,14 +1306,27 @@ public class EksClusterManager
String endpoint = cluster.getInternalEndpoint() != null
? cluster.getInternalEndpoint()
: cluster.getEndpoint();
if (endpoint == null || cluster.getContainerId() == null) {
// Read once: a node replaced while the API is probed must not have the old node's answer acted on.
String containerId = cluster.getContainerId();
if (endpoint == null || containerId == null) {
return false;
}
// Nothing is executed in the container until its API answers: see pendingGuestSetups.
if (!apiAnswers(endpoint)) {
return false;
}
GuestSetup setup = pendingGuestSetups.get(containerId);
if (setup != null) {
startGuestSetup(cluster, containerId, setup);
return false;
}
return addonsDeployed(containerId);
}
// /livez endpoint on the k3s API server (usually unauthenticated)
String livezUrl = endpoint + "/livez";
/** Whether the k3s API server answers on {@code /livez}, which is usually unauthenticated. */
boolean apiAnswers(String endpoint) {
try {
HttpURLConnection conn = (HttpURLConnection) URI.create(livezUrl).toURL().openConnection();
HttpURLConnection conn = (HttpURLConnection) URI.create(endpoint + "/livez").toURL().openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
@@ -1276,12 +1335,99 @@ public class EksClusterManager
disableSslVerification(https);
}
int code = conn.getResponseCode();
return (code == 200 || code == 401 || code == 403) && addonsDeployed(cluster.getContainerId());
return code == 200 || code == 401 || code == 403;
} catch (Exception e) {
return false;
}
}
/** Holds a container's guest setup until its API server answers, which {@link #isReady} checks. */
void deferGuestSetup(String containerId, boolean logsFromNow) {
GuestSetup previous = pendingGuestSetups.put(containerId, new GuestSetup(logsFromNow));
if (previous != null) {
abandon(previous, "its container was started again");
}
}
void abandonGuestSetup(String containerId, String reason) {
GuestSetup setup = containerId == null ? null : pendingGuestSetups.remove(containerId);
if (setup != null) {
abandon(setup, reason);
}
}
/** Waits for a setup already running, so what it attached is there for the caller to release. */
private static void abandon(GuestSetup setup, String reason) {
synchronized (setup) {
setup.done.completeExceptionally(new IllegalStateException(reason));
}
}
/** Whether the container may be executed in: its API server has answered since it started. */
private boolean guestReachable(String containerId) {
GuestSetup setup = pendingGuestSetups.get(containerId);
return setup == null || setup.apiAnswered;
}
/** For tests: whether the container's guest setup still waits. */
boolean awaitingGuestSetup(String containerId) {
return pendingGuestSetups.containsKey(containerId);
}
private void startGuestSetup(Cluster cluster, String containerId, GuestSetup setup) {
synchronized (setup) {
if (setup.started || setup.done.isDone()) {
return;
}
setup.started = true;
setup.apiAnswered = true;
}
guestSetupExecutor.execute(() -> runGuestSetup(cluster, containerId, setup));
}
/** Runs the node's guest setup on the calling thread, as once its API has answered; for tests. */
void setUpGuest(Cluster cluster) {
String containerId = cluster.getContainerId();
GuestSetup setup = containerId == null ? null : pendingGuestSetups.get(containerId);
if (setup != null) {
runGuestSetup(cluster, containerId, setup);
}
}
/**
* Runs the setup a started container waited for, once its API server has answered: the link-local metadata
* endpoint, the Pod Identity forward, the VPC routes, the audit log follower, and the node registration listeners
* (attaching a volume makes its device node in the container), all of which execute in it.
*/
private void runGuestSetup(Cluster cluster, String containerId, GuestSetup setup) {
synchronized (setup) {
if (setup.done.isDone()) {
return;
}
setup.apiAnswered = true;
try {
if (containerId.equals(cluster.getContainerId())) {
configureLinkLocalMetadataEndpoint(cluster, containerId);
configurePodIdentityForward(cluster, containerId);
configureVpcRoutes(cluster, containerId);
attachClusterLogs(cluster, setup.logsFromNow, false, true);
notifyNodeRegistrationListeners(cluster);
LOG.infov("Set up the node of EKS cluster {0} once its API server answered", cluster.getName());
}
} catch (RuntimeException e) {
LOG.warnv("Could not set up the node of EKS cluster {0}: {1}", cluster.getName(), e.getMessage());
} finally {
pendingGuestSetups.remove(containerId, setup);
setup.done.complete(null);
}
}
}
/** For tests: how long node group user data waits for its node's guest setup. */
void guestSetupTimeout(Duration timeout) {
this.guestSetupTimeout = timeout;
}
/**
* k3s creates its Addon objects only after its embedded CRDs are established. A k3s stopped
* before that leaves a CRD unestablished for good, and every later start waits on it forever.
@@ -1358,6 +1504,7 @@ public class EksClusterManager
*/
public void stopCluster(Cluster cluster) {
String resourceName = clusterResourceName(cluster);
abandonGuestSetup(cluster.getContainerId(), "its cluster was deleted");
if (cluster.getContainerId() == null) {
releaseClusterVpcLease(cluster, resourceName);
unregisterMetadataEndpoint(cluster);
@@ -1561,6 +1708,16 @@ public class EksClusterManager
}
private void attachClusterLogs(Cluster cluster, boolean fromNow) {
attachClusterLogs(cluster, fromNow, true, true);
}
/**
* Attaches the control plane log stream, read through Docker's log API, and the audit log follower, a
* {@code tail -F} executed in the container, either or both. Attaching the stream replaces whatever was attached;
* the follower alone is added to it, as a started node gets its stream at once and its follower once its API has
* answered (see {@link #pendingGuestSetups}).
*/
private void attachClusterLogs(Cluster cluster, boolean fromNow, boolean api, boolean audit) {
if (logStreamer == null || cluster == null || !hasLoggingEnabled(cluster)) {
return;
}
@@ -1569,17 +1726,19 @@ public class EksClusterManager
return;
}
String resourceName = clusterResourceName(cluster);
// Logs are attached only for a container that was just started or adopted, so a handle
// still registered under this name follows an earlier container: close it rather than
// leave the new cluster without control-plane logs.
closeQuietly(clusterLogHandles.remove(resourceName));
if (api) {
// Logs are attached only for a container that was just started or adopted, so a handle
// still registered under this name follows an earlier container: close it rather than
// leave the new cluster without control-plane logs.
closeQuietly(clusterLogHandles.remove(resourceName));
}
String logGroup = "/aws/eks/" + cluster.getName() + "/cluster";
String hash = containerId.length() >= 32 ? containerId.substring(0, 32) : containerId;
String region = clusterRegion(cluster);
String accountId = resolveClusterAccountId(cluster);
List<Closeable> handles = new ArrayList<>();
if (hasLoggingEnabled(cluster, "api")) {
if (api && hasLoggingEnabled(cluster, "api")) {
try {
String logStream = "kube-apiserver-" + hash;
Closeable handle = fromNow
@@ -1596,7 +1755,7 @@ public class EksClusterManager
}
}
if (hasLoggingEnabled(cluster, "audit")) {
if (audit && hasLoggingEnabled(cluster, "audit")) {
try {
Closeable auditHandle = attachAuditLogFollower(
containerId, accountId, logGroup, hash, region, cluster.getName(), fromNow);
@@ -1609,15 +1768,24 @@ public class EksClusterManager
}
}
if (handles.size() == 1) {
closeQuietly(clusterLogHandles.put(resourceName, handles.getFirst()));
} else if (handles.size() > 1) {
closeQuietly(clusterLogHandles.put(resourceName, () -> {
for (Closeable h : handles) {
closeQuietly(h);
}
}));
if (handles.isEmpty()) {
return;
}
Closeable attached = handles.size() == 1 ? handles.getFirst() : closingAll(handles);
if (api) {
closeQuietly(clusterLogHandles.put(resourceName, attached));
} else {
clusterLogHandles.merge(resourceName, attached,
(stream, follower) -> closingAll(List.of(stream, follower)));
}
}
private static Closeable closingAll(List<Closeable> handles) {
return () -> {
for (Closeable h : handles) {
closeQuietly(h);
}
};
}
private Closeable attachAuditLogFollower(String containerId, String accountId, String logGroup,
@@ -2724,6 +2892,12 @@ public class EksClusterManager
}
void registerClusterNodeInstance(Cluster cluster, String containerId) {
recordClusterNodeInstance(cluster, containerId);
notifyNodeRegistrationListeners(cluster);
}
/** Records the cluster's node as an EC2 instance, without telling the listeners, which may execute in it. */
private void recordClusterNodeInstance(Cluster cluster, String containerId) {
try {
String accountId = resolveClusterAccountId(cluster);
String region = clusterRegion(cluster);
@@ -2732,20 +2906,27 @@ public class EksClusterManager
recordNodeContainer(nodeInstance, containerId, containerIps);
clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));
registerClusterNodeVpc(cluster, accountId, region, containerIps.allIps());
for (Consumer<Instance> listener : nodeRegistrationListeners) {
try {
listener.accept(nodeInstance);
} catch (Exception e) {
LOG.warnv("Node registration listener failed for cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
} catch (Exception e) {
LOG.warnv("Could not register cluster node instance for EKS cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
private void notifyNodeRegistrationListeners(Cluster cluster) {
ClusterNodeRecord node = clusterNodeInstances.get(clusterResourceName(cluster));
if (node == null) {
return;
}
for (Consumer<Instance> listener : nodeRegistrationListeners) {
try {
listener.accept(node.instance());
} catch (Exception e) {
LOG.warnv("Node registration listener failed for cluster {0}: {1}",
cluster.getName(), e.getMessage());
}
}
}
void configureLinkLocalMetadataEndpoint(Cluster cluster, String containerId) {
if (!config.services().eks().imds()) {
return;
@@ -2824,7 +3005,10 @@ public class EksClusterManager
* alone.
*/
public void podIdentityAgentChanged(Cluster cluster) {
if (podIdentityForwardEnabled() && cluster.getContainerId() != null) {
// A node whose API has not answered yet reads the add-on store in its guest setup instead: Terraform sends
// this add-on seconds after CreateCluster.
if (podIdentityForwardEnabled() && cluster.getContainerId() != null
&& guestReachable(cluster.getContainerId())) {
reconcilePodIdentityForward(cluster, cluster.getContainerId());
}
}
@@ -3010,9 +3194,11 @@ public class EksClusterManager
return;
}
for (Cluster cluster : activeClusters.values()) {
// A node whose API has not answered yet gets every route table's routes from its guest setup.
if (cluster.getResourcesVpcConfig() != null
&& routeTable.getVpcId().equals(cluster.getResourcesVpcConfig().getVpcId())
&& cluster.getContainerId() != null) {
&& cluster.getContainerId() != null
&& guestReachable(cluster.getContainerId())) {
String clusterAccount = resolveClusterAccountId(cluster);
if (routeTable.getOwnerId() != null && clusterAccount != null
&& !routeTable.getOwnerId().equals(clusterAccount)) {
@@ -3443,7 +3629,8 @@ public class EksClusterManager
}
String containerId = cluster.getContainerId();
if (containerId != null && !containerId.isBlank()) {
// A node whose API has not answered yet is registered by finalizeCluster, as one with no container is.
if (containerId != null && !containerId.isBlank() && guestReachable(containerId)) {
try {
registerNodeInCluster(cluster, containerId, instance);
} catch (Exception e) {
@@ -3516,11 +3703,22 @@ public class EksClusterManager
return false;
}
/**
* Registers every joined instance as a node. One that fails is dropped from the joined set, so the readiness
* poller finds it still to join and joins it again, and the others are registered regardless.
*/
void registerAllJoinedNodes(Cluster cluster, String containerId) {
Map<String, Instance> map = joinedClusterInstances.get(clusterResourceName(cluster));
if (map != null) {
for (Instance inst : map.values()) {
if (map == null) {
return;
}
for (Instance inst : List.copyOf(map.values())) {
try {
registerNodeInCluster(cluster, containerId, inst);
} catch (RuntimeException e) {
map.remove(inst.getInstanceId(), inst);
LOG.warnv("Could not register joined instance {0} as a node of EKS cluster {1}, "
+ "joining it again later: {2}", inst.getInstanceId(), cluster.getName(), e.getMessage());
}
}
}
@@ -3668,9 +3866,13 @@ public class EksClusterManager
return UserDataPipeline.ExecutionResult.skipped("No Docker daemon reachable");
}
String context = "EKS cluster " + cluster.getName() + " (nodegroup " + nodegroupName + ")";
SetUpNode node = awaitSetUpNode(cluster);
if (node.failure() != null) {
return node.failure();
}
return UserDataPipeline.executeUserData(
dockerClient,
cluster.getContainerId(),
node.containerId(),
context,
userData,
Duration.ofMinutes(30),
@@ -3680,6 +3882,47 @@ public class EksClusterManager
}
/**
* Waits for the node's guest setup before its user data runs: user data executes in the container, and it may
* read the metadata endpoint the setup configures. A node replaced meanwhile, as a node capacity swap does, is
* waited for in turn, so the user data runs in the node that is there once it is set up.
*/
SetUpNode awaitSetUpNode(Cluster cluster) {
long deadline = System.nanoTime() + guestSetupTimeout.toNanos();
while (true) {
String containerId = cluster.getContainerId();
if (containerId == null || containerId.isBlank()) {
return new SetUpNode(null, UserDataPipeline.ExecutionResult.error("The node of EKS cluster "
+ cluster.getName() + " is gone, so the user data did not run"));
}
GuestSetup setup = pendingGuestSetups.get(containerId);
if (setup != null) {
try {
setup.done.get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
} catch (TimeoutException e) {
return new SetUpNode(null, UserDataPipeline.ExecutionResult.error("The Kubernetes API server of "
+ "EKS cluster " + cluster.getName() + " did not answer within "
+ guestSetupTimeout.toMinutes() + " minutes, so its node was not set up and the user data"
+ " did not run"));
} catch (ExecutionException e) {
// Abandoned for a replacement, or for this container's own restart: wait for that one instead.
if (containerId.equals(cluster.getContainerId()) && !pendingGuestSetups.containsKey(containerId)) {
return new SetUpNode(null, UserDataPipeline.ExecutionResult.error("The node of EKS cluster "
+ cluster.getName() + " was not set up because " + e.getCause().getMessage()
+ ", so the user data did not run"));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return new SetUpNode(null, UserDataPipeline.ExecutionResult.error("Interrupted while waiting for "
+ "the node of EKS cluster " + cluster.getName() + " to be set up"));
}
}
if (containerId.equals(cluster.getContainerId()) && !pendingGuestSetups.containsKey(containerId)) {
return new SetUpNode(containerId, null);
}
}
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
return execInContainerForResult(containerId, cmd, 10).throwIfTimedOut(containerId).stdout();
}
@@ -0,0 +1,403 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.model.Container;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.core.common.docker.UserDataPipeline;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.RouteTable;
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.services.eks.model.LogSetup;
import io.floci.aws.services.eks.model.Logging;
import io.floci.aws.services.eks.model.ResourcesVpcConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Issue #5389: on a cgroup v2 host, k3s moves the root cgroup's processes into {@code /init} and then enables the
* cgroup controllers, which the kernel allows only while the root cgroup is empty. An exec landing in between makes
* kubelet exit for good, so nothing is executed in a started k3s container until its API server, which k3s serves
* only after that step, has answered.
*/
class EksClusterGuestSetupTest {
private static final String CONTAINER_ID = "container-id-123456789012345678901234567890";
private EmulatorConfig config;
private ContainerLifecycleManager lifecycleManager;
private ContainerBuilder containerBuilder;
private PortAllocator portAllocator;
private DockerClient dockerClient;
private EksClusterManager manager;
@BeforeEach
void setUp() {
config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.EksServiceConfig eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);
when(config.services()).thenReturn(services);
when(config.storage()).thenReturn(Mockito.mock(EmulatorConfig.StorageConfig.class));
when(services.eks()).thenReturn(eks);
when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
when(eks.apiServerBasePort()).thenReturn(6440);
when(eks.apiServerMaxPort()).thenReturn(6499);
when(eks.dockerNetwork()).thenReturn(Optional.empty());
when(eks.endpointMode()).thenReturn("host");
when(eks.vpcRouteProgramming()).thenReturn(true);
lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);
containerBuilder = Mockito.mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
portAllocator = Mockito.mock(PortAllocator.class);
when(portAllocator.allocate(6440, 6499)).thenReturn(6443);
dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(lifecycleManager.create(any())).thenReturn(CONTAINER_ID);
when(lifecycleManager.startCreated(any(), any())).thenReturn(new ContainerInfo(CONTAINER_ID, Map.of()));
manager = Mockito.spy(new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), portAllocator,
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, Mockito.mock(RegionResolver.class)));
}
@Test
void aStartedClusterIsNotExecutedInBeforeItsApiAnswers() {
Cluster cluster = cluster();
doReturn(false).when(manager).apiAnswers(anyString());
manager.startCluster(cluster);
assertFalse(manager.isReady(cluster));
verify(manager, never()).configureLinkLocalMetadataEndpoint(any(), any());
verify(manager, never()).configurePodIdentityForward(any(), any());
verify(manager, never()).configureVpcRoutes(any(), any());
verify(dockerClient, never()).execCreateCmd(anyString());
}
@Test
void theSetupIsRegisteredBeforeTheContainerStarts() {
AtomicBoolean awaitingAtStart = new AtomicBoolean();
when(lifecycleManager.startCreated(any(), any())).thenAnswer(invocation -> {
awaitingAtStart.set(manager.awaitingGuestSetup(CONTAINER_ID));
return new ContainerInfo(CONTAINER_ID, Map.of());
});
manager.startCluster(cluster());
assertTrue(awaitingAtStart.get(), "a readiness check must not see the container started without its setup");
}
@Test
void theNodeIsSetUpOnceWhenItsApiFirstAnswers() {
Cluster cluster = cluster();
doReturn(false).when(manager).apiAnswers(anyString());
manager.startCluster(cluster);
manager.isReady(cluster);
doReturn(true).when(manager).apiAnswers(anyString());
assertFalse(manager.isReady(cluster), "a node is ready only once it is set up");
assertEquals(CONTAINER_ID, manager.awaitSetUpNode(cluster).containerId());
manager.isReady(cluster);
InOrder order = inOrder(manager);
order.verify(manager).configureLinkLocalMetadataEndpoint(cluster, CONTAINER_ID);
order.verify(manager).configurePodIdentityForward(cluster, CONTAINER_ID);
order.verify(manager).configureVpcRoutes(cluster, CONTAINER_ID);
verify(manager, times(1)).configureLinkLocalMetadataEndpoint(any(), any());
}
@Test
void aSlowSetupDoesNotHoldTheReadinessCheck() {
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
release.await(10, TimeUnit.SECONDS);
return null;
}).when(manager).configureLinkLocalMetadataEndpoint(any(), any());
doReturn(true).when(manager).apiAnswers(anyString());
Cluster cluster = cluster();
manager.startCluster(cluster);
assertFalse(assertTimeoutPreemptively(Duration.ofSeconds(5), () -> manager.isReady(cluster)));
release.countDown();
assertNull(manager.awaitSetUpNode(cluster).failure());
}
@Test
void anAdoptedContainerWaitsForItsApiToo() {
// adopt() starts a container a Docker daemon reboot stopped, which boots k3s again.
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(survivingContainer()));
when(lifecycleManager.adopt(CONTAINER_ID, List.of(6443), Optional.empty()))
.thenReturn(new ContainerInfo(CONTAINER_ID, Map.of(), Map.of(6443, 6512)));
Cluster cluster = cluster();
doReturn(false).when(manager).apiAnswers(anyString());
manager.restoreCluster(cluster);
manager.isReady(cluster);
verify(manager, never()).configureLinkLocalMetadataEndpoint(any(), any());
verify(dockerClient, never()).execCreateCmd(anyString());
doReturn(true).when(manager).apiAnswers(anyString());
manager.isReady(cluster);
manager.awaitSetUpNode(cluster);
verify(manager).configureLinkLocalMetadataEndpoint(cluster, CONTAINER_ID);
}
@Test
void registrationListenersRunOnceTheApiAnswers() {
// Restoring an attached volume makes its device node in the container.
AtomicInteger notified = new AtomicInteger();
manager.addNodeRegistrationListener(instance -> notified.incrementAndGet());
Cluster cluster = cluster();
manager.startCluster(cluster);
assertEquals(0, notified.get());
manager.setUpGuest(cluster);
assertEquals(1, notified.get());
}
@Test
void userDataFailsTheNodeGroupWhenTheApiNeverAnswers() {
Cluster cluster = cluster();
manager.startCluster(cluster);
manager.guestSetupTimeout(Duration.ofMillis(100));
UserDataPipeline.ExecutionResult result =
manager.executeUserData(cluster, "workers", "#!/bin/bash\necho joined\n");
assertFalse(result.isSuccess());
assertTrue(result.getFailureMessage().contains("did not answer within"), result.getFailureMessage());
verify(dockerClient, never()).execCreateCmd(anyString());
}
@Test
void userDataGoesAheadOnceTheNodeIsSetUp() throws Exception {
Cluster cluster = cluster();
manager.startCluster(cluster);
CompletableFuture<EksClusterManager.SetUpNode> waiting =
CompletableFuture.supplyAsync(() -> manager.awaitSetUpNode(cluster));
manager.setUpGuest(cluster);
assertEquals(new EksClusterManager.SetUpNode(CONTAINER_ID, null), waiting.get(10, TimeUnit.SECONDS));
}
@Test
void userDataFollowsANodeReplacedWhileItWaits() throws Exception {
Cluster cluster = cluster();
manager.startCluster(cluster);
AtomicReference<EksClusterManager.SetUpNode> result = new AtomicReference<>();
Thread waiting = new Thread(() -> result.set(manager.awaitSetUpNode(cluster)));
waiting.start();
// Waiting on the first node's setup.
await().atMost(Duration.ofSeconds(10)).until(() -> waiting.getState() == Thread.State.TIMED_WAITING);
// A node capacity swap starts a new container and drops the old one's setup.
manager.deferGuestSetup("replacement", false);
cluster.setContainerId("replacement");
manager.abandonGuestSetup(CONTAINER_ID, "its container was replaced");
manager.setUpGuest(cluster);
waiting.join(10_000);
assertEquals(new EksClusterManager.SetUpNode("replacement", null), result.get());
}
@Test
void aRouteTableUpdateLeavesANodeWhoseApiHasNotAnsweredToItsSetup() {
Cluster cluster = cluster();
cluster.setResourcesVpcConfig(vpcConfig("vpc-1"));
manager.startCluster(cluster);
RouteTable routeTable = new RouteTable();
routeTable.setVpcId("vpc-1");
manager.onRouteTableUpdated("us-east-1", routeTable);
verify(manager, never()).configureVpcRoutes(any(), any());
manager.setUpGuest(cluster);
manager.onRouteTableUpdated("us-east-1", routeTable);
verify(manager, times(2)).configureVpcRoutes(cluster, CONTAINER_ID);
}
@Test
void anInstanceJoiningBeforeTheApiAnswersIsRecordedForFinalizeToRegister() {
Cluster cluster = cluster();
manager.startCluster(cluster);
manager.joinInstance(cluster, instance("i-0123456789abcdef0"));
assertTrue(manager.isInstanceJoined(cluster, "i-0123456789abcdef0"));
verify(dockerClient, never()).execCreateCmd(anyString());
}
@Test
void aJoinedInstanceThatFailsToRegisterIsJoinedAgainLaterWithoutHoldingBackTheOthers() {
Cluster cluster = cluster();
manager.startCluster(cluster);
manager.joinInstance(cluster, instance("i-0000000000000000a"));
manager.joinInstance(cluster, instance("i-0000000000000000b"));
when(dockerClient.execCreateCmd(anyString())).thenThrow(new RuntimeException("docker exec failed"));
assertDoesNotThrow(() -> manager.registerAllJoinedNodes(cluster, CONTAINER_ID));
// Left out of the joined set, so the readiness poller joins them again.
assertFalse(manager.isInstanceJoined(cluster, "i-0000000000000000a"));
assertFalse(manager.isInstanceJoined(cluster, "i-0000000000000000b"));
}
@Test
void anAddOnChangeBeforeTheApiAnswersIsLeftToTheSetup() {
// Terraform sends CreateAddon for eks-pod-identity-agent seconds after CreateCluster.
EmulatorConfig.TlsConfig tls = Mockito.mock(EmulatorConfig.TlsConfig.class);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(config.services().eks().podIdentityWebhook()).thenReturn(true);
EksAddonService addons = Mockito.mock(EksAddonService.class);
when(addons.isInstalled(any(), eq(EksPodIdentityWebhook.POD_IDENTITY_ADDON))).thenReturn(true);
manager.setAddonService(addons);
Cluster cluster = cluster();
manager.startCluster(cluster);
manager.podIdentityAgentChanged(cluster);
verify(addons, never()).isInstalled(any(), anyString());
verify(dockerClient, never()).execCreateCmd(anyString());
}
@Test
void aDeleteWaitsForASetupAlreadyRunningAndReleasesTheLogFollowerItAttached() throws Exception {
DockerClient docker = Mockito.mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(docker);
ExecCreateCmd execCreateCmd = Mockito.mock(ExecCreateCmd.class, Mockito.RETURNS_SELF);
ExecCreateCmdResponse execCreate = Mockito.mock(ExecCreateCmdResponse.class);
when(execCreate.getId()).thenReturn("exec-123");
when(docker.execCreateCmd(anyString())).thenReturn(execCreateCmd);
when(execCreateCmd.exec()).thenReturn(execCreate);
ExecStartCmd execStartCmd = Mockito.mock(ExecStartCmd.class, Mockito.RETURNS_SELF);
when(docker.execStartCmd("exec-123")).thenReturn(execStartCmd);
ResultCallback.Adapter<?> auditFollower = Mockito.mock(ResultCallback.Adapter.class);
Mockito.doReturn(auditFollower).when(execStartCmd).exec(any());
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
EksClusterManager logging = Mockito.spy(new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), portAllocator,
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, regionResolver, null, null, Mockito.mock(ContainerLogStreamer.class)));
CountDownLatch setupRunning = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
setupRunning.countDown();
release.await(10, TimeUnit.SECONDS);
return null;
}).when(logging).configureLinkLocalMetadataEndpoint(any(), any());
doReturn(true).when(logging).apiAnswers(anyString());
Cluster cluster = cluster();
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("audit"), true))));
logging.startCluster(cluster);
logging.isReady(cluster);
assertTrue(setupRunning.await(10, TimeUnit.SECONDS));
Thread delete = new Thread(() -> logging.stopCluster(cluster));
delete.start();
await().atMost(Duration.ofSeconds(10)).until(() -> delete.getState() == Thread.State.BLOCKED
|| delete.getState() == Thread.State.TERMINATED);
assertEquals(Thread.State.BLOCKED, delete.getState(), "the delete waits for the running setup");
release.countDown();
delete.join(10_000);
// The delete hands the follower the setup attached to the container's removal, which closes it.
verify(lifecycleManager).stopAndRemoveStrict(CONTAINER_ID, auditFollower, 5, true);
assertNull(logging.getLogHandle(cluster));
}
@Test
void deletingAClusterDropsItsPendingSetup() {
Cluster cluster = cluster();
manager.startCluster(cluster);
manager.stopCluster(cluster);
assertFalse(manager.awaitingGuestSetup(CONTAINER_ID));
}
private static Cluster cluster() {
Cluster cluster = new Cluster();
cluster.setName("demo");
return cluster;
}
private static Instance instance(String instanceId) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setRegion("us-east-1");
instance.setImageId("ami-0123456789abcdef0");
return instance;
}
private static ResourcesVpcConfig vpcConfig(String vpcId) {
ResourcesVpcConfig config = new ResourcesVpcConfig();
config.setVpcId(vpcId);
return config;
}
private static Container survivingContainer() {
try {
return new ObjectMapper().readValue("{\"Id\":\"" + CONTAINER_ID + "\",\"Labels\":{"
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}",
Container.class);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -725,6 +725,7 @@ class EksClusterManagerTest {
Cluster cluster = cluster();
spyManager.restoreCluster(cluster);
spyManager.setUpGuest(cluster);
verify(spyManager).configurePodIdentityForward(cluster, "cid-1");
}
@@ -4223,6 +4224,8 @@ class EksClusterManagerTest {
manager.startCluster(cluster);
manager.setUpGuest(cluster);
verify(logStreamer).attachForAccount(
eq("000000000000"),
eq("container-id-123456789012345678901234567890"),
@@ -4291,6 +4294,7 @@ class EksClusterManagerTest {
cluster.setName("prod-cluster");
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
Mockito.doThrow(new IllegalStateException("Failed to remove container"))
.when(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle, 5, true);
@@ -4305,6 +4309,7 @@ class EksClusterManagerTest {
stale.setName("prod-cluster");
stale.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(stale);
manager.setUpGuest(stale);
Closeable freshHandle = Mockito.mock(Closeable.class);
when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
.thenReturn(freshHandle);
@@ -4314,6 +4319,8 @@ class EksClusterManagerTest {
manager.startCluster(recreated);
manager.setUpGuest(recreated);
verify(mockHandle).close();
assertEquals(freshHandle, manager.getLogHandle(recreated));
}
@@ -4324,6 +4331,7 @@ class EksClusterManagerTest {
cluster.setName("prod-cluster");
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
Mockito.doThrow(new IllegalStateException("Failed to remove container"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle, 5, true);
@@ -4358,6 +4366,8 @@ class EksClusterManagerTest {
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
assertEquals(mockHandle, manager.getLogHandle(cluster));
manager.stopCluster(cluster);
@@ -4380,6 +4390,8 @@ class EksClusterManagerTest {
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
manager.stopCluster(cluster);
verify(lifecycleManager).stopAndRemoveStrict("container-id-123456789012345678901234567890", mockHandle, 5, true);
@@ -4393,6 +4405,8 @@ class EksClusterManagerTest {
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
manager.detachCluster(cluster);
verify(mockHandle).close();
@@ -4418,6 +4432,8 @@ class EksClusterManagerTest {
manager.restoreCluster(cluster);
manager.setUpGuest(cluster);
verify(logStreamer).attachFromNowForAccount(
eq("000000000000"),
eq("adopted-container-id-12345678901234567890"),
@@ -4560,6 +4576,8 @@ class EksClusterManagerTest {
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("audit"), true))));
manager.startCluster(cluster);
manager.setUpGuest(cluster);
assertEquals(mockAuditHandle, manager.getLogHandle(cluster));
verify(logStreamer).execLogCallbackForAccount(
"000000000000", "/aws/eks/audit-cluster/cluster",