diff --git a/docs/services/ecr.md b/docs/services/ecr.md index 64bf4f1b50..3b87820537 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -124,6 +124,13 @@ aws ecr delete-repository --repository-name floci-it/app --force \ --endpoint-url $AWS_ENDPOINT ``` +!!! note "Pulling from other containers (EKS, same-network consumers)" + The `localhost`-based repository URI only works from the host. From other containers + on the Docker network, the registry is reachable at `http://floci-ecr-registry:5000` + (container name + container-internal port — not the published `5100+` host port). + [Floci EKS](eks.md#pulling-images-from-floci-ecr) clusters get a containerd mirror + for this automatically, so Helm charts can reference the pushed URI as-is. + ## SDK Example (Java) ```java diff --git a/docs/services/eks.md b/docs/services/eks.md index e4cec5d86c..d1138bf00c 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -79,6 +79,51 @@ services: | `FLOCI_SERVICES_EKS_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave k3s containers running after Floci stops | | `FLOCI_SERVICES_EKS_ENDPOINT_MODE` | `host` | `describe-cluster` endpoint: `host` (`localhost:`) or `network` (container DNS) | | `FLOCI_SERVICES_EKS_IAM_AUTH_WEBHOOK` | `true` | Wire a token-auth webhook into k3s so `aws eks get-token` works | +| `FLOCI_SERVICES_EKS_ECR_REGISTRY_MIRROR` | `true` | Inject a containerd `registries.yaml` so pods can pull images pushed to [Floci ECR](ecr.md) | + +### Pulling images from Floci ECR + +Images pushed to the [Floci ECR registry](ecr.md) use `localhost`-based repository URIs +(for example `000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:tag`). Inside a k3s +cluster that hostname would resolve to the k3s container itself, and containerd insists +on HTTPS for anything it doesn't recognize as loopback — so, out of the box, k3s cannot +pull from the registry even though `docker push` from the host works. + +Floci solves this at cluster creation: each new k3s container gets a generated +`/etc/rancher/k3s/registries.yaml` that mirrors every repository hostname the emulator +can mint — the default account across the full region catalog, plus the path-style +`localhost:` form used by `FLOCI_SERVICES_ECR_URI_STYLE=path` — to the registry +container's in-network endpoint (`http://floci-ecr-registry:5000`). The same image +reference then works for the host-side push and the in-cluster pull, with no retagging +and no manual containerd configuration: + +```bash +aws ecr create-repository --repository-name my-repo +docker build -t 000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:v1 . +docker push 000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo:v1 + +aws eks create-cluster --name demo ... +helm install my-app ./chart \ + --set image.repository=000000000000.dkr.ecr.us-east-1.localhost:5100/my-repo \ + --set image.tag=v1 +``` + +Requirements and limits: + +- The k3s and registry containers must share a Docker network — set the global + `FLOCI_SERVICES_DOCKER_NETWORK` (as in the standard `docker-compose.yml`) or the + per-service network variables. +- Only Floci-mintable hostnames are mirrored; public registries (docker.io, ghcr.io, …) + are never touched. +- 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 (or after the registry was re-created on a different port) can be fixed + manually — the k3s container filesystem survives a restart: + + ```bash + docker cp registries.yaml floci-eks-:/etc/rancher/k3s/registries.yaml + docker restart floci-eks- + ``` ### Mock mode (CI / tests) diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 250fff3014..cd9e3ecf9c 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1396,6 +1396,15 @@ public interface EmulatorConfig { */ @WithDefault("true") boolean iamAuthWebhook(); + + /** + * 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. + */ + @WithDefault("true") + boolean ecrRegistryMirror(); } interface InitHooksConfig { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsRegions.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsRegions.java new file mode 100644 index 0000000000..2a94e46b54 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsRegions.java @@ -0,0 +1,20 @@ +package io.github.hectorvent.floci.core.common; + +import java.util.List; + +/** + * Catalog of AWS regions the emulator advertises. Single source of truth for + * every feature that enumerates regions (EC2 DescribeRegions, EKS ECR-mirror + * hostnames, ...). + */ +public final class AwsRegions { + + public static final List ALL = List.of( + "us-east-1", "us-east-2", "us-west-1", "us-west-2", + "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", + "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", + "ap-south-1", "sa-east-1", "ca-central-1"); + + private AwsRegions() { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 84b6cbdbea..b0cc012be7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -26,6 +26,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ec2.model.Address; @@ -2406,12 +2407,7 @@ public class Ec2Service { } public List describeRegions() { - return List.of( - "us-east-1", "us-east-2", "us-west-1", "us-west-2", - "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", - "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", - "ap-south-1", "sa-east-1", "ca-central-1" - ); + return AwsRegions.ALL; } public Map describeAccountAttributes(String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java index dc42c592ab..5a5308dfc9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/registry/EcrRegistryManager.java @@ -109,10 +109,18 @@ public class EcrRegistryManager { return accountId + "/" + region + "/" + repoName; } + /** + * The registry endpoint reachable from other containers on the Docker network: + * the container name plus the container-internal port (not the published host port). + */ + public String internalEndpoint() { + return "http://" + registryContainerName() + ":" + CONTAINER_INTERNAL_PORT; + } + /** Returns a {@link RegistryHttpClient} bound to the current registry endpoint. */ public RegistryHttpClient httpClient() { if (containerDetector.isRunningInContainer()) { - return new RegistryHttpClient("http://" + registryContainerName() + ":" + CONTAINER_INTERNAL_PORT); + return new RegistryHttpClient(internalEndpoint()); } return new RegistryHttpClient("http://localhost:" + effectivePort()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index 23bdb1047f..e77c596369 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.eks; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; @@ -9,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec; import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.common.docker.PortAllocator; +import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager; import io.github.hectorvent.floci.services.eks.model.CertificateAuthority; import io.github.hectorvent.floci.services.eks.model.Cluster; import com.github.dockerjava.api.async.ResultCallback; @@ -16,8 +18,12 @@ import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.model.Frame; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.jboss.logging.Logger; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; @@ -42,6 +48,9 @@ public class EksClusterManager { private static final String WEBHOOK_CONFIG_DIR = "/etc"; private static final String WEBHOOK_CONFIG_FILE = "token-webhook.yaml"; private static final String WEBHOOK_CONFIG_PATH = WEBHOOK_CONFIG_DIR + "/" + WEBHOOK_CONFIG_FILE; + // Tar entry extracted at /etc; the archive path creates /etc/rancher/k3s, which does not + // exist yet in a created-but-not-started k3s container. + private static final String REGISTRIES_TAR_ENTRY = "rancher/k3s/registries.yaml"; private static final String ENDPOINT_MODE_NETWORK = "network"; private final ContainerBuilder containerBuilder; @@ -49,6 +58,7 @@ public class EksClusterManager { private final ContainerDetector containerDetector; private final PortAllocator portAllocator; private final DockerHostResolver dockerHostResolver; + private final EcrRegistryManager ecrRegistryManager; private final EmulatorConfig config; @Inject @@ -57,12 +67,14 @@ public class EksClusterManager { ContainerDetector containerDetector, PortAllocator portAllocator, DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, EmulatorConfig config) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.containerDetector = containerDetector; this.portAllocator = portAllocator; this.dockerHostResolver = dockerHostResolver; + this.ecrRegistryManager = ecrRegistryManager; this.config = config; } @@ -137,6 +149,7 @@ public class EksClusterManager { if (webhookLocalFile != null) { copyWebhookIntoContainer(containerId, webhookLocalFile, cluster.getName()); } + injectEcrRegistryMirror(containerId, cluster.getName()); ContainerInfo info = lifecycleManager.startCreated(containerId, spec); // Public endpoint: see floci.services.eks.endpoint-mode. `host` (default) is the host-reachable @@ -287,6 +300,99 @@ 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 emulator can mint — default account across + * the full region catalog, plus the path-style {@code localhost:} form — to the registry + * container's in-network endpoint. Public registries are never matched. A failure disables the + * mirror for this cluster but does not abort its startup, matching the webhook contract. + */ + void injectEcrRegistryMirror(String containerId, String clusterName) { + if (!config.services().eks().ecrRegistryMirror() || !config.services().ecr().enabled()) { + return; + } + try { + ecrRegistryManager.ensureStarted(); + } catch (Exception e) { + LOG.warnv("EKS cluster {0} gets no ECR registry mirror: registry unavailable: {1}", + clusterName, e.getMessage()); + return; + } + List regions = new ArrayList<>(AwsRegions.ALL); + if (!regions.contains(config.defaultRegion())) { + regions.add(config.defaultRegion()); + } + String content = buildRegistriesYaml(config.defaultAccountId(), regions, + ecrRegistryManager.effectivePort(), ecrRegistryManager.internalEndpoint()); + writeRegistriesYaml(clusterName, content); + try { + lifecycleManager.getDockerClient() + .copyArchiveToContainerCmd(containerId) + .withTarInputStream(new ByteArrayInputStream(tarSingleFile(REGISTRIES_TAR_ENTRY, content))) + .withRemotePath("/etc") + .exec(); + LOG.infov("Injected ECR registry mirror ({0}) into k3s cluster {1}", + ecrRegistryManager.internalEndpoint(), 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()); + } + } + + /** Best-effort local copy for inspection/debugging; the container copy streams from memory. */ + private void writeRegistriesYaml(String clusterName, String content) { + Path localFile = Paths.get(config.services().eks().dataPath(), "registries", clusterName, "registries.yaml") + .toAbsolutePath().normalize(); + try { + Files.createDirectories(localFile.getParent()); + Files.writeString(localFile, content); + } catch (IOException e) { + LOG.debugv("Could not write local registries.yaml copy for cluster {0}: {1}", + clusterName, e.getMessage()); + } + } + + private static byte[] tarSingleFile(String entryName, String content) { + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] data = content.getBytes(StandardCharsets.UTF_8); + try (TarArchiveOutputStream tar = new TarArchiveOutputStream(out)) { + TarArchiveEntry entry = new TarArchiveEntry(entryName); + entry.setSize(data.length); + entry.setMode(0644); + tar.putArchiveEntry(entry); + tar.write(data); + tar.closeArchiveEntry(); + } + return out.toByteArray(); + } catch (IOException e) { + throw new IllegalStateException("Could not build in-memory tar for " + entryName, e); + } + } + + /** + * Builds the k3s registries.yaml content. One mirror entry per hostname-style repository URI + * ({@code .dkr.ecr..localhost:}) plus one for the path-style form + * ({@code localhost:}), all pointing at the registry's in-network endpoint. k3s supports + * no partial wildcards and a {@code "*"} catch-all would also intercept public registries, + * so the hostnames are enumerated explicitly. + */ + static String buildRegistriesYaml(String accountId, List regions, int hostPort, String endpoint) { + StringBuilder yaml = new StringBuilder("mirrors:\n"); + for (String region : regions) { + appendMirror(yaml, accountId + ".dkr.ecr." + region + ".localhost:" + hostPort, endpoint); + } + appendMirror(yaml, "localhost:" + hostPort, endpoint); + return yaml.toString(); + } + + private static void appendMirror(StringBuilder yaml, String host, String endpoint) { + yaml.append(" \"").append(host).append("\":\n") + .append(" endpoint:\n") + .append(" - \"").append(endpoint).append("\"\n"); + } + /** The Floci token-webhook URL as reachable from inside the k3s container. */ String webhookUrl() { return "http://" + dockerHostResolver.resolve() + ":" + config.port() + "/_floci/eks/token-webhook"; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index f3d4f8b994..4ab03672fd 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -355,6 +355,7 @@ floci: keep-running-on-shutdown: false endpoint-mode: host # host = https://localhost: (host-reachable); network = container DNS name iam-auth-webhook: true # wire a token-auth webhook into k3s so `aws eks get-token` works + ecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECR elbv2: enabled: true mock: false diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index 245288bd07..13696dd458 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -1,9 +1,33 @@ package io.github.hectorvent.floci.services.eks; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; +import io.github.hectorvent.floci.core.common.docker.PortAllocator; +import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; + +import java.nio.file.Path; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; class EksClusterManagerTest { @@ -50,4 +74,124 @@ class EksClusterManagerTest { assertEquals("https://localhost:6500", EksClusterManager.resolvePublicEndpoint(true, "bogus", "floci-eks-demo", 6500)); } + + @Test + void registriesYamlMirrorsEveryRegionHostnameAndThePathStyleForm() { + String yaml = EksClusterManager.buildRegistriesYaml( + "000000000000", AwsRegions.ALL, 5100, "http://floci-ecr-registry:5000"); + + assertTrue(yaml.startsWith("mirrors:\n")); + for (String region : AwsRegions.ALL) { + assertTrue(yaml.contains("\"000000000000.dkr.ecr." + region + ".localhost:5100\":"), + "should mirror the " + region + " hostname"); + } + assertTrue(yaml.contains("\"localhost:5100\":"), "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-ecr-registry:5000\"")).count(); + assertEquals(AwsRegions.ALL.size() + 1, endpoints, + "every mirror should point at the registry's in-network endpoint"); + } + + @Test + void registriesYamlUsesTheActualRegistryPortAndEndpoint() { + String yaml = EksClusterManager.buildRegistriesYaml( + "111122223333", List.of("eu-central-1"), 5142, "http://my-registry:5000"); + + assertTrue(yaml.contains("\"111122223333.dkr.ecr.eu-central-1.localhost:5142\":")); + assertTrue(yaml.contains("\"localhost:5142\":")); + assertTrue(yaml.contains("- \"http://my-registry:5000\"")); + } + + /** Mirror-injection guard behavior, without a Docker daemon. */ + @Nested + class InjectEcrRegistryMirror { + + @TempDir + Path tempDir; + + private ContainerLifecycleManager lifecycleManager; + private DockerClient dockerClient; + private CopyArchiveToContainerCmd copyCmd; + private EcrRegistryManager registryManager; + private EmulatorConfig.EksServiceConfig eks; + private EmulatorConfig.EcrServiceConfig ecr; + private EksClusterManager manager; + + @BeforeEach + void setUp() { + lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); + dockerClient = Mockito.mock(DockerClient.class); + copyCmd = Mockito.mock(CopyArchiveToContainerCmd.class, Mockito.RETURNS_SELF); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + when(dockerClient.copyArchiveToContainerCmd(anyString())).thenReturn(copyCmd); + + registryManager = Mockito.mock(EcrRegistryManager.class); + when(registryManager.effectivePort()).thenReturn(5100); + when(registryManager.internalEndpoint()).thenReturn("http://floci-ecr-registry:5000"); + + EmulatorConfig config = Mockito.mock(EmulatorConfig.class); + eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class); + ecr = Mockito.mock(EmulatorConfig.EcrServiceConfig.class); + when(config.services()).thenReturn(Mockito.mock(EmulatorConfig.ServicesConfig.class)); + when(config.services().eks()).thenReturn(eks); + when(config.services().ecr()).thenReturn(ecr); + when(config.defaultRegion()).thenReturn("us-east-1"); + when(config.defaultAccountId()).thenReturn("000000000000"); + when(eks.ecrRegistryMirror()).thenReturn(true); + when(eks.dataPath()).thenReturn(tempDir.toString()); + when(ecr.enabled()).thenReturn(true); + + manager = new EksClusterManager( + Mockito.mock(ContainerBuilder.class), lifecycleManager, + Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), + Mockito.mock(DockerHostResolver.class), registryManager, config); + } + + @Test + void injectsTheMirrorIntoTheContainer() { + manager.injectEcrRegistryMirror("container-1", "demo"); + + verify(registryManager).ensureStarted(); + verify(copyCmd).withRemotePath("/etc"); + verify(copyCmd).exec(); + } + + @Test + void skipsWhenTheKnobIsOff() { + when(eks.ecrRegistryMirror()).thenReturn(false); + + manager.injectEcrRegistryMirror("container-1", "demo"); + + verifyNoInteractions(registryManager); + verify(lifecycleManager, never()).getDockerClient(); + } + + @Test + void skipsWhenEcrIsDisabled() { + when(ecr.enabled()).thenReturn(false); + + manager.injectEcrRegistryMirror("container-1", "demo"); + + verifyNoInteractions(registryManager); + verify(lifecycleManager, never()).getDockerClient(); + } + + @Test + void registryStartupFailureSkipsTheMirrorWithoutAborting() { + Mockito.doThrow(new RuntimeException("no docker")).when(registryManager).ensureStarted(); + + manager.injectEcrRegistryMirror("container-1", "demo"); + + verify(lifecycleManager, never()).getDockerClient(); + } + + @Test + void copyFailureDoesNotAbortClusterCreation() { + when(copyCmd.exec()).thenThrow(new RuntimeException("copy failed")); + + manager.injectEcrRegistryMirror("container-1", "demo"); + + verify(copyCmd).exec(); + } + } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index e627ae89fa..36c46fc2b2 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -217,6 +217,7 @@ floci: eks: enabled: true mock: true + ecr-registry-mirror: true pipes: enabled: true elbv2: