fix(eks): share a cluster node's mounts so CSI drivers can mount volumes (#8207)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-13 16:09:32 -04:00
1 parent 6341708315
commit 25811dd4c6
4 files changed
+227 -31

No files matched your search

+1 -1
View File
@@ -567,7 +567,7 @@ The node name, the instance ID in `spec.providerID`, and the synthetic EC2 insta
Stock Amazon EKS clusters historically define a default `gp2` StorageClass pointing to the legacy in-tree `kubernetes.io/aws-ebs` plugin, but run no active storage provisioner without the EBS CSI driver. Unqualified PersistentVolumeClaims remain `Pending` on EKS because nothing can provision them. Floci matches this behavior by disabling k3s's bundled `local-path` provisioner and StorageClass, preventing unqualified claims from silently binding to the node filesystem.
Callers requiring dynamic volume provisioning can install a driver (such as the `aws-ebs-csi-driver` addon) and define their desired StorageClass.
Callers requiring dynamic volume provisioning can install a driver (such as the `aws-ebs-csi-driver` addon) and define their desired StorageClass. As on an EKS node, the cluster node's mounts are shared, so a driver's node plugin can mount volumes under `/var/lib/kubelet` with `Bidirectional` propagation.
For local testing workflows that rely on automatic volume binding without a CSI driver, set `floci.services.eks.default-storage-class: true` (or `FLOCI_SERVICES_EKS_DEFAULT_STORAGE_CLASS=true`) to retain k3s's bundled `local-path` provisioner and default StorageClass.
@@ -116,6 +116,8 @@ public class EksClusterManager
private static final String NODE_CAPACITY_LABEL = "io.floci.eks.node-capacity";
private static final String DEFAULT_STORAGE_CLASS_LABEL = "io.floci.eks.default-storage-class";
private static final String ENDPOINT_HOST_LABEL = "io.floci.eks.endpoint-host";
/** Marks a node started behind {@link #RSHARE_ENTRYPOINT}, whose mounts are shared. */
private static final String SHARED_MOUNTS_LABEL = "io.floci.eks.shared-mounts";
private static final Pattern HOSTNAME = Pattern.compile(
"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*");
@@ -680,6 +682,7 @@ public class EksClusterManager
"eks", cluster.getName(), labelAccountId, clusterRegion(cluster)));
labels.put(NODE_CAPACITY_LABEL, capacityLabel(cluster, nodeLimits));
labels.put(DEFAULT_STORAGE_CLASS_LABEL, String.valueOf(defaultStorageClass));
labels.put(SHARED_MOUNTS_LABEL, "true");
if (!"localhost".equals(endpointHost)) {
labels.put(ENDPOINT_HOST_LABEL, endpointHost);
}
@@ -761,19 +764,16 @@ public class EksClusterManager
serverArgs.addAll(callerArgs);
}
if (config.services().eks().disableCni()) {
// A container's /sys mount defaults to private propagation, which breaks
// Cilium's BPF filesystem mount ("mounted on /sys but it is not a shared or
// slave mount") — real EKS/kubeadm nodes don't hit this since they're VMs,
// not nested containers. `mount --make-rshared /` before k3s starts fixes
// it; kind's own node image runs the same fix in its entrypoint for the
// same reason. RSHARE_ENTRYPOINT is POSIX sh-compatible (no bashisms) — the
// k3s image has no bash, only busybox sh.
specBuilder.withEntrypoint(RSHARE_ENTRYPOINT);
specBuilder.withCmd(buildRshareWrappedCmd(serverArgs));
} else {
specBuilder.withCmd(serverArgs);
}
// A container's mounts default to private propagation, which a pod asking for mount
// propagation cannot start on: a CSI node plugin mounts its volumes under
// /var/lib/kubelet/pods with Bidirectional propagation ("is not a shared mount"), a node
// exporter reads / with HostToContainer, and Cilium mounts its BPF filesystem on /sys
// ("is not a shared or slave mount"). An EKS node is a VM, whose mounts are shared.
// `mount --make-rshared /` before k3s starts gives the node the same; kind's own node
// image runs the same fix in its entrypoint. RSHARE_ENTRYPOINT is POSIX sh-compatible
// (no bashisms): the k3s image has no bash, only busybox sh.
specBuilder.withEntrypoint(RSHARE_ENTRYPOINT);
specBuilder.withCmd(buildRshareWrappedCmd(serverArgs));
ContainerSpec spec = specBuilder.build();
// create -> inject webhook kubeconfig -> start, so the file exists before the API server boots.
@@ -864,7 +864,10 @@ public class EksClusterManager
startCluster(cluster);
return;
}
if (capacityChanged || onAnotherNetwork(existing.get())
// A node started before its mounts were shared keeps private mounts, on which a CSI node plugin's
// Bidirectional mounts fail: it is replaced on the same data volume, as one with another capacity is.
boolean privateMounts = existingLabels == null || !"true".equals(existingLabels.get(SHARED_MOUNTS_LABEL));
if (capacityChanged || privateMounts || onAnotherNetwork(existing.get())
|| !endpointHost.equals(certificateHost(existingLabels))) {
replaceClusterContainer(cluster, null);
}
@@ -1589,20 +1592,19 @@ public class EksClusterManager
/**
* Overrides the image's default {@code ["/bin/k3s"]} entrypoint so a {@code mount
* --make-rshared /} can run immediately before k3s starts (see the disableCni branch
* in {@link #startCluster} for why). POSIX sh-compatible — the k3s image has no bash.
* A failed mount is logged to stderr rather than silently ignored, since it means the
* external CNI's BPF filesystem mount will fail later in a much more confusing way.
* --make-rshared /} can run immediately before k3s starts (see {@link #startCluster} for
* why). POSIX sh-compatible: the k3s image has no bash. A failed mount is logged to stderr
* rather than silently ignored, since it means a pod asking for mount propagation, a CSI
* node plugin or an external CNI, will fail later in a much more confusing way.
*/
static final List<String> RSHARE_ENTRYPOINT = List.of("sh", "-c",
"mount --make-rshared / || echo 'floci: WARN: mount --make-rshared / failed; "
+ "external CNI may not work' >&2; exec /bin/k3s \"$@\"");
+ "CSI drivers and an external CNI may not work' >&2; exec /bin/k3s \"$@\"");
/**
* Builds the CMD to pair with {@link #RSHARE_ENTRYPOINT}: an unused $0 placeholder
* followed by the real k3s server args, so the entrypoint's "$@" expands to exactly
* {@code serverArgs} — the same args {@code withCmd(serverArgs)} would pass directly
* when the entrypoint isn't overridden.
* {@code serverArgs}, the args the image's own {@code /bin/k3s} entrypoint would take.
*/
static List<String> buildRshareWrappedCmd(List<String> serverArgs) {
List<String> wrappedCmd = new ArrayList<>();
@@ -456,7 +456,8 @@ class EksClusterManagerTest {
"io.floci.account", "000000000000",
"io.floci.region", "us-east-1",
"io.floci.eks.node-capacity", "m5.large:unbounded",
"io.floci.eks.default-storage-class", "false"));
"io.floci.eks.default-storage-class", "false",
"io.floci.eks.shared-mounts", "true"));
}
@ParameterizedTest
@@ -491,6 +492,40 @@ class EksClusterManagerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startClusterSharesTheNodesMountsWhetherOrNotItsCniIsDisabled(boolean disableCni) {
EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
when(config.services().eks().defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
when(config.services().eks().disableCni()).thenReturn(disableCni);
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class, Mockito.RETURNS_DEEP_STUBS);
when(lifecycleManager.create(any())).thenReturn("container-id");
ContainerBuilder 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"));
EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager,
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
config, new RegionResolver("us-east-1", "000000000000"));
Cluster cluster = new Cluster();
cluster.setName("my-cluster");
manager.startCluster(cluster);
// k3s starts behind `mount --make-rshared /`, so a CSI node plugin's Bidirectional mounts
// work on every node, not only on one whose CNI is replaced.
verify(builder).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> cmdCaptor = ArgumentCaptor.forClass(List.class);
verify(builder).withCmd(cmdCaptor.capture());
assertEquals(List.of("floci-k3s", "server"), cmdCaptor.getValue().subList(0, 2));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void startClusterDefaultStorageClassFlag(boolean defaultStorageClass) {
@@ -578,13 +613,13 @@ class EksClusterManagerTest {
// Container's getters are final, so survivors are built from JSON instead of mocked.
private Container survivingContainer(String id) {
return containerFromJson("{\"Id\":\"" + id + "\","
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}");
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}");
}
private Container survivingContainerOwnedBy(String id, String accountId) {
return containerFromJson("{\"Id\":\"" + id + "\","
+ "\"Labels\":{\"io.floci.account\":\"" + accountId + "\","
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}");
+ "\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}");
}
private Container containerFromJson(String json) {
@@ -677,7 +712,7 @@ class EksClusterManagerTest {
@Test
void restoreClusterPreservesDefaultStorageClassLabelFromSurvivingContainer() {
Container container = containerFromJson("{\"Id\":\"cid-new\","
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\","
+ "\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\","
+ "\"io.floci.eks.default-storage-class\":\"false\"}}");
when(lifecycleManager.findByName("floci-eks-demo"))
.thenReturn(Optional.of(container));
@@ -742,12 +777,30 @@ class EksClusterManagerTest {
private void restoreSurvivorOn(String networks) {
when(containerBuilder.resolveDockerNetwork(Optional.empty())).thenReturn(Optional.of("floci_default"));
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"},"
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"},"
+ "\"NetworkSettings\":{\"Networks\":{" + networks + "}}}")));
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
}
@Test
void replacesASurvivorStartedBeforeItsMountsWereShared() {
// Created by an earlier Floci: no shared-mounts label, so its node's mounts are private.
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}")));
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
stubFreshStart("cid-new", 6440);
Cluster cluster = cluster();
manager.restoreCluster(cluster);
assertEquals("cid-new", cluster.getContainerId());
verify(dockerClient).stopContainerCmd("cid-old");
// The replacement is started behind the entrypoint that shares the node's mounts.
verify(containerBuilder.newContainer("rancher/k3s:v1.30.0-k3s1")).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT);
}
@Test
void recreatesASurvivorWhoseCertificateLacksTheEndpointHost() {
when(config.services().eks().endpointHost()).thenReturn(Optional.of("aws.example.test"));
@@ -769,7 +822,7 @@ class EksClusterManagerTest {
void adoptsASurvivorCreatedForTheConfiguredEndpointHost() {
when(config.services().eks().endpointHost()).thenReturn(Optional.of("aws.example.test"));
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\","
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\","
+ "\"io.floci.eks.endpoint-host\":\"aws.example.test\"}}")));
when(lifecycleManager.adopt(eq("cid-1"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512)));
@@ -785,7 +838,7 @@ class EksClusterManagerTest {
@Test
void recreatesASurvivorCreatedForAnotherEndpointHostWhenTheHostIsUnset() {
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\","
"{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\","
+ "\"io.floci.eks.endpoint-host\":\"aws.example.test\"}}")));
when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440)));
@@ -852,7 +905,8 @@ class EksClusterManagerTest {
void aSurvivorSizedFromTheConfiguredTypeIsKept() {
when(config.services().eks().nodeInstanceType()).thenReturn(Optional.of("t2.2xlarge"));
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large@t2.2xlarge:unbounded\"}}")));
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large@t2.2xlarge:unbounded\","
+ "\"io.floci.eks.shared-mounts\":\"true\"}}")));
when(lifecycleManager.adopt(eq("cid-1"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6440)));
@@ -869,7 +923,7 @@ class EksClusterManagerTest {
when(config.services().eks().endpointMode()).thenReturn("network");
when(config.services().eks().endpointHost()).thenReturn(Optional.of("aws.example.test"));
when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson(
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"}}")));
"{\"Id\":\"cid-1\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\",\"io.floci.eks.shared-mounts\":\"true\"}}")));
when(lifecycleManager.adopt(eq("cid-1"), eq(List.of(6443)), any()))
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512)));
@@ -0,0 +1,140 @@
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.eks.model.Cluster;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.RealEksProfile;
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 java.time.Duration;
import java.time.Instant;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Docker integration test verifying that a cluster's node shares its mounts as an EKS node does, so a pod asking
* for mount propagation starts: a CSI node plugin mounts its volumes under {@code /var/lib/kubelet/pods} with
* {@code Bidirectional} propagation, and a node exporter reads the node's {@code /} with {@code HostToContainer}.
* On a node whose mounts are private, containerd refuses both ("is not a shared mount").
*
* <p>The cluster is started through {@link EksClusterManager} directly and runs on {@link RealEksProfile} with the
* other classes that run a real cluster.
*/
@QuarkusTest
@TestProfile(RealEksProfile.class)
class EksNodeMountPropagationDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksNodeMountPropagationDockerIntegrationTest.class);
private static final String ACCOUNT = "000000000000";
private static final String POD = "mount-propagation";
@Inject
DockerClient dockerClient;
@Inject
EksClusterManager eksClusterManager;
private Cluster cluster;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker daemon must be available for EKS mount propagation test");
}
@AfterEach
void tearDown() {
if (cluster != null) {
try {
eksClusterManager.stopCluster(cluster);
} catch (Exception e) {
LOG.warnv(e, "Failed to stop test cluster {0}", cluster.getName());
}
}
}
@Test
void aPodAskingForMountPropagationStartsOnTheNode() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String clusterName = "mount-prop-" + suffix;
cluster = new Cluster();
cluster.setName(clusterName);
cluster.setAccountId(ACCOUNT);
cluster.setArn("arn:aws:eks:us-east-1:" + ACCOUNT + ":cluster/" + clusterName);
cluster.setCreatedAt(Instant.now());
cluster.setRoleArn("arn:aws:iam::" + ACCOUNT + ":role/eks-service-role");
eksClusterManager.startCluster(cluster);
assertNotNull(cluster.getContainerId(), "Container ID must not be null");
String containerId = cluster.getContainerId();
await("k3s API server ready").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2))
.until(() -> eksClusterManager.isReady(cluster));
eksClusterManager.finalizeCluster(cluster);
await("default serviceaccount created").atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofSeconds(2))
.until(() -> kubectl(containerId, "get", "serviceaccount", "default").exitCode() == 0);
String podYaml = """
apiVersion: v1
kind: Pod
metadata:
name: %s
namespace: default
spec:
containers:
- name: plugin
image: alpine:3.21
command: ["sleep", "3600"]
securityContext:
privileged: true
volumeMounts:
- name: kubelet-pods
mountPath: /var/lib/kubelet/pods
mountPropagation: Bidirectional
- name: node-root
mountPath: /host/root
mountPropagation: HostToContainer
readOnly: true
volumes:
- name: kubelet-pods
hostPath:
path: /var/lib/kubelet/pods
type: Directory
- name: node-root
hostPath:
path: /
""".formatted(POD);
ContainerExec.Result applied = exec(containerId, "sh", "-c",
"cat << 'EOF' | kubectl apply -f -\n" + podYaml + "\nEOF");
assertEquals(0, applied.exitCode(), "kubectl apply failed: " + applied.stderr());
await("mount propagation pod running").atMost(Duration.ofSeconds(90)).pollInterval(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals("Running",
kubectl(containerId, "get", "pod", POD, "-o", "jsonpath={.status.phase}").stdout().trim(),
() -> "the pod must start, but its container reports: " + kubectl(containerId, "get", "pod",
POD, "-o", "jsonpath={.status.containerStatuses[0].state}").stdout()));
}
private ContainerExec.Result kubectl(String containerId, String... args) {
String[] cmd = new String[args.length + 1];
cmd[0] = "kubectl";
System.arraycopy(args, 0, cmd, 1, args.length);
return exec(containerId, cmd);
}
private ContainerExec.Result exec(String containerId, String... cmd) {
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
}
}