diff --git a/docs/services/eks.md b/docs/services/eks.md index 5bd656cee3..dcae6af7b2 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -702,6 +702,17 @@ Stock Amazon EKS clusters historically define a default `gp2` StorageClass point 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. +An [EKS Auto Mode](https://docs.aws.amazon.com/eks/latest/userguide/automode.html) cluster with block storage enabled (`storageConfig.blockStorage.enabled`) provisions the claims of a StorageClass whose provisioner is `ebs.csi.eks.amazonaws.com`, as Auto Mode's EBS capability does. Floci serves them from the node's disk with a local-path provisioner registered under that name (`FLOCI_SERVICES_EKS_BLOCK_STORAGE_PROVISIONER_IMAGE`), installed while block storage is enabled. As on AWS, the cluster gets no StorageClass; create one naming the provisioner: + +```yaml +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: auto-ebs-sc +provisioner: ebs.csi.eks.amazonaws.com +volumeBindingMode: WaitForFirstConsumer +``` + 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. ## Joining EC2 instances as cluster nodes @@ -763,6 +774,8 @@ does not enable it; omitted or false values keep the simulated behavior. | `FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR` | `true` | Inject a containerd `registries.yaml` so pods can pull images pushed to [Floci ECR](ecr.md) | | `FLOCI_SERVICES_EKS_DISABLE_CNI` | `false` | Start k3s without bundled flannel, network policy, and kube-proxy so an external CNI can take over | | `FLOCI_SERVICES_EKS_DEFAULT_STORAGE_CLASS` | `false` | Retain k3s bundled local-path provisioner and default StorageClass (default false matches EKS with no default class) | +| `FLOCI_SERVICES_EKS_BLOCK_STORAGE_PROVISIONER_IMAGE` | `rancher/local-path-provisioner:v0.0.35` | Provisioner that serves EKS Auto Mode block storage (`ebs.csi.eks.amazonaws.com`) | +| `FLOCI_SERVICES_EKS_BLOCK_STORAGE_HELPER_IMAGE` | `rancher/mirrored-library-busybox:1.37.0` | Helper pod image of that provisioner | | `FLOCI_SERVICES_EKS_IRSA_SIGNING_KEY` | `true` | Pass the cluster OIDC signing key to k3s so in-cluster projected service account tokens can assume IAM roles via Floci STS | | `FLOCI_SERVICES_EKS_POD_IDENTITY_WEBHOOK` | `true` | Register a mutating admission webhook that injects pod identity credentials. Needs `FLOCI_TLS_ENABLED=true` | | `FLOCI_SERVICES_EKS_IMDS` | `false` | Enable link-local IMDS (`169.254.169.254`) proxy in cluster containers | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index ad67e2e05c..4677a4c5f9 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -4301,6 +4301,19 @@ public interface EmulatorConfig { @WithDefault("false") boolean defaultStorageClass(); + /** + * The local-path provisioner image that serves EKS Auto Mode block storage: while a cluster's + * {@code storageConfig.blockStorage} is enabled, claims of a StorageClass whose provisioner is + * {@code ebs.csi.eks.amazonaws.com} are provisioned from the node's disk by it. The default is the version + * k3s v1.36.0+k3s1 bundles. + */ + @WithDefault("rancher/local-path-provisioner:v0.0.35") + String blockStorageProvisionerImage(); + + /** The image of the helper pods that {@link #blockStorageProvisionerImage()} runs to create and remove volumes. */ + @WithDefault("rancher/mirrored-library-busybox:1.37.0") + String blockStorageHelperImage(); + /** * When true, exposes an IMDS link-local proxy (169.254.169.254:80) inside the cluster container's * network namespace that relays to Floci's EC2 metadata service. diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index 749b2733ae..20663a87a4 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -77,6 +77,7 @@ import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.Inet4Address; import java.net.Inet6Address; @@ -172,6 +173,13 @@ public class EksClusterManager # Floci registers no EKS Pod Identity webhook for this cluster now; its log says why. # k3s deletes the MutatingWebhookConfiguration an earlier version of this file created. """; + static final String BLOCK_STORAGE_MANIFEST_FILE = "floci-eks-auto-mode-block-storage.yaml"; + static final String BLOCK_STORAGE_MANIFEST_TAR_ENTRY = "server/manifests/" + BLOCK_STORAGE_MANIFEST_FILE; + // The manifest once block storage is off: no objects, so k3s deletes the provisioner it held before. + static final String BLOCK_STORAGE_MANIFEST_REMOVED = """ + # EKS Auto Mode block storage is off for this cluster. + # k3s deletes the provisioner an earlier version of this file created. + """; private static final String ENDPOINT_MODE_NETWORK = "network"; public static final String DEFAULT_POD_CIDR = "10.42.0.0/16"; @@ -1007,6 +1015,7 @@ public class EksClusterManager injectEcrRegistryMirror(containerId, cluster, registries); linkContainerdCertsDir(containerId, cluster.getName()); registerPodIdentityWebhook(containerId, cluster); + applyBlockStorage(containerId, cluster); if (signingKeyFiles != null) { copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName()); } @@ -1164,6 +1173,7 @@ public class EksClusterManager // The manifest written at creation names the address and certificate Floci had then. registerPodIdentityWebhook(info.containerId(), cluster, () -> survivingNodeResolvesThroughFloci(info.containerId())); + applyBlockStorage(info.containerId(), cluster); activeClusters.put(clusterResourceName(cluster), cluster); attachClusterLogs(cluster, true, true, false); @@ -3000,13 +3010,62 @@ public class EksClusterManager } private void installPodIdentityManifest(String containerId, Cluster cluster, String manifest) { - writeLocalCopy(localClusterFile(cluster, "webhook", POD_IDENTITY_MANIFEST_FILE), manifest, cluster.getName()); - byte[] tar = tarSingleFile(POD_IDENTITY_MANIFEST_TAR_ENTRY, manifest); + installManifest(containerId, cluster, "webhook", POD_IDENTITY_MANIFEST_FILE, POD_IDENTITY_MANIFEST_TAR_ENTRY, + manifest); + } + + /** + * Writes {@code manifest} into the k3s container's {@code server/manifests}, which k3s applies, and keeps a + * local copy under {@code //...} for {@link #localClusterFile}. + */ + private void installManifest(String containerId, Cluster cluster, String kind, String fileName, String tarEntry, + String manifest) { + writeLocalCopy(localClusterFile(cluster, kind, fileName), manifest, cluster.getName()); + byte[] tar = tarSingleFile(tarEntry, manifest); RetryingTarCopier.copyStreamed(lifecycleManager.getDockerClient(), containerId, K3S_DATA_DIR, - POD_IDENTITY_MANIFEST_FILE, out -> out.write(tar), + fileName, out -> out.write(tar), RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis); } + /** + * Installs the EKS Auto Mode block storage provisioner while the cluster's {@code storageConfig.blockStorage} is + * enabled: claims of a StorageClass naming {@code ebs.csi.eks.amazonaws.com} are then provisioned from the + * node's disk. Otherwise, if it was installed before, replaces it with {@link #BLOCK_STORAGE_MANIFEST_REMOVED}: + * the manifest lives on the cluster's data volume, which outlives a restart, and k3s prunes what it created. + */ + void applyBlockStorage(String containerId, Cluster cluster) { + boolean enabled = cluster.getStorageConfig() != null && cluster.getStorageConfig().blockStorage() != null + && Boolean.TRUE.equals(cluster.getStorageConfig().blockStorage().enabled()); + try { + if (!enabled && !Files.exists(localClusterFile(cluster, "auto-mode", BLOCK_STORAGE_MANIFEST_FILE))) { + return; + } + installManifest(containerId, cluster, "auto-mode", BLOCK_STORAGE_MANIFEST_FILE, + BLOCK_STORAGE_MANIFEST_TAR_ENTRY, enabled ? blockStorageManifest() : BLOCK_STORAGE_MANIFEST_REMOVED); + if (enabled) { + LOG.infov("Installed the EKS Auto Mode block storage provisioner for cluster {0}", cluster.getName()); + } + } catch (Exception e) { + LOG.warnv("EKS cluster {0} gets no Auto Mode block storage: could not install {1} into the k3s " + + "container: {2}", cluster.getName(), BLOCK_STORAGE_MANIFEST_FILE, e.getMessage()); + } + } + + /** The block storage manifest with the configured provisioner and helper images. */ + String blockStorageManifest() { + // An inline literal, which the native image build finds and packages. + try (InputStream in = EksClusterManager.class.getResourceAsStream("/eks/auto-mode-block-storage.yaml")) { + if (in == null) { + throw new IllegalStateException("missing resource /eks/auto-mode-block-storage.yaml"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8) + .replace("%PROVISIONER_IMAGE%", config.services().eks().blockStorageProvisionerImage()) + .replace("%HELPER_IMAGE%", config.services().eks().blockStorageHelperImage()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + /** * Whether an adopted node resolves through Floci's DNS server. A container keeps the resolvers it was * created with, so a node created while that server was off or out of its reach cannot find Floci's diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java index 6a00750495..b9c12d5aa2 100644 --- a/src/main/java/io/floci/aws/services/eks/EksService.java +++ b/src/main/java/io/floci/aws/services/eks/EksService.java @@ -1148,6 +1148,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun + "change the supportType", 400); } AutoMode nextAutoMode = request.changesAutoMode() ? requireAutoModeChange(cluster, request) : null; + // Read before the write below, which may change this very object. + boolean blockStorageWasOn = blockStorageOn(cluster.getStorageConfig()); Boolean finalPublicAccess = publicAccess; Boolean finalPrivateAccess = privateAccess; @@ -1203,6 +1205,11 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun + "logging, accessConfig.authenticationMode, upgradePolicy.supportType and the EKS Auto Mode " + "configuration only", 400); } + if (nextAutoMode != null && blockStorageOn(nextAutoMode.storage()) != blockStorageWasOn + && !config.services().eks().mock() && clusterManager != null && cluster.getContainerId() != null) { + // The running node gets the block storage provisioner, or loses it, as it would when it next starts. + clusterManager.applyBlockStorage(cluster.getContainerId(), requireClusterInRequestRegion(name)); + } LOG.infov("Updated the configuration of EKS cluster {0}: {1}", cluster.getName(), updates.stream().map(Update::type).toList()); return updates; @@ -1253,6 +1260,10 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun } } + private static boolean blockStorageOn(StorageConfig storage) { + return storage != null && storage.blockStorage() != null && Boolean.TRUE.equals(storage.blockStorage().enabled()); + } + private static AutoMode autoMode(Cluster cluster) { return new AutoMode(cluster.getComputeConfig(), cluster.getStorageConfig(), elasticLoadBalancing(cluster.getKubernetesNetworkConfig())); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7861108f25..29e2eec2da 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -967,6 +967,8 @@ floci: ecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECR disable-cni: false # start k3s without its bundled flannel/kube-proxy so a real CNI (e.g. Cilium) can take over default-storage-class: false # start k3s without its bundled local-path provisioner to match EKS + block-storage-provisioner-image: rancher/local-path-provisioner:v0.0.35 # serves EKS Auto Mode block storage (ebs.csi.eks.amazonaws.com) + block-storage-helper-image: rancher/mirrored-library-busybox:1.37.0 # its helper pods imds: false # expose link-local IMDS (169.254.169.254) inside the cluster container imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true) vpc-pod-network: false # give pods addresses from /28 prefixes of the node's subnet, as VPC CNI prefix delegation does diff --git a/src/main/resources/eks/auto-mode-block-storage.yaml b/src/main/resources/eks/auto-mode-block-storage.yaml new file mode 100644 index 0000000000..47ea3675e2 --- /dev/null +++ b/src/main/resources/eks/auto-mode-block-storage.yaml @@ -0,0 +1,133 @@ +# EKS Auto Mode block storage, installed by Floci while the cluster's storageConfig.blockStorage is enabled. +# Claims of a StorageClass whose provisioner is ebs.csi.eks.amazonaws.com, the name Auto Mode's EBS provisioner +# answers to, are served by the local-path provisioner from the node's disk. As on AWS, no StorageClass is created. +# Adapted from k3s's manifests/local-storage.yaml (v1.36.0+k3s1, Apache-2.0); every object has its own name, so it +# runs beside k3s's bundled provisioner when floci.services.eks.default-storage-class keeps that one. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: floci-auto-mode-ebs-provisioner + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: floci-auto-mode-ebs-provisioner +rules: +- apiGroups: [""] + resources: ["nodes", "persistentvolumeclaims", "configmaps", "pods/log"] + verbs: ["get", "list", "watch"] +- apiGroups: [""] + resources: ["endpoints", "persistentvolumes", "pods"] + verbs: ["*"] +- apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +- apiGroups: ["storage.k8s.io"] + resources: ["storageclasses"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: floci-auto-mode-ebs-provisioner +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: floci-auto-mode-ebs-provisioner +subjects: +- kind: ServiceAccount + name: floci-auto-mode-ebs-provisioner + namespace: kube-system +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: floci-auto-mode-ebs-provisioner + namespace: kube-system +spec: + revisionHistoryLimit: 0 + strategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 + selector: + matchLabels: + app: floci-auto-mode-ebs-provisioner + template: + metadata: + labels: + app: floci-auto-mode-ebs-provisioner + spec: + priorityClassName: "system-node-critical" + serviceAccountName: floci-auto-mode-ebs-provisioner + tolerations: + - key: "CriticalAddonsOnly" + operator: "Exists" + - key: "node-role.kubernetes.io/control-plane" + operator: "Exists" + effect: "NoSchedule" + nodeSelector: + kubernetes.io/os: linux + containers: + - name: provisioner + image: "%PROVISIONER_IMAGE%" + imagePullPolicy: IfNotPresent + command: + - local-path-provisioner + - start + - --config + - /etc/config/config.json + - --provisioner-name + - ebs.csi.eks.amazonaws.com + - --configmap-name + - floci-auto-mode-ebs-provisioner + - --service-account-name + - floci-auto-mode-ebs-provisioner + volumeMounts: + - name: config-volume + mountPath: /etc/config/ + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + volumes: + - name: config-volume + configMap: + name: floci-auto-mode-ebs-provisioner +--- +kind: ConfigMap +apiVersion: v1 +metadata: + name: floci-auto-mode-ebs-provisioner + namespace: kube-system +data: + config.json: |- + { + "nodePathMap":[ + { + "node":"DEFAULT_PATH_FOR_NON_LISTED_NODES", + "paths":["/var/lib/rancher/k3s/storage/ebs"] + } + ] + } + setup: |- + #!/bin/sh + set -eu + mkdir -m 0777 -p "${VOL_DIR}" + chmod 700 "${VOL_DIR}/.." + teardown: |- + #!/bin/sh + set -eu + rm -rf "${VOL_DIR}" + helperPod.yaml: |- + apiVersion: v1 + kind: Pod + metadata: + name: helper-pod + spec: + containers: + - name: helper-pod + image: "%HELPER_IMAGE%" + imagePullPolicy: IfNotPresent diff --git a/src/test/java/io/floci/aws/services/eks/EksAutoModeBlockStorageDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksAutoModeBlockStorageDockerIntegrationTest.java new file mode 100644 index 0000000000..a015f93a57 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksAutoModeBlockStorageDockerIntegrationTest.java @@ -0,0 +1,133 @@ +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.BlockStorage; +import io.floci.aws.services.eks.model.Cluster; +import io.floci.aws.services.eks.model.StorageConfig; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EksTestNode; +import io.floci.aws.testing.RdsMockProfile; +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.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * EKS Auto Mode block storage on a real k3s node: with {@code storageConfig.blockStorage} enabled, a claim of a + * StorageClass whose provisioner is {@code ebs.csi.eks.amazonaws.com} is bound to a volume that provisioner made; + * without it, no provisioner answers to that name. Runs on {@link RdsMockProfile} with the other classes that run a + * real cluster. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class EksAutoModeBlockStorageDockerIntegrationTest { + + private static final Logger LOG = Logger.getLogger(EksAutoModeBlockStorageDockerIntegrationTest.class); + private static final String ACCOUNT = "000000000000"; + private static final String PROVISIONER = "floci-auto-mode-ebs-provisioner"; + + @Inject + DockerClient dockerClient; + + @Inject + EksClusterManager eksClusterManager; + + private Cluster cluster; + + @BeforeEach + void requireDocker() { + boolean dockerAvailable = DockerAvailability.answers(dockerClient); + if (!dockerAvailable) { + LOG.warn("Docker daemon is not available; skipping EksAutoModeBlockStorageDockerIntegrationTest"); + } + Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for the Auto Mode block storage test"); + } + + @AfterEach + void tearDown() { + if (cluster != null) { + try { + eksClusterManager.stopCluster(cluster); + } catch (Exception e) { + LOG.warnv("Failed to stop test cluster: {0}", e.getMessage()); + } + } + } + + @Test + void aClaimOfTheAutoModeProvisionerIsBoundWhileBlockStorageIsEnabled() { + cluster = EksTestNode.cluster(ACCOUNT, "ebs-on-" + UUID.randomUUID().toString().substring(0, 8)); + cluster.setStorageConfig(new StorageConfig(new BlockStorage(true))); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90)); + + node.apply(""" + apiVersion: storage.k8s.io/v1 + kind: StorageClass + metadata: + name: auto-ebs-sc + provisioner: ebs.csi.eks.amazonaws.com + volumeBindingMode: WaitForFirstConsumer + --- + apiVersion: v1 + kind: PersistentVolumeClaim + metadata: + name: data + namespace: default + spec: + storageClassName: auto-ebs-sc + accessModes: ["ReadWriteOnce"] + resources: + requests: + storage: 1Gi + --- + apiVersion: v1 + kind: Pod + metadata: + name: writer + namespace: default + spec: + containers: + - name: writer + image: rancher/mirrored-library-busybox:1.37.0 + command: ["sh", "-c", "echo stored > /data/file && sleep 3600"] + volumeMounts: + - name: data + mountPath: /data + volumes: + - name: data + persistentVolumeClaim: + claimName: data"""); + + await("claim bound").atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofSeconds(3)) + .until(() -> "Bound".equals(node.kubectlOutput("get", "pvc", "data", "-n", "default", + "-o", "jsonpath={.status.phase}"))); + String volume = node.kubectlOutput("get", "pvc", "data", "-n", "default", "-o", "jsonpath={.spec.volumeName}"); + assertEquals("ebs.csi.eks.amazonaws.com", node.kubectlOutput("get", "pv", volume, + "-o", "jsonpath={.metadata.annotations.pv\\.kubernetes\\.io/provisioned-by}")); + await("pod wrote to the volume").atMost(Duration.ofMinutes(2)).pollInterval(Duration.ofSeconds(3)) + .until(() -> node.kubectl("exec", "writer", "-n", "default", "--", "cat", "/data/file") + .stdout().trim().equals("stored")); + } + + @Test + void noProvisionerAnswersToTheAutoModeNameWithoutBlockStorage() { + cluster = EksTestNode.cluster(ACCOUNT, "ebs-off-" + UUID.randomUUID().toString().substring(0, 8)); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90)); + + ContainerExec.Result deployment = node.kubectl("get", "deployment", PROVISIONER, "-n", "kube-system"); + assertEquals(1, deployment.exitCode(), deployment.summary()); + assertEquals("Error from server (NotFound): deployments.apps \"" + PROVISIONER + "\" not found", + deployment.stderr().trim()); + } +} diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 200760f174..8b0e8c9c3f 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -55,6 +55,7 @@ import io.floci.aws.services.ec2.model.Placement; import io.floci.aws.services.ec2.net.VpcNetworkManager; import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; import io.floci.aws.services.ecr.registry.EcrRegistryManager; +import io.floci.aws.services.eks.model.BlockStorage; import io.floci.aws.services.eks.model.CertificateAuthority; import io.floci.aws.services.eks.model.Cluster; import io.floci.aws.services.eks.model.ClusterIdentity; @@ -64,6 +65,7 @@ import io.floci.aws.services.eks.model.Logging; import io.floci.aws.services.eks.model.Nodegroup; import io.floci.aws.services.eks.model.OidcIdentity; import io.floci.aws.services.eks.model.ResourcesVpcConfig; +import io.floci.aws.services.eks.model.StorageConfig; import io.floci.aws.testing.ThreadStates; import io.floci.aws.testutil.LogCapture; import jakarta.ws.rs.core.Response; @@ -565,6 +567,25 @@ class EksClusterManagerTest { assertEquals(List.of("floci-k3s", "server"), cmdCaptor.getValue().subList(0, 2)); } + @Test + void theBlockStorageManifestRunsTheConfiguredImagesUnderTheAutoModeProvisionerName() { + EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS); + when(config.services().eks().blockStorageProvisionerImage()).thenReturn("mirror.test/local-path:v1"); + when(config.services().eks().blockStorageHelperImage()).thenReturn("mirror.test/busybox:v2"); + EksClusterManager manager = EksClusterManagers.create(Mockito.mock(ContainerBuilder.class), + Mockito.mock(ContainerLifecycleManager.class), Mockito.mock(ContainerDetector.class), + Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), + Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000")); + + String manifest = manager.blockStorageManifest(); + + assertTrue(manifest.contains("image: \"mirror.test/local-path:v1\""), manifest); + assertTrue(manifest.contains("image: \"mirror.test/busybox:v2\""), manifest); + assertTrue(manifest.contains("- --provisioner-name\n - ebs.csi.eks.amazonaws.com\n"), manifest); + assertFalse(manifest.contains("%"), manifest); + assertFalse(manifest.contains("kind: StorageClass"), manifest); + } + @ParameterizedTest @ValueSource(booleans = {true, false}) void startClusterDefaultStorageClassFlag(boolean defaultStorageClass) { @@ -4274,6 +4295,45 @@ class EksClusterManagerTest { reachableEndpoint); } + @Test + void aClusterThatHadTheBlockStorageProvisionerGetsTheEmptyManifestOnceBlockStorageIsOff() throws Exception { + Path localCopy = blockStorageCopy(); + Files.createDirectories(localCopy.getParent()); + Files.writeString(localCopy, "kind: Deployment\n"); + + manager.applyBlockStorage("container-1", cluster()); + + verify(dockerClient).copyArchiveToContainerCmd("container-1"); + verify(copyCmd).withRemotePath("/var/lib/rancher/k3s"); + assertEquals(EksClusterManager.BLOCK_STORAGE_MANIFEST_REMOVED, Files.readString(localCopy)); + } + + @Test + void aClusterThatNeverHadTheBlockStorageProvisionerGetsNoCopy() { + manager.applyBlockStorage("container-1", cluster()); + + verify(dockerClient, never()).copyArchiveToContainerCmd(anyString()); + assertFalse(Files.exists(blockStorageCopy())); + } + + @Test + void aClusterWithBlockStorageGetsTheProvisioner() throws Exception { + when(eks.blockStorageProvisionerImage()).thenReturn("rancher/local-path-provisioner:v0.0.35"); + when(eks.blockStorageHelperImage()).thenReturn("rancher/mirrored-library-busybox:1.37.0"); + Cluster cluster = cluster(); + cluster.setStorageConfig(new StorageConfig(new BlockStorage(true))); + + manager.applyBlockStorage("container-1", cluster); + + verify(dockerClient).copyArchiveToContainerCmd("container-1"); + assertEquals(manager.blockStorageManifest(), Files.readString(blockStorageCopy())); + } + + private Path blockStorageCopy() { + return tempDir.resolve("auto-mode/000000000000/us-east-1/demo") + .resolve(EksClusterManager.BLOCK_STORAGE_MANIFEST_FILE); + } + private String writtenManifest() throws Exception { return Files.readString(tempDir.resolve("webhook/000000000000/us-east-1/demo") .resolve("floci-eks-pod-identity.yaml")); diff --git a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java index 5632c11041..16bb63cf02 100644 --- a/src/test/java/io/floci/aws/services/eks/EksServiceTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksServiceTest.java @@ -403,6 +403,45 @@ class EksServiceTest { assertTrue(oidcService.findVerificationKey(issuer).isPresent()); } + @Test + void turningAutoModeOnGivesTheRunningNodeBlockStorageAndAPoolChangeDoesNotReapplyIt() { + StorageBackend rawClusters = new InMemoryStorage<>(); + AccountAwareStorageBackend clusterStore = new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"); + Cluster running = new Cluster(); + running.setName("auto-running"); + running.setArn("arn:aws:eks:us-east-1:000000000000:cluster/auto-running"); + running.setStatus(ClusterStatus.ACTIVE); + running.setContainerId("k3s-auto-running"); + running.setKubernetesNetworkConfig(new KubernetesNetworkConfig()); + clusterStore.putForAccount("000000000000", EksService.clusterKey("us-east-1", "auto-running"), running); + EksClusterManager clusterManager = mock(EksClusterManager.class); + EksAddonService addons = mock(EksAddonService.class); + when(addons.recordUpdate(any(), anyString(), any(), any(), any())) + .thenReturn(new Update("u", "Successful", "AutoModeUpdate", List.of(), 0, List.of())); + EksService service = new EksService(fixedStorageFactory(clusterStore), testConfig(false), + new RegionResolver("us-east-1", "000000000000"), clusterManager, null, + new EksOidcService(fixedStorageFactory(new InMemoryStorage()), + new ObjectMapper()), mock(EksAccessEntryService.class), + mock(EksPodIdentityAssociationService.class), addons); + KubernetesNetworkConfig loadBalancing = new KubernetesNetworkConfig(); + loadBalancing.setElasticLoadBalancing(new ElasticLoadBalancing(true)); + String nodeRole = "arn:aws:iam::000000000000:role/eks-auto-node"; + + service.updateClusterConfig("auto-running", new UpdateClusterConfigRequest(null, null, null, null, null, + new ComputeConfig(true, List.of("general-purpose", "system"), nodeRole), + new StorageConfig(new BlockStorage(true)), loadBalancing)); + + ArgumentCaptor applied = ArgumentCaptor.forClass(Cluster.class); + verify(clusterManager).applyBlockStorage(eq("k3s-auto-running"), applied.capture()); + assertEquals(Boolean.TRUE, applied.getValue().getStorageConfig().blockStorage().enabled()); + + service.updateClusterConfig("auto-running", new UpdateClusterConfigRequest(null, null, null, null, null, + new ComputeConfig(true, List.of("general-purpose"), nodeRole), + new StorageConfig(new BlockStorage(true)), loadBalancing)); + + verify(clusterManager, times(1)).applyBlockStorage(anyString(), any()); + } + @Test void initRestoresPersistedClustersAfterARestart() { // A cluster restored from eks-clusters.json after a Floci/Docker restart (#2609) has no