diff --git a/docs/services/ecr.md b/docs/services/ecr.md index 551c574823..51c05fb7b2 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -255,11 +255,13 @@ and restart Docker Desktop, following [Docker's CA certificate instructions](htt !!! note "Pulling from other containers (EKS, same-network consumers)" The `localhost`-based repository URI only works from the host. [Floci EKS](eks.md#pulling-images-from-floci-ecr) configures a containerd mirror to reach Floci's data plane, so Helm charts can reference the - pushed URI as-is. + pushed URI as-is, or the image by its AWS registry host + (`.dkr.ecr..amazonaws.com`) for the cluster's and the default account. When TLS URI advertising is enabled, newly configured EKS registry mirrors accept both - the loopback and TLS names and forward them to the same internal HTTP endpoint. Recreate - existing clusters to pick up changed registry mirror settings. Automatic rewrites of + the loopback and TLS names and forward them to the same internal HTTP endpoint. An existing + cluster picks up a changed mirror set when Floci next starts, which replaces its node on its data + volume. Automatic rewrites of AWS-shaped Lambda/ECS image references continue using the plain HTTP loopback address; an explicitly supplied TLS image reference is used as supplied. diff --git a/docs/services/eks.md b/docs/services/eks.md index 1f322b0786..5bd656cee3 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -892,27 +892,37 @@ helm install my-app ./chart \ --set image.tag=v1 ``` +The same two accounts' registry hosts as AWS names them, +`.dkr.ecr..amazonaws.com` (`amazonaws.com.cn` in the China regions), are +mirrored too, so a chart written for EKS that names its own account's images that way pulls +them from Floci unchanged: + +```bash +helm install my-app ./chart \ + --set image.repository=000000000000.dkr.ecr.us-east-1.amazonaws.com/my-repo \ + --set image.tag=v1 +``` + +containerd still tries AWS itself last, so an image Floci does not hold is looked for there, +as it would be without the mirror. + Requirements and limits: - The k3s container must reach Floci's Docker-network address. Set the global `FLOCI_SERVICES_DOCKER_NETWORK` as in the standard `docker-compose.yml` or the EKS service network variable. -- Only Floci-mintable hostnames are mirrored; public registries (docker.io, ghcr.io, …) - are never touched. +- Only Floci-mintable hostnames and the two accounts' AWS registry hosts are mirrored; + public registries (docker.io, ghcr.io, …) and other accounts' AWS registries, such as the + ones EKS add-on images come from, are never touched. - Mirrored hostnames carry the port the repository URIs advertise, which is the host port when Floci's container publishes `4566` on another one (see [ECR](ecr.md#docker-compose-port-mapping)). - Repository URIs using a non-default `registryId` (account) are not covered. -- The mirror set is snapshotted when the cluster is created. Clusters created before this - feature can be fixed manually because the k3s container filesystem survives a restart. A surviving - container keeps the name it was created with, so those clusters are still `floci-eks-` - while newer ones are `floci-aws-eks-`, and a non-default account adds `.` before - the cluster name. Look the name up first: - - ```bash - docker ps --filter name= --format '{{.Names}}' - docker cp registries.yaml :/etc/rancher/k3s/registries.yaml - docker restart - ``` +- A node keeps the mirror set it was started with. When Floci starts, a surviving node whose + `registries.yaml` differs from the one Floci gives it now, such as one created before a mirror + entry was added, is replaced on its data volume, as one with another capacity is, and the + replacement gets the current set. It is not replaced while the registry is unavailable, since the + replacement would get no mirror either, nor to take its mirror away when + `FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR` is off. ### DNS resolution and Route 53 private hosted zones diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 0d05a1b8ac..ad67e2e05c 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -4270,8 +4270,9 @@ public interface EmulatorConfig { /** * When true (and ECR is enabled), each new k3s cluster gets a generated * {@code /etc/rancher/k3s/registries.yaml} that mirrors every ECR repository URI the - * emulator can mint to the registry container's in-network endpoint, so pods can pull - * images pushed to Floci ECR without any manual containerd configuration. + * emulator can mint, and the cluster's and default account's registry hosts as AWS names + * them, to the registry container's in-network endpoint, so pods can pull images pushed to + * Floci ECR without any manual containerd configuration. */ @WithDefault("true") boolean ecrRegistryMirror(); diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java index b993562817..e3fa578563 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlane.java @@ -3,6 +3,8 @@ package io.floci.aws.services.ecr.registry; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.NetworkExposureGuard; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.AwsPartitions; +import io.floci.aws.core.common.AwsRegions; import io.floci.aws.services.ecr.EcrService; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; @@ -42,6 +44,12 @@ public class EcrRegistryDataPlane { private static final Logger LOG = Logger.getLogger(EcrRegistryDataPlane.class); private static final Pattern ECR_HOST = Pattern.compile( "^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.localhost(?:\\.floci\\.io)?(?::[0-9]+)?$"); + /** + * An account's registry host as AWS names it, {@code .dkr.ecr..}, which containerd sends + * as a mirror request's {@code ns} when an EKS node's registries.yaml mirrors it to Floci. + */ + private static final Pattern AWS_ECR_HOST = Pattern.compile( + "^([0-9]{12})\\.dkr\\.ecr\\.([a-z0-9-]+)\\.(" + AwsPartitions.dnsSuffixRegex() + ")(?::[0-9]+)?$"); private static final String MANIFESTS_PATH = "/manifests/"; private static final long REPOSITORY_LOCK_POLL_MILLIS = 5; /** @@ -695,11 +703,8 @@ public class EcrRegistryDataPlane { if (!registryPath.startsWith("/v2/")) { return Optional.empty(); } - Matcher hostMatch = ECR_HOST.matcher(host == null ? "" : host); - if (!hostMatch.matches()) { - hostMatch = ECR_HOST.matcher(queryParameter(query, "ns")); - } - if (hostMatch.matches()) { + Matcher hostMatch = registryHost(host, query); + if (hostMatch != null) { String repository = "/v2/".equals(registryPath) ? "" : repositoryName(registryPath.substring("/v2/".length())); String storageRepositoryName = hostMatch.group(1) + "/" + hostMatch.group(2) + "/" + repository; String backendUri = repository.isEmpty() @@ -734,6 +739,25 @@ public class EcrRegistryDataPlane { registryPath + querySuffix(query, true), tag(registryPath))); } + /** + * The registry a request is for: its host when that is a Floci repository host, else the registry a mirror request + * names in {@code ns}, a Floci repository host or an account's AWS registry host in that region's partition. A request + * with an AWS registry host in its {@code Host} header is not routed here. + */ + private static Matcher registryHost(String host, String query) { + Matcher byHost = ECR_HOST.matcher(host == null ? "" : host); + if (byHost.matches()) { + return byHost; + } + String namespace = queryParameter(query, "ns"); + Matcher byNamespace = ECR_HOST.matcher(namespace); + if (byNamespace.matches()) { + return byNamespace; + } + Matcher mirrored = AWS_ECR_HOST.matcher(namespace); + return mirrored.matches() && AwsRegions.dnsSuffixFor(mirrored.group(2)).equals(mirrored.group(3)) ? mirrored : null; + } + private static boolean isLoopbackHost(String host) { HostAndPort authority = host == null ? null : HostAndPort.parseAuthority(host, -1); return authority != null && NetworkExposureGuard.isLoopback(authority.host()); 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 f69262dae7..749b2733ae 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -13,6 +13,7 @@ import io.floci.aws.config.FlociCertificateAuthority; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; +import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StripedLocks; import io.floci.aws.core.common.dns.DnsAnswer; @@ -137,6 +138,8 @@ public class EksClusterManager private static final String SHARED_MOUNTS_LABEL = "io.floci.eks.shared-mounts"; /** The pod network a node was started with: {@link #FLANNEL_POD_NETWORK}, or {@code vpc:} and its prefixes. */ private static final String POD_NETWORK_LABEL = "io.floci.eks.pod-network"; + /** The digest of the registries.yaml a node was started with; a node without one has none, or predates the label. */ + private static final String REGISTRY_MIRROR_LABEL = "io.floci.eks.registry-mirror"; private static final String FLANNEL_POD_NETWORK = "flannel"; private static final String VPC_POD_NETWORK_LABEL_PREFIX = "vpc:"; /** The k3s arguments that leave pod addresses to the VPC pod network's bridge configuration. */ @@ -778,6 +781,7 @@ public class EksClusterManager SigningKeyFiles signingKeyFiles = null; String auditPolicyLocalFile = null; String podResolvConf = null; + String registries = null; ContainerSpec spec; String containerId; try { @@ -842,6 +846,10 @@ public class EksClusterManager labels.put(DEFAULT_STORAGE_CLASS_LABEL, String.valueOf(defaultStorageClass)); labels.put(SHARED_MOUNTS_LABEL, "true"); labels.put(POD_NETWORK_LABEL, podNetworkLabel(podNetwork)); + registries = startingRegistriesYaml(cluster); + if (registries != null) { + labels.put(REGISTRY_MIRROR_LABEL, registryMirrorLabel(registries)); + } if (!"localhost".equals(endpointHost)) { labels.put(ENDPOINT_HOST_LABEL, endpointHost); } @@ -996,7 +1004,7 @@ public class EksClusterManager if (auditPolicyLocalFile != null) { copyAuditPolicyIntoContainer(containerId, auditPolicyLocalFile, cluster.getName()); } - injectEcrRegistryMirror(containerId, cluster); + injectEcrRegistryMirror(containerId, cluster, registries); linkContainerdCertsDir(containerId, cluster.getName()); registerPodIdentityWebhook(containerId, cluster); if (signingKeyFiles != null) { @@ -1102,9 +1110,10 @@ public class EksClusterManager // 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)); - // One started with another pod network is replaced too. + // One started with another pod network or registry mirror is replaced too. if (capacityChanged || privateMounts || onAnotherNetwork(existing.get()) - || !endpointHost.equals(certificateHost(existingLabels)) || podNetworkChanged(cluster, existingLabels)) { + || !endpointHost.equals(certificateHost(existingLabels)) || podNetworkChanged(cluster, existingLabels) + || registryMirrorChanged(cluster, existingLabels)) { replaceClusterContainer(cluster, null); } } @@ -2780,44 +2789,83 @@ public class EksClusterManager } /** - * Generates and injects {@code /etc/rancher/k3s/registries.yaml} into the (created, - * not-yet-started) k3s container so its containerd can pull images pushed to the Floci ECR - * registry. Mirrors every repository hostname the cluster can pull from Floci: its own account - * and the default account, across every region of the cluster's partition, plus the path-style - * {@code localhost:} form, including {@code localhost.floci.io} aliases when TLS registry - * URIs are enabled, to Floci's in-network data plane. Public registries are never matched. A - * failure disables the mirror for this cluster but does not abort its startup, matching the - * webhook contract. + * The {@code /etc/rancher/k3s/registries.yaml} Floci gives {@code cluster}'s k3s container so its containerd can pull + * images pushed to the Floci ECR registry, or null when it gives none: the mirror or ECR is off. It mirrors every + * repository hostname the cluster can pull from Floci: its own account and the default account, across every region + * of the cluster's partition, plus the path-style {@code localhost:} form, including {@code localhost.floci.io} + * aliases when TLS registry URIs are enabled, to Floci's in-network data plane. The same two accounts' registry hosts + * as AWS names them are mirrored as well. Public registries and other accounts' are never matched. */ - void injectEcrRegistryMirror(String containerId, Cluster cluster) { - String clusterName = cluster.getName(); + String registriesYaml(Cluster cluster) { if (!config.services().eks().ecrRegistryMirror() || !config.services().ecr().enabled()) { - return; + return null; + } + String region = regionResolver.regionOf(cluster.getArn()); + String endpoint = "http://" + dockerHostResolver.resolve() + ":" + config.port(); + boolean tlsUri = config.services().ecr().tlsUri() && config.tls().enabled(); + return buildRegistriesYaml(mirrorAccounts(resolveClusterAccountId(cluster), config.defaultAccountId()), + mirrorRegions(region), ecrRegistryManager.advertisedPort(), endpoint, tlsUri); + } + + /** + * The registries.yaml a k3s container created now gets: {@link #registriesYaml}, or none when the registry is + * unavailable, matching the webhook contract: the cluster starts without a mirror. + */ + String startingRegistriesYaml(Cluster cluster) { + String content = registriesYaml(cluster); + if (content == null) { + return null; } try { ecrRegistryManager.ensureStarted(); } catch (Exception e) { LOG.warnv("EKS cluster {0} gets no ECR registry mirror: registry unavailable: {1}", - clusterName, e.getMessage()); + cluster.getName(), e.getMessage()); + return null; + } + return content; + } + + /** + * Injects {@code content}, from {@link #startingRegistriesYaml}, into the created, not yet started k3s container. A + * failure leaves this cluster without the mirror but does not abort its startup. + */ + void injectEcrRegistryMirror(String containerId, Cluster cluster, String content) { + if (content == null) { return; } - String region = regionResolver.regionOf(cluster.getArn()); - String endpoint = "http://" + dockerHostResolver.resolve() + ":" + config.port(); - boolean tlsUri = config.services().ecr().tlsUri() && config.tls().enabled(); - String content = buildRegistriesYaml(mirrorAccounts(resolveClusterAccountId(cluster), config.defaultAccountId()), - mirrorRegions(region), ecrRegistryManager.advertisedPort(), endpoint, tlsUri); + String clusterName = cluster.getName(); writeLocalCopy(localClusterFile(cluster, "registries", "registries.yaml"), content, clusterName); try { RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/etc", REGISTRIES_TAR_ENTRY, content.getBytes(StandardCharsets.UTF_8), 0644, RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis); - LOG.infov("Injected ECR registry mirror ({0}) into k3s cluster {1}", endpoint, clusterName); + LOG.infov("Injected ECR registry mirror into k3s cluster {0}", clusterName); } catch (Exception e) { LOG.warnv("EKS cluster {0} gets no ECR registry mirror: could not copy registries.yaml " + "into the k3s container: {1}", clusterName, e.getMessage()); } } + /** + * Whether a surviving node runs another registries.yaml than the one Floci gives it now, such as one written before + * the mirror set grew, or none: it is replaced then, on its data volume, and its replacement gets the current one. + * It is not replaced while the registry is unavailable, as the replacement would get no mirror either, nor to take + * a mirror away when the setting is off. + */ + boolean registryMirrorChanged(Cluster cluster, Map existingLabels) { + String wanted = registriesYaml(cluster); + if (wanted == null || existingLabels != null + && registryMirrorLabel(wanted).equals(existingLabels.get(REGISTRY_MIRROR_LABEL))) { + return false; + } + return startingRegistriesYaml(cluster) != null; + } + + static String registryMirrorLabel(String registriesYaml) { + return Digests.sha256Hex(registriesYaml); + } + /** * Symlinks {@code /etc/containerd/certs.d} to k3s containerd's certs directory * ({@code /var/lib/rancher/k3s/agent/etc/containerd/certs.d}) inside the container before start. @@ -3079,8 +3127,11 @@ public class EksClusterManager * ({@code localhost:}), all pointing at Floci's in-network data plane. The port is the * one the repository URIs advertise, which differs from the endpoint's port when Floci's * container publishes its port on another host port. The TLS URI mode adds the corresponding - * {@code localhost.floci.io} aliases. k3s supports no partial wildcards and a {@code "*"} - * catch-all would also intercept public registries, so the hostnames are enumerated explicitly. + * {@code localhost.floci.io} aliases. Each account's registry host as AWS names it, + * {@code .dkr.ecr..}, is mirrored too, so an image a chart names + * that way is pulled from Floci; containerd still tries AWS last, for an image Floci does not + * hold. k3s supports no partial wildcards and a {@code "*"} catch-all would also intercept + * public registries and other accounts' registries, so the hostnames are enumerated explicitly. */ static String buildRegistriesYaml(String accountId, List regions, int advertisedPort, String endpoint) { return buildRegistriesYaml(accountId, regions, advertisedPort, endpoint, false); @@ -3101,6 +3152,7 @@ public class EksClusterManager appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost.floci.io:" + advertisedPort, endpoint); } + appendMirror(yaml, accountId + ".dkr.ecr." + region + "." + AwsRegions.dnsSuffixFor(region), endpoint); } } appendMirror(yaml, "localhost:" + advertisedPort, endpoint); diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java index 58fcfe8a61..43afd47dbd 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryDataPlaneTest.java @@ -116,6 +116,39 @@ class EcrRegistryDataPlaneTest { assertEquals("/v2/123456789012/eu-west-1/team/app/tags/list", requestNoPort.backendUri()); } + @Test + void aMirrorRequestForAnAccountsAwsRegistryHostIsServedFromThatAccountsRepository() { + EcrRegistryDataPlane.RegistryRequest request = EcrRegistryDataPlane.requestFor("172.17.0.1:4566", + "/v2/team/app/manifests/v1", "ns=111122223333.dkr.ecr.eu-west-1.amazonaws.com", "hostname").orElseThrow(); + + assertEquals("111122223333", request.accountId()); + assertEquals("eu-west-1", request.region()); + assertEquals("team/app", request.repositoryName()); + assertEquals("111122223333/eu-west-1/team/app", request.storageRepositoryName()); + assertEquals("v1", request.tag()); + assertEquals("/v2/111122223333/eu-west-1/team/app/manifests/v1", request.backendUri()); + + EcrRegistryDataPlane.RegistryRequest china = EcrRegistryDataPlane.requestFor("172.17.0.1:4566", + "/v2/app/blobs/sha256:abc", "ns=111122223333.dkr.ecr.cn-north-1.amazonaws.com.cn", "hostname").orElseThrow(); + assertEquals("cn-north-1", china.region()); + assertEquals("/v2/111122223333/cn-north-1/app/blobs/sha256:abc", china.backendUri()); + } + + @Test + void anAwsRegistryHostIsServedOnlyAsAMirrorRequestsNamespaceInItsRegionsPartition() { + // A region under another partition's suffix names no registry. + assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/app/manifests/v1", + "ns=111122223333.dkr.ecr.cn-north-1.amazonaws.com", "hostname").isPresent()); + assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/app/manifests/v1", + "ns=111122223333.dkr.ecr.us-east-1.amazonaws.com.cn", "hostname").isPresent()); + // Another registry's namespace, such as a public registry's, is not Floci's. + assertFalse(EcrRegistryDataPlane.requestFor("172.17.0.1:4566", "/v2/library/nginx/manifests/1", + "ns=docker.io", "hostname").isPresent()); + // A request sent to the AWS host itself is not a mirror request. + assertFalse(EcrRegistryDataPlane.requestFor("111122223333.dkr.ecr.us-east-1.amazonaws.com", + "/v2/app/manifests/v1", null, "hostname").isPresent()); + } + @Test void malformedAccountOrNonEcrHostIsRejected() { // Less than 12 digits 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 88dc93e533..200760f174 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -259,11 +259,13 @@ class EksClusterManagerTest { for (String region : AwsRegions.advertised("aws")) { assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:4566\":"), "should mirror the " + region + " hostname"); + assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".amazonaws.com\":"), + "should mirror the account's " + region + " registry host as AWS names it"); } assertTrue(yaml.contains("\"localhost:4566\":"), "should mirror the path-style form"); assertFalse(yaml.contains("\"*\""), "must not catch-all public registries"); long endpoints = yaml.lines().filter(l -> l.contains("- \"http://floci:4566\"")).count(); - assertEquals(AwsRegions.advertised("aws").size() + 1, endpoints, + assertEquals(2L * AwsRegions.advertised("aws").size() + 1, endpoints, "every mirror should point at Floci's in-network data plane"); } @@ -286,16 +288,17 @@ class EksClusterManagerTest { for (String region : AwsRegions.advertised("aws")) { assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost:4577\":")); assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".localhost.floci.io:4577\":")); + assertTrue(yaml.contains("\"111122223333.dkr.ecr." + region + ".amazonaws.com\":")); } assertTrue(yaml.contains("\"localhost:4577\":")); assertTrue(yaml.contains("\"localhost.floci.io:4577\":")); assertFalse(yaml.contains("*"), "mirrors must not intercept unrelated registries"); - assertFalse(yaml.contains("amazonaws.com")); + assertFalse(yaml.contains("amazonaws.com:"), "the AWS registry host carries no port"); assertFalse(yaml.contains("docker.io")); assertFalse(yaml.contains("ghcr.io")); assertFalse(yaml.contains("https://"), "internal pulls still use the HTTP data plane"); long endpoints = yaml.lines().filter(line -> line.contains("- \"" + endpoint + "\"")).count(); - assertEquals(2L * (AwsRegions.advertised("aws").size() + 1), endpoints); + assertEquals(3L * AwsRegions.advertised("aws").size() + 2, endpoints); } @Test @@ -316,11 +319,12 @@ class EksClusterManagerTest { for (String region : AwsRegions.advertised("aws-cn")) { assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:4566\":"), region); + assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".amazonaws.com.cn\":"), region); } assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-north-1.localhost:4566\":")); assertFalse(yaml.contains(".us-east-1.")); - assertFalse(yaml.contains("amazonaws"), "repository URIs are Floci's localhost hosts in every partition"); - assertEquals(AwsRegions.advertised("aws-cn").size() + 1, + assertFalse(yaml.contains(".amazonaws.com\""), "the China regions' registry hosts are under amazonaws.com.cn"); + assertEquals(2L * AwsRegions.advertised("aws-cn").size() + 1, yaml.lines().filter(line -> line.contains("- \"http://floci:4566\"")).count()); } @@ -330,14 +334,21 @@ class EksClusterManagerTest { EksClusterManager.mirrorAccounts("111122223333", "000000000000"), List.of("eu-central-1"), 4566, "http://floci:4566", false); + // Only these two accounts: another account's registry, such as the ones EKS add-on images come from, stays AWS's. assertEquals(""" mirrors: "111122223333.dkr.ecr.eu-central-1.localhost:4566": endpoint: - "http://floci:4566" + "111122223333.dkr.ecr.eu-central-1.amazonaws.com": + endpoint: + - "http://floci:4566" "000000000000.dkr.ecr.eu-central-1.localhost:4566": endpoint: - "http://floci:4566" + "000000000000.dkr.ecr.eu-central-1.amazonaws.com": + endpoint: + - "http://floci:4566" "localhost:4566": endpoint: - "http://floci:4566" @@ -345,7 +356,7 @@ class EksClusterManagerTest { } @Test - void registriesYamlKeepsTheExistingOutputWhenTlsUrisAreDisabled() { + void registriesYamlHasNoTlsAliasesWhenTlsUrisAreDisabled() { String yaml = EksClusterManager.buildRegistriesYaml( "111122223333", List.of("eu-central-1"), 4566, "http://floci:4566", false); @@ -354,6 +365,9 @@ class EksClusterManagerTest { "111122223333.dkr.ecr.eu-central-1.localhost:4566": endpoint: - "http://floci:4566" + "111122223333.dkr.ecr.eu-central-1.amazonaws.com": + endpoint: + - "http://floci:4566" "localhost:4566": endpoint: - "http://floci:4566" @@ -647,6 +661,7 @@ class EksClusterManagerTest { private ContainerBuilder containerBuilder; private ContainerBuilder.Builder builder; private ContainerDetector containerDetector; + private EcrRegistryManager registryManager; private EksClusterManager manager; @BeforeEach @@ -677,9 +692,10 @@ class EksClusterManagerTest { when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); containerDetector = Mockito.mock(ContainerDetector.class); + registryManager = Mockito.mock(EcrRegistryManager.class); manager = EksClusterManagers.create(containerBuilder, lifecycleManager, containerDetector, portAllocator, - Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), + Mockito.mock(DockerHostResolver.class), registryManager, config, Mockito.mock(RegionResolver.class)); } @@ -876,6 +892,60 @@ class EksClusterManagerTest { verify(containerBuilder.newContainer("rancher/k3s:v1.30.0-k3s1")).withEntrypoint(EksClusterManager.RSHARE_ENTRYPOINT); } + @Test + void replacesASurvivorStartedWithAnotherRegistryMirrorAndLabelsItsReplacement(@TempDir Path dataPath) { + Cluster cluster = mirroredCluster(dataPath); + String older = EksClusterManager.buildRegistriesYaml("000000000000", List.of("us-east-1"), 4566, + "http://floci:4566"); + restoreSurvivorWithMirror(EksClusterManager.registryMirrorLabel(older)); + stubFreshStart("cid-new", 6440); + + manager.restoreCluster(cluster); + + assertEquals("cid-new", cluster.getContainerId()); + @SuppressWarnings("unchecked") + ArgumentCaptor> labels = ArgumentCaptor.forClass(Map.class); + verify(builder).withLabels(labels.capture()); + assertEquals(EksClusterManager.registryMirrorLabel(manager.registriesYaml(cluster)), + labels.getValue().get("io.floci.eks.registry-mirror")); + } + + @Test + void keepsASurvivorStartedWithTheRegistryMirrorFlociGivesItNow(@TempDir Path dataPath) { + Cluster cluster = mirroredCluster(dataPath); + restoreSurvivorWithMirror(EksClusterManager.registryMirrorLabel(manager.registriesYaml(cluster))); + + manager.restoreCluster(cluster); + + assertEquals("cid-old", cluster.getContainerId()); + verify(lifecycleManager, never()).create(any()); + } + + /** The cluster, with the registry mirror on and ECR enabled. */ + private Cluster mirroredCluster(Path dataPath) { + EmulatorConfig.EcrServiceConfig ecr = Mockito.mock(EmulatorConfig.EcrServiceConfig.class); + when(config.services().ecr()).thenReturn(ecr); + when(ecr.enabled()).thenReturn(true); + when(config.services().eks().ecrRegistryMirror()).thenReturn(true); + when(config.services().eks().dataPath()).thenReturn(dataPath.toString()); + when(config.port()).thenReturn(4566); + when(registryManager.advertisedPort()).thenReturn(4566); + Cluster cluster = cluster(); + cluster.setAccountId("000000000000"); + cluster.setArn("arn:aws:eks:us-east-1:000000000000:cluster/demo"); + cluster.setDockerName("floci-eks-demo"); + return cluster; + } + + private void restoreSurvivorWithMirror(String mirrorLabel) { + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.of(containerFromJson( + "{\"Id\":\"cid-old\",\"Labels\":{\"io.floci.eks.node-capacity\":\"m5.large:unbounded\"," + + "\"io.floci.eks.shared-mounts\":\"true\",\"io.floci.eks.registry-mirror\":\"" + + mirrorLabel + "\"}}"))); + when(lifecycleManager.adopt(eq("cid-old"), eq(List.of(6443)), any())) + .thenReturn(new ContainerInfo("cid-old", Map.of(), Map.of(6443, 6440))); + } + @Test void recreatesASurvivorWhoseCertificateLacksTheEndpointHost() { when(config.services().eks().endpointHost()).thenReturn(Optional.of("aws.example.test")); @@ -1717,10 +1787,14 @@ class EksClusterManagerTest { return cluster; } + /** Injects the mirror a node created now gets, as a launch does. */ + private void inject(Cluster cluster) { + manager.injectEcrRegistryMirror("container-1", cluster, manager.startingRegistriesYaml(cluster)); + } + @Test void aDefaultCommercialClusterKeepsTheDeploymentWideMirror() throws Exception { - manager.injectEcrRegistryMirror("container-1", - clusterWithArn("arn:aws:eks:us-east-1:000000000000:cluster/demo")); + inject(clusterWithArn("arn:aws:eks:us-east-1:000000000000:cluster/demo")); assertEquals(EksClusterManager.buildRegistriesYaml("000000000000", AwsRegions.advertised("aws"), 4566, "http://floci:4566"), Files.readString(tempDir.resolve("registries/000000000000/us-east-1/demo/registries.yaml"))); @@ -1728,8 +1802,7 @@ class EksClusterManagerTest { @Test void aChinaClusterInACommercialDeploymentMirrorsItsOwnPartitionsRegions() throws Exception { - manager.injectEcrRegistryMirror("container-1", - clusterWithArn("arn:aws-cn:eks:cn-north-1:000000000000:cluster/demo")); + inject(clusterWithArn("arn:aws-cn:eks:cn-north-1:000000000000:cluster/demo")); String yaml = Files.readString(tempDir.resolve("registries/000000000000/cn-north-1/demo/registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.cn-north-1.localhost:4566\":")); @@ -1742,7 +1815,7 @@ class EksClusterManagerTest { Cluster cluster = clusterWithArn("arn:aws:eks:eu-west-1:111122223333:cluster/demo"); cluster.setAccountId("111122223333"); - manager.injectEcrRegistryMirror("container-1", cluster); + inject(cluster); String yaml = Files.readString(tempDir.resolve("registries/111122223333/eu-west-1/demo/registries.yaml")); assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-west-1.localhost:4566\":")); @@ -1751,7 +1824,7 @@ class EksClusterManagerTest { @Test void injectsTheMirrorIntoTheContainer() throws Exception { - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); verify(registryManager).ensureStarted(); verify(copyCmd).withRemotePath("/etc"); @@ -1767,7 +1840,7 @@ class EksClusterManagerTest { // k3s still reaches Floci on its own port inside the Docker network. when(registryManager.advertisedPort()).thenReturn(54321); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost:54321\":")); @@ -1784,7 +1857,7 @@ class EksClusterManagerTest { when(tls.enabled()).thenReturn(true); when(ecr.tlsUri()).thenReturn(true); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertTrue(yaml.contains("\"000000000000.dkr.ecr.us-east-1.localhost.floci.io:4566\":")); @@ -1800,7 +1873,7 @@ class EksClusterManagerTest { when(config.tls()).thenReturn(tls); when(ecr.tlsUri()).thenReturn(true); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); String yaml = Files.readString(manager.localClusterFile(demoCluster(), "registries", "registries.yaml")); assertFalse(yaml.contains("localhost.floci.io")); @@ -1812,7 +1885,7 @@ class EksClusterManagerTest { void skipsWhenTheKnobIsOff() { when(eks.ecrRegistryMirror()).thenReturn(false); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); verifyNoInteractions(registryManager); verify(lifecycleManager, never()).getDockerClient(); @@ -1822,7 +1895,7 @@ class EksClusterManagerTest { void skipsWhenEcrIsDisabled() { when(ecr.enabled()).thenReturn(false); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); verifyNoInteractions(registryManager); verify(lifecycleManager, never()).getDockerClient(); @@ -1832,7 +1905,7 @@ class EksClusterManagerTest { void registryStartupFailureSkipsTheMirrorWithoutAborting() { Mockito.doThrow(new RuntimeException("no docker")).when(registryManager).ensureStarted(); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); verify(lifecycleManager, never()).getDockerClient(); } @@ -1841,10 +1914,37 @@ class EksClusterManagerTest { void copyFailureDoesNotAbortClusterCreation() { when(copyCmd.exec()).thenThrow(new RuntimeException("copy failed")); - manager.injectEcrRegistryMirror("container-1", demoCluster()); + inject(demoCluster()); verify(copyCmd).exec(); } + + @Test + void aSurvivorIsReplacedWhenItRunsAnotherMirrorThanFlociGivesItNow() { + Cluster cluster = demoCluster(); + String current = manager.registriesYaml(cluster); + + // Started with the mirror Floci gives it now: kept. + assertFalse(manager.registryMirrorChanged(cluster, + Map.of("io.floci.eks.registry-mirror", EksClusterManager.registryMirrorLabel(current)))); + // Started with one written before the mirror set grew: replaced. + String older = EksClusterManager.buildRegistriesYaml("000000000000", List.of("us-east-1"), 4566, + "http://floci:4566"); + assertTrue(manager.registryMirrorChanged(cluster, + Map.of("io.floci.eks.registry-mirror", EksClusterManager.registryMirrorLabel(older)))); + // Started before the label, or without a mirror: replaced, to get it. + assertTrue(manager.registryMirrorChanged(cluster, Map.of())); + assertTrue(manager.registryMirrorChanged(cluster, null)); + } + + @Test + void aSurvivorIsKeptWhenItsReplacementWouldGetNoMirrorEither() { + Mockito.doThrow(new RuntimeException("no docker")).when(registryManager).ensureStarted(); + assertFalse(manager.registryMirrorChanged(demoCluster(), Map.of()), "the registry is unavailable"); + + when(eks.ecrRegistryMirror()).thenReturn(false); + assertFalse(manager.registryMirrorChanged(demoCluster(), Map.of()), "the mirror is off"); + } } @Nested diff --git a/src/test/java/io/floci/aws/services/eks/EksEcrMirrorNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksEcrMirrorNightlyIntegrationTest.java new file mode 100644 index 0000000000..619afcd1dd --- /dev/null +++ b/src/test/java/io/floci/aws/services/eks/EksEcrMirrorNightlyIntegrationTest.java @@ -0,0 +1,127 @@ +package io.floci.aws.services.eks; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.services.eks.model.Cluster; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.EcrRequests; +import io.floci.aws.testing.EcrTestImages; +import io.floci.aws.testing.EksTestNode; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +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.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * The registry mirror Floci gives a k3s node, run for real: in a cluster of an account other than the default one, a pod + * pulls an image by its own account's registry host as AWS names it, and another pod by the default account's, both + * images pushed to Floci ECR, as a chart written for EKS names them. Nothing but Floci holds either image, so each pod + * runs only if containerd took the mirror and Floci served the mirror request from that account's repository. + * + *

A nightly check: it starts a k3s cluster. Its own profile has Floci listen on the port it advertises, which is the + * one the generated mirror sends the node to. + */ +@QuarkusTest +@TestProfile(EksEcrMirrorNightlyIntegrationTest.Profile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +// Bounded waits: the k3s image's pull and the API server, two minutes, then two pods; the Nightly checks job's timeout +// counts the 10. +@Timeout(value = 10, unit = TimeUnit.MINUTES) +class EksEcrMirrorNightlyIntegrationTest { + + /** EKS runs its clusters for real, and Floci listens on the port its registry mirror names. */ + public static final class Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.eks.mock", "false", + "quarkus.http.test-port", String.valueOf(PORT), + "floci.port", String.valueOf(PORT), + "floci.base-url", "http://localhost:" + PORT); + } + } + + private static final int PORT = 4593; + private static final String REGION = "us-east-1"; + private static final String CLUSTER_ACCOUNT = "111122223333"; + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final Duration API_SERVER_TIMEOUT = Duration.ofSeconds(120); + private static final Duration POD_TIMEOUT = Duration.ofSeconds(90); + + @Inject + DockerClient dockerClient; + + @Inject + EksClusterManager eksClusterManager; + + private Cluster cluster; + private final List> repositories = new ArrayList<>(); + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(DockerAvailability.answers(dockerClient), + "Docker daemon must be available for the EKS registry mirror check"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void tearDown() { + if (cluster != null) { + eksClusterManager.stopCluster(cluster); + } + for (List repository : repositories) { + EcrRequests.ecr(repository.get(0), REGION, "DeleteRepository", + "{\"repositoryName\":\"" + repository.get(1) + "\",\"force\":true}"); + } + } + + @Test + void podsPullTheirAccountsAndTheDefaultAccountsImagesByTheAwsRegistryHost() throws IOException { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String ownImage = pushImage(CLUSTER_ACCOUNT, "mirror-own-" + suffix); + String defaultImage = pushImage(DEFAULT_ACCOUNT, "mirror-default-" + suffix); + + cluster = EksTestNode.cluster(CLUSTER_ACCOUNT, "ecr-mirror-" + suffix); + EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, API_SERVER_TIMEOUT); + + runPod(node, "own-account", ownImage); + runPod(node, "default-account", defaultImage); + } + + /** Creates {@code repo} in {@code account} and pushes the image to it; returns its reference by the AWS host. */ + private String pushImage(String account, String repo) throws IOException { + EcrRequests.ecr(account, REGION, "CreateRepository", "{\"repositoryName\":\"" + repo + "\"}"); + repositories.add(List.of(account, repo)); + EcrTestImages.pushSleepImage(dockerClient, account + ".dkr.ecr." + REGION + ".localhost:" + PORT, repo, "v1"); + return account + ".dkr.ecr." + REGION + ".amazonaws.com/" + repo + ":v1"; + } + + private static void runPod(EksTestNode node, String name, String image) { + node.apply(""" + apiVersion: v1 + kind: Pod + metadata: + name: %s + spec: + containers: + - name: workload + image: %s + command: ["/bin/sleep", "3600"] + """.formatted(name, image)); + node.awaitPodRunning(name, POD_TIMEOUT); + } +} 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 e1f561d186..1f0539acfd 100644 --- a/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksRegistryHostsDockerIntegrationTest.java @@ -3,7 +3,6 @@ package io.floci.aws.services.eks; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.Frame; -import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.docker.ContainerExec; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.services.ec2.Ec2Service; @@ -12,6 +11,8 @@ 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.EcrRequests; +import io.floci.aws.testing.EcrTestImages; import io.floci.aws.testing.EksTestNode; import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RdsMockProfile; @@ -19,8 +20,6 @@ import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import jakarta.inject.Inject; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import org.junit.jupiter.api.Assumptions; @@ -30,8 +29,6 @@ import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; 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; @@ -40,7 +37,6 @@ import java.util.Base64; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; -import java.util.zip.GZIPOutputStream; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; @@ -114,10 +110,10 @@ class EksRegistryHostsDockerIntegrationTest { // ECR answers a push to a repository nobody created with NAME_UNKNOWN, so the account creates it first. RestAssuredJsonUtils.configureAwsContentTypes(); - ecrAsImageAccount("CreateRepository", "{\"repositoryName\":\"" + repo + "\"}"); - cleanup.register(() -> ecrAsImageAccount("DeleteRepository", + EcrRequests.ecr(IMAGE_ACCOUNT, "us-east-1", "CreateRepository", "{\"repositoryName\":\"" + repo + "\"}"); + cleanup.register(() -> EcrRequests.ecr(IMAGE_ACCOUNT, "us-east-1", "DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}")); - pushMinimalImage(host, repo); + EcrTestImages.pushSleepImage(dockerClient, host, repo, "v1"); given().contentType(JSON) .body("{\"name\":\"" + clusterName + "\",\"roleArn\":" @@ -287,168 +283,6 @@ class EksRegistryHostsDockerIntegrationTest { return out.toString(StandardCharsets.UTF_8) + problem; } - /** - * Pushes a minimal, genuinely pullable image via raw OCI Distribution calls against Floci's - * ECR data plane. The image contains a tiny static executable at {@code /bin/sleep} so kubelet - * can both unpack and run it to reach {@code Running}. - */ - private void pushMinimalImage(String host, String repo) throws Exception { - String arch = "amd64"; - boolean isArm64 = false; - try { - String dockerArch = dockerClient.infoCmd().exec().getArchitecture(); - if (dockerArch != null && (dockerArch.contains("aarch64") || dockerArch.contains("arm64"))) { - arch = "arm64"; - isArm64 = true; - } - } catch (Exception ignored) { - // default to amd64 - } - - byte[] elfBytes = buildPauseElf(isArm64); - byte[] tarBytes; - try (ByteArrayOutputStream tarOut = new ByteArrayOutputStream(); - TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut)) { - TarArchiveEntry entry = new TarArchiveEntry("bin/sleep"); - entry.setMode(0755); - entry.setSize(elfBytes.length); - tar.putArchiveEntry(entry); - tar.write(elfBytes); - tar.closeArchiveEntry(); - tar.finish(); - tarBytes = tarOut.toByteArray(); - } - ByteArrayOutputStream gzOut = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(gzOut)) { - gzip.write(tarBytes); - } - byte[] layerBytes = gzOut.toByteArray(); - String diffId = "sha256:" + Digests.sha256Hex(tarBytes); - String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes); - - byte[] configBytes = ("{\"architecture\":\"" + arch + "\",\"os\":\"linux\",\"config\":{}," - + "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}") - .getBytes(StandardCharsets.UTF_8); - String configDigest = "sha256:" + Digests.sha256Hex(configBytes); - - uploadBlob(host, repo, layerDigest, layerBytes); - uploadBlob(host, repo, configDigest, configBytes); - - String manifestJson = """ - { - "schemaVersion": 2, - "mediaType": "application/vnd.docker.distribution.manifest.v2+json", - "config": { - "mediaType": "application/vnd.docker.container.image.v1+json", - "size": %d, - "digest": "%s" - }, - "layers": [ - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": %d, - "digest": "%s" - } - ] - } - """.formatted(configBytes.length, configDigest, layerBytes.length, layerDigest); - - given().header("Host", host) - .contentType("application/vnd.docker.distribution.manifest.v2+json") - .body(manifestJson) - .when().put("/v2/" + repo + "/manifests/v1") - .then().statusCode(201); - } - - private static byte[] buildPauseElf(boolean isArm64) { - byte[] code; - short machine; - if (isArm64) { - // aarch64: sys_ppoll(NULL, 0, NULL, NULL, 0) (syscall 73) sleeps indefinitely at 0% CPU - code = new byte[]{ - 0x00, 0x00, (byte) 0x80, (byte) 0xd2, // mov x0, #0 - 0x01, 0x00, (byte) 0x80, (byte) 0xd2, // mov x1, #0 - 0x02, 0x00, (byte) 0x80, (byte) 0xd2, // mov x2, #0 - 0x03, 0x00, (byte) 0x80, (byte) 0xd2, // mov x3, #0 - 0x04, 0x00, (byte) 0x80, (byte) 0xd2, // mov x4, #0 - 0x28, 0x09, (byte) 0x80, (byte) 0xd2, // mov x8, #73 - 0x01, 0x00, 0x00, (byte) 0xd4, // svc #0 - (byte) 0xf9, (byte) 0xff, (byte) 0xff, 0x17 // b -7 - }; - machine = (short) 0xB7; - } else { - // x86_64: sys_pause() (syscall 34) sleeps indefinitely at 0% CPU - code = new byte[]{ - (byte) 0xb8, 0x22, 0x00, 0x00, 0x00, // mov eax, 34 - 0x0f, 0x05, // syscall - (byte) 0xeb, (byte) 0xf7 // jmp -9 - }; - machine = (short) 0x3E; - } - long baseAddr = 0x400000L; - long entryPoint = baseAddr + 0x78L; - int fileSize = 0x78 + code.length; - - ByteBuffer buf = ByteBuffer.allocate(fileSize).order(ByteOrder.LITTLE_ENDIAN); - // ELF header (64 bytes) - buf.put(new byte[]{0x7F, 'E', 'L', 'F', 2, 1, 1, 0}); - buf.put(new byte[8]); // padding - buf.putShort((short) 2); // ET_EXEC - buf.putShort(machine); - buf.putInt(1); // EV_CURRENT - buf.putLong(entryPoint); - buf.putLong(64L); // e_phoff - buf.putLong(0L); // e_shoff - buf.putInt(0); // e_flags - buf.putShort((short) 64); // e_ehsize - buf.putShort((short) 56); // e_phentsize - buf.putShort((short) 1); // e_phnum - buf.putShort((short) 0); // e_shentsize - buf.putShort((short) 0); // e_shnum - buf.putShort((short) 0); // e_shstrndx - - // Program header (56 bytes) - buf.putInt(1); // PT_LOAD - buf.putInt(7); // PF_R | PF_W | PF_X - buf.putLong(0L); // p_offset - buf.putLong(baseAddr); // p_vaddr - buf.putLong(baseAddr); // p_paddr - buf.putLong(fileSize); // p_filesz - buf.putLong(fileSize); // p_memsz - buf.putLong(0x1000L); // p_align - - // Code - buf.put(code); - return buf.array(); - } - - private static void ecrAsImageAccount(String action, String body) { - given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action) - .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + IMAGE_ACCOUNT - + "/20260923/us-east-1/ecr/aws4_request") - .contentType("application/x-amz-json-1.1") - .body(body) - .when().post("/") - .then().statusCode(200); - } - - private void uploadBlob(String host, String repo, String digest, byte[] content) { - String location = given().header("Host", host) - .when().post("/v2/" + repo + "/blobs/uploads/") - .then().statusCode(202) - .extract().header("Location"); - assertNotNull(location); - String separator = location.contains("?") ? "&" : "?"; - given().header("Host", host) - // The Location header already carries a percent-encoded _state token; RestAssured's - // default encoding would double-encode it and corrupt the token. - .urlEncodingEnabled(false) - .contentType("application/octet-stream") - .body(content) - .when().put(location + separator + "digest=" + digest) - .then().statusCode(201); - } - private void waitUntilReady(Cluster cluster) { await("cluster ACTIVE").atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(1)) .until(() -> { diff --git a/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java index cd0f5325e6..06144215e1 100644 --- a/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksVpcPodNetworkNightlyIntegrationTest.java @@ -15,6 +15,7 @@ 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.io.IOException; import java.net.URI; @@ -40,8 +41,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * arguments, on a network standing in for Floci's and a second standing in for the VPC's: its pods take addresses from * both of its prefixes, and those answer another container on the VPC network and, on Linux, this JVM, the way Floci's * health checks and load balancers dial a {@code TargetType ip} target. It pulls k3s and busybox and runs fourteen pods, - * so it runs nightly rather than in the pull request shards. + * so it runs with the nightly checks ({@code -Dnightly.checks.enabled=true}) rather than in the pull request shards. */ +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") class EksVpcPodNetworkNightlyIntegrationTest { private static final Logger LOG = Logger.getLogger(EksVpcPodNetworkNightlyIntegrationTest.class); diff --git a/src/test/java/io/floci/aws/testing/EcrRequests.java b/src/test/java/io/floci/aws/testing/EcrRequests.java new file mode 100644 index 0000000000..a945e422da --- /dev/null +++ b/src/test/java/io/floci/aws/testing/EcrRequests.java @@ -0,0 +1,19 @@ +package io.floci.aws.testing; + +import static io.restassured.RestAssured.given; + +/** ECR JSON requests signed for an account in a region, which must succeed. */ +public final class EcrRequests { + + private EcrRequests() { + } + + public static void ecr(String account, String region, String action, String body) { + given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action) + .header("Authorization", EnforcementFixtures.auth(account, region, "ecr")) + .contentType("application/x-amz-json-1.1") + .body(body) + .when().post("/") + .then().statusCode(200); + } +} diff --git a/src/test/java/io/floci/aws/testing/EcrTestImages.java b/src/test/java/io/floci/aws/testing/EcrTestImages.java new file mode 100644 index 0000000000..c7614c70d4 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/EcrTestImages.java @@ -0,0 +1,182 @@ +package io.floci.aws.testing; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.Digests; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.jboss.logging.Logger; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPOutputStream; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * A minimal image that a k3s node can pull from Floci ECR and run: one layer holding a tiny static executable at + * {@code /bin/sleep} that sleeps without end at no CPU, built for the Docker daemon's architecture, pushed through the + * registry API as {@code docker push} would. + */ +public final class EcrTestImages { + + private static final Logger LOG = Logger.getLogger(EcrTestImages.class); + + private EcrTestImages() { + } + + /** + * Pushes the image to {@code repo} as {@code tag}, sending {@code host}, one of Floci's repository hosts, as the + * {@code Host} header. The repository must exist: ECR refuses a push to one nobody created. + */ + public static void pushSleepImage(DockerClient dockerClient, String host, String repo, String tag) + throws IOException { + boolean arm64 = isArm64(dockerClient); + byte[] executable = sleepExecutable(arm64); + byte[] tarBytes; + try (ByteArrayOutputStream tarOut = new ByteArrayOutputStream(); + TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut)) { + TarArchiveEntry entry = new TarArchiveEntry("bin/sleep"); + entry.setMode(0755); + entry.setSize(executable.length); + tar.putArchiveEntry(entry); + tar.write(executable); + tar.closeArchiveEntry(); + tar.finish(); + tarBytes = tarOut.toByteArray(); + } + ByteArrayOutputStream gzOut = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(gzOut)) { + gzip.write(tarBytes); + } + byte[] layerBytes = gzOut.toByteArray(); + String diffId = "sha256:" + Digests.sha256Hex(tarBytes); + String layerDigest = "sha256:" + Digests.sha256Hex(layerBytes); + + byte[] configBytes = ("{\"architecture\":\"" + (arm64 ? "arm64" : "amd64") + "\",\"os\":\"linux\",\"config\":{}," + + "\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[\"" + diffId + "\"]}}") + .getBytes(StandardCharsets.UTF_8); + String configDigest = "sha256:" + Digests.sha256Hex(configBytes); + + uploadBlob(host, repo, layerDigest, layerBytes); + uploadBlob(host, repo, configDigest, configBytes); + + String manifestJson = """ + { + "schemaVersion": 2, + "mediaType": "application/vnd.docker.distribution.manifest.v2+json", + "config": { + "mediaType": "application/vnd.docker.container.image.v1+json", + "size": %d, + "digest": "%s" + }, + "layers": [ + { + "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", + "size": %d, + "digest": "%s" + } + ] + } + """.formatted(configBytes.length, configDigest, layerBytes.length, layerDigest); + + given().header("Host", host) + .contentType("application/vnd.docker.distribution.manifest.v2+json") + .body(manifestJson) + .when().put("/v2/" + repo + "/manifests/" + tag) + .then().statusCode(201); + } + + private static boolean isArm64(DockerClient dockerClient) { + try { + String architecture = dockerClient.infoCmd().exec().getArchitecture(); + return architecture != null && (architecture.contains("aarch64") || architecture.contains("arm64")); + } catch (RuntimeException e) { + LOG.warnv("Could not read the Docker daemon's architecture, so the image is built for amd64: {0}", + e.getMessage()); + return false; + } + } + + private static byte[] sleepExecutable(boolean arm64) { + byte[] code; + short machine; + if (arm64) { + // aarch64: sys_ppoll(NULL, 0, NULL, NULL, 0) (syscall 73) sleeps indefinitely at 0% CPU + code = new byte[]{ + 0x00, 0x00, (byte) 0x80, (byte) 0xd2, // mov x0, #0 + 0x01, 0x00, (byte) 0x80, (byte) 0xd2, // mov x1, #0 + 0x02, 0x00, (byte) 0x80, (byte) 0xd2, // mov x2, #0 + 0x03, 0x00, (byte) 0x80, (byte) 0xd2, // mov x3, #0 + 0x04, 0x00, (byte) 0x80, (byte) 0xd2, // mov x4, #0 + 0x28, 0x09, (byte) 0x80, (byte) 0xd2, // mov x8, #73 + 0x01, 0x00, 0x00, (byte) 0xd4, // svc #0 + (byte) 0xf9, (byte) 0xff, (byte) 0xff, 0x17 // b -7 + }; + machine = (short) 0xB7; + } else { + // x86_64: sys_pause() (syscall 34) sleeps indefinitely at 0% CPU + code = new byte[]{ + (byte) 0xb8, 0x22, 0x00, 0x00, 0x00, // mov eax, 34 + 0x0f, 0x05, // syscall + (byte) 0xeb, (byte) 0xf7 // jmp -9 + }; + machine = (short) 0x3E; + } + long baseAddr = 0x400000L; + long entryPoint = baseAddr + 0x78L; + int fileSize = 0x78 + code.length; + + ByteBuffer buf = ByteBuffer.allocate(fileSize).order(ByteOrder.LITTLE_ENDIAN); + // ELF header (64 bytes) + buf.put(new byte[]{0x7F, 'E', 'L', 'F', 2, 1, 1, 0}); + buf.put(new byte[8]); // padding + buf.putShort((short) 2); // ET_EXEC + buf.putShort(machine); + buf.putInt(1); // EV_CURRENT + buf.putLong(entryPoint); + buf.putLong(64L); // e_phoff + buf.putLong(0L); // e_shoff + buf.putInt(0); // e_flags + buf.putShort((short) 64); // e_ehsize + buf.putShort((short) 56); // e_phentsize + buf.putShort((short) 1); // e_phnum + buf.putShort((short) 0); // e_shentsize + buf.putShort((short) 0); // e_shnum + buf.putShort((short) 0); // e_shstrndx + + // Program header (56 bytes) + buf.putInt(1); // PT_LOAD + buf.putInt(7); // PF_R | PF_W | PF_X + buf.putLong(0L); // p_offset + buf.putLong(baseAddr); // p_vaddr + buf.putLong(baseAddr); // p_paddr + buf.putLong(fileSize); // p_filesz + buf.putLong(fileSize); // p_memsz + buf.putLong(0x1000L); // p_align + + // Code + buf.put(code); + return buf.array(); + } + + private static void uploadBlob(String host, String repo, String digest, byte[] content) { + String location = given().header("Host", host) + .when().post("/v2/" + repo + "/blobs/uploads/") + .then().statusCode(202) + .extract().header("Location"); + assertNotNull(location); + String separator = location.contains("?") ? "&" : "?"; + given().header("Host", host) + // The Location header already carries a percent-encoded _state token; RestAssured's + // default encoding would double-encode it and corrupt the token. + .urlEncodingEnabled(false) + .contentType("application/octet-stream") + .body(content) + .when().put(location + separator + "digest=" + digest) + .then().statusCode(201); + } +}