From f89fa536f02e9c9a6122a61984e496d2f1b5bcd3 Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:10:12 +0100 Subject: [PATCH] test(eks): move the IRSA, storage class and registry host Docker tests onto EksTestNode (#8843) --- .../eks/EksIrsaDockerIntegrationTest.java | 158 +++-------------- ...EksRegistryHostsDockerIntegrationTest.java | 167 ++++++------------ .../EksStorageClassDockerIntegrationTest.java | 92 +++------- .../io/floci/aws/testing/EksTestNode.java | 36 +++- 4 files changed, 135 insertions(+), 318 deletions(-) diff --git a/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java index 6faab86293..d28819fdb1 100644 --- a/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksIrsaDockerIntegrationTest.java @@ -1,10 +1,11 @@ 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.services.eks.model.ClusterIdentity; import io.floci.aws.services.eks.model.OidcIdentity; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EksTestNode; import io.floci.aws.testing.S3IamEnforcementProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -15,7 +16,7 @@ import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Instant; +import java.time.Duration; import java.util.UUID; import static io.restassured.RestAssured.given; @@ -24,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * Docker integration test for EKS IRSA: verifies that k3s signs projected service account tokens @@ -56,6 +56,8 @@ class EksIrsaDockerIntegrationTest { "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/iam/aws4_request, " + "SignedHeaders=host, Signature=setup"; private static final String ACCOUNT = "000000000000"; + private static final String POD = "irsa-workload-pod"; + private static final Duration API_SERVER_TIMEOUT = Duration.ofSeconds(60); @Inject DockerClient dockerClient; @@ -73,7 +75,7 @@ class EksIrsaDockerIntegrationTest { @BeforeEach void requireDocker() { - boolean dockerAvailable = isDockerAvailable(); + boolean dockerAvailable = DockerAvailability.answers(dockerClient); if (!dockerAvailable) { LOG.warn("Docker daemon is not available; skipping EksIrsaDockerIntegrationTest"); } @@ -101,63 +103,27 @@ class EksIrsaDockerIntegrationTest { } @Test - void projectedServiceAccountTokenAssumesRoleAndEnforcesPolicy() throws Exception { + void projectedServiceAccountTokenAssumesRoleAndEnforcesPolicy() { String suffix = UUID.randomUUID().toString().substring(0, 8); String clusterName = "irsa-dock-" + suffix; roleName = "irsa-dock-role-" + suffix; wrongSubjectRoleName = "irsa-dock-wrong-sub-" + suffix; wrongClusterRoleName = "irsa-dock-wrong-clus-" + 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"); - + cluster = EksTestNode.cluster(ACCOUNT, clusterName); String issuer = oidcService.newIssuerUrl("us-east-1"); cluster.setIdentity(new ClusterIdentity( new OidcIdentity(issuer))); oidcService.ensureKeyForAccount(ACCOUNT, EksService.clusterKey("us-east-1", clusterName), issuer); - eksClusterManager.startCluster(cluster); - assertNotNull(cluster.getContainerId(), "Container ID must not be null"); - - // Wait for k3s API server readiness (up to 60s) - long deadline = System.currentTimeMillis() + 60000; - boolean ready = false; - while (System.currentTimeMillis() < deadline) { - if (eksClusterManager.isReady(cluster)) { - ready = true; - break; - } - Thread.sleep(2000); - } - assertTrue(ready, "k3s API server must become ready within 60 seconds"); - eksClusterManager.finalizeCluster(cluster); - - String containerId = cluster.getContainerId(); - - // Wait for default serviceaccount to be created by controller manager (up to 30s) - long saDeadline = System.currentTimeMillis() + 30000; - boolean saReady = false; - while (System.currentTimeMillis() < saDeadline) { - ContainerExec.Result saResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "serviceaccount", "default"}); - if (saResult.exitCode() == 0) { - saReady = true; - break; - } - Thread.sleep(1000); - } - assertTrue(saReady, "default serviceaccount must be created within 30 seconds"); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT); // Create a pod with a projected service account token with audience sts.amazonaws.com - String podYaml = """ + node.apply(""" apiVersion: v1 kind: Pod metadata: - name: irsa-workload-pod + name: %s namespace: default spec: containers: @@ -176,57 +142,28 @@ class EksIrsaDockerIntegrationTest { path: token expirationSeconds: 86400 audience: sts.amazonaws.com - """; - - execInContainer(containerId, new String[]{"sh", "-c", - "cat << 'EOF' | kubectl apply -f -\n" + podYaml + "\nEOF"}); - - // Wait for the pod to be running (up to 45s) - long podDeadline = System.currentTimeMillis() + 45000; - boolean podRunning = false; - while (System.currentTimeMillis() < podDeadline) { - ContainerExec.Result statusResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "pod", "irsa-workload-pod", "-o", "jsonpath={.status.phase}"}); - if ("Running".equalsIgnoreCase(statusResult.stdout().trim())) { - podRunning = true; - break; - } - Thread.sleep(2000); - } - assertTrue(podRunning, "irsa-workload-pod must reach Running state"); + """.formatted(POD)); + node.awaitPodRunning(POD, Duration.ofSeconds(45)); // The pod is Running, so it was scheduled onto the node, which the kubelet // registered with its provider ID: the node is guaranteed to exist here. - ContainerExec.Result nodeResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "nodes", "-o", "jsonpath={.items[0].spec.providerID}"}); - assertEquals(0, nodeResult.exitCode(), "kubectl get nodes failed"); - assertEquals(eksClusterManager.deriveClusterNodeProviderId(cluster), nodeResult.stdout().trim(), + assertEquals(eksClusterManager.deriveClusterNodeProviderId(cluster), + node.kubectlOutput("get", "nodes", "-o", "jsonpath={.items[0].spec.providerID}"), "Node providerID must match the derived AWS provider ID"); - - ContainerExec.Result nodeNameResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "nodes", "-o", "jsonpath={.items[0].metadata.name}"}); - assertEquals(0, nodeNameResult.exitCode(), "kubectl get nodes failed"); - assertEquals(eksClusterManager.deriveClusterNodePrivateDnsName(cluster), nodeNameResult.stdout().trim(), + assertEquals(eksClusterManager.deriveClusterNodePrivateDnsName(cluster), + node.kubectlOutput("get", "nodes", "-o", "jsonpath={.items[0].metadata.name}"), "Node name must match the derived cluster node private DNS name"); - - ContainerExec.Result zoneResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "nodes", "-o", - "jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/zone}"}); - assertEquals(0, zoneResult.exitCode(), "kubectl get nodes failed"); - assertEquals(eksClusterManager.deriveClusterNodeAvailabilityZone(cluster), zoneResult.stdout().trim(), + assertEquals(eksClusterManager.deriveClusterNodeAvailabilityZone(cluster), + node.kubectlOutput("get", "nodes", "-o", + "jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/zone}"), "Node topology zone label must match the derived availability zone"); - - ContainerExec.Result regionResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "nodes", "-o", - "jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/region}"}); - assertEquals(0, regionResult.exitCode(), "kubectl get nodes failed"); - assertEquals(eksClusterManager.clusterRegion(cluster), regionResult.stdout().trim(), + assertEquals(eksClusterManager.clusterRegion(cluster), + node.kubectlOutput("get", "nodes", "-o", + "jsonpath={.items[0].metadata.labels.topology\\.kubernetes\\.io/region}"), "Node topology region label must match the cluster region"); // Extract the projected token from the pod volume - String token = execInContainer(containerId, - new String[]{"kubectl", "exec", "irsa-workload-pod", "--", "cat", "/var/run/secrets/tokens/token"}).trim(); - assertNotNull(token); + String token = node.kubectlOutput("exec", POD, "--", "cat", "/var/run/secrets/tokens/token"); assertFalse(token.isBlank(), "Projected service account token must not be blank"); // Create IAM role with federated trust policy matching cluster issuer and subject @@ -321,30 +258,14 @@ class EksIrsaDockerIntegrationTest { // 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 + String containerId = node.containerId(); dockerClient.stopContainerCmd(containerId).exec(); dockerClient.removeContainerCmd(containerId).exec(); - eksClusterManager.startCluster(cluster); - String recreatedContainerId = cluster.getContainerId(); - assertNotNull(recreatedContainerId); - assertNotEquals(containerId, recreatedContainerId); - - long recreateDeadline = System.currentTimeMillis() + 60000; - boolean recreateReady = false; - while (System.currentTimeMillis() < recreateDeadline) { - if (eksClusterManager.isReady(cluster)) { - recreateReady = true; - break; - } - Thread.sleep(2000); - } - assertTrue(recreateReady, "k3s API server must become ready after container recreation"); - eksClusterManager.finalizeCluster(cluster); - - ContainerExec.Result recreatedNodeResult = execInContainerWithExitCode(recreatedContainerId, - new String[]{"kubectl", "get", "nodes", "-o", "jsonpath={.items[*].metadata.name}"}); - assertEquals(0, recreatedNodeResult.exitCode(), "kubectl get nodes failed on recreated cluster"); - assertEquals(eksClusterManager.deriveClusterNodePrivateDnsName(cluster), recreatedNodeResult.stdout().trim(), + EksTestNode recreated = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT); + assertNotEquals(containerId, recreated.containerId()); + assertEquals(eksClusterManager.deriveClusterNodePrivateDnsName(cluster), + recreated.kubectlOutput("get", "nodes", "-o", "jsonpath={.items[*].metadata.name}"), "Recreated cluster must keep the same node name without leaving duplicate or stale nodes"); } @@ -376,25 +297,4 @@ class EksIrsaDockerIntegrationTest { } catch (Exception ignored) { } } - - private boolean isDockerAvailable() { - try { - dockerClient.pingCmd().exec(); - return true; - } catch (Exception e) { - return false; - } - } - - private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) { - return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId); - } - - private String execInContainer(String containerId, String[] cmd) throws Exception { - ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd); - if (result.exitCode() != 0) { - throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr()); - } - return result.stdout(); - } } diff --git a/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java index bdd6a7455f..902cd680f4 100644 --- a/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java @@ -11,6 +11,8 @@ import io.floci.aws.services.ec2.model.LaunchTemplate; import io.floci.aws.services.ec2.model.LaunchTemplateData; 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.PartitionCleanup; import io.floci.aws.testing.RdsMockProfile; import io.quarkus.test.junit.QuarkusTest; @@ -30,6 +32,7 @@ import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Base64; @@ -39,9 +42,9 @@ import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * Docker-gated integration test proving containerd registry host configuration via node group launch @@ -64,6 +67,7 @@ class EksRegistryHostsDockerIntegrationTest { private static final Logger LOG = Logger.getLogger(EksRegistryHostsDockerIntegrationTest.class); private static final String JSON = "application/json"; + private static final String POD = "registry-hosts-pod"; @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); @@ -88,7 +92,7 @@ class EksRegistryHostsDockerIntegrationTest { @BeforeEach void requireDocker() { - boolean dockerAvailable = isDockerAvailable(); + boolean dockerAvailable = DockerAvailability.answers(dockerClient); if (!dockerAvailable) { LOG.warn("Docker daemon is not available; skipping EksRegistryHostsDockerIntegrationTest"); } @@ -119,16 +123,21 @@ class EksRegistryHostsDockerIntegrationTest { assertNotNull(cluster.getContainerId(), "Container ID must not be null"); waitUntilReady(cluster); eksClusterManager.finalizeCluster(cluster); - String containerId = cluster.getContainerId(); // Verify symlink was created before container started - ContainerExec.Result linkResult = execInContainerWithExitCode(containerId, - new String[]{"readlink", "/etc/containerd/certs.d"}); - assertEquals(0, linkResult.exitCode(), "readlink /etc/containerd/certs.d must succeed"); - assertEquals(EksClusterManager.CONTAINERD_CERTS_TARGET, linkResult.stdout().trim()); + assertEquals(EksClusterManager.CONTAINERD_CERTS_TARGET, EksTestNode.of(dockerClient, eksClusterManager, cluster) + .execOutput("readlink", "/etc/containerd/certs.d")); // Configure registry host via node group launch template user data String endpoint = "http://" + dockerHostResolver.resolve() + ":" + httpPort; + String hostsToml = """ + server = "https://%s" + + [host."%s"] + capabilities = ["pull", "resolve"] + [host."%s".header] + "X-Floci-Test" = "registry-hosts" + """.formatted(host, endpoint, endpoint).stripTrailing(); String userDataScript = """ MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="==MYBOUNDARY==" @@ -139,16 +148,11 @@ class EksRegistryHostsDockerIntegrationTest { #!/bin/sh mkdir -p /etc/containerd/certs.d/%s cat << 'EOF' > /etc/containerd/certs.d/%s/hosts.toml - server = "https://%s" - - [host."%s"] - capabilities = ["pull", "resolve"] - [host."%s".header] - "X-Floci-Test" = "registry-hosts" + %s EOF --==MYBOUNDARY==-- - """.formatted(host, host, host, endpoint, endpoint); + """.formatted(host, host, hostsToml); LaunchTemplateData ltData = new LaunchTemplateData(); ltData.setUserData(Base64.getEncoder().encodeToString(userDataScript.getBytes(StandardCharsets.UTF_8))); @@ -176,92 +180,62 @@ class EksRegistryHostsDockerIntegrationTest { cluster = eksService.describeCluster(clusterName); assertNotNull(cluster.getContainerId(), "Container ID must not be null after node group creation"); waitUntilReady(cluster); - containerId = cluster.getContainerId(); + EksTestNode node = EksTestNode.of(dockerClient, eksClusterManager, cluster); // Verify user data script wrote hosts.toml into k3s certs.d through the symlink - String hostsToml = execInContainer(containerId, new String[]{"cat", - EksClusterManager.CONTAINERD_CERTS_TARGET + "/" + host + "/hosts.toml"}); - assertTrue(hostsToml.contains("\"X-Floci-Test\" = \"registry-hosts\""), - "the configured header must be present in the container's hosts.toml via the certs.d symlink"); + String hostsTomlPath = EksClusterManager.CONTAINERD_CERTS_TARGET + "/" + host + "/hosts.toml"; + assertEquals(hostsToml, node.execOutput("cat", hostsTomlPath), + "the user data's hosts.toml must be in the container's certs.d via the symlink"); // Verify hosts.toml survives container restart - dockerClient.restartContainerCmd(containerId).exec(); + dockerClient.restartContainerCmd(node.containerId()).exec(); Instant restartCompletedAt = Instant.now(); waitUntilReady(cluster); - String hostsTomlAfterRestart = null; - long restartDeadline = System.currentTimeMillis() + 30000; - while (System.currentTimeMillis() < restartDeadline) { - try { - hostsTomlAfterRestart = execInContainer(containerId, new String[]{"cat", - EksClusterManager.CONTAINERD_CERTS_TARGET + "/" + host + "/hosts.toml"}); - break; - } catch (Exception ignored) { - Thread.sleep(1000); - } - } - assertNotNull(hostsTomlAfterRestart, "hosts.toml must survive container restart"); - assertTrue(hostsTomlAfterRestart.contains("\"X-Floci-Test\" = \"registry-hosts\""), - "the configured header must survive container restart"); + await("hosts.toml after the restart").atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofSeconds(1)) + .ignoreExceptions() + .untilAsserted(() -> assertEquals(hostsToml, node.execOutput("cat", hostsTomlPath), + "hosts.toml must survive container restart")); - long saDeadline = System.currentTimeMillis() + 30000; - boolean ready = false; - while (System.currentTimeMillis() < saDeadline) { - ContainerExec.Result saResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "--request-timeout=2s", "get", "serviceaccount", "default"}); - ContainerExec.Result nodeReady = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "--request-timeout=2s", "wait", - "--for=condition=Ready", "nodes", "--all", "--timeout=1s"}); - ContainerExec.Result leases = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "--request-timeout=2s", "get", "leases", "-n", "kube-node-lease", - "-o", "jsonpath={.items[*].spec.renewTime}"}); - String renewals = leases.stdout().trim(); - boolean freshHeartbeat = leases.exitCode() == 0 && !renewals.isEmpty() - && Arrays.stream(renewals.split("\\s+")) - .allMatch(renewal -> Instant.parse(renewal).isAfter(restartCompletedAt)); - if (saResult.exitCode() == 0 && nodeReady.exitCode() == 0 && freshHeartbeat) { - ready = true; - break; - } - Thread.sleep(1000); - } - assertTrue(ready, "serviceaccount and Ready nodes with renewed Leases must be available within 30 seconds"); + await("serviceaccount and Ready nodes with renewed Leases").atMost(Duration.ofSeconds(30)) + .pollInterval(Duration.ofSeconds(1)) + .until(() -> node.kubectl("--request-timeout=2s", "get", "serviceaccount", "default").exitCode() == 0 + && node.kubectl("--request-timeout=2s", "wait", "--for=condition=Ready", "nodes", "--all", + "--timeout=1s").exitCode() == 0 + && leasesRenewedAfter(node, restartCompletedAt)); - String podYaml = """ + node.apply(""" apiVersion: v1 kind: Pod metadata: - name: registry-hosts-pod + name: %s spec: containers: - name: workload image: %s command: ["/bin/sleep", "3600"] - """.formatted(imageRef); - execInContainer(containerId, new String[]{"sh", "-c", - "cat << 'EOF' | kubectl apply -f -\n" + podYaml + "\nEOF"}); + """.formatted(POD, imageRef)); + try { + node.awaitPodRunning(POD, Duration.ofSeconds(45)); + } catch (RuntimeException e) { + logPodDiagnostics(node.containerId()); + throw e; + } + node.kubectl("delete", "pod", POD, "--now"); + } - long deadline = System.currentTimeMillis() + 45000; - boolean running = false; - while (System.currentTimeMillis() < deadline) { - ContainerExec.Result status = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "pod", "registry-hosts-pod", "-o", "jsonpath={.status.phase}"}); - if ("Running".equalsIgnoreCase(status.stdout().trim())) { - running = true; - break; - } - Thread.sleep(2000); - } - if (!running) { - logPodDiagnostics(containerId); - } - assertTrue(running, "registry-hosts-pod must reach Running, pulling its image through the configured host"); - execInContainerWithExitCode(containerId, new String[]{"kubectl", "delete", "pod", "registry-hosts-pod", "--now"}); + /** Whether every node's Lease was renewed after {@code restart}. */ + private static boolean leasesRenewedAfter(EksTestNode node, Instant restart) { + ContainerExec.Result leases = node.kubectl("--request-timeout=2s", "get", "leases", "-n", "kube-node-lease", + "-o", "jsonpath={.items[*].spec.renewTime}"); + String renewals = leases.stdout().trim(); + return leases.exitCode() == 0 && !renewals.isEmpty() + && Arrays.stream(renewals.split("\\s+")).allMatch(renewal -> Instant.parse(renewal).isAfter(restart)); } /** Cleanup removes the k3s container, and kubelet's output reaches nothing else. */ private void logPodDiagnostics(String containerId) { String[][] commands = { - {"kubectl", "describe", "pod", "registry-hosts-pod"}, + {"kubectl", "describe", "pod", POD}, {"kubectl", "describe", "nodes"}, {"kubectl", "get", "pods", "-A", "-o", "wide"}, {"crictl", "images"}, @@ -458,36 +432,11 @@ class EksRegistryHostsDockerIntegrationTest { .then().statusCode(201); } - private boolean isDockerAvailable() { - try { - dockerClient.pingCmd().exec(); - return true; - } catch (Exception e) { - return false; - } - } - - private void waitUntilReady(Cluster cluster) throws Exception { - long deadline = System.currentTimeMillis() + 60000; - while (System.currentTimeMillis() < deadline) { - Cluster c = eksService.describeCluster(cluster.getName()); - if (c.getStatus() == ClusterStatus.ACTIVE && !c.isFinalizePending()) { - return; - } - Thread.sleep(1000); - } - throw new IllegalStateException("Cluster did not become ACTIVE within timeout"); - } - - private String execInContainer(String containerId, String[] cmd) { - ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd); - if (result.exitCode() != 0) { - throw new IllegalStateException("Command failed with exit code " + result.exitCode() + ": " + result.summary()); - } - return result.stdout(); - } - - private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) { - return ContainerExec.run(dockerClient, containerId, cmd, 30); + private void waitUntilReady(Cluster cluster) { + await("cluster ACTIVE").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(1)) + .until(() -> { + Cluster c = eksService.describeCluster(cluster.getName()); + return c.getStatus() == ClusterStatus.ACTIVE && !c.isFinalizePending(); + }); } } diff --git a/src/test/java/io/floci/aws/services/eks/EksStorageClassDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksStorageClassDockerIntegrationTest.java index 26dc184285..f4be4d934d 100644 --- a/src/test/java/io/floci/aws/services/eks/EksStorageClassDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksStorageClassDockerIntegrationTest.java @@ -3,6 +3,8 @@ 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.EksTestNode; import io.floci.aws.testing.RdsMockProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -13,13 +15,11 @@ import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Instant; +import java.time.Duration; 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.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * Docker integration test verifying that freshly created clusters start with no StorageClass, @@ -46,7 +46,7 @@ class EksStorageClassDockerIntegrationTest { @BeforeEach void requireDocker() { - boolean dockerAvailable = isDockerAvailable(); + boolean dockerAvailable = DockerAvailability.answers(dockerClient); if (!dockerAvailable) { LOG.warn("Docker daemon is not available; skipping EksStorageClassDockerIntegrationTest"); } @@ -65,80 +65,28 @@ class EksStorageClassDockerIntegrationTest { } @Test - void clusterStartsWithoutStorageClassAndCoreDnsRemainsAvailable() throws Exception { - String suffix = UUID.randomUUID().toString().substring(0, 8); - String clusterName = "sc-dock-" + 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"); - - // Wait for k3s API server readiness (up to 60s) - long deadline = System.currentTimeMillis() + 60000; - boolean ready = false; - while (System.currentTimeMillis() < deadline) { - if (eksClusterManager.isReady(cluster)) { - ready = true; - break; - } - Thread.sleep(2000); - } - assertTrue(ready, "k3s API server must become ready within 60 seconds"); - eksClusterManager.finalizeCluster(cluster); - - String containerId = cluster.getContainerId(); + void clusterStartsWithoutStorageClassAndCoreDnsRemainsAvailable() { + cluster = EksTestNode.cluster(ACCOUNT, "sc-dock-" + UUID.randomUUID().toString().substring(0, 8)); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(60)); // 1. Verify CoreDNS deployment is present and healthy in kube-system - long corednsDeadline = System.currentTimeMillis() + 60000; - boolean corednsRolledOut = false; - while (System.currentTimeMillis() < corednsDeadline) { - ContainerExec.Result rolloutResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "rollout", "status", "deployment/coredns", "-n", "kube-system", "--timeout=10s"}); - if (rolloutResult.exitCode() == 0) { - corednsRolledOut = true; - break; - } - Thread.sleep(2000); - } - assertTrue(corednsRolledOut, "CoreDNS deployment must be successfully rolled out"); + await("CoreDNS rolled out").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(2)) + .until(() -> node.kubectl("rollout", "status", "deployment/coredns", "-n", "kube-system", + "--timeout=10s").exitCode() == 0); // 2. Verify CoreDNS pods are running and ready - ContainerExec.Result podsResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "pods", "-n", "kube-system", "-l", "k8s-app=kube-dns", - "-o", "jsonpath={.items[*].status.phase}"}); - assertEquals(0, podsResult.exitCode(), "kubectl get pods failed: " + podsResult.stderr()); - assertTrue(podsResult.stdout().contains("Running"), - "CoreDNS pod must be in Running phase, but got: " + podsResult.stdout()); + assertEquals("Running", node.kubectlOutput("get", "pods", "-n", "kube-system", "-l", "k8s-app=kube-dns", + "-o", "jsonpath={.items[*].status.phase}"), + "CoreDNS pod must be in Running phase"); // 3. Verify no StorageClass exists in the cluster after manifests settle - ContainerExec.Result scResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "storageclass", "-o", "jsonpath={.items[*].metadata.name}"}); - assertEquals(0, scResult.exitCode(), "kubectl get storageclass failed: " + scResult.stderr()); - assertTrue(scResult.stdout().trim().isEmpty(), - "No StorageClass should exist in newly created cluster, but found: " + scResult.stdout()); + assertEquals("", node.kubectlOutput("get", "storageclass", "-o", "jsonpath={.items[*].metadata.name}"), + "No StorageClass should exist in newly created cluster"); // 4. Explicitly verify local-path StorageClass is absent - ContainerExec.Result localPathResult = execInContainerWithExitCode(containerId, - new String[]{"kubectl", "get", "storageclass", "local-path"}); - assertNotEquals(0, localPathResult.exitCode(), "local-path StorageClass must not exist"); - } - - private boolean isDockerAvailable() { - try { - dockerClient.pingCmd().exec(); - return true; - } catch (Exception e) { - return false; - } - } - - private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) { - return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId); + ContainerExec.Result localPath = node.kubectl("get", "storageclass", "local-path"); + assertEquals(1, localPath.exitCode(), localPath.summary()); + assertEquals("Error from server (NotFound): storageclasses.storage.k8s.io \"local-path\" not found", + localPath.stderr().trim(), "local-path StorageClass must not exist"); } } diff --git a/src/test/java/io/floci/aws/testing/EksTestNode.java b/src/test/java/io/floci/aws/testing/EksTestNode.java index c0a8e6ecb2..7a53d96277 100644 --- a/src/test/java/io/floci/aws/testing/EksTestNode.java +++ b/src/test/java/io/floci/aws/testing/EksTestNode.java @@ -13,8 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** - * The k3s node of a cluster that a Docker integration test starts through {@link EksClusterManager}, with - * {@code kubectl} and other commands run in it. + * The k3s node of a cluster that a Docker integration test starts, through {@link EksClusterManager} or the EKS API, + * with {@code kubectl} and other commands run in it. */ public final class EksTestNode { @@ -57,6 +57,11 @@ public final class EksTestNode { return node; } + /** The node of {@code cluster}, which was started some other way, such as through the EKS API. */ + public static EksTestNode of(DockerClient dockerClient, EksClusterManager eksClusterManager, Cluster cluster) { + return new EksTestNode(dockerClient, eksClusterManager, cluster); + } + /** The node's container, as the cluster names it now. */ public String containerId() { return cluster.getContainerId(); @@ -70,8 +75,7 @@ public final class EksTestNode { /** Applies {@code yaml} with {@code kubectl apply}. */ public void apply(String yaml) { - ContainerExec.Result applied = exec("sh", "-c", "cat << 'EOF' | kubectl apply -f -\n" + yaml + "\nEOF"); - assertEquals(0, applied.exitCode(), "kubectl apply failed: " + applied.stderr()); + execOutput("sh", "-c", "cat << 'EOF' | kubectl apply -f -\n" + yaml + "\nEOF"); } /** @@ -86,14 +90,30 @@ public final class EksTestNode { "jsonpath={.status.containerStatuses[0].state}").stdout())); } + /** Runs {@code kubectl} with {@code args}, which must succeed, and returns what it printed to stdout, trimmed. */ + public String kubectlOutput(String... args) { + return execOutput(kubectlCommand(args)); + } + + /** Runs {@code command}, which must succeed, and returns what it printed to stdout, trimmed. */ + public String execOutput(String... command) { + ContainerExec.Result result = exec(command); + assertEquals(0, result.exitCode(), () -> String.join(" ", command) + " failed: " + result.summary()); + return result.stdout().trim(); + } + public ContainerExec.Result kubectl(String... args) { - String[] command = new String[args.length + 1]; - command[0] = "kubectl"; - System.arraycopy(args, 0, command, 1, args.length); - return exec(command); + return exec(kubectlCommand(args)); } public ContainerExec.Result exec(String... command) { return ContainerExec.run(dockerClient, containerId(), command, 30).throwIfTimedOut(containerId()); } + + private static String[] kubectlCommand(String... args) { + String[] command = new String[args.length + 1]; + command[0] = "kubectl"; + System.arraycopy(args, 0, command, 1, args.length); + return command; + } }