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

@@ -311,6 +311,56 @@ class EcrTest {
assertThat(url).endsWith("/v2/" + repo + "/blobs/" + layerDigest);
}
@Test
@Order(15)
@DisplayName("BatchDeleteImage removes only the named tag while another tag shares the manifest")
void batchDeleteImageRemovesOnlyTheNamedTag() throws Exception {
String repo = "floci-it/batch-delete-" + System.nanoTime();
ecr.createRepository(b -> b.repositoryName(repo));
reposToCleanup.add(repo);
String config = "{\"architecture\":\"amd64\",\"os\":\"linux\"}";
String layer = "floci batch delete layer bytes";
String configDigest = uploadLayer(repo, config.getBytes(StandardCharsets.UTF_8));
String layerDigest = uploadLayer(repo, layer.getBytes(StandardCharsets.UTF_8));
String manifest = "{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\","
+ "\"config\":{\"mediaType\":\"application/vnd.oci.image.config.v1+json\",\"size\":"
+ config.length() + ",\"digest\":\"" + configDigest + "\"},"
+ "\"layers\":[{\"mediaType\":\"application/vnd.oci.image.layer.v1.tar\",\"size\":"
+ layer.length() + ",\"digest\":\"" + layerDigest + "\"}]}";
String manifestDigest = sha256(manifest.getBytes(StandardCharsets.UTF_8));
ecr.putImage(b -> b.repositoryName(repo).imageTag("release").imageManifest(manifest));
ecr.putImage(b -> b.repositoryName(repo).imageTag("stable").imageManifest(manifest));
BatchDeleteImageResponse first = ecr.batchDeleteImage(b -> b.repositoryName(repo)
.imageIds(ImageIdentifier.builder().imageTag("release").build(),
ImageIdentifier.builder().imageTag("missing").build()));
assertThat(first.imageIds()).hasSize(1);
assertThat(first.imageIds().get(0).imageTag()).isEqualTo("release");
assertThat(first.imageIds().get(0).imageDigest()).isEqualTo(manifestDigest);
assertThat(first.failures()).hasSize(1);
assertThat(first.failures().get(0).imageId().imageTag()).isEqualTo("missing");
assertThat(first.failures().get(0).failureCodeAsString()).isEqualTo("ImageNotFound");
BatchGetImageResponse survivor = ecr.batchGetImage(b -> b.repositoryName(repo)
.imageIds(ImageIdentifier.builder().imageTag("stable").build()));
assertThat(survivor.images()).hasSize(1);
assertThat(survivor.images().get(0).imageId().imageDigest()).isEqualTo(manifestDigest);
BatchDeleteImageResponse second = ecr.batchDeleteImage(b -> b.repositoryName(repo)
.imageIds(ImageIdentifier.builder().imageTag("stable").build()));
assertThat(second.imageIds()).hasSize(1);
assertThat(second.imageIds().get(0).imageTag()).isEqualTo("stable");
assertThat(second.imageIds().get(0).imageDigest()).isEqualTo(manifestDigest);
BatchGetImageResponse gone = ecr.batchGetImage(b -> b.repositoryName(repo)
.imageIds(ImageIdentifier.builder().imageTag("stable").build()));
assertThat(gone.images()).isEmpty();
assertThat(gone.failures()).hasSize(1);
assertThat(gone.failures().get(0).failureCodeAsString()).isEqualTo("ImageNotFound");
}
private static String uploadLayer(String repo, byte[] bytes) throws Exception {
String uploadId = ecr.initiateLayerUpload(b -> b.repositoryName(repo)).uploadId();
UploadLayerPartResponse part = ecr.uploadLayerPart(b -> b.repositoryName(repo).uploadId(uploadId)
+3 -2
View File
@@ -24,7 +24,7 @@
| `ListImages` | Enumerate paginated tags and digests in a repository |
| `DescribeImages` | Image metadata: digest, size, push timestamp, manifest media type |
| `BatchGetImage` | Fetch image manifests, honoring `acceptedMediaTypes` |
| `BatchDeleteImage` | Delete images by tag or digest |
| `BatchDeleteImage` | Delete images by tag or digest; a tag delete removes only that tag |
| `PutImage` | Write an image manifest under a tag, or under its digest, into the backing registry |
| `BatchCheckLayerAvailability` | Report which layers a repository holds, with their sizes |
| `GetDownloadUrlForLayer` | Return the layer's address on Floci's registry endpoint |
@@ -66,6 +66,7 @@ the optional `filter` fields.
- Upload sessions live in memory: a restart ends them, and one left idle for a day is dropped.
- `GetDownloadUrlForLayer` returns `<scheme>://<repository URI host>/v2/<repo>/blobs/<digest>`, served by Floci's registry endpoint without credentials, in place of AWS's pre-signed S3 URL.
- `BatchCheckLayerAvailability` lists held layers as `AVAILABLE`, and a layer the repository does not hold under `failures` as `MissingLayerDigest`.
- **Image deletion.** `BatchDeleteImage` follows the AWS rules. Deleting by `imageTag` removes only that tag: when other tags reference the same manifest they keep serving the shared digest, so `docker pull`, `batch-get-image` and `describe-images` by a surviving tag still find the image. The manifest is deleted once the last tag referencing it goes. Deleting by `imageDigest` removes the image together with all of its tags, and the response reports one `imageIds` entry per removed tag, as the API reference's example does. Unknown tags come back per entry under `failures` as `ImageNotFound`. A manifest write to the repository, a `docker push`, a `crane delete` or a `PutImage`, is coordinated with the delete that rewrites a shared manifest under its surviving tags, so a push that arrives during the delete is never overwritten by the restore; it waits and lands after it.
- **Authorization.** `GetAuthorizationToken` returns `Base64("AWS:floci")` plus a proxy endpoint. The backing `registry:2` runs without auth, so any `aws ecr get-login-password | docker login` succeeds.
- **Pull through cache rule configuration.** Pull-through cache rule actions persist AWS-compatible rule metadata with account and Region isolation. `UpdatePullThroughCacheRule` preserves fields omitted by the request and refreshes `updatedAt`. `ValidatePullThroughCacheRule` checks that the rule exists and reports it as valid; Floci does not contact the upstream registry or validate credentials. Rules do not proxy or cache images from the configured upstream registry.
- **Registry settings.** The registry policy, replication configuration and scanning configuration are kept per account and Region and returned as written. Floci does not replicate or scan images, or evaluate the registry policy.
@@ -295,6 +296,6 @@ does not resolve container names, which Floci uses to reach the registry. Create
`FLOCI_SERVICES_ECR_DOCKER_NETWORK=floci-net` if selecting the registry network explicitly.
See [Docker's bridge network documentation](https://docs.docker.com/engine/network/drivers/bridge/).
**Disk not reclaimed after deleting images.** `BatchDeleteImage` removes manifests but blobs remain on disk until garbage collection runs. Trigger it with `curl -X POST http://localhost:4566/_floci/ecr/gc`. The endpoint runs `registry garbage-collect` inside the backing container and returns the reclaimed blob list. The operation is serialized — ECR API calls block for its duration (typically a few seconds).
**Disk not reclaimed after deleting images.** Deleting the last tag of an image, or deleting by digest, removes its manifest, but blobs remain on disk until garbage collection runs. Trigger it with `curl -X POST http://localhost:4566/_floci/ecr/gc`. The endpoint runs `registry garbage-collect` inside the backing container and returns the reclaimed blob list. The operation is serialized: ECR API calls block for its duration (typically a few seconds).
**`*.localhost` does not resolve to loopback on this platform.** Set `floci.services.ecr.uri-style: path` to fall back to `localhost:<port>/<account>/<region>/<repo>` URIs.
@@ -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) {
@@ -212,6 +212,66 @@ class EcrImagePushApiDockerIntegrationTest {
@Test
@Order(7)
void batchDeleteImageByTagLeavesTheSurvivingTagPullable() throws Exception {
call("BatchDeleteImage", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":["
+ "{\"imageTag\":\"v1\"},{\"imageTag\":\"nope\"}]}")
.statusCode(200)
.body("imageIds", hasSize(1))
.body("imageIds[0].imageTag", equalTo("v1"))
.body("imageIds[0].imageDigest", equalTo(manifestDigest))
.body("failures", hasSize(1))
.body("failures[0].imageId.imageTag", equalTo("nope"))
.body("failures[0].failureCode", equalTo("ImageNotFound"));
call("DescribeImages", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":[{\"imageTag\":\"release\"}]}")
.statusCode(200)
.body("imageDetails[0].imageDigest", equalTo(manifestDigest))
.body("imageDetails[0].imageTags", hasSize(1))
.body("imageDetails[0].imageTags[0]", equalTo("release"));
Fetched byTag = registryGet("000000000000.dkr.ecr.us-east-1.localhost",
"/v2/" + repo + "/manifests/release", DOCKER_MANIFEST);
assertEquals(200, byTag.statusCode());
assertEquals(manifestDigest, byTag.digest());
Fetched byDigest = registryGet("000000000000.dkr.ecr.us-east-1.localhost",
"/v2/" + repo + "/manifests/" + manifestDigest, DOCKER_MANIFEST);
assertEquals(200, byDigest.statusCode());
assertEquals(manifestDigest, byDigest.digest());
}
@Test
@Order(8)
void batchDeleteImageByDigestRemovesTheManifestAndEveryTag() throws Exception {
call("PutImage", putImage(repo, manifest, "v1")).statusCode(200)
.body("image.imageId.imageDigest", equalTo(manifestDigest));
call("BatchDeleteImage", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":"
+ "[{\"imageDigest\":\"" + manifestDigest + "\"}]}")
.statusCode(200)
.body("imageIds", hasSize(2))
.body("imageIds.imageTag", hasItems("v1", "release"))
.body("imageIds.imageDigest", hasItems(manifestDigest, manifestDigest))
.body("failures", hasSize(0));
call("ListImages", "{\"repositoryName\":\"" + repo + "\"}")
.statusCode(200)
.body("imageIds", hasSize(0));
Fetched byDigest = registryGet("000000000000.dkr.ecr.us-east-1.localhost",
"/v2/" + repo + "/manifests/" + manifestDigest, DOCKER_MANIFEST);
assertEquals(404, byDigest.statusCode());
call("BatchGetImage", "{\"repositoryName\":\"" + repo + "\",\"imageIds\":[{\"imageTag\":\"release\"}]}")
.statusCode(200)
.body("images", hasSize(0))
.body("failures", hasSize(1))
.body("failures[0].imageId.imageTag", equalTo("release"))
.body("failures[0].failureCode", equalTo("ImageNotFound"));
}
@Test
@Order(9)
void anImmutableTagIsWrittenOnce() {
String upload = initiate(immutableRepo);
part(immutableRepo, upload, 0, config).statusCode(200);
@@ -231,7 +291,7 @@ class EcrImagePushApiDockerIntegrationTest {
/** Last, since every class on this profile shares one registry. */
@Test
@Order(8)
@Order(10)
void cleanUp() {
call("DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}").statusCode(200);
call("DeleteRepository", "{\"repositoryName\":\"" + immutableRepo + "\",\"force\":true}").statusCode(200);
@@ -4,11 +4,13 @@ import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
import io.github.hectorvent.floci.services.ecr.model.Image;
import io.github.hectorvent.floci.services.ecr.model.ImageDetail;
import io.github.hectorvent.floci.services.ecr.model.ImageIdentifier;
import io.github.hectorvent.floci.services.ecr.model.ImageMetadata;
@@ -26,13 +28,18 @@ import org.mockito.Mockito;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -40,6 +47,8 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
@@ -805,6 +814,412 @@ class EcrServiceTest {
}
}
// ------------------------------------------------------------
// BatchDeleteImage
// ------------------------------------------------------------
private static final String DELETE_MANIFEST = """
{
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": 1, "digest": "sha256:c"},
"layers": []
}
""";
private static final String DELETE_DIGEST = "sha256:"
+ Digests.sha256Hex(DELETE_MANIFEST.getBytes(StandardCharsets.UTF_8));
@Test
void batchDeleteImageByTagKeepsTheSharedManifestForTheSurvivingTags() throws Exception {
String repositoryName = "batch-delete/shared-manifest";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
try (MultiTagRegistryServer registry = new MultiTagRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, "release", "stable")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier("release", null)), null, REGION);
assertTrue(result.failures().isEmpty(), () -> "unexpected failures: " + result.failures());
assertEquals(1, result.imageIds().size());
assertEquals("release", result.imageIds().get(0).getImageTag());
assertEquals(DELETE_DIGEST, result.imageIds().get(0).getImageDigest());
assertEquals(List.of(DELETE_DIGEST), registry.deletedManifests());
assertEquals(List.of("stable"), registry.putTags());
List<ImageIdentifier> remaining = service.listImages(repositoryName, null, REGION, null, null).items();
assertEquals(1, remaining.size());
assertEquals("stable", remaining.get(0).getImageTag());
assertEquals(DELETE_DIGEST, remaining.get(0).getImageDigest());
EcrService.BatchGetImageResult got = service.batchGetImage(
repositoryName, List.of(new ImageIdentifier("stable", null)), null, null, REGION);
assertTrue(got.failures().isEmpty(), () -> "unexpected failures: " + got.failures());
assertEquals(1, got.images().size());
assertEquals(DELETE_DIGEST, got.images().get(0).getImageId().getImageDigest());
EcrService.DescribeImagesResult described = service.describeImages(
repositoryName, List.of(new ImageIdentifier("stable", null)), null, REGION);
assertTrue(described.failures().isEmpty(), () -> "unexpected failures: " + described.failures());
assertEquals(1, described.imageDetails().size());
assertEquals(DELETE_DIGEST, described.imageDetails().get(0).getImageDigest());
assertEquals(List.of("stable"), described.imageDetails().get(0).getImageTags());
}
}
@Test
void batchDeleteImageByTagKeepsTheImagePushedAtOfTheSurvivingTag() throws Exception {
String repositoryName = "batch-delete/pushed-at";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
InMemoryStorage<String, ImageMetadata> metaStore = new InMemoryStorage<>();
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, "release", "stable")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
withMeta.createRepository(repositoryName, null, null, null, null, null, null, REGION);
withMeta.describeImages(repositoryName, List.of(new ImageIdentifier("stable", null)), null, REGION);
ImageMetadata before = metaStore.scan(k -> k.endsWith(DELETE_DIGEST)).get(0);
withMeta.batchDeleteImage(repositoryName, List.of(new ImageIdentifier("release", null)), null, REGION);
List<ImageMetadata> after = metaStore.scan(k -> k.endsWith(DELETE_DIGEST));
assertEquals(1, after.size());
assertEquals(before.getPushedAt(), after.get(0).getPushedAt());
}
}
@Test
void batchDeleteImageByTagDeletesTheManifestWhenTheLastTagGoes() throws Exception {
String repositoryName = "batch-delete/last-tag";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
try (MultiTagRegistryServer registry = new MultiTagRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, "v1")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier("v1", null)), null, REGION);
assertTrue(result.failures().isEmpty(), () -> "unexpected failures: " + result.failures());
assertEquals(1, result.imageIds().size());
assertEquals("v1", result.imageIds().get(0).getImageTag());
assertEquals(DELETE_DIGEST, result.imageIds().get(0).getImageDigest());
assertEquals(List.of(DELETE_DIGEST), registry.deletedManifests());
assertTrue(registry.putTags().isEmpty());
assertTrue(service.listImages(repositoryName, null, REGION, null, null).items().isEmpty());
}
}
@Test
void batchDeleteImageByDigestDeletesTheManifestAndAllItsTags() throws Exception {
String repositoryName = "batch-delete/by-digest";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
try (MultiTagRegistryServer registry = new MultiTagRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, "release", "stable")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier(null, DELETE_DIGEST)), null, REGION);
assertTrue(result.failures().isEmpty(), () -> "unexpected failures: " + result.failures());
assertEquals(2, result.imageIds().size());
List<String> reportedTags = result.imageIds().stream().map(ImageIdentifier::getImageTag).toList();
assertTrue(reportedTags.contains("release"), "imageIds must report tag release");
assertTrue(reportedTags.contains("stable"), "imageIds must report tag stable");
for (ImageIdentifier id : result.imageIds()) {
assertEquals(DELETE_DIGEST, id.getImageDigest());
}
assertEquals(List.of(DELETE_DIGEST), registry.deletedManifests());
assertTrue(registry.tags().isEmpty());
assertTrue(service.listImages(repositoryName, null, REGION, null, null).items().isEmpty());
}
}
@Test
void batchDeleteImageReportsAnUnknownTagAsAnImageFailure() throws Exception {
String repositoryName = "batch-delete/unknown-tag";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
try (MultiTagRegistryServer registry = new MultiTagRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, "release", "stable")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(repositoryName,
List.of(new ImageIdentifier("nope", null), new ImageIdentifier("release", null)),
null, REGION);
assertEquals(1, result.imageIds().size());
assertEquals("release", result.imageIds().get(0).getImageTag());
assertEquals(1, result.failures().size());
assertEquals("nope", result.failures().get(0).getImageId().getImageTag());
assertEquals("ImageNotFound", result.failures().get(0).getFailureCode());
assertEquals(List.of("stable"), registry.tags());
}
}
@Test
void batchDeleteImageRefusesTheDeleteWhenTheTagListingFails() throws Exception {
String repositoryName = "batch-delete/listing-fails";
RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class);
when(registryManager.httpClient()).thenReturn(http);
when(http.headManifestDigest(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST);
when(http.listTagsStrict(anyString())).thenThrow(new ConnectException("Connection refused"));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier("release", null)), null, REGION);
assertTrue(result.imageIds().isEmpty());
assertEquals(1, result.failures().size());
assertEquals("ServerException", result.failures().get(0).getFailureCode());
verify(http, never()).deleteManifest(anyString(), anyString());
}
@Test
void batchDeleteByTagHoldsTheRepositoryWriteLockFromTheDeleteThroughTheRestore() throws Exception {
String repositoryName = "batch-delete/lock-held";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
CountDownLatch deleteArrived = new CountDownLatch(1);
CountDownLatch deleteMayProceed = new CountDownLatch(1);
CountDownLatch restoreArrived = new CountDownLatch(1);
CountDownLatch restoreMayProceed = new CountDownLatch(1);
try (PausableRegistryServer registry = new PausableRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST,
deleteArrived, deleteMayProceed, restoreArrived, restoreMayProceed, "release", "stable")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<EcrService.BatchDeleteImageResult> batch = executor.submit(
() -> service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier("release", null)), null, REGION));
assertTrue(deleteArrived.await(5, TimeUnit.SECONDS),
"the shared manifest delete reached the registry");
assertTrue(repositoryWriteLockHeld(internal),
"the delete must hold the repository write lock while the manifest is dropped");
deleteMayProceed.countDown();
assertTrue(restoreArrived.await(5, TimeUnit.SECONDS),
"the surviving tag's manifest reached the registry again");
assertTrue(repositoryWriteLockHeld(internal),
"the delete must hold the repository write lock while surviving tags are restored");
restoreMayProceed.countDown();
EcrService.BatchDeleteImageResult result = batch.get(5, TimeUnit.SECONDS);
assertTrue(result.failures().isEmpty(), () -> "unexpected failures: " + result.failures());
assertEquals(1, result.imageIds().size());
assertEquals("release", result.imageIds().get(0).getImageTag());
assertEquals(List.of("stable"), registry.putTags());
assertEquals(DELETE_DIGEST, registry.digestOf("stable"));
assertTrue(service.tryLockRepositoryWrites(internal),
"the repository write lock must be free after the delete");
service.unlockRepositoryWrites(internal);
} finally {
deleteMayProceed.countDown();
restoreMayProceed.countDown();
executor.shutdownNow();
}
}
}
@Test
void putImageHoldsTheRepositoryWriteLockForItsManifestWrite() throws Exception {
String repositoryName = "put-image/lock-held";
String internal = ACCOUNT + "/" + REGION + "/" + repositoryName;
String replacement = DELETE_MANIFEST.replace("\"size\": 1", "\"size\": 2");
String replacementDigest = "sha256:" + Digests.sha256Hex(replacement.getBytes(StandardCharsets.UTF_8));
CountDownLatch putArrived = new CountDownLatch(1);
CountDownLatch putMayProceed = new CountDownLatch(1);
try (PausableRegistryServer registry = new PausableRegistryServer(
internal, DELETE_DIGEST, DELETE_MANIFEST, null, null, putArrived, putMayProceed, "v1")) {
when(registryManager.httpClient())
.thenReturn(new RegistryHttpClient("http://localhost:" + registry.port()));
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<Image> push = executor.submit(
() -> service.putImage(repositoryName, replacement, null, "v1", null, null, REGION));
assertTrue(putArrived.await(5, TimeUnit.SECONDS),
"the replacement manifest reached the registry");
assertTrue(repositoryWriteLockHeld(internal),
"PutImage must hold the repository write lock while it writes the manifest");
putMayProceed.countDown();
Image image = push.get(5, TimeUnit.SECONDS);
assertEquals(replacementDigest, image.getImageId().getImageDigest());
assertEquals(replacementDigest, registry.digestOf("v1"));
assertTrue(service.tryLockRepositoryWrites(internal),
"the repository write lock must be free after the push");
service.unlockRepositoryWrites(internal);
} finally {
putMayProceed.countDown();
executor.shutdownNow();
}
}
}
@Test
void batchDeleteByTagHoldsTheRegistryManagerMonitorAcrossTheSwap() throws Exception {
String repositoryName = "batch-delete/monitor-held";
RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class);
when(registryManager.httpClient()).thenReturn(http);
when(http.headManifestDigest(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST);
when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST);
when(http.listTagsStrict(anyString())).thenReturn(List.of("stable"));
when(http.getManifest(anyString(), anyString(), any())).thenReturn(new RegistryHttpClient.ManifestResult(
DELETE_DIGEST, DELETE_MANIFEST, "application/vnd.docker.distribution.manifest.v2+json"));
AtomicBoolean holdsAtDrop = new AtomicBoolean();
AtomicBoolean holdsAtRestore = new AtomicBoolean();
when(http.deleteManifest(anyString(), anyString())).thenAnswer(inv -> {
holdsAtDrop.set(Thread.holdsLock(registryManager));
return true;
});
when(http.putManifest(anyString(), anyString(), anyString(), any())).thenAnswer(inv -> {
holdsAtRestore.set(Thread.holdsLock(registryManager));
return DELETE_DIGEST;
});
service.createRepository(repositoryName, null, null, null, null, null, null, REGION);
EcrService.BatchDeleteImageResult result = service.batchDeleteImage(
repositoryName, List.of(new ImageIdentifier("release", null)), null, REGION);
assertTrue(result.failures().isEmpty(), () -> "unexpected failures: " + result.failures());
assertEquals(1, result.imageIds().size());
assertTrue(holdsAtDrop.get(),
"the drop must run under the registry manager's monitor, which /_floci/ecr/gc holds");
assertTrue(holdsAtRestore.get(),
"the restore must run under the same monitor hold the drop opened");
}
/** Probes the repository write lock without taking it: true when another writer holds it. */ private boolean repositoryWriteLockHeld(String storageRepositoryName) {
boolean acquired = service.tryLockRepositoryWrites(storageRepositoryName);
if (acquired) {
service.unlockRepositoryWrites(storageRepositoryName);
}
return !acquired;
}
@Test
void repositoryWriteLockEntriesAreCollectedOnceTheirWritersAreDone() {
String internal = ACCOUNT + "/" + REGION + "/write-locks/collected";
assertTrue(service.tryLockRepositoryWrites(internal));
assertEquals(1, service.liveRepositoryWriteLocks(), "a held lock keeps its entry");
service.unlockRepositoryWrites(internal);
assertEquals(0, service.liveRepositoryWriteLocks(),
"the entry is collected once its writer is done");
String missing = ACCOUNT + "/" + REGION + "/no-such/repository";
assertTrue(service.tryLockRepositoryWrites(missing),
"a registry write to a repository that does not exist takes the lock all the same");
service.unlockRepositoryWrites(missing);
assertEquals(0, service.liveRepositoryWriteLocks(),
"a missing repository's lock entry must not stay in memory");
}
/**
* A writer waiting on a held lock keeps the entry in the map, so a writer arriving later
* meets the same lock instance and stays mutual-excluded with it: were the entry removed
* at the release, the later writer would take a fresh instance while the waiter still
* queues on the old one, and both would believe they hold the repository's write lock.
*/
@Test
void aWaitingWriterKeepsTheLockEntrySharedWithLaterArrivals() throws Exception {
String internal = ACCOUNT + "/" + REGION + "/write-locks/waiting";
assertTrue(service.tryLockRepositoryWrites(internal), "the test holds the lock first");
AtomicReference<Thread> waiterThread = new AtomicReference<>();
CountDownLatch waiterStarted = new CountDownLatch(1);
CountDownLatch waiterHeld = new CountDownLatch(1);
CountDownLatch waiterMayRelease = new CountDownLatch(1);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> waiter = executor.submit(() -> {
waiterThread.set(Thread.currentThread());
waiterStarted.countDown();
service.lockRepositoryWrites(internal);
waiterHeld.countDown();
waiterMayRelease.await();
service.unlockRepositoryWrites(internal);
return null;
});
assertTrue(waiterStarted.await(5, TimeUnit.SECONDS));
awaitParkedOnTheLock(waiterThread.get());
service.unlockRepositoryWrites(internal);
assertTrue(waiterHeld.await(5, TimeUnit.SECONDS),
"the waiting writer takes the lock once the holder releases it");
assertFalse(service.tryLockRepositoryWrites(internal),
"a later writer must be mutual-excluded by the writer waiting on the same entry");
waiterMayRelease.countDown();
waiter.get(5, TimeUnit.SECONDS);
assertTrue(service.tryLockRepositoryWrites(internal),
"the lock is free again once its last writer is done");
service.unlockRepositoryWrites(internal);
assertEquals(0, service.liveRepositoryWriteLocks(),
"the entry is collected once its last writer is done");
} finally {
waiterMayRelease.countDown();
executor.shutdownNow();
}
}
@Test
void anInterruptedLockWaiterLeavesNoEntryBehind() throws Exception {
String internal = ACCOUNT + "/" + REGION + "/write-locks/interrupted";
service.lockRepositoryWrites(internal);
AtomicReference<Thread> waiterThread = new AtomicReference<>();
CountDownLatch waiterStarted = new CountDownLatch(1);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> waiter = executor.submit(() -> {
waiterThread.set(Thread.currentThread());
waiterStarted.countDown();
service.lockRepositoryWrites(internal);
return null;
});
assertTrue(waiterStarted.await(5, TimeUnit.SECONDS));
awaitParkedOnTheLock(waiterThread.get());
waiterThread.get().interrupt();
ExecutionException failed = assertThrows(ExecutionException.class,
() -> waiter.get(5, TimeUnit.SECONDS),
"the interrupted waiter fails instead of taking the lock");
assertEquals("ServerException", ((AwsException) failed.getCause()).getErrorCode());
service.unlockRepositoryWrites(internal);
assertEquals(0, service.liveRepositoryWriteLocks(),
"the interrupted waiter's entry is collected once the holder is done");
} finally {
executor.shutdownNow();
}
}
/** Polls until the waiter is parked on the lock's semaphore, so it holds the entry. */
private static void awaitParkedOnTheLock(Thread waiter) throws InterruptedException {
long deadline = System.currentTimeMillis() + 5_000;
while (waiter.getState() != Thread.State.WAITING) {
assertTrue(System.currentTimeMillis() < deadline,
"the waiting writer never parked on the lock");
Thread.sleep(5);
}
}
@Test
void bareEntryClaimedByOtherAccountIsNotResolvedForThisScope() throws Exception {
// Both accounts have metadata for the same repo name in the same region;
@@ -1340,6 +1755,289 @@ class EcrServiceTest {
}
}
/** Registry fake holding several tags over one shared manifest, following registry:2's answers. */
private static final class MultiTagRegistryServer implements AutoCloseable {
private final HttpServer server;
private final String repository;
private final String digest;
private final String manifest;
private final List<String> tags = new ArrayList<>();
private final List<String> deletedManifests = new ArrayList<>();
private final List<String> putTags = new ArrayList<>();
private boolean manifestGone;
private MultiTagRegistryServer(String repository, String digest, String manifest, String... tags)
throws IOException {
this.repository = repository;
this.digest = digest;
this.manifest = manifest;
this.tags.addAll(List.of(tags));
this.server = HttpServer.create(new InetSocketAddress(0), 0);
this.server.createContext("/v2/", this::handle);
this.server.start();
}
private int port() {
return server.getAddress().getPort();
}
private List<String> tags() {
return List.copyOf(tags);
}
private List<String> deletedManifests() {
return List.copyOf(deletedManifests);
}
private List<String> putTags() {
return List.copyOf(putTags);
}
private void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String method = exchange.getRequestMethod();
if ("/v2/".equals(path) && "GET".equals(method)) {
send(exchange, 200, "");
return;
}
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
sendJson(exchange, 200, "{\"repositories\":[\"" + repository + "\"]}");
return;
}
String manifestsPrefix = "/v2/" + repository + "/manifests/";
if ((path.equals("/v2/" + repository + "/tags/list")) && "GET".equals(method)) {
String listed = tags.isEmpty()
? "null"
: "[" + tags.stream().map(t -> "\"" + t + "\"")
.reduce((a, b) -> a + "," + b).orElse("") + "]";
sendJson(exchange, 200, "{\"name\":\"" + repository + "\",\"tags\":" + listed + "}");
return;
}
if (path.startsWith(manifestsPrefix)) {
String reference = path.substring(manifestsPrefix.length());
if ("DELETE".equals(method)) {
if (digest.equals(reference) && !manifestGone) {
deletedManifests.add(reference);
manifestGone = true;
tags.clear();
exchange.sendResponseHeaders(202, -1);
exchange.close();
return;
}
exchange.sendResponseHeaders(404, -1);
exchange.close();
return;
}
if ("PUT".equals(method)) {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
if (manifest.equals(body)) {
if (manifestGone) {
manifestGone = false;
}
if (!tags.contains(reference)) {
tags.add(reference);
}
putTags.add(reference);
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
exchange.sendResponseHeaders(201, -1);
exchange.close();
return;
}
sendJson(exchange, 400, "{\"errors\":[{\"code\":\"DIGEST_INVALID\"}]}");
return;
}
boolean byDigest = digest.equals(reference);
boolean byTag = !byDigest && tags.contains(reference);
if ((byDigest || byTag) && !manifestGone && ("GET".equals(method) || "HEAD".equals(method))) {
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
if ("HEAD".equals(method)) {
exchange.sendResponseHeaders(200, -1);
exchange.close();
return;
}
exchange.getResponseHeaders().add("Content-Type",
"application/vnd.docker.distribution.manifest.v2+json");
send(exchange, 200, manifest);
return;
}
}
exchange.sendResponseHeaders(404, -1);
exchange.close();
}
private static void sendJson(HttpExchange exchange, int status, String body) throws IOException {
exchange.getResponseHeaders().add("Content-Type", "application/json");
send(exchange, status, body);
}
private static void send(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes();
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
@Override
public void close() {
server.stop(0);
}
}
/**
* Registry fake over tags and manifests the way registry:2 holds them, which parks the
* digest delete and the manifest PUT of a test's choosing until the test lets them continue,
* so the test can observe what the service holds while a write is in flight.
*/
private static final class PausableRegistryServer implements AutoCloseable {
private static final String MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json";
private final HttpServer server;
private final String repository;
private final Map<String, String> manifests = new ConcurrentHashMap<>();
private final Map<String, String> mediaTypes = new ConcurrentHashMap<>();
private final Map<String, String> tags = new ConcurrentHashMap<>();
private final List<String> putTags = Collections.synchronizedList(new ArrayList<>());
private final CountDownLatch deleteArrived;
private final CountDownLatch deleteMayProceed;
private final CountDownLatch putArrived;
private final CountDownLatch putMayProceed;
private PausableRegistryServer(String repository, String digest, String manifest,
CountDownLatch deleteArrived, CountDownLatch deleteMayProceed,
CountDownLatch putArrived, CountDownLatch putMayProceed,
String... tags) throws IOException {
this.repository = repository;
this.deleteArrived = deleteArrived;
this.deleteMayProceed = deleteMayProceed;
this.putArrived = putArrived;
this.putMayProceed = putMayProceed;
this.manifests.put(digest, manifest);
this.mediaTypes.put(digest, MANIFEST_MEDIA_TYPE);
for (String tag : tags) {
this.tags.put(tag, digest);
}
this.server = HttpServer.create(new InetSocketAddress(0), 0);
this.server.createContext("/v2/", this::handle);
this.server.start();
}
private int port() {
return server.getAddress().getPort();
}
private List<String> putTags() {
synchronized (putTags) {
return List.copyOf(putTags);
}
}
private String digestOf(String tag) {
return tags.get(tag);
}
private void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String method = exchange.getRequestMethod();
if ("/v2/".equals(path) && "GET".equals(method)) {
send(exchange, 200, "");
return;
}
if ("/v2/_catalog".equals(path) && "GET".equals(method)) {
sendJson(exchange, 200, "{\"repositories\":[\"" + repository + "\"]}");
return;
}
String manifestsPrefix = "/v2/" + repository + "/manifests/";
if (path.equals("/v2/" + repository + "/tags/list") && "GET".equals(method)) {
String listed = tags.isEmpty()
? "null"
: "[" + tags.keySet().stream().map(t -> "\"" + t + "\"")
.reduce((a, b) -> a + "," + b).orElse("") + "]";
sendJson(exchange, 200, "{\"name\":\"" + repository + "\",\"tags\":" + listed + "}");
return;
}
if (path.startsWith(manifestsPrefix)) {
String reference = path.substring(manifestsPrefix.length());
if ("DELETE".equals(method)) {
park(deleteArrived, deleteMayProceed);
if (manifests.remove(reference) == null) {
exchange.sendResponseHeaders(404, -1);
exchange.close();
return;
}
tags.values().removeAll(List.of(reference));
exchange.sendResponseHeaders(202, -1);
exchange.close();
return;
}
if ("PUT".equals(method)) {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
park(putArrived, putMayProceed);
String digest = "sha256:" + Digests.sha256Hex(body.getBytes(StandardCharsets.UTF_8));
manifests.put(digest, body);
String mediaType = exchange.getRequestHeaders().getFirst("Content-Type");
mediaTypes.put(digest, mediaType == null ? MANIFEST_MEDIA_TYPE : mediaType);
if (!digest.equals(reference)) {
tags.put(reference, digest);
putTags.add(reference);
}
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
exchange.sendResponseHeaders(201, -1);
exchange.close();
return;
}
String digest = tags.containsKey(reference) ? tags.get(reference) : reference;
if (manifests.containsKey(digest) && ("GET".equals(method) || "HEAD".equals(method))) {
exchange.getResponseHeaders().add("Docker-Content-Digest", digest);
if ("HEAD".equals(method)) {
exchange.sendResponseHeaders(200, -1);
exchange.close();
return;
}
exchange.getResponseHeaders().add("Content-Type",
mediaTypes.getOrDefault(digest, MANIFEST_MEDIA_TYPE));
send(exchange, 200, manifests.get(digest));
return;
}
}
exchange.sendResponseHeaders(404, -1);
exchange.close();
}
private void park(CountDownLatch arrived, CountDownLatch mayProceed) throws IOException {
if (arrived == null || mayProceed == null) {
return;
}
arrived.countDown();
try {
if (!mayProceed.await(30, TimeUnit.SECONDS)) {
throw new IOException("parked registry write was never continued");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("parked registry write was interrupted", e);
}
}
private static void sendJson(HttpExchange exchange, int status, String body) throws IOException {
exchange.getResponseHeaders().add("Content-Type", "application/json");
send(exchange, status, body);
}
private static void send(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes();
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
@Override
public void close() {
server.stop(0);
}
}
// ------------------------------------------------------------
// Registry settings
// ------------------------------------------------------------
@@ -32,6 +32,7 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -49,6 +50,8 @@ import static org.mockito.Mockito.when;
class EcrRegistryDataPlaneTest {
private Vertx vertx;
private Semaphore repositoryWriteLock;
private CountDownLatch repositoryWriteLockRefused;
@BeforeEach
void setUp() {
@@ -371,6 +374,199 @@ class EcrRegistryDataPlaneTest {
}
}
/**
* A manifest push takes its repository's write lock before anything of it reaches the
* registry, the same lock a BatchDeleteImage holds while it drops a shared manifest and
* writes it back under its surviving tags: a push that arrives during such a delete waits
* for it instead of landing between the drop and the write-back, where the restore would
* overwrite it. Reads take no lock and answer while the push waits.
*/
@Test
void aManifestPushWaitsForTheRepositoryWriteLockAndCompletesAfterIt() throws Exception {
AtomicInteger manifestWrites = new AtomicInteger();
HttpServer registry = vertx.createHttpServer()
.requestHandler(request -> {
if (request.method() == HttpMethod.PUT) {
request.bodyHandler(body -> {
manifestWrites.incrementAndGet();
request.response().setStatusCode(201).end();
});
} else if (request.method() == HttpMethod.HEAD) {
request.response().setStatusCode(404).end();
} else {
request.response().setStatusCode(200).end();
}
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
HttpServer dataPlane = null;
HttpClient client = null;
try {
dataPlane = dataPlane(registry, false);
client = vertx.createHttpClient();
assertTrue(repositoryWriteLock.tryAcquire(), "the test takes the lock a delete would hold");
Future<HttpClientResponse> push = client.request(new RequestOptions()
.setHost("127.0.0.1")
.setPort(dataPlane.actualPort())
.setMethod(HttpMethod.PUT)
.setURI("/v2/platform/api/manifests/v1"))
.compose(request -> {
request.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566");
request.setChunked(true);
return request.send(Buffer.buffer("{}"));
});
Integer readStatus = client.request(new RequestOptions()
.setHost("127.0.0.1")
.setPort(dataPlane.actualPort())
.setMethod(HttpMethod.GET)
.setURI("/v2/platform/api/manifests/v1"))
.compose(request -> {
request.putHeader("Host", "000000000000.dkr.ecr.us-east-1.localhost:4566");
return request.send().map(HttpClientResponse::statusCode);
})
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
assertEquals(200, readStatus, "a read answers while a write waits for the lock");
assertTrue(repositoryWriteLockRefused.await(5, TimeUnit.SECONDS),
"the push is parked waiting for the repository's write lock");
assertEquals(0, manifestWrites.get(),
"the push must not reach the registry while the repository's delete holds the lock");
repositoryWriteLock.release();
HttpClientResponse response = push.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
assertEquals(201, response.statusCode());
assertEquals(1, manifestWrites.get());
assertTrue(acquiredWithin(repositoryWriteLock, 5_000),
"the exchange returns the write lock with its answer");
} finally {
if (client != null) {
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
if (dataPlane != null) {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
/**
* Two manifest PUTs to one repository on one HTTP/2 connection: the first holds the
* repository's write lock and is parked mid-body at the registry, the second waits for the
* lock. The second push's body must not sit unread in the connection's flow-control
* window, where it would keep the first push's remaining bytes from ever arriving: the
* first could not finish, would never release the lock, and both would wait forever. The
* data plane drains a waiting manifest body, so the second push's whole body reaches the
* data plane while the first is still parked, and both pushes then complete, in order,
* once the registry answers.
*/
@Test
void concurrentManifestPushesOnOneConnectionDoNotDeadlock() throws Exception {
int parkedBodyBytes = 4 * 1024 * 1024;
int waitingBodyBytes = 2 * 1024 * 1024;
CountDownLatch parkedArrived = new CountDownLatch(1);
CountDownLatch parkedAnswered = new CountDownLatch(1);
AtomicReference<HttpServerRequest> parkedRequest = new AtomicReference<>();
AtomicInteger order = new AtomicInteger();
AtomicInteger parkedAnsweredAt = new AtomicInteger(-1);
AtomicInteger waitingArrivedAt = new AtomicInteger(-1);
AtomicInteger registryParkedBodyBytes = new AtomicInteger();
AtomicInteger registryWaitingBodyBytes = new AtomicInteger();
HttpServer registry = vertx.createHttpServer()
.requestHandler(request -> {
if (request.path().endsWith("/manifests/first")) {
parkedRequest.set(request);
request.pause();
parkedArrived.countDown();
return;
}
if (!request.path().endsWith("/manifests/second")) {
request.response().setStatusCode(405).end();
return;
}
waitingArrivedAt.set(order.incrementAndGet());
request.bodyHandler(body -> {
registryWaitingBodyBytes.set(body.length());
request.response().setStatusCode(201).end();
});
})
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
HttpServer dataPlane = null;
HttpClient client = null;
try {
dataPlane = dataPlane(registry, false);
// HTTP/2 with prior knowledge: both pushes are streams on one connection, as
// crane's are.
client = vertx.createHttpClient(new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(false));
SocketAddress server = SocketAddress.inetSocketAddress(dataPlane.actualPort(), "127.0.0.1");
Future<HttpClientResponse> first = client.request(new RequestOptions()
.setServer(server)
.setHost("000000000000.dkr.ecr.us-east-1.localhost")
.setPort(4566)
.setMethod(HttpMethod.PUT)
.setURI("/v2/platform/api/manifests/first"))
.compose(request -> request.send(Buffer.buffer(new byte[parkedBodyBytes])));
assertTrue(parkedArrived.await(5, TimeUnit.SECONDS),
"the push that holds the lock reached the registry");
HttpClientRequest waiting = client.request(new RequestOptions()
.setServer(server)
.setHost("000000000000.dkr.ecr.us-east-1.localhost")
.setPort(4566)
.setMethod(HttpMethod.PUT)
.setURI("/v2/platform/api/manifests/second"))
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
waiting.setChunked(true);
Future<HttpClientResponse> second = waiting.response();
List<Future<Void>> writes = new ArrayList<>();
for (int written = 0; written < waitingBodyBytes; written += 64 * 1024) {
writes.add(waiting.write(Buffer.buffer(new byte[64 * 1024])));
}
Future.join(writes).toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
assertEquals(1, parkedAnswered.getCount(),
"the waiting push's whole body must reach the data plane while the push"
+ " holding the lock is still parked");
waiting.end();
HttpServerRequest parked = parkedRequest.get();
parked.bodyHandler(body -> {
registryParkedBodyBytes.set(body.length());
parkedAnsweredAt.set(order.incrementAndGet());
parked.response().setStatusCode(201).end();
parkedAnswered.countDown();
});
parked.resume();
assertEquals(201, first.toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS).statusCode());
assertEquals(201, second.toCompletionStage().toCompletableFuture()
.get(10, TimeUnit.SECONDS).statusCode());
assertEquals(parkedBodyBytes, registryParkedBodyBytes.get());
assertEquals(waitingBodyBytes, registryWaitingBodyBytes.get());
assertTrue(waitingArrivedAt.get() > parkedAnsweredAt.get(),
"the waiting push reaches the registry only after the push holding the"
+ " lock is answered");
assertTrue(acquiredWithin(repositoryWriteLock, 5_000),
"both exchanges return the write lock with their answers");
} finally {
if (client != null) {
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
if (dataPlane != null) {
dataPlane.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
registry.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
/**
* An HTTP/2 client such as crane sends every upload of a push as a stream on one
* connection, and the data plane needs a registry connection for each. An upload left
@@ -651,6 +847,22 @@ class EcrRegistryDataPlaneTest {
return null;
})
.when(ecrService).releaseImmutableTag(anyString());
// The repository write lock lives in EcrService too, so the mock holds a real one,
// and counts a latch each time it refuses a writer.
repositoryWriteLock = new Semaphore(1);
repositoryWriteLockRefused = new CountDownLatch(1);
when(ecrService.tryLockRepositoryWrites(anyString()))
.thenAnswer(call -> {
if (repositoryWriteLock.tryAcquire()) {
return true;
}
repositoryWriteLockRefused.countDown();
return false;
});
Mockito.doAnswer(call -> {
repositoryWriteLock.release();
return null;
}).when(ecrService).unlockRepositoryWrites(anyString());
when(ecrService.registryRepositoryName("platform/api", "000000000000", "us-east-1"))
.thenReturn("legacy/platform-api");
@@ -664,6 +876,21 @@ class EcrRegistryDataPlaneTest {
private record ManifestResponse(int statusCode, String body) {
}
/**
* Takes the semaphore within {@code millis}, for assertions that follow an exchange whose
* end, and with it its lock release, runs on the event loop after its answer is seen.
*/
private static boolean acquiredWithin(Semaphore semaphore, long millis) throws InterruptedException {
long deadline = System.currentTimeMillis() + millis;
while (!semaphore.tryAcquire()) {
if (System.currentTimeMillis() >= deadline) {
return false;
}
Thread.sleep(10);
}
return true;
}
private ManifestResponse putManifest(int port) throws Exception {
return putManifest(port, "000000000000.dkr.ecr.us-east-1.localhost:4566");
}