fix(ecr): count untagged images when deciding whether a repository is empty (#8651)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-16 17:28:03 -04:00
1 parent bda82cc98d
commit 5ea7186549
3 files changed
+134 -12

No files matched your search

@@ -652,13 +652,14 @@ public class EcrService implements ResourceProvider, Resettable {
String key = key(region, account, repositoryName);
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(repositoryName, account));
// Check whether the registry has any tagged images for this repo.
// Check whether the registry has any images for this repo, tagged or not.
// A test double with no HTTP client means no backing registry exists,
// so there is nothing to clean up. Any failure against a real client
// aborts the delete: an unreachable registry cannot prove the repo
// empty (non-force must not bypass RepositoryNotEmptyException) and
// force must not orphan pullable images behind deleted metadata.
List<String> tags;
boolean untaggedImages = false;
boolean registryAvailable = true;
if (registryManager.httpClient() == null) {
// Test double without an HTTP layer (Mockito default): no backing
@@ -666,7 +667,11 @@ public class EcrService implements ResourceProvider, Resettable {
tags = List.of();
registryAvailable = false;
} else try {
tags = listTagsOrThrow(account, region, repositoryName);
String internal = resolveRegistryRepoNameStrict(account, region, repositoryName);
tags = registryManager.httpClient().listTagsStrict(internal);
if (tags.isEmpty() && !force) {
untaggedImages = holdsImage(account, region, repositoryName, internal);
}
} catch (Exception e) {
if (isRegistryUnreachable(e)) {
throw new AwsException("ServerException",
@@ -679,7 +684,7 @@ public class EcrService implements ResourceProvider, Resettable {
+ e.getMessage(),
500);
}
if (!tags.isEmpty() && !force) {
if ((!tags.isEmpty() || untaggedImages) && !force) {
throw new AwsException("RepositoryNotEmptyException",
"The repository with name '" + repositoryName
+ "' in registry with id '" + account + "' cannot be deleted because it still contains images",
@@ -698,8 +703,8 @@ public class EcrService implements ResourceProvider, Resettable {
String metaPrefix = key + "::";
synchronized (imageMetaStore) {
pendingImagePushes.keySet().removeIf(k -> k.startsWith(metaPrefix));
for (ImageMetadata meta : imageMetaStore.scan(k -> k.startsWith(metaPrefix))) {
imageMetaStore.delete(metaPrefix + meta.getDigest());
for (ImageMetadata meta : storedImageRecords(account, metaPrefix)) {
removeImagePush(account, region, repositoryName, meta.getDigest());
}
}
if (!hasRepositories()) {
@@ -1934,13 +1939,48 @@ public class EcrService implements ResourceProvider, Resettable {
}
/**
* Lists tags and propagates registry failures. Used by force-delete to
* distinguish "registry unreachable" (skip cleanup) from "registry
* available but listing failed" (abort deletion).
* Whether the registry still holds a manifest of the repository, for a repository with no tags.
* The registry cannot list manifests, so candidates come from the push record every manifest
* write leaves in {@code imageMetaStore}, plus a push whose record could not be written yet
* ({@code pendingImagePushes}); one counts only while the registry has its manifest.
*/
private List<String> listTagsOrThrow(String account, String region, String repoName) throws Exception {
return registryManager.httpClient()
.listTagsStrict(resolveRegistryRepoNameStrict(account, region, repoName));
private boolean holdsImage(String account, String region, String repositoryName, String internal)
throws IOException, InterruptedException {
String metaPrefix = key(region, account, repositoryName) + "::";
Set<String> digests = new LinkedHashSet<>();
synchronized (imageMetaStore) {
storedImageRecords(account, metaPrefix).forEach(meta -> digests.add(meta.getDigest()));
pendingImagePushes.forEach((k, meta) -> {
if (k.startsWith(metaPrefix)) {
digests.add(meta.getDigest());
}
});
}
for (String digest : digests) {
if (registryManager.httpClient().headManifestDigestStrict(internal, digest, null) != null) {
return true;
}
}
return false;
}
/**
* The push records of one repository in {@code account}. A record written before the store was
* account-aware sits under its bare key; its key names the account, so it is moved to the
* account's partition here, as {@link #recordImagePush} and {@link #removeImagePush} do for one digest.
*/
private List<ImageMetadata> storedImageRecords(String account, String metaPrefix) {
synchronized (imageMetaStore) {
if (imageMetaStore instanceof AccountAwareStorageBackend<ImageMetadata> aware) {
for (ImageMetadata legacy : aware.scanRaw(
k -> !AccountAwareStorageBackend.hasAccountPrefix(k) && k.startsWith(metaPrefix))) {
String digest = legacy.getDigest();
aware.getForAccountMigratingLegacy(account, metaPrefix + digest, m -> digest.equals(m.getDigest()));
}
return aware.scanForAccount(account, k -> k.startsWith(metaPrefix));
}
return imageMetaStore.scan(k -> k.startsWith(metaPrefix));
}
}
/**
@@ -309,9 +309,38 @@ class EcrImagePushApiDockerIntegrationTest {
assertEquals(pushTime, retaggedPushTime);
}
/** Last, since every class on this profile shares one registry. */
@Test
@Order(11)
void anUntaggedImageKeepsItsRepositoryFromBeingDeletedWithoutForce() {
String untaggedRepo = repo + "-untagged";
call("CreateRepository", "{\"repositoryName\":\"" + untaggedRepo + "\"}").statusCode(200);
String upload = initiate(untaggedRepo);
part(untaggedRepo, upload, 0, config).statusCode(200);
complete(untaggedRepo, upload, configDigest).statusCode(200);
String bare = """
{
"schemaVersion": 2,
"mediaType": "%s",
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "size": %d, "digest": "%s"},
"layers": []
}""".formatted(DOCKER_MANIFEST, config.length, configDigest);
String bareDigest = "sha256:" + Digests.sha256Hex(bare.getBytes(StandardCharsets.UTF_8));
call("PutImage", "{\"repositoryName\":\"" + untaggedRepo + "\",\"imageManifest\":" + Json.encode(bare) + "}")
.statusCode(200).body("image.imageId.imageDigest", equalTo(bareDigest));
String byDigest = "{\"repositoryName\":\"" + untaggedRepo + "\",\"imageIds\":"
+ "[{\"imageDigest\":\"" + bareDigest + "\"}]}";
call("DeleteRepository", "{\"repositoryName\":\"" + untaggedRepo + "\"}").statusCode(400)
.body("__type", equalTo("RepositoryNotEmptyException"));
call("BatchGetImage", byDigest).statusCode(200).body("images", hasSize(1)).body("failures", hasSize(0));
call("BatchDeleteImage", byDigest).statusCode(200).body("failures", hasSize(0));
call("DeleteRepository", "{\"repositoryName\":\"" + untaggedRepo + "\"}").statusCode(200);
}
/** Last, since every class on this profile shares one registry. */
@Test
@Order(12)
void cleanUp() {
call("DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}").statusCode(200);
call("DeleteRepository", "{\"repositoryName\":\"" + immutableRepo + "\",\"force\":true}").statusCode(200);
@@ -551,6 +551,59 @@ class EcrServiceTest {
}
}
@Test
void deleteRepository_withoutForceRefusesWhileAnUntaggedImageRemains() throws Exception {
InMemoryStorage<String, ImageMetadata> metaStore = new InMemoryStorage<>();
EcrService withMeta = new EcrService(new InMemoryStorage<>(), metaStore, pullThroughCacheRuleStore,
registryManager, Mockito.mock(EmulatorConfig.class), new RegionResolver(REGION, ACCOUNT));
RegistryHttpClient http = Mockito.mock(RegistryHttpClient.class);
when(registryManager.httpClient()).thenReturn(http);
when(http.listTagsStrict(anyString())).thenReturn(List.of());
when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST);
withMeta.createRepository(REPO, null, null, null, null, null, null, REGION);
withMeta.recordImagePush(ACCOUNT, REGION, REPO, DELETE_DIGEST, Instant.now());
AwsException ex = assertThrows(AwsException.class, () -> withMeta.deleteRepository(REPO, null, false, REGION));
assertEquals("RepositoryNotEmptyException", ex.getErrorCode());
when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(null);
assertEquals(REPO, withMeta.deleteRepository(REPO, null, false, REGION).getRepositoryName());
// A push whose record write failed, and a record kept under the bare key of the
// pre-account store, still count as an image while the registry holds its manifest.
for (boolean legacy : new boolean[] {false, true}) {
InMemoryStorage<String, ImageMetadata> delegate = new InMemoryStorage<>() {
@Override
public void put(String key, ImageMetadata value) {
if (!legacy) {
throw new IllegalStateException("store down");
}
super.put(key, value);
}
};
EcrService other = new EcrService(new InMemoryStorage<>(),
new AccountAwareStorageBackend<>(delegate, null, ACCOUNT), pullThroughCacheRuleStore,
registryManager, Mockito.mock(EmulatorConfig.class), new RegionResolver(REGION, ACCOUNT));
when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(DELETE_DIGEST);
other.createRepository(REPO, null, null, null, null, null, null, REGION);
if (legacy) {
delegate.put(REGION + "::" + ACCOUNT + "::" + REPO + "::" + DELETE_DIGEST,
new ImageMetadata(DELETE_DIGEST, Instant.now()));
} else {
assertThrows(IllegalStateException.class,
() -> other.recordImagePush(ACCOUNT, REGION, REPO, DELETE_DIGEST, Instant.now()));
}
ex = assertThrows(AwsException.class, () -> other.deleteRepository(REPO, null, false, REGION),
"legacy=" + legacy);
assertEquals("RepositoryNotEmptyException", ex.getErrorCode(), "legacy=" + legacy);
when(http.headManifestDigestStrict(anyString(), anyString(), any())).thenReturn(null);
assertEquals(REPO, other.deleteRepository(REPO, null, false, REGION).getRepositoryName());
assertTrue(delegate.keys().stream().noneMatch(k -> k.contains("::" + REPO + "::")), "legacy=" + legacy);
}
}
@Test
void deleteRepository_keepsSharedRegistryStorageForRemainingRepositories() {
service.createRepository(REPO, null, null, null, null, null, null, REGION);