fix(ecr): record image push time for registry uploads (#8530)

An image pushed through the Registry V2 endpoint now records its push
time when the registry accepts the manifest, so DescribeImages reports
the push time instead of the time of the first read. A tag added to an
existing digest keeps the first push time, a digest delete clears it,
and a metadata write that fails keeps the registry's response and the
first push time for the next read.
This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-11-16 07:21:24 -04:00
1 parent f733c91a74
commit e8f5a696a8
5 files changed
+283 -22

No files matched your search

@@ -14,6 +14,7 @@ import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.concurrent.KeyedWriteLocks;
import io.floci.aws.core.resource.ExplorerResource;
import io.floci.aws.core.resource.ResourceProvider;
@@ -54,7 +55,7 @@ import java.util.function.Function;
import java.util.regex.Pattern;
@ApplicationScoped
public class EcrService implements ResourceProvider {
public class EcrService implements ResourceProvider, Resettable {
/**
* A private ECR registry host in any partition, {@code <account>.dkr.ecr.<region>.<dnsSuffix>},
@@ -93,6 +94,8 @@ public class EcrService implements ResourceProvider {
private final StorageBackend<String, Repository> repoStore;
private final StorageBackend<String, ImageMetadata> imageMetaStore;
// Keep the first timestamp across write failures. Access is guarded by imageMetaStore.
private final Map<String, ImageMetadata> pendingImagePushes = new HashMap<>();
private final StorageBackend<String, PullThroughCacheRule> pullThroughCacheRuleStore;
private final StorageBackend<String, RegistrySettings> registrySettingsStore;
private final Map<String, Object> registryLocks = new ConcurrentHashMap<>();
@@ -693,8 +696,11 @@ public class EcrService implements ResourceProvider {
repoStore.delete(key);
// Drop cached image metadata for this repo.
String metaPrefix = key + "::";
for (ImageMetadata meta : imageMetaStore.scan(k -> k.startsWith(metaPrefix))) {
imageMetaStore.delete(metaPrefix + meta.getDigest());
synchronized (imageMetaStore) {
pendingImagePushes.keySet().removeIf(k -> k.startsWith(metaPrefix));
for (ImageMetadata meta : imageMetaStore.scan(k -> k.startsWith(metaPrefix))) {
imageMetaStore.delete(metaPrefix + meta.getDigest());
}
}
if (!hasRepositories()) {
registryManager.pruneStorage();
@@ -801,12 +807,7 @@ public class EcrService implements ResourceProvider {
d.setImageManifestMediaType(m.mediaType());
d.setArtifactMediaType(RegistryHttpClient.artifactMediaTypeFromManifest(m.body()));
String metaKey = imageMetaKey(region, repo.getRegistryId(), repositoryName, m.digest());
ImageMetadata meta = imageMetaStore.get(metaKey).orElseGet(() -> {
ImageMetadata fresh = new ImageMetadata(m.digest(), Instant.now());
imageMetaStore.put(metaKey, fresh);
return fresh;
});
ImageMetadata meta = describeImagePush(repo.getRegistryId(), region, repositoryName, m.digest());
d.setImagePushedAt(meta.getPushedAt());
details.add(d);
} catch (Exception e) {
@@ -937,7 +938,7 @@ public class EcrService implements ResourceProvider {
return;
}
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
removeImagePush(repo.getRegistryId(), region, repositoryName, digest);
return;
}
RegistryHttpClient.ManifestResult manifest = http.getManifest(internal, digest, null);
@@ -990,7 +991,7 @@ public class EcrService implements ResourceProvider {
deleted.add(new ImageIdentifier(removedTag, digest));
}
}
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
removeImagePush(repo.getRegistryId(), region, repositoryName, digest);
}
/**
@@ -1102,10 +1103,7 @@ public class EcrService implements ResourceProvider {
String stored = http.putManifest(storage, imageTag != null ? imageTag : digest, mediaType, imageManifest);
String finalDigest = stored != null ? stored : digest;
// A retag keeps the image's first push time, as DescribeImages records it.
String metaKey = imageMetaKey(region, repo.getRegistryId(), repositoryName, finalDigest);
if (imageMetaStore.get(metaKey).isEmpty()) {
imageMetaStore.put(metaKey, new ImageMetadata(finalDigest, Instant.now()));
}
recordImagePush(repo.getRegistryId(), region, repositoryName, finalDigest, Instant.now());
Image image = new Image();
image.setRegistryId(repo.getRegistryId());
@@ -1806,6 +1804,59 @@ public class EcrService implements ResourceProvider {
return refreshRepositoryUri(repo, region);
}
public ImageMetadata recordImagePush(String account, String region, String repositoryName,
String digest, Instant pushedAt) {
String key = imageMetaKey(region, account, repositoryName, digest);
synchronized (imageMetaStore) {
Optional<ImageMetadata> existing = imageMetaStore instanceof AccountAwareStorageBackend<ImageMetadata> aware
? aware.getForAccountMigratingLegacy(account, key, metadata -> digest.equals(metadata.getDigest()))
: imageMetaStore.get(key);
ImageMetadata metadata = existing.orElseGet(() -> {
ImageMetadata pending = pendingImagePushes.computeIfAbsent(key,
ignored -> new ImageMetadata(digest, pushedAt));
AccountAwareStorageBackend.putInAccount(imageMetaStore, account, key, pending);
return pending;
});
pendingImagePushes.remove(key);
return metadata;
}
}
private ImageMetadata describeImagePush(String account, String region, String repositoryName, String digest) {
synchronized (imageMetaStore) {
try {
return recordImagePush(account, region, repositoryName, digest, Instant.now());
} catch (RuntimeException storageFailure) {
ImageMetadata pending = pendingImagePushes.get(imageMetaKey(region, account, repositoryName, digest));
if (pending == null) {
throw storageFailure;
}
LOG.debugv(storageFailure, "Using pending ECR push time for {0} in {1}", digest, repositoryName);
return pending;
}
}
}
public void removeImagePush(String account, String region, String repositoryName, String digest) {
String key = imageMetaKey(region, account, repositoryName, digest);
synchronized (imageMetaStore) {
pendingImagePushes.remove(key);
if (imageMetaStore instanceof AccountAwareStorageBackend<ImageMetadata> aware) {
aware.getForAccountMigratingLegacy(account, key, metadata -> digest.equals(metadata.getDigest()));
aware.deleteForAccount(account, key);
} else {
imageMetaStore.delete(key);
}
}
}
@Override
public void clear() {
synchronized (imageMetaStore) {
pendingImagePushes.clear();
}
}
private static String imageMetaKey(String region, String account, String repoName, String digest) {
return key(region, account, repoName) + "::" + digest;
}
@@ -8,6 +8,7 @@ import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonArray;
@@ -18,10 +19,12 @@ import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -35,6 +38,7 @@ import java.util.regex.Pattern;
@ApplicationScoped
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]+)?$");
private static final String MANIFESTS_PATH = "/manifests/";
@@ -298,8 +302,7 @@ public class EcrRegistryDataPlane {
failUnlessGone(context, 502);
return;
}
copyResponseHeaders(context, upstreamResponse.result(), request);
upstreamResponse.result().pipeTo(context.response()).onComplete(ignored -> exchange.end());
handleRegistryResponse(context, request, exchange, upstreamResponse.result());
});
Buffer waitingBody = exchange.replayBody();
if (waitingBody == null) {
@@ -317,6 +320,69 @@ public class EcrRegistryDataPlane {
});
}
private void handleRegistryResponse(RoutingContext context, RegistryRequest request, Exchange exchange,
HttpClientResponse upstream) {
if (exchange.ended()) {
return;
}
Runnable update = exchange.holdingWriteLock() ? manifestMetadataUpdate(context, request, upstream) : null;
if (update == null) {
forwardResponse(context, request, exchange, upstream);
return;
}
upstream.pause();
exchange.updatingManifestMetadata = true;
vertx.executeBlocking(() -> {
try {
update.run();
} catch (RuntimeException firstFailure) {
LOG.debugv(firstFailure, "Retrying ECR manifest metadata update for {0}", request.storageRepositoryName());
update.run();
}
return null;
}, false).onComplete(result -> {
exchange.updatingManifestMetadata = false;
if (result.failed()) {
LOG.warnv(result.cause(), "Registry accepted {0} {1}, but the ECR manifest metadata update failed",
context.request().method(), request.backendUri());
}
if (exchange.endRequested) {
exchange.end();
} else {
forwardResponse(context, request, exchange, upstream);
}
});
}
private Runnable manifestMetadataUpdate(RoutingContext context, RegistryRequest request,
HttpClientResponse upstream) {
HttpMethod method = context.request().method();
if (method == HttpMethod.PUT && upstream.statusCode() == 201) {
String digest = upstream.getHeader("Docker-Content-Digest");
if (digest != null && !digest.isBlank()) {
Instant pushedAt = Instant.now();
return () -> ecrService.recordImagePush(request.accountId(), request.region(),
request.repositoryName(), digest, pushedAt);
}
}
if (method == HttpMethod.DELETE && upstream.statusCode() == 202) {
String path = context.request().path();
String digest = path.substring(path.lastIndexOf('/') + 1);
// Registry V2 deletes a manifest by digest. A tag alone does not identify this metadata.
if (digest.contains(":")) {
return () -> ecrService.removeImagePush(request.accountId(), request.region(),
request.repositoryName(), digest);
}
}
return null;
}
private static void forwardResponse(RoutingContext context, RegistryRequest request, Exchange exchange,
HttpClientResponse upstream) {
copyResponseHeaders(context, upstream, request);
upstream.pipeTo(context.response()).onComplete(ignored -> exchange.end());
}
private static void registryUnavailable(RoutingContext context) {
registryUnavailable(context, "ECR registry is unavailable. Check Docker and registry connectivity. "
+ "When running Floci in Docker, use a user-defined network shared with the registry "
@@ -361,7 +427,7 @@ public class EcrRegistryDataPlane {
}
private static void copyResponseHeaders(RoutingContext context,
io.vertx.core.http.HttpClientResponse upstream,
HttpClientResponse upstream,
RegistryRequest request) {
context.response().setStatusCode(upstream.statusCode());
upstream.headers().forEach(header -> {
@@ -419,6 +485,8 @@ public class EcrRegistryDataPlane {
private final AtomicBoolean admissionReleased = new AtomicBoolean();
private Buffer waitingBody;
private boolean waitingBodyRead;
private boolean updatingManifestMetadata;
private boolean endRequested;
private HttpClient client;
private Exchange(String immutableTag, String writeLockRepository, boolean isWrite) {
@@ -498,6 +566,11 @@ public class EcrRegistryDataPlane {
}
private void end() {
if (updatingManifestMetadata) {
// Keep the repository lock until the metadata write finishes, even on disconnect.
endRequested = true;
return;
}
if (!ended.compareAndSet(false, true)) {
return;
}