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;
}
@@ -289,9 +289,29 @@ class EcrImagePushApiDockerIntegrationTest {
.body("image.imageManifestMediaType", equalTo("application/vnd.oci.image.manifest.v1+json"));
}
/** Last, since every class on this profile shares one registry. */
@Test
@Order(10)
void registryRetagPreservesImagePushTime() throws Exception {
String host = "000000000000.dkr.ecr.us-east-1.localhost";
String path = "/v2/" + repo + "/manifests/";
Fetched pushed = registryRequest(host, path + "registry", HttpMethod.PUT, null, manifest);
assertEquals(201, pushed.statusCode());
assertEquals(manifestDigest, pushed.digest());
long pushTime = call("DescribeImages", "{\"repositoryName\":\"" + repo
+ "\",\"imageIds\":[{\"imageTag\":\"registry\"}]}")
.statusCode(200).extract().jsonPath().getLong("imageDetails[0].imagePushedAt");
assertEquals(201, registryRequest(host, path + "registry-retag", HttpMethod.PUT, null, manifest).statusCode());
long retaggedPushTime = call("DescribeImages", "{\"repositoryName\":\"" + repo
+ "\",\"imageIds\":[{\"imageTag\":\"registry-retag\"}]}")
.statusCode(200).extract().jsonPath().getLong("imageDetails[0].imagePushedAt");
assertEquals(pushTime, retaggedPushTime);
}
/** Last, since every class on this profile shares one registry. */
@Test
@Order(11)
void cleanUp() {
call("DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}").statusCode(200);
call("DeleteRepository", "{\"repositoryName\":\"" + immutableRepo + "\",\"force\":true}").statusCode(200);
@@ -322,19 +342,27 @@ class EcrImagePushApiDockerIntegrationTest {
/** A GET through Floci's registry data plane, by the host name a Docker client would use. */
private Fetched registryGet(String host, String path, String accept) throws Exception {
return registryRequest(host, path, HttpMethod.GET, accept, null);
}
private Fetched registryRequest(String host, String path, HttpMethod method, String accept,
String manifestBody) throws Exception {
int port = RestAssured.port;
HttpClient client = vertx.createHttpClient();
RequestOptions options = new RequestOptions()
.setServer(SocketAddress.inetSocketAddress(port, "127.0.0.1"))
.setHost(host)
.setPort(port)
.setMethod(HttpMethod.GET)
.setMethod(method)
.setURI(path);
return client.request(options)
.compose(request -> {
if (accept != null) {
request.putHeader("Accept", accept);
}
if (manifestBody != null) {
return request.putHeader("Content-Type", DOCKER_MANIFEST).send(manifestBody);
}
return request.send();
})
.compose(response -> response.body().map(body -> new Fetched(
@@ -869,6 +869,54 @@ class EcrServiceTest {
}
}
@Test
void describeKeepsAcceptedPushTimeWhileMetadataWritesFail() throws Exception {
String repo = "batch-delete/push-recovery";
String internal = ACCOUNT + "/" + REGION + "/" + repo;
AtomicBoolean unavailable = new AtomicBoolean(true);
InMemoryStorage<String, ImageMetadata> metaStore = new InMemoryStorage<>() {
@Override
public void put(String key, ImageMetadata metadata) {
if (unavailable.get()) {
throw new IllegalStateException("metadata store unavailable");
}
super.put(key, metadata);
}
};
EcrService withMeta = new EcrService(new InMemoryStorage<>(), metaStore, pullThroughCacheRuleStore,
registryManager, Mockito.mock(EmulatorConfig.class), new RegionResolver(REGION, ACCOUNT));
try (MultiTagRegistryServer registry = new MultiTagRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, "stable")) {
when(registryManager.httpClient()).thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
withMeta.createRepository(repo, null, null, null, null, null, null, REGION);
Instant pushedAt = Instant.parse("2026-01-01T00:00:00Z");
assertThrows(IllegalStateException.class,
() -> withMeta.recordImagePush(ACCOUNT, REGION, repo, DELETE_DIGEST, pushedAt));
List<ImageIdentifier> images = List.of(new ImageIdentifier("stable", null));
EcrService.DescribeImagesResult duringOutage = withMeta.describeImages(repo, images, null, REGION);
assertEquals(1, duringOutage.imageDetails().size());
assertEquals(pushedAt, duringOutage.imageDetails().getFirst().getImagePushedAt());
assertTrue(metaStore.scan(key -> true).isEmpty());
unavailable.set(false);
assertEquals(pushedAt, withMeta.describeImages(repo, images, null, REGION)
.imageDetails().getFirst().getImagePushedAt());
assertEquals(pushedAt, metaStore.scan(key -> true).getFirst().getPushedAt());
withMeta.removeImagePush(ACCOUNT, REGION, repo, DELETE_DIGEST);
unavailable.set(true);
assertThrows(IllegalStateException.class,
() -> withMeta.recordImagePush(ACCOUNT, REGION, repo, DELETE_DIGEST, pushedAt));
withMeta.removeImagePush(ACCOUNT, REGION, repo, DELETE_DIGEST);
unavailable.set(false);
Instant repushedAt = pushedAt.plusSeconds(1);
assertEquals(repushedAt,
withMeta.recordImagePush(ACCOUNT, REGION, repo, DELETE_DIGEST, repushedAt).getPushedAt());
}
}
@Test
void batchDeleteImageByTagKeepsTheImagePushedAtOfTheSurvivingTag() throws Exception {
String repositoryName = "batch-delete/pushed-at";
@@ -44,13 +44,16 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/** Unit tests for routing AWS-shaped ECR repository URIs through Floci's data plane. */
class EcrRegistryDataPlaneTest {
private Vertx vertx;
private EcrService ecrService;
private Semaphore repositoryWriteLock;
private CountDownLatch repositoryWriteLockRefused;
@@ -243,8 +246,61 @@ class EcrRegistryDataPlaneTest {
"/v2/000000000000/us-east-1/platform/api/blobs/uploads/upload-id", request));
}
@Test
void recordsOnlyAcceptedManifestWritesBeforeResponding() throws Exception {
String digest = "sha256:" + "a".repeat(64);
AtomicBoolean accept = new AtomicBoolean();
HttpServer registry = vertx.createHttpServer()
.requestHandler(request -> request.bodyHandler(body -> {
int successStatus = request.method() == HttpMethod.DELETE ? 202 : 201;
request.response().putHeader("Docker-Content-Digest", digest)
.setStatusCode(accept.get() ? successStatus : 400).end();
}))
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
HttpServer dataPlane = null;
try {
dataPlane = dataPlane(registry, false);
assertEquals(400, putManifest(dataPlane.actualPort()).statusCode());
Mockito.verify(ecrService, Mockito.never()).recordImagePush(anyString(), anyString(),
anyString(), anyString(), any());
String manifestPath = "/v2/platform/api/manifests/" + digest;
assertEquals(400, request(dataPlane.actualPort(), HttpMethod.DELETE, manifestPath).status());
Mockito.verify(ecrService, Mockito.never()).removeImagePush(anyString(), anyString(), anyString(), anyString());
Mockito.doAnswer(call -> {
assertEquals(0, repositoryWriteLock.availablePermits());
return null;
}).when(ecrService).recordImagePush(eq("000000000000"), eq("us-east-1"),
eq("platform/api"), eq(digest), any());
accept.set(true);
assertEquals(201, putManifest(dataPlane.actualPort()).statusCode());
Mockito.verify(ecrService).recordImagePush(eq("000000000000"), eq("us-east-1"),
eq("platform/api"), eq(digest), any());
Mockito.doAnswer(call -> {
assertEquals(0, repositoryWriteLock.availablePermits());
return null;
}).when(ecrService).removeImagePush("000000000000", "us-east-1", "platform/api", digest);
assertEquals(202, request(dataPlane.actualPort(), HttpMethod.DELETE, manifestPath).status());
Mockito.verify(ecrService).removeImagePush("000000000000", "us-east-1", "platform/api", digest);
Mockito.doThrow(new IllegalStateException("metadata store unavailable"))
.when(ecrService).recordImagePush(eq("000000000000"), eq("us-east-1"),
eq("platform/api"), eq(digest), any());
assertEquals(201, putManifest(dataPlane.actualPort()).statusCode());
} finally {
if (dataPlane != null) {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
@Test
void immutableTagRejectsReplacementBeforeItReachesTheRegistry() throws Exception {
String digest = "sha256:" + "b".repeat(64);
AtomicBoolean tagExists = new AtomicBoolean();
AtomicInteger manifestWrites = new AtomicInteger();
AtomicReference<String> headPath = new AtomicReference<>();
@@ -263,7 +319,7 @@ class EcrRegistryDataPlaneTest {
manifestBody.set(body.toString());
manifestWrites.incrementAndGet();
tagExists.set(true);
request.response().setStatusCode(201).end();
request.response().setStatusCode(201).putHeader("Docker-Content-Digest", digest).end();
});
} else {
request.response().setStatusCode(405).end();
@@ -275,6 +331,9 @@ class EcrRegistryDataPlaneTest {
HttpServer dataPlane = null;
try {
dataPlane = dataPlane(registry, true);
Mockito.doThrow(new IllegalStateException("transient metadata store failure")).doReturn(null)
.when(ecrService).recordImagePush(eq("000000000000"), eq("us-east-1"),
eq("platform/api"), eq(digest), any());
assertEquals(201, putManifest(dataPlane.actualPort()).statusCode());
@@ -290,6 +349,8 @@ class EcrRegistryDataPlaneTest {
error.getString("message"));
assertEquals(1, manifestWrites.get());
Mockito.verify(ecrService, Mockito.times(2)).recordImagePush(eq("000000000000"), eq("us-east-1"),
eq("platform/api"), eq(digest), any());
assertEquals("/v2/legacy/platform-api/manifests/v1", headPath.get());
assertEquals("/v2/legacy/platform-api/manifests/v1", manifestPath.get());
assertEquals("{}", manifestBody.get());
@@ -914,7 +975,7 @@ class EcrRegistryDataPlaneTest {
private HttpServer dataPlane(EcrRegistryManager registryManager, boolean immutableTags,
CountDownLatch tagReleased) throws Exception {
EcrService ecrService = Mockito.mock(EcrService.class);
ecrService = Mockito.mock(EcrService.class);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
when(config.services().ecr().enabled()).thenReturn(true);
when(config.services().ecr().uriStyle()).thenReturn("hostname");