mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(eks): start an EKS cluster's node again when its container exits by itself (#9750)
A k3s node whose container exited without Floci stopping it (k3s crashing, say) stayed stopped until Floci restarted, and a container started again outside Floci had none of its attached EBS volumes' devices, so their mounts failed. Floci now watches each node container, as it watches an EC2 instance's, adopts one that exited again as a restart adopts it, and makes its volumes' devices again. Once its API server answers, the readiness poller sets it up and finalizes it as it does a replaced node, so the link-local metadata and Pod Identity addresses, the VPC routes and the log follower are made again in the started container. A node that exits more than three times within ten minutes is left stopped. The exit goes to EksService, as EC2 hands a guest's shutdown to Ec2Service, and EksService starts the node again under the cluster's capacity lock, which DeleteCluster and the first node group's replacement hold, so an exit handled while the cluster is deleted, or once it is gone, leaves the node stopped. Each restart has its own number that the poller clears only once it finalized that one, so a restart during the finalize is kept, and deleting a cluster forgets its restarts. The node restart Docker test's volume helper image is prefetched under its own class name.
This commit is contained in:
1 parent
96819a87fd
commit
0ad01626bd
9 files changed
+579
-3
No files matched your search
@@ -71,6 +71,11 @@ if starts Ec2GuestShutdownDockerNightlyIntegrationTest; then
|
||||
ecr public.ecr.aws/docker/library/alpine:latest
|
||||
pull alpine:3.21
|
||||
fi
|
||||
# EksNodeRestartDockerNightlyIntegrationTest attaches a volume to a k3s node through the same volume helper; the k3s
|
||||
# image is pulled for the /eks/ package below.
|
||||
if starts EksNodeRestartDockerNightlyIntegrationTest; then
|
||||
pull alpine:3.21
|
||||
fi
|
||||
test_image() {
|
||||
image="$(grep -oE "$1 *= *\"[^\"]+\"" "${TEST_IMAGES:-/dev/null}" | grep -oE '"[^"]+"' | tr -d '"')"
|
||||
[ -n "$image" ] || echo "$(date -u +%H:%M:%S) prefetch skipped: TestImages.$1 not readable" >> "$PREFETCH_LOG"
|
||||
|
||||
@@ -814,6 +814,16 @@ services:
|
||||
!!! note "No port mapping needed for k3s ports"
|
||||
k3s containers bind their API server port (6500-6599) directly on the host via Docker: no `ports:` entry is required in `docker-compose.yml`. See [Ports Reference](../configuration/ports.md#ports-65006599-eks-real-mode) for the full explanation.
|
||||
|
||||
#### A node that stops by itself comes back
|
||||
|
||||
On EKS the control plane comes back by itself. While Floci runs, a cluster's k3s container that exits without
|
||||
Floci stopping it, k3s crashing say, is adopted again as a Floci restart adopts it, and the devices of the EBS
|
||||
volumes attached to its node are made again, as a stopped container loses them. Once its API server answers, what
|
||||
Floci sets up in the node is made again too, as after a Floci restart: the link-local metadata and Pod Identity
|
||||
addresses, the VPC routes and the audit log follower, and the node is finalized (its joined instances' nodes and
|
||||
its Auto Mode label). A container started again outside Floci meanwhile (`docker start`) gets the same. A node that
|
||||
exits more than 3 times within 10 minutes is left stopped, with an error in Floci's log.
|
||||
|
||||
#### Clusters survive a restart
|
||||
|
||||
With a persistent [storage mode](../configuration/storage.md) (the default), clusters recorded in
|
||||
|
||||
@@ -26,8 +26,10 @@ import io.floci.aws.core.common.dns.DnsRecordSource;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerExitWatcher;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLiveness;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerNetworks;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
@@ -94,10 +96,12 @@ import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -115,6 +119,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
@@ -199,6 +204,9 @@ public class EksClusterManager
|
||||
/** The label EKS Auto Mode's nodes carry, given to the cluster's node while compute is on. */
|
||||
static final String AUTO_COMPUTE_LABEL_KEY = "eks.amazonaws.com/compute-type"; // partition-literal: a label
|
||||
static final String AUTO_COMPUTE_LABEL = AUTO_COMPUTE_LABEL_KEY + "=auto";
|
||||
/** How often a node that keeps exiting is started again within {@link #NODE_RESTART_WINDOW}. */
|
||||
static final int MAX_NODE_RESTARTS = 3;
|
||||
static final Duration NODE_RESTART_WINDOW = Duration.ofMinutes(10);
|
||||
static final String LOAD_BALANCING_MANIFEST_FILE = "floci-eks-auto-mode-load-balancing.yaml";
|
||||
static final String LOAD_BALANCING_MANIFEST_TAR_ENTRY = "server/manifests/" + LOAD_BALANCING_MANIFEST_FILE;
|
||||
// The manifest once load balancing is off: no objects, so k3s deletes the IngressClassParams kind it held before.
|
||||
@@ -252,6 +260,25 @@ public class EksClusterManager
|
||||
private final Ec2ImageCatalog imageCatalog;
|
||||
private final Ec2InstanceTypeCatalog instanceTypeCatalog = new Ec2InstanceTypeCatalog();
|
||||
private final Map<String, ClusterNodeRecord> clusterNodeInstances = new ConcurrentHashMap<>();
|
||||
/** Node containers whose exit is watched, so one recorded again isn't watched twice. */
|
||||
private final Set<String> watchedNodeContainers = ConcurrentHashMap.newKeySet();
|
||||
/** Node containers Floci stops or replaces itself, whose exit is no crash. */
|
||||
private final Set<String> flociStoppedNodeContainers = ConcurrentHashMap.newKeySet();
|
||||
/** When each cluster's node was last started again after it exited, for {@link #MAX_NODE_RESTARTS}. */
|
||||
private final Map<String, Deque<Instant>> nodeRestarts = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Clusters whose node was started again after it exited by itself, each with its restart's number, which the
|
||||
* readiness poller sets up and finalizes as it does a replaced node: a started container has lost the setup
|
||||
* executed in it. A restart during the poller's finalize has a new number, so finalizing the earlier one keeps it.
|
||||
*/
|
||||
private final Map<String, Long> restartedNodes = new ConcurrentHashMap<>();
|
||||
private final AtomicLong nodeRestartNumbers = new AtomicLong();
|
||||
/**
|
||||
* Takes a node container's exit that Floci didn't cause. {@link EksService} handles it under the cluster's
|
||||
* capacity lock, which DeleteCluster and a node replacement hold, so a cluster being deleted isn't brought back;
|
||||
* without it the node is started again at once.
|
||||
*/
|
||||
private volatile Consumer<NodeExit> nodeExitHandler = this::restartExitedNode;
|
||||
private final Map<String, Map<String, Instance>> joinedClusterInstances = new ConcurrentHashMap<>();
|
||||
private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();
|
||||
private final List<Consumer<Instance>> nodeRegistrationListeners = new CopyOnWriteArrayList<>();
|
||||
@@ -1253,6 +1280,7 @@ public class EksClusterManager
|
||||
try {
|
||||
docker.renameContainerCmd(oldId).withName(backupName).exec();
|
||||
renamed = true;
|
||||
flociStoppedNodeContainers.add(oldId);
|
||||
docker.stopContainerCmd(oldId).exec();
|
||||
if (lease != null && ec2 != null) {
|
||||
ec2.detachContainerFromVpc(lease.accountId(), lease.region(), lease.vpcId(), oldId);
|
||||
@@ -1550,6 +1578,9 @@ public class EksClusterManager
|
||||
public void stopCluster(Cluster cluster) {
|
||||
String resourceName = clusterResourceName(cluster);
|
||||
abandonGuestSetup(cluster.getContainerId(), "its cluster was deleted");
|
||||
// A cluster made again under the name starts with no restarts of its own.
|
||||
restartedNodes.remove(resourceName);
|
||||
nodeRestarts.remove(resourceName);
|
||||
if (cluster.getContainerId() == null) {
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
@@ -1560,6 +1591,7 @@ public class EksClusterManager
|
||||
// Strict: a container Docker could not remove may still be running and publishing the
|
||||
// port, so the delete fails and keeps the cluster record, its metadata endpoint, log
|
||||
// handle and port reservation; a retried delete releases them once the container is gone.
|
||||
flociStoppedNodeContainers.add(cluster.getContainerId());
|
||||
lifecycleManager.stopAndRemoveStrict(cluster.getContainerId(), logStream, 5, true);
|
||||
releaseClusterVpcLease(cluster, resourceName);
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
@@ -1723,9 +1755,13 @@ public class EksClusterManager
|
||||
/**
|
||||
* Releases Floci's hold on the given cluster (its metadata endpoint and log stream) and leaves
|
||||
* the k3s container running, so a later Floci start can re-latch it through
|
||||
* {@link #restoreCluster}. Used on shutdown when keep-running-on-shutdown is enabled.
|
||||
* {@link #restoreCluster}. Used on shutdown when keep-running-on-shutdown is enabled. Its node is no longer
|
||||
* watched: an exit after this is no longer Floci's to bring back, and the next start adopts it.
|
||||
*/
|
||||
public void detachCluster(Cluster cluster) {
|
||||
if (cluster.getContainerId() != null) {
|
||||
flociStoppedNodeContainers.add(cluster.getContainerId());
|
||||
}
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
closeQuietly(clusterLogHandles.remove(clusterResourceName(cluster)));
|
||||
if (cluster.getContainerId() != null) {
|
||||
@@ -3500,12 +3536,150 @@ public class EksClusterManager
|
||||
recordNodeContainer(nodeInstance, containerId, containerIps);
|
||||
clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));
|
||||
registerClusterNodeVpc(cluster, accountId, region, containerIps.allIps());
|
||||
watchNodeContainer(cluster, containerId);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not register cluster node instance for EKS cluster {0}: {1}",
|
||||
cluster.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches the cluster's node container for an exit Floci didn't cause, such as k3s crashing. On EKS the control
|
||||
* plane comes back by itself, so {@link #onNodeContainerExit} starts it again.
|
||||
*/
|
||||
private void watchNodeContainer(Cluster cluster, String containerId) {
|
||||
DockerClient streaming = lifecycleManager.getStreamingDockerClient();
|
||||
// Without a Docker client (no daemon behind the manager) there is no container to watch.
|
||||
if (containerId == null || streaming == null || !watchedNodeContainers.add(containerId)) {
|
||||
return;
|
||||
}
|
||||
flociStoppedNodeContainers.remove(containerId);
|
||||
ContainerExitWatcher.watch(lifecycleManager.getDockerClient(), streaming, containerId,
|
||||
exitCode -> CompletableFuture.runAsync(() -> onNodeContainerExit(cluster, containerId, exitCode)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings back a cluster's node whose container exited without Floci stopping it: adopted again as a
|
||||
* restart adopts it, with its attached EBS volumes' devices made again, which a stopped container loses. A
|
||||
* container started again meanwhile outside Floci only gets its volumes' devices. A node that keeps exiting is
|
||||
* left stopped after {@link #MAX_NODE_RESTARTS} in {@link #NODE_RESTART_WINDOW}. The exit goes to the
|
||||
* {@link #setNodeExitHandler node exit handler}, which {@link EksService} sets, as EC2 hands a guest's shutdown
|
||||
* to {@link io.floci.aws.services.ec2.Ec2Service}.
|
||||
*/
|
||||
void onNodeContainerExit(Cluster cluster, String containerId, int exitCode) {
|
||||
watchedNodeContainers.remove(containerId);
|
||||
if (flociStoppedNodeContainers.remove(containerId)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
nodeExitHandler.accept(new NodeExit(cluster, containerId, exitCode));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv("Could not handle the exit of the k3s node of EKS cluster {0}: {1}", cluster.getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** A node container's exit that Floci didn't cause, with its exit code. */
|
||||
public record NodeExit(Cluster cluster, String containerId, int exitCode) {}
|
||||
|
||||
/** Called with each node container's exit that Floci didn't cause, so the node can be started again. */
|
||||
void setNodeExitHandler(Consumer<NodeExit> nodeExitHandler) {
|
||||
this.nodeExitHandler = nodeExitHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the exited node again, unless Floci stopped it meanwhile (a delete or replacement waited for by the
|
||||
* handler), or its cluster or container isn't this one's any more.
|
||||
*/
|
||||
public void restartExitedNode(NodeExit exit) {
|
||||
Cluster cluster = exit.cluster();
|
||||
String containerId = exit.containerId();
|
||||
int exitCode = exit.exitCode();
|
||||
String resourceName = clusterResourceName(cluster);
|
||||
if (flociStoppedNodeContainers.remove(containerId)) {
|
||||
return;
|
||||
}
|
||||
// A cluster deleted or replaced meanwhile isn't this node's any more: Floci stopped it.
|
||||
if (!containerId.equals(cluster.getContainerId()) || activeClusters.get(resourceName) != cluster) {
|
||||
return;
|
||||
}
|
||||
ContainerLiveness liveness = lifecycleManager.probeContainer(containerId);
|
||||
if (liveness == ContainerLiveness.UNKNOWN) {
|
||||
LOG.warnv("The k3s node container {0} of EKS cluster {1} exited (code {2}), and Docker can't say whether "
|
||||
+ "it runs again; it isn''t started", containerId, cluster.getName(), String.valueOf(exitCode));
|
||||
return;
|
||||
}
|
||||
if (liveness == ContainerLiveness.RUNNING) {
|
||||
LOG.infov("The k3s node container {0} of EKS cluster {1} was started again outside Floci; its volumes'' "
|
||||
+ "devices and its setup are made again", containerId, cluster.getName());
|
||||
// Started again, it lost the NAT rules, routes and log follower set up in it, as well as the devices.
|
||||
deferGuestSetup(containerId, true);
|
||||
restartedNodes.put(resourceName, nodeRestartNumbers.incrementAndGet());
|
||||
restoreNodeVolumeDevices(cluster);
|
||||
watchNodeContainer(cluster, containerId);
|
||||
return;
|
||||
}
|
||||
if (!nodeRestartAllowed(resourceName)) {
|
||||
LOG.errorv("The k3s node container {0} of EKS cluster {1} exited (code {2}) {3} times within {4}; it is "
|
||||
+ "left stopped", containerId, cluster.getName(), String.valueOf(exitCode),
|
||||
String.valueOf(MAX_NODE_RESTARTS + 1), NODE_RESTART_WINDOW);
|
||||
return;
|
||||
}
|
||||
LOG.warnv("The k3s node container {0} of EKS cluster {1} exited (code {2}); starting it again",
|
||||
containerId, cluster.getName(), String.valueOf(exitCode));
|
||||
try {
|
||||
restoreCluster(cluster);
|
||||
restartedNodes.put(resourceName, nodeRestartNumbers.incrementAndGet());
|
||||
restoreNodeVolumeDevices(cluster);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.errorv("Could not start the k3s node of EKS cluster {0} again: {1}", cluster.getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the cluster's node was started again after it exited by itself and is still to be set up and
|
||||
* finalized, once its API server answers, as the readiness poller does a replaced node.
|
||||
*/
|
||||
public boolean nodeRestarted(Cluster cluster) {
|
||||
return nodeRestart(cluster) != 0;
|
||||
}
|
||||
|
||||
/** The number of the cluster's restart still to be set up and finalized, or 0 when there is none. */
|
||||
public long nodeRestart(Cluster cluster) {
|
||||
return restartedNodes.getOrDefault(clusterResourceName(cluster), 0L);
|
||||
}
|
||||
|
||||
/** The readiness poller set up and finalized the cluster's restart {@code restart}; a later one stays. */
|
||||
public void restartedNodeFinalized(Cluster cluster, long restart) {
|
||||
restartedNodes.remove(clusterResourceName(cluster), restart);
|
||||
}
|
||||
|
||||
private boolean nodeRestartAllowed(String resourceName) {
|
||||
Instant now = Instant.now();
|
||||
Deque<Instant> restarts = nodeRestarts.computeIfAbsent(resourceName, key -> new ArrayDeque<>());
|
||||
synchronized (restarts) {
|
||||
while (!restarts.isEmpty() && restarts.peekFirst().isBefore(now.minus(NODE_RESTART_WINDOW))) {
|
||||
restarts.pollFirst();
|
||||
}
|
||||
if (restarts.size() >= MAX_NODE_RESTARTS) {
|
||||
return false;
|
||||
}
|
||||
restarts.addLast(now);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Makes again the devices of the EBS volumes attached to the cluster's node, as a started container has none. */
|
||||
private void restoreNodeVolumeDevices(Cluster cluster) {
|
||||
ClusterNodeRecord node = clusterNodeInstances.get(clusterResourceName(cluster));
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (node == null || ec2 == null) {
|
||||
return;
|
||||
}
|
||||
ec2.restoreAttachedVolumesForInstance(node.region(), node.instance());
|
||||
}
|
||||
|
||||
private void notifyNodeRegistrationListeners(Cluster cluster) {
|
||||
ClusterNodeRecord node = clusterNodeInstances.get(clusterResourceName(cluster));
|
||||
if (node == null) {
|
||||
|
||||
@@ -176,6 +176,36 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
this.autoModeCleanups = autoModeCleanups;
|
||||
if (this.clusterManager != null) {
|
||||
this.clusterManager.setEc2Service(this.ec2Service);
|
||||
this.clusterManager.setNodeExitHandler(this::onNodeExit);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A cluster's node container exited without Floci stopping it, k3s crashing say: its node is started again, as
|
||||
* EKS brings its control plane back. Under the cluster's capacity lock, which DeleteCluster and the first node
|
||||
* group's node replacement hold, so a cluster being deleted, or gone, is left alone instead of being brought back.
|
||||
*/
|
||||
void onNodeExit(EksClusterManager.NodeExit exit) {
|
||||
Cluster cluster = exit.cluster();
|
||||
String accountId = allClusterEntries().stream()
|
||||
.filter(entry -> entry.value() != null && entry.value().getArn() != null
|
||||
&& entry.value().getArn().equals(cluster.getArn()))
|
||||
.map(AccountAwareStorageBackend.AccountEntry::accountId).findFirst().orElse(null);
|
||||
if (accountId == null) {
|
||||
LOG.infov("The k3s node of EKS cluster {0} exited after its cluster was deleted; it isn''t started again",
|
||||
cluster.getName());
|
||||
return;
|
||||
}
|
||||
String key = clusterKey(cluster);
|
||||
synchronized (capacityLock(accountId, key)) {
|
||||
synchronized (clustersBeingDeleted) {
|
||||
if (isClusterDeleting(accountId, cluster) || findClusterForAccount(accountId, key).isEmpty()) {
|
||||
LOG.infov("The k3s node of EKS cluster {0} exited while its cluster is deleted; it isn''t "
|
||||
+ "started again", cluster.getName());
|
||||
return;
|
||||
}
|
||||
}
|
||||
clusterManager.restartExitedNode(exit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3007,7 +3037,11 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
try {
|
||||
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
|
||||
Cluster cluster = entry.value();
|
||||
boolean replacedNode = cluster.getStatus() == ClusterStatus.ACTIVE && cluster.isFinalizePending();
|
||||
// A node replaced, or started again after it exited by itself, is set up and finalized again. Only
|
||||
// the restart read here is marked done: one during the finalize is verified by the next poll.
|
||||
long restart = clusterManager.nodeRestart(cluster);
|
||||
boolean replacedNode = cluster.getStatus() == ClusterStatus.ACTIVE
|
||||
&& (cluster.isFinalizePending() || restart != 0);
|
||||
if (cluster.getStatus() == ClusterStatus.CREATING || replacedNode) {
|
||||
if (clusterManager.isReady(cluster)) {
|
||||
clusterManager.finalizeCluster(cluster);
|
||||
@@ -3021,6 +3055,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
putCluster(cluster);
|
||||
}
|
||||
if (restart != 0) {
|
||||
clusterManager.restartedNodeFinalized(cluster, restart);
|
||||
}
|
||||
if (replacedNode) {
|
||||
LOG.infov("Replaced k3s node of EKS cluster {0} is ready", cluster.getName());
|
||||
} else {
|
||||
|
||||
@@ -34,6 +34,7 @@ import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLiveness;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
@@ -136,6 +137,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
@@ -884,6 +886,134 @@ class EksClusterManagerTest {
|
||||
verify(lifecycleManager).adopt("cid-1", List.of(6443), Optional.of("eks-net"));
|
||||
}
|
||||
|
||||
/** An adopted node whose container exited without Floci stopping it is adopted again, k3s crashing say. */
|
||||
@Test
|
||||
void aNodeThatExitedByItselfIsStartedAgain() {
|
||||
Ec2Service ec2 = Mockito.mock(Ec2Service.class);
|
||||
manager.setEc2Service(ec2);
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 1);
|
||||
|
||||
verify(lifecycleManager, times(2)).adopt("cid-1", List.of(6443), Optional.empty());
|
||||
assertEquals("cid-1", cluster.getContainerId());
|
||||
// Its attached volumes' devices are made again in the started container.
|
||||
verify(ec2).restoreAttachedVolumesForInstance(anyString(),
|
||||
argThat(node -> "cid-1".equals(node.getDockerContainerId())));
|
||||
// Its setup waits for its API server again, and the readiness poller is to finalize it.
|
||||
assertTrue(manager.awaitingGuestSetup("cid-1"));
|
||||
assertTrue(manager.nodeRestarted(cluster));
|
||||
long first = manager.nodeRestart(cluster);
|
||||
// Exiting again while the poller finalizes the first restart is a restart of its own, which stays.
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 1);
|
||||
long second = manager.nodeRestart(cluster);
|
||||
assertNotEquals(first, second);
|
||||
manager.restartedNodeFinalized(cluster, first);
|
||||
assertEquals(second, manager.nodeRestart(cluster));
|
||||
manager.restartedNodeFinalized(cluster, second);
|
||||
assertFalse(manager.nodeRestarted(cluster));
|
||||
}
|
||||
|
||||
/** A node running again by the time its exit is seen, started outside Floci, isn't adopted again. */
|
||||
@Test
|
||||
void aNodeRunningAgainIsNotAdoptedAgain() {
|
||||
Ec2Service ec2 = Mockito.mock(Ec2Service.class);
|
||||
manager.setEc2Service(ec2);
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.RUNNING);
|
||||
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 1);
|
||||
|
||||
verify(lifecycleManager, times(1)).adopt("cid-1", List.of(6443), Optional.empty());
|
||||
// Started outside Floci, it still lost its volumes' devices and the setup executed in it.
|
||||
verify(ec2).restoreAttachedVolumesForInstance(anyString(),
|
||||
argThat(node -> "cid-1".equals(node.getDockerContainerId())));
|
||||
assertTrue(manager.awaitingGuestSetup("cid-1"));
|
||||
assertTrue(manager.nodeRestarted(cluster));
|
||||
// A cluster deleted meanwhile has nothing left to finalize.
|
||||
manager.stopCluster(cluster);
|
||||
assertFalse(manager.nodeRestarted(cluster));
|
||||
}
|
||||
|
||||
/** The node of a cluster Floci stopped, deleted or replaced, isn't started again; nor one Docker can't see. */
|
||||
@Test
|
||||
void aNodeFlociStoppedIsNotStartedAgain() {
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
manager.stopCluster(cluster);
|
||||
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 137);
|
||||
|
||||
verify(lifecycleManager, times(1)).adopt("cid-1", List.of(6443), Optional.empty());
|
||||
assertFalse(manager.nodeRestarted(cluster));
|
||||
|
||||
Cluster other = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.UNKNOWN);
|
||||
manager.onNodeContainerExit(other, "cid-1", 1);
|
||||
verify(lifecycleManager, times(2)).adopt("cid-1", List.of(6443), Optional.empty());
|
||||
}
|
||||
|
||||
/** A node Floci let go of, as at a shutdown that leaves it running, isn't started again when it exits. */
|
||||
@Test
|
||||
void aDetachedNodeIsNotStartedAgain() {
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
manager.detachCluster(cluster);
|
||||
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 0);
|
||||
|
||||
verify(lifecycleManager, times(1)).adopt("cid-1", List.of(6443), Optional.empty());
|
||||
assertFalse(manager.nodeRestarted(cluster));
|
||||
}
|
||||
|
||||
/** A cluster made again under a deleted one's name doesn't inherit the deleted one's restarts. */
|
||||
@Test
|
||||
void aClusterMadeAgainUnderTheNameHasItsOwnRestarts() {
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
for (int i = 0; i <= EksClusterManager.MAX_NODE_RESTARTS; i++) {
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 1);
|
||||
}
|
||||
manager.stopCluster(cluster);
|
||||
|
||||
// Its own node container, which is started again on its first exit.
|
||||
Cluster again = adoptedNode("cid-2");
|
||||
when(lifecycleManager.probeContainer("cid-2")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
manager.onNodeContainerExit(again, "cid-2", 1);
|
||||
|
||||
verify(lifecycleManager, times(1 + EksClusterManager.MAX_NODE_RESTARTS))
|
||||
.adopt("cid-1", List.of(6443), Optional.empty());
|
||||
verify(lifecycleManager, times(2)).adopt("cid-2", List.of(6443), Optional.empty());
|
||||
}
|
||||
|
||||
/** A node that keeps exiting is started again three times within ten minutes, then left stopped. */
|
||||
@Test
|
||||
void aNodeThatKeepsExitingIsLeftStoppedAfterThreeRestarts() {
|
||||
Cluster cluster = adoptedNode("cid-1");
|
||||
when(lifecycleManager.probeContainer("cid-1")).thenReturn(ContainerLiveness.NOT_RUNNING);
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
manager.onNodeContainerExit(cluster, "cid-1", 1);
|
||||
}
|
||||
|
||||
verify(lifecycleManager, times(1 + EksClusterManager.MAX_NODE_RESTARTS))
|
||||
.adopt("cid-1", List.of(6443), Optional.empty());
|
||||
}
|
||||
|
||||
private Cluster adoptedNode(String containerId) {
|
||||
when(lifecycleManager.findByName("floci-eks-demo"))
|
||||
.thenReturn(Optional.of(survivingContainer(containerId)));
|
||||
when(lifecycleManager.adopt(containerId, List.of(6443), Optional.empty()))
|
||||
.thenReturn(new ContainerInfo(containerId, Map.of(), Map.of(6443, 6512)));
|
||||
Cluster cluster = cluster();
|
||||
manager.restoreCluster(cluster);
|
||||
// Its setup ran once its API server answered, as a restart's adoption has it run.
|
||||
manager.setUpGuest(cluster);
|
||||
assertFalse(manager.awaitingGuestSetup(containerId));
|
||||
return cluster;
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptsASurvivingContainerAndKeepsItsPublishedPort() {
|
||||
when(lifecycleManager.findByName("floci-eks-demo"))
|
||||
|
||||
@@ -260,7 +260,9 @@ class EksIrsaDockerNightlyIntegrationTest {
|
||||
|
||||
// 5. Container recreation: recreate the cluster container and verify that k3s
|
||||
// reuses the same node name on the existing data volume without duplicate or stale nodes
|
||||
// Floci lets go of it first, as at a shutdown, so its node isn't started again while it is replaced.
|
||||
String containerId = node.containerId();
|
||||
eksClusterManager.detachCluster(cluster);
|
||||
dockerClient.stopContainerCmd(containerId).exec();
|
||||
dockerClient.removeContainerCmd(containerId).exec();
|
||||
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.core.common.docker.ContainerExec;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.Ec2VolumeBlockDeviceManager;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterStatus;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.IndependentServiceSettingsProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* An EKS cluster's k3s node on a real container: killed outside Floci, as k3s crashing ends it, it runs again as the
|
||||
* same container, with the device of the EBS volume attached to it made again. Runs on
|
||||
* {@link IndependentServiceSettingsProfile}, whose EC2 attaches volumes as block devices; the node is started through
|
||||
* {@link EksClusterManager}, which runs a k3s container whatever the EKS mock setting.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IndependentServiceSettingsProfile.class)
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
class EksNodeRestartDockerNightlyIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksNodeRestartDockerNightlyIntegrationTest.class);
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DEVICE = "/dev/xvdf";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
@Inject
|
||||
EksService eksService;
|
||||
|
||||
@Inject
|
||||
Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
Ec2VolumeBlockDeviceManager volumeBlockDevices;
|
||||
|
||||
private Cluster cluster;
|
||||
private String volumeId;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
boolean available = DockerAvailability.answers(dockerClient) && volumeBlockDevices.isAvailable();
|
||||
if (!available) {
|
||||
LOG.warn("Docker or EBS block devices are not available; skipping EksNodeRestartDockerNightlyIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(available, "Docker and EBS block devices must be available for the node restart test");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (volumeId != null) {
|
||||
try {
|
||||
ec2Service.detachVolume(REGION, volumeId, null, null, true);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Ignoring detach error during test cleanup: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
ec2Service.deleteVolume(REGION, volumeId);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Ignoring delete volume error during test cleanup: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
if (cluster != null) {
|
||||
try {
|
||||
eksService.deleteClusterForAccount(ACCOUNT, cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to delete the test cluster: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
eksClusterManager.stopCluster(cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(value = 10, unit = TimeUnit.MINUTES)
|
||||
void aNodeKilledOutsideFlociRunsAgainWithItsVolumesDevice() {
|
||||
cluster = EksTestNode.cluster(ACCOUNT, "restart-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(120));
|
||||
// Stored, as EksService, which handles a node's exit, only starts an existing cluster's node again.
|
||||
cluster.setStatus(ClusterStatus.ACTIVE);
|
||||
eksService.putClusterForAccount(ACCOUNT, cluster);
|
||||
String containerId = cluster.getContainerId();
|
||||
Instance node = eksClusterManager.listInstances(ACCOUNT, REGION).stream()
|
||||
.filter(instance -> containerId.equals(instance.getDockerContainerId()))
|
||||
.findFirst().orElseThrow();
|
||||
// Attached as the EBS CSI driver's AttachVolume attaches it: through EC2, to the node's instance.
|
||||
Volume volume = ec2Service.createVolume(REGION, node.getPlacement().getAvailabilityZone(), "gp3", 1, false,
|
||||
3000, 125, null, null);
|
||||
volumeId = volume.getVolumeId();
|
||||
ec2Service.attachVolume(REGION, volumeId, node.getInstanceId(), DEVICE);
|
||||
assertEquals(0, deviceCheck(containerId).exitCode(), "the device after the attach");
|
||||
|
||||
// An exit Floci didn't make.
|
||||
dockerClient.killContainerCmd(containerId).exec();
|
||||
|
||||
await("node container running again").atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofSeconds(2))
|
||||
.until(() -> Boolean.TRUE.equals(dockerClient.inspectContainerCmd(containerId).exec()
|
||||
.getState().getRunning()));
|
||||
await("volume device made again").atMost(Duration.ofMinutes(2)).pollInterval(Duration.ofSeconds(2))
|
||||
.until(() -> deviceCheck(containerId).exitCode() == 0);
|
||||
assertEquals(containerId, cluster.getContainerId());
|
||||
// The setup executed in the node (NAT rules, routes, log follower) is made again once its API server answers:
|
||||
// EksService's readiness poller asks isReady, which starts it, until the node is ready, then finalizes it and
|
||||
// marks the restart done.
|
||||
await("restarted node set up and finalized again").atMost(Duration.ofMinutes(3))
|
||||
.pollInterval(Duration.ofSeconds(2))
|
||||
.until(() -> !eksClusterManager.nodeRestarted(cluster)
|
||||
&& !eksClusterManager.awaitingGuestSetup(containerId));
|
||||
assertEquals(ClusterStatus.ACTIVE, cluster.getStatus());
|
||||
}
|
||||
|
||||
private ContainerExec.Result deviceCheck(String containerId) {
|
||||
return eksClusterManager.execInContainerForResult(containerId,
|
||||
new String[]{"sh", "-c", "test -b " + DEVICE}, 15);
|
||||
}
|
||||
}
|
||||
@@ -1656,6 +1656,78 @@ class EksServiceTest {
|
||||
verify(clusterManager).finalizeCluster(cluster);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readinessPollerSetsUpAndFinalizesANodeStartedAgainAfterItExited() {
|
||||
EksClusterManager clusterManager = capacitySwapManager(true);
|
||||
EksService service = newService(clusterManager, false);
|
||||
Cluster cluster = activeClusterWithRunningNode(service, "restarted-node");
|
||||
when(clusterManager.nodeRestart(cluster)).thenReturn(7L);
|
||||
|
||||
// Its API server not answering yet, isReady (which starts the node's setup once it does) is asked again.
|
||||
service.pollClusterReadiness();
|
||||
verify(clusterManager).isReady(cluster);
|
||||
verify(clusterManager, never()).finalizeCluster(cluster);
|
||||
|
||||
when(clusterManager.isReady(cluster)).thenReturn(true);
|
||||
service.pollClusterReadiness();
|
||||
verify(clusterManager).finalizeCluster(cluster);
|
||||
// Only the restart read before the finalize is marked done.
|
||||
verify(clusterManager).restartedNodeFinalized(cluster, 7L);
|
||||
assertEquals(ClusterStatus.ACTIVE, service.describeCluster("restarted-node").getStatus());
|
||||
|
||||
when(clusterManager.nodeRestart(cluster)).thenReturn(0L);
|
||||
service.pollClusterReadiness();
|
||||
verify(clusterManager).finalizeCluster(cluster);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeExitOfAnActiveClusterStartsItsNodeAgain() {
|
||||
EksClusterManager clusterManager = capacitySwapManager(true);
|
||||
EksService service = newService(clusterManager, false);
|
||||
Cluster cluster = activeClusterWithRunningNode(service, "exited-node");
|
||||
EksClusterManager.NodeExit exit = new EksClusterManager.NodeExit(cluster, "existing-container", 1);
|
||||
|
||||
service.onNodeExit(exit);
|
||||
|
||||
verify(clusterManager).restartExitedNode(exit);
|
||||
}
|
||||
|
||||
/**
|
||||
* A node exit seen while its cluster is deleted waits for the delete, which holds the cluster's capacity lock,
|
||||
* and then finds the cluster gone: the node the delete removed isn't started again.
|
||||
*/
|
||||
@Test
|
||||
void aNodeExitDuringADeleteWaitsAndLeavesTheNodeStopped() throws Exception {
|
||||
EksClusterManager clusterManager = capacitySwapManager(true);
|
||||
EksService service = newService(clusterManager, false);
|
||||
Cluster cluster = activeClusterWithRunningNode(service, "exit-during-delete");
|
||||
CountDownLatch stopping = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
stopping.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
return null;
|
||||
}).when(clusterManager).stopCluster(cluster);
|
||||
AtomicReference<Throwable> deleteError = new AtomicReference<>();
|
||||
Thread deleter = deleteThread(service, "exit-during-delete", deleteError);
|
||||
Thread exiting = Thread.ofPlatform().unstarted(() -> service.onNodeExit(
|
||||
new EksClusterManager.NodeExit(cluster, "existing-container", 1)));
|
||||
try {
|
||||
deleter.start();
|
||||
assertTrue(stopping.await(10, TimeUnit.SECONDS));
|
||||
exiting.start();
|
||||
|
||||
assertEquals(Thread.State.BLOCKED, awaitBlockedOrTerminated(exiting, "the exit waits for the delete"));
|
||||
} finally {
|
||||
release.countDown();
|
||||
deleter.join(10_000);
|
||||
exiting.join(10_000);
|
||||
}
|
||||
|
||||
assertNull(deleteError.get());
|
||||
verify(clusterManager, never()).restartExitedNode(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedNodeReplacementStillHasThePreviousNodeVerified() {
|
||||
EksClusterManager clusterManager = capacitySwapManager(false);
|
||||
|
||||
@@ -51,7 +51,8 @@ import java.util.Map;
|
||||
* {@code floci.services.iot.mqtt.port=}{@value #IOT_MQTT_PORT} pin to an address it knows.</li>
|
||||
* <li>{@code floci.services.ec2.mock=false} runs instances as real containers, and
|
||||
* {@code floci.services.ec2.volume-block-devices=true} attaches EBS volumes to them as block
|
||||
* devices. {@code Ec2VolumeBlockDeviceDockerNightlyIntegrationTest} relies on both.</li>
|
||||
* devices. {@code Ec2VolumeBlockDeviceDockerNightlyIntegrationTest} relies on both, and so does
|
||||
* {@code EksNodeRestartDockerNightlyIntegrationTest}, which attaches a volume to an EKS cluster's node.</li>
|
||||
* <li>{@code floci.services.sagemaker.gpu.enabled=true} gives a training job on a GPU instance
|
||||
* type a GPU, and fails a job whose GPU request Floci cannot honour rather than training it on
|
||||
* CPU. {@code SageMakerGpuIntegrationTest} relies on it.</li>
|
||||
|
||||
Reference in new issue
Block a user