fix(ecr): delete only the named tag in BatchDeleteImage (#6597)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-29 00:06:36 -04:00
1 parent da8e22744b
commit 9ce1b1755e
8 files changed
+1506 -31

No files matched your search

@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.core.common.concurrent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
/**
* One write lock per key: writers of the same key exclude one another, writers of distinct
* keys never wait for each other. A semaphore of one permit rather than a monitor, because
* a writer may release the lock from a different thread than it took it on, which a
* synchronized block and a {@code ReentrantLock} both forbid.
*
* <p>Entries are keyed and reference-counted. Every participant, the holder and each
* waiter alike, is counted on its key's entry from before it tries the semaphore until it
* has released the permit or given up, and each count is taken and dropped inside the
* map's own per-key computation. No entry is removed or replaced while any participant
* still coordinates on it, so every writer reaching a key in that window meets the same
* instance and a waiter can never be mutual-excluded against a fresh instance a later
* arrival takes. An entry is collected once its last participant departs, which keeps a
* key written once, or a key whose resource later goes away, from leaving an entry behind
* for the life of the pool.
*/
public final class KeyedWriteLocks<K> {
private final Map<K, Entry> entries = new ConcurrentHashMap<>();
/**
* Takes the key's lock, waiting for its current holder to release it. Interruptible: on
* interruption the waiter's count departs and the interrupt status stays cleared before
* {@code InterruptedException} is rethrown for the caller to translate and restore.
*/
public void acquire(K key) throws InterruptedException {
Entry entry = retain(key);
try {
entry.permits.acquire();
} catch (InterruptedException e) {
depart(key, entry);
throw e;
}
}
/**
* One try at {@link #acquire}, for callers that must not block a thread. The caller
* that succeeds owns the entry's count until its {@link #release}.
*/
public boolean tryAcquire(K key) {
Entry entry = retain(key);
if (entry.permits.tryAcquire()) {
return true;
}
depart(key, entry);
return false;
}
/**
* Ends one writer's hold: the permit goes back and, with it, the writer's count on
* the entry. The holder's own count keeps the entry in the map until here, so the
* lookup meets the instance the writer acquired. May run on a thread other than the
* one the lock was taken on.
*/
public void release(K key) {
Entry entry = entries.get(key);
entry.permits.release();
depart(key, entry);
}
/** The entries still counting participants, for tests. */
public int size() {
return entries.size();
}
/**
* The key's entry with this participant counted on it: from before the participant
* tries the semaphore until it releases the permit or gives up, the entry cannot be
* removed, so every participant reaching the key in that window meets the same
* instance and a waiter can never be mutual-excluded against a fresh instance a later
* arrival takes.
*/
private Entry retain(K key) {
return entries.compute(key, (ignored, existing) -> {
Entry entry = existing != null ? existing : new Entry();
entry.participants.incrementAndGet();
return entry;
});
}
/**
* Ends one participant's count on the entry. The decrement and the removal decision
* run inside the map's own per-key computation, so a participant arriving on the same
* key cannot slip between the count reaching zero and the entry leaving, and cannot
* end up counted on an instance the map no longer holds.
*/
private void depart(K key, Entry entry) {
entries.compute(key, (ignored, existing) ->
entry.participants.decrementAndGet() > 0 || existing != entry ? existing : null);
}
/** One key's write semaphore and the count of participants still coordinating on it. */
private static final class Entry {
private final Semaphore permits = new Semaphore(1);
private final AtomicInteger participants = new AtomicInteger();
}
}
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.concurrent.KeyedWriteLocks;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@@ -97,6 +98,7 @@ public class EcrService implements ResourceProvider {
private final RegionResolver regionResolver;
private final EcrLayerUploads layerUploads = new EcrLayerUploads(this::discardUpload);
private final Set<String> inFlightImmutableTags = ConcurrentHashMap.newKeySet();
private final KeyedWriteLocks<String> repositoryWriteLocks = new KeyedWriteLocks<>();
@Inject
public EcrService(StorageFactory factory,
@@ -856,21 +858,16 @@ public class EcrService implements ResourceProvider {
if (imageIds == null) imageIds = List.of();
for (ImageIdentifier id : imageIds) {
try {
String digest = id.getImageDigest();
if (digest == null && id.getImageTag() != null) {
digest = http.headManifestDigest(internal, id.getImageTag(), null);
lockRepositoryWrites(internal);
try {
if (id.getImageDigest() == null && id.getImageTag() != null) {
deleteImageTag(repo, repositoryName, internal, http, id, region, deleted, failures);
} else {
deleteImageDigest(repo, repositoryName, internal, http, id, region, deleted, failures);
}
} finally {
unlockRepositoryWrites(internal);
}
if (digest == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
continue;
}
boolean ok = http.deleteManifest(internal, digest);
if (!ok) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
continue;
}
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
} catch (Exception e) {
failures.add(new ImageFailure(id, "ImageNotFound", e.getMessage()));
}
@@ -878,6 +875,139 @@ public class EcrService implements ResourceProvider {
return new BatchDeleteImageResult(deleted, failures);
}
/**
* Deletes one tag as BatchDeleteImage does on AWS: the manifest goes with it only when no
* other tag still references the shared digest. The backing registry deletes manifests by
* digest only, and that untags every tag the digest has, so while another tag remains the
* manifest is dropped and immediately written back under the surviving tags from a copy
* read before the drop, which restores the identical digest. The repository's write lock
* (see {@link #lockRepositoryWrites}) is held across the whole sequence, so a manifest
* pushed to the repository between the drop and the write-back cannot be overwritten by
* the restore, and the drop and the restore run under the registry manager's monitor,
* the monitor {@code /_floci/ecr/gc} holds while it runs, so a concurrent GC cannot see
* the manifest's layers as unreferenced in that window and reclaim them out from under
* the restore.
*/
private void deleteImageTag(Repository repo, String repositoryName, String internal,
RegistryHttpClient http, ImageIdentifier id, String region,
List<ImageIdentifier> deleted, List<ImageFailure> failures)
throws Exception {
String digest = http.headManifestDigest(internal, id.getImageTag(), null);
if (digest == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
List<String> survivingTags;
try {
survivingTags = tagsReferencing(internal, http, digest, id.getImageTag());
} catch (Exception e) {
failures.add(new ImageFailure(id, "ServerException",
"The tags of '" + repositoryName + "' could not be listed before deleting tag '"
+ id.getImageTag() + "': " + e.getMessage()));
return;
}
if (survivingTags.isEmpty()) {
if (!http.deleteManifest(internal, digest)) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
return;
}
RegistryHttpClient.ManifestResult manifest = http.getManifest(internal, digest, null);
if (manifest == null || manifest.body() == null || manifest.mediaType() == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
synchronized (registryManager) {
if (!http.deleteManifest(internal, digest)) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
for (String survivingTag : survivingTags) {
restoreTag(internal, http, digest, manifest, survivingTag, id.getImageTag(), repositoryName);
}
}
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
}
/**
* Deletes a manifest with every tag that references it, reporting one imageId per removed
* tag the way the API reference's example response does.
*/
private void deleteImageDigest(Repository repo, String repositoryName, String internal,
RegistryHttpClient http, ImageIdentifier id, String region,
List<ImageIdentifier> deleted, List<ImageFailure> failures)
throws Exception {
String digest = id.getImageDigest();
if (digest == null) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
List<String> removedTags;
try {
removedTags = tagsReferencing(internal, http, digest, null);
} catch (Exception e) {
failures.add(new ImageFailure(id, "ServerException",
"The tags of '" + repositoryName + "' could not be listed before deleting manifest '"
+ digest + "': " + e.getMessage()));
return;
}
if (!http.deleteManifest(internal, digest)) {
failures.add(new ImageFailure(id, "ImageNotFound", "Image not found"));
return;
}
if (removedTags.isEmpty()) {
deleted.add(new ImageIdentifier(id.getImageTag(), digest));
} else {
for (String removedTag : removedTags) {
deleted.add(new ImageIdentifier(removedTag, digest));
}
}
imageMetaStore.delete(imageMetaKey(region, repo.getRegistryId(), repositoryName, digest));
}
/**
* The repository's tags, other than {@code exclude}, that resolve to {@code digest}. Both
* calls are strict, so a registry that answers an error fails the delete instead of quietly
* dropping a surviving tag from the set to restore.
*/
private List<String> tagsReferencing(String internal, RegistryHttpClient http,
String digest, String exclude) throws Exception {
List<String> referencing = new ArrayList<>();
for (String tag : http.listTagsStrict(internal)) {
if (tag.equals(exclude)) {
continue;
}
if (digest.equals(http.headManifestDigestStrict(internal, tag, null))) {
referencing.add(tag);
}
}
return referencing;
}
/**
* Writes a manifest back under one of its tags after the digest-addressed delete removed
* them all. The requested tag is already gone when this runs, so its delete is reported as
* done; a restore that fails leaves the surviving tag broken, which is logged for the
* operator because no imageId can say it.
*/
private void restoreTag(String internal, RegistryHttpClient http, String digest,
RegistryHttpClient.ManifestResult manifest, String survivingTag,
String deletedTag, String repositoryName) {
try {
String restored = http.putManifest(internal, survivingTag, manifest.mediaType(), manifest.body());
if (restored != null && !restored.equals(digest)) {
LOG.warnv("Restoring ECR tag {0} in repository {1} rewrote manifest {2} as {3}",
survivingTag, repositoryName, digest, restored);
}
} catch (Exception e) {
LOG.warnv("Restoring ECR tag {0} of manifest {1} in repository {2} failed after deleting tag {3}: {4}",
survivingTag, digest, repositoryName, deletedTag, e.getMessage());
}
}
// ============================================================
// Image push through the API (PutImage and the layer API)
// ============================================================
@@ -917,8 +1047,13 @@ public class EcrService implements ResourceProvider {
throw imageTagAlreadyExists(imageTag, repositoryName);
}
try {
return callRegistry(() -> writeManifest(repo, repositoryName, storage, http, imageManifest, mediaType,
imageTag, digest, guarded, region), EcrService::putImageError);
lockRepositoryWrites(storage);
try {
return callRegistry(() -> writeManifest(repo, repositoryName, storage, http, imageManifest, mediaType,
imageTag, digest, guarded, region), EcrService::putImageError);
} finally {
unlockRepositoryWrites(storage);
}
} finally {
if (guarded != null) {
releaseImmutableTag(guarded);
@@ -1121,6 +1256,48 @@ public class EcrService implements ResourceProvider {
inFlightImmutableTags.remove(key);
}
/**
* The write lock every manifest write to one backing registry repository takes: the data
* plane's manifest PUTs and deletes, {@code PutImage}, and the BatchDeleteImage sequence
* that drops a shared manifest by digest and writes it back under its surviving tags. A
* write that lands between that sequence's steps would otherwise be overwritten by the
* restore of the older manifest. Keyed by the repository name as the backing registry
* stores it, the only namespace in which two writes address the same manifests. The
* lock's entry counting, its cross-thread release and its interruption behavior are
* {@link KeyedWriteLocks}' contract; the interruption surfaces here as a
* {@code ServerException}.
*/
public void lockRepositoryWrites(String storageRepositoryName) {
try {
repositoryWriteLocks.acquire(storageRepositoryName);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AwsException("ServerException",
"Interrupted while waiting for the write lock on " + storageRepositoryName, 500);
}
}
/**
* One try at {@link #lockRepositoryWrites}, for callers that must not block a thread. The
* caller that succeeds owns the lock until its {@code unlockRepositoryWrites}.
*/
public boolean tryLockRepositoryWrites(String storageRepositoryName) {
return repositoryWriteLocks.tryAcquire(storageRepositoryName);
}
/**
* Ends one writer's hold of the repository's write lock; see
* {@link #lockRepositoryWrites}.
*/
public void unlockRepositoryWrites(String storageRepositoryName) {
repositoryWriteLocks.release(storageRepositoryName);
}
/** The repository write lock entries still counting writers, for tests. */
int liveRepositoryWriteLocks() {
return repositoryWriteLocks.size();
}
/** The media type sent, else the manifest's own {@code mediaType}; with neither, the request is refused. */
private static String manifestMediaType(String manifest, String given) {
JsonNode root;
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.NetworkExposureGuard;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
@@ -37,6 +38,14 @@ public class EcrRegistryDataPlane {
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/";
private static final long REPOSITORY_LOCK_POLL_MILLIS = 5;
/**
* The most a manifest PUT waiting for its repository's write lock may buffer. A manifest
* is kilobytes of JSON with layer references, and a body past this is refused rather than
* held in memory; the plane-wide request limit is gigabytes, so nothing else bounds a
* body that waits.
*/
private static final int WAITING_MANIFEST_BODY_LIMIT_BYTES = 4 * 1024 * 1024;
private static final Set<String> HOP_BY_HOP_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"te", "trailers", "transfer-encoding", "upgrade");
@@ -86,14 +95,90 @@ public class EcrRegistryDataPlane {
return;
}
Exchange exchange = new Exchange(immutableTag);
Exchange exchange = new Exchange(immutableTag, manifestWriteRepository(context, registryRequest));
// A client that goes away, by resetting its HTTP/2 stream or closing the connection, ends
// the exchange at any point, the registry check included: otherwise the registry keeps
// waiting for the rest of a body with a Content-Length, and the exchange's connection,
// client and immutable tag lock stay.
context.response().closeHandler(closed -> exchange.end());
context.request().exceptionHandler(failure -> exchange.end());
checkTagAndProxy(context, registryRequest, exchange);
lockRepositoryWritesThenCheck(context, registryRequest, exchange);
}
/**
* The repository a manifest write must hold the write lock of, or null when the request
* moves no manifest: only PUT and DELETE below a repository's {@code manifests/} path change
* which manifest a tag resolves to, so blob uploads and reads pass untouched.
*/
private static String manifestWriteRepository(RoutingContext context, RegistryRequest request) {
String method = context.request().method().name();
if (!"PUT".equals(method) && !"DELETE".equals(method)) {
return null;
}
return request.backendUri().startsWith("/v2/" + request.storageRepositoryName() + MANIFESTS_PATH)
? request.storageRepositoryName()
: null;
}
/**
* A manifest write takes its repository's write lock before anything of it reaches the
* registry. That is the same lock BatchDeleteImage holds across the sequence that drops a
* shared manifest by digest and writes it back under its surviving tags, so a push that
* arrives during such a delete waits here instead of landing between the drop and the
* write-back and being overwritten by the restore. The event loop thread must not block on
* the lock, so each poll rechecks; a waiting PUT drains its body into memory rather than
* leaving it unread, which keeps the connection's flow-control window moving for the
* exchange that holds the lock. A client that goes away ends the exchange and the polling
* with it.
*/
private void lockRepositoryWritesThenCheck(RoutingContext context, RegistryRequest request, Exchange exchange) {
if (exchange.ended() || exchange.holdingWriteLock()) {
return;
}
String repository = exchange.writeLockRepository();
if (repository == null || ecrService.tryLockRepositoryWrites(repository)) {
exchange.writeLockAcquired();
if (exchange.waitingBodyReady()) {
checkTagAndProxy(context, request, exchange);
}
return;
}
drainWaitingBody(context, request, exchange);
vertx.setTimer(REPOSITORY_LOCK_POLL_MILLIS,
ignored -> lockRepositoryWritesThenCheck(context, request, exchange));
}
/**
* Reads the whole body of a manifest PUT that waits for its repository's write lock into
* memory, so its bytes do not sit unread in the client connection's flow-control window:
* on one HTTP/2 connection they would fill the window the exchange holding the lock needs
* for its own remaining bytes, and neither push would ever finish. The buffered bytes are
* replayed to the registry in the live request's place once the exchange has the lock. A
* manifest DELETE sends no body and keeps waiting paused as before, and a PUT that takes
* the lock on the first try streams its body untouched.
*/
private void drainWaitingBody(RoutingContext context, RegistryRequest request, Exchange exchange) {
if (!"PUT".equals(context.request().method().name()) || !exchange.startWaitingBody()) {
return;
}
context.request().handler(chunk -> {
if (exchange.ended()) {
return;
}
if (!exchange.appendWaitingBody(chunk)) {
exchange.end();
failUnlessGone(context, 413);
}
});
context.request().endHandler(ignored -> {
if (exchange.ended() || !exchange.finishWaitingBody()) {
return;
}
if (exchange.holdingWriteLock()) {
checkTagAndProxy(context, request, exchange);
}
});
context.request().resume();
}
private String immutableTag(RoutingContext context, RegistryRequest request) {
@@ -172,11 +257,19 @@ public class EcrRegistryDataPlane {
copyResponseHeaders(context, upstreamResponse.result(), request);
upstreamResponse.result().pipeTo(context.response()).onComplete(ignored -> exchange.end());
});
clientReq.send(context.request()).onFailure(ignored -> {
exchange.end();
failUnlessGone(context, 502);
});
context.request().resume();
Buffer waitingBody = exchange.replayBody();
if (waitingBody == null) {
clientReq.send(context.request()).onFailure(ignored -> {
exchange.end();
failUnlessGone(context, 502);
});
context.request().resume();
} else {
clientReq.send(waitingBody).onFailure(ignored -> {
exchange.end();
failUnlessGone(context, 502);
});
}
});
}
@@ -255,25 +348,83 @@ public class EcrRegistryDataPlane {
}
/**
* One proxied request: the registry client it opens once it gets that far, and the immutable
* tag it holds. It ends once, at whichever comes first of the registry's answer, a failure and
* the client going away; the close handler also fires after an exchange that ended normally,
* when another exchange may already hold the same tag.
* One proxied request: the registry client it opens once it gets that far, the immutable
* tag it holds, the repository write lock it holds once a manifest write has it, and the
* body a manifest PUT drains while it waits for that lock. It ends once, at whichever
* comes first of the registry's answer, a failure and the client going away; the close
* handler also fires after an exchange that ended normally, when another exchange may
* already hold the same tag.
*/
private final class Exchange {
private final String immutableTag;
private final String writeLockRepository;
private final AtomicBoolean writeLockHeld = new AtomicBoolean();
private final AtomicBoolean ended = new AtomicBoolean();
private Buffer waitingBody;
private boolean waitingBodyRead;
private HttpClient client;
private Exchange(String immutableTag) {
private Exchange(String immutableTag, String writeLockRepository) {
this.immutableTag = immutableTag;
this.writeLockRepository = writeLockRepository;
}
private boolean ended() {
return ended.get();
}
private String writeLockRepository() {
return writeLockRepository;
}
private boolean holdingWriteLock() {
return writeLockHeld.get();
}
private void writeLockAcquired() {
if (writeLockRepository != null) {
writeLockHeld.set(true);
}
}
/**
* Starts the buffer a waiting manifest PUT drains its body into, once: from here the
* bytes are read instead of left to hold the client connection's flow-control window.
*/
private boolean startWaitingBody() {
if (waitingBody != null) {
return false;
}
waitingBody = Buffer.buffer();
return true;
}
/** Appends one chunk of the drained body, or refuses it past the buffering limit. */
private boolean appendWaitingBody(Buffer chunk) {
waitingBody.appendBuffer(chunk);
return waitingBody.length() <= WAITING_MANIFEST_BODY_LIMIT_BYTES;
}
/** Marks the drained body complete, once; the exchange may then continue to the registry. */
private boolean finishWaitingBody() {
if (waitingBodyRead) {
return false;
}
waitingBodyRead = true;
return true;
}
/** Whether nothing of a waiting body still holds the exchange back from the registry. */
private boolean waitingBodyReady() {
return waitingBody == null || waitingBodyRead;
}
/** The drained body to send the registry in the live request's place, or null. */
private Buffer replayBody() {
return waitingBodyRead ? waitingBody : null;
}
private HttpClient open(HttpClient registryClient) {
client = registryClient;
return registryClient;
@@ -283,6 +434,7 @@ public class EcrRegistryDataPlane {
if (!ended.compareAndSet(false, true)) {
return;
}
releaseWriteLock();
if (client == null) {
release(immutableTag);
return;
@@ -292,6 +444,12 @@ public class EcrRegistryDataPlane {
// tag cannot start its check while this one can still reach the registry.
client.close().onComplete(closed -> release(immutableTag));
}
private void releaseWriteLock() {
if (writeLockRepository != null && writeLockHeld.compareAndSet(true, false)) {
ecrService.unlockRepositoryWrites(writeLockRepository);
}
}
}
static Optional<RegistryRequest> requestFor(String host, String path, String query, String uriStyle) {