fix(ecr): scope the registry data plane to each account and answer NAME_UNKNOWN (#9171)

The registry data plane and the catalog reconcile run outside any request, so the
account-aware repository store read and wrote them as the default account. A repository
another account created was not found: its IMMUTABLE tags were not enforced, and the
reconcile recreated it in the default account's partition. The data plane's lookups now
read the repository in the account its registry host names, and the reconcile reads and
writes each entry in the account it belongs to, the configured default account for a
pre-proxy namespace even when a request of another account started the registry.

A push or pull for a repository nobody created fell back to the default namespace, so
registry:2 stored it and the next start adopted it. Once the catalog has been read, such a
name now answers 404 NAME_UNKNOWN before any byte reaches the registry, once it has been
checked against the registry running now: a recovered registry's catalog is read again.
Until then it answers unavailable, since its images may be in the registry: the start's
catalog read is strict now, so a failed read no longer counts as an empty catalog, and the
data plane retries it, at most every 30 seconds. A client that leaves while the catalog is
read gives its write admission back at once, and a lookup that fails after the read is
answered with a 500 rather than left waiting.

The EKS registry-hosts and ECR TLS data-plane tests create their repository before pushing.

Closes #6101
Closes #6140

Co-authored-by: Yi-111-a <153097222+Yi-111-a@users.noreply.github.com>
This commit is contained in:
Priamo GermosenandYi-111-a authored and GitHub committed 2026-11-22 09:14:38 -04:00
1 parent a966242daf
commit d8809f6f0e
11 files changed
+676 -47

No files matched your search

@@ -296,23 +296,27 @@ public class EcrService implements ResourceProvider, Resettable {
* Recreates {@link Repository} metadata entries for registry namespaces found in the catalog.
* Namespaces created by Floci are {@code <account>/<region>/<repoName>}; pre-proxy registry
* namespaces are recovered for the default account and region without moving image storage.
*
* <p>The catalog is read when the registry starts, outside any request or inside the one that
* happened to start it, so each entry is read and written in the account it belongs to: the
* configured default account for a pre-proxy namespace, the account a namespaced one begins with.
*/
void reconcileFromCatalog(List<String> catalog) {
if (catalog == null || catalog.isEmpty()) {
return;
}
String defaultAccount = regionResolver.getDefaultAccountId();
String defaultRegion = regionResolver.getDefaultRegion();
int recreated = 0;
for (String registryRepositoryName : catalog) {
String defaultAccount = regionResolver.getAccountId();
String defaultRegion = regionResolver.getDefaultRegion();
String legacyKey = key(defaultRegion, defaultAccount, registryRepositoryName);
Optional<Repository> legacyRepository = repoStore.get(legacyKey);
Optional<Repository> legacyRepository = repositoryInAccount(defaultAccount, legacyKey);
if (legacyRepository.isPresent()) {
Repository repo = legacyRepository.get();
repo.setRepositoryUri(registryManager.getRepositoryUri(
defaultAccount, defaultRegion, repo.getRepositoryName()));
repo.setRegistryRepositoryName(registryRepositoryName);
repoStore.put(legacyKey, repo);
AccountAwareStorageBackend.putInAccount(repoStore, defaultAccount, legacyKey, repo);
continue;
}
String[] parts = registryRepositoryName.split("/", 3);
@@ -322,14 +326,14 @@ public class EcrService implements ResourceProvider, Resettable {
String region = namespaced ? parts[1] : defaultRegion;
String repoName = namespaced ? parts[2] : registryRepositoryName;
String key = key(region, account, repoName);
Optional<Repository> existing = repoStore.get(key);
Optional<Repository> existing = repositoryInAccount(account, key);
if (existing.isPresent()) {
Repository repo = existing.get();
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
if (!namespaced) {
repo.setRegistryRepositoryName(registryRepositoryName);
}
repoStore.put(key, repo);
AccountAwareStorageBackend.putInAccount(repoStore, account, key, repo);
continue;
}
Repository repo = new Repository();
@@ -341,7 +345,7 @@ public class EcrService implements ResourceProvider, Resettable {
repo.setRegistryRepositoryName(registryRepositoryName);
}
repo.setCreatedAt(Instant.now());
repoStore.put(key, repo);
AccountAwareStorageBackend.putInAccount(repoStore, account, key, repo);
recreated++;
}
if (recreated > 0) {
@@ -349,6 +353,18 @@ public class EcrService implements ResourceProvider, Resettable {
}
}
/**
* The repository stored under {@code key} in {@code account}. An entry from before the store was kept by account
* is the default account's, as the store reads it, and moves into that account when it asks.
*/
private Optional<Repository> repositoryInAccount(String account, String key) {
if (repoStore instanceof AccountAwareStorageBackend<Repository> aware) {
boolean ownsLegacyEntries = account.equals(regionResolver.getDefaultAccountId());
return aware.getForAccountMigratingLegacy(account, key, repo -> ownsLegacyEntries);
}
return repoStore.get(key);
}
// ============================================================
// Repository creation templates
// ============================================================
@@ -1715,21 +1731,42 @@ public class EcrService implements ResourceProvider, Resettable {
return repo;
}
/** Returns whether the repository rejects a second manifest write for an existing tag. */
/**
* Returns whether the repository rejects a second manifest write for an existing tag. The registry data plane
* asks outside any request, so the repository is read in the account its registry host names.
*/
public boolean isImageTagImmutable(String repositoryName, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, repositoryName))
return dataPlaneRepository(repositoryName, account, region)
.map(Repository::getImageTagMutability)
.filter("IMMUTABLE"::equals)
.isPresent();
}
/** Returns the physical registry namespace selected for an ECR repository. */
/**
* Returns the physical registry namespace of an ECR repository, for the registry data plane, which asks outside
* any request: the repository is read in the account its registry host names. A name with no repository is
* refused as ECR refuses it, with {@code RepositoryNotFoundException} the data plane answers as
* {@code NAME_UNKNOWN}, once the registry's catalog has been read into the metadata. Before that, a repository
* whose images the registry holds may have no metadata yet, so the name is refused as unavailable rather than
* as missing.
*/
public String registryRepositoryName(String repositoryName, String registryId, String region) {
String account = effectiveAccount(registryId);
return repoStore.get(key(region, account, repositoryName))
return dataPlaneRepository(repositoryName, account, region)
.map(repo -> registryRepositoryName(repo, region))
.orElseGet(() -> registryManager.internalRepoName(account, region, repositoryName));
.orElseThrow(() -> {
if (!registryManager.isCatalogReconciled()) {
return new IllegalStateException("The ECR registry catalog has not been read yet, so "
+ "repository '" + repositoryName + "' in registry " + account
+ " cannot be told from a missing one.");
}
return notFound(repositoryName, account);
});
}
private Optional<Repository> dataPlaneRepository(String repositoryName, String account, String region) {
return AccountAwareStorageBackend.readInAccount(repoStore, account, key(region, account, repositoryName));
}
public void tagResource(String repoName, String registryId, Map<String, String> tags, String region) {
@@ -2,6 +2,7 @@ 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.services.ecr.EcrService;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
@@ -91,19 +92,105 @@ public class EcrRegistryDataPlane {
return;
}
boolean writeAdmissionHeld = isWrite;
context.request().pause();
RegistryRequest registryRequest = request.get();
if (registryRequest.repositoryName().isEmpty()) {
admit(context, registryRequest, isWrite);
} else if (registryManager.isCatalogReconciled()) {
String storage;
try {
storage = ecrService.registryRepositoryName(
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region());
} catch (RuntimeException e) {
// The registry may have been recovered since its catalog was read, so a name that catalog does
// not place is checked against the registry running now before it is refused.
resolveAfterTheCatalogThenAdmit(context, registryRequest, isWrite);
return;
}
admit(context, registryRequest.withStorageRepositoryName(storage), isWrite);
} else {
resolveAfterTheCatalogThenAdmit(context, registryRequest, isWrite);
}
}
/**
* Until the catalog of the registry running now has been read, a name with no metadata cannot be told from a
* repository whose images the registry holds, so the registry is started, or recovered, and its catalog read
* first, off the event loop, before the name is resolved.
*
* <p>Exactly one of the client leaving and the read finishing takes the request on: a client that goes away
* meanwhile gives its write admission back at once, so garbage collection does not wait on a write that can
* no longer come.
*/
private void resolveAfterTheCatalogThenAdmit(RoutingContext context, RegistryRequest registryRequest,
boolean writeAdmitted) {
AtomicBoolean waiting = new AtomicBoolean(true);
context.response().closeHandler(closed -> {
if (waiting.compareAndSet(true, false) && writeAdmitted) {
registryManager.releaseWriteAdmission();
}
});
vertx.<String>executeBlocking(promise -> {
try {
registryManager.ensureStarted();
registryManager.ensureCatalogReconciled();
promise.complete(ecrService.registryRepositoryName(
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
} catch (Exception e) {
promise.fail(e);
}
}).onComplete(result -> {
if (!waiting.compareAndSet(true, false)) {
return;
}
if (context.response().closed()) {
if (writeAdmitted) {
registryManager.releaseWriteAdmission();
}
} else if (result.failed()) {
refuseUnresolved(context, registryRequest, writeAdmitted, result.cause());
} else {
try {
admit(context, registryRequest.withStorageRepositoryName(result.result()), writeAdmitted);
} catch (Throwable t) {
// admit gave back what it took. Off the router's call stack nothing else answers the failure,
// so it gets the 500 the synchronous path's would.
context.request().resume();
context.fail(t);
}
}
});
}
/**
* Answers a request whose repository could not be resolved: {@code 404 NAME_UNKNOWN} for one nobody created, as
* ECR answers before any byte reaches the registry, and unavailable for anything else.
*/
private void refuseUnresolved(RoutingContext context, RegistryRequest registryRequest,
boolean writeAdmissionHeld, Throwable failure) {
if (writeAdmissionHeld) {
registryManager.releaseWriteAdmission();
}
context.request().resume();
if (failure instanceof AwsException aws && "RepositoryNotFoundException".equals(aws.getErrorCode())) {
if (!context.response().ended() && !context.response().closed()) {
context.response().putHeader("Docker-Distribution-API-Version", "registry/2.0");
registryError(context, 404, "NAME_UNKNOWN", aws.getMessage());
}
return;
}
LOG.debugv(failure, "Could not resolve ECR repository {0} in registry {1}",
registryRequest.repositoryName(), registryRequest.accountId());
registryUnavailable(context);
}
/** Takes a resolved request on to its immutable-tag claim, its repository write lock and the registry. */
private void admit(RoutingContext context, RegistryRequest registryRequest, boolean writeAdmitted) {
boolean writeAdmissionHeld = writeAdmitted;
Exchange activeExchange = null;
String immutableTag = null;
boolean tagClaimed = false;
try {
context.request().pause();
RegistryRequest registryRequest = request.get();
if (!registryRequest.repositoryName().isEmpty()) {
registryRequest = registryRequest.withStorageRepositoryName(
ecrService.registryRepositoryName(
registryRequest.repositoryName(), registryRequest.accountId(), registryRequest.region()));
}
immutableTag = immutableTag(context, registryRequest);
if (immutableTag != null) {
if (!ecrService.claimImmutableTag(immutableTag)) {
@@ -118,7 +205,8 @@ public class EcrRegistryDataPlane {
tagClaimed = true;
}
Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest), isWrite);
Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest),
isWriteRequest(context.request().method()));
activeExchange = exchange;
writeAdmissionHeld = false;
context.response().closeHandler(closed -> exchange.end());
@@ -133,7 +221,6 @@ public class EcrRegistryDataPlane {
release(immutableTag);
}
if (writeAdmissionHeld) {
writeAdmissionHeld = false;
registryManager.releaseWriteAdmission();
}
}
@@ -66,6 +66,7 @@ public class EcrRegistryManager {
private static final String NAMED_VOLUME = "ecr-registry-data";
private static final String REPOSITORIES_PATH = "/var/lib/registry/docker/registry/v2/repositories/";
private static final int GC_KILL_GRACE_SECONDS = 2;
static final long RECONCILE_RETRY_MILLIS = 30_000;
/**
* Matches an AWS-shaped ECR image URI in any partition:
@@ -112,6 +113,8 @@ public class EcrRegistryManager {
private volatile boolean started;
private volatile boolean ready;
private volatile boolean reconciled;
/** When a reconcile retry last failed, by {@link #clock}; 0 while none has. */
private volatile long reconcileRetryFailedAt;
// Bug #6150: Track active garbage collection window
private volatile boolean garbageCollecting;
private final Object writeAdmissionLock = new Object();
@@ -402,6 +405,33 @@ public class EcrRegistryManager {
this.reconcileHook = hook;
}
/**
* Reads the catalog into the reconcile hook again when the read at start failed, so a
* registry that answered its health check but not its catalog does not leave the
* repositories it holds without metadata. A no-op once a read succeeded, with no hook,
* or before the registry started. A retry that fails waits {@link #RECONCILE_RETRY_MILLIS}
* before the next, so a lookup made meanwhile does not pay a catalog read each time.
*
* <p>Holds the monitor {@link #ensureStarted()} and the storage deletes take, so the
* hook's metadata writes cannot interleave with a forced repository delete.
*/
public synchronized void ensureCatalogReconciled() {
if (reconciled || reconcileHook == null || !started) {
return;
}
long now = clock.millis();
if (reconcileRetryFailedAt != 0 && now - reconcileRetryFailedAt < RECONCILE_RETRY_MILLIS) {
return;
}
runReconcileOnce();
reconcileRetryFailedAt = reconciled ? 0 : now;
}
/** Whether the registry's catalog has been read into the reconcile hook since it started. */
public boolean isCatalogReconciled() {
return reconciled;
}
/**
* Attempts {@link #ensureStarted()} and reports whether the backing registry is
* usable, instead of propagating the failure. Callers that only need repository
@@ -468,6 +498,9 @@ public class EcrRegistryManager {
registryAddress = null;
started = false;
ready = false;
// The recovered registry's catalog is read again: it can hold images the one read before did not.
reconciled = false;
reconcileRetryFailedAt = 0;
if (presence == ContainerPresence.ABSENT) {
portAllocator.release(hostPort);
hostPort = config.services().ecr().registryBasePort();
@@ -630,7 +663,9 @@ public class EcrRegistryManager {
return;
}
try {
List<String> repos = httpClient().catalog();
// The strict read: a catalog the registry failed to give is not an empty one, and taking
// it as one would leave the repositories it holds without metadata.
List<String> repos = httpClient().catalogStrict();
reconcileHook.accept(repos);
reconciled = true;
} catch (Exception e) {
@@ -870,6 +905,7 @@ public class EcrRegistryManager {
started = false;
ready = false;
reconciled = false;
reconcileRetryFailedAt = 0;
reopenWriteAdmission();
hostPort = config.services().ecr().registryBasePort();
}