mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ecr): apply repository lifecycle policies in the background (#9318)
A sweep now applies every repository's lifecycle policy, as ECR does within a day of an image meeting a rule, and expires the images its rules select: imageCountMoreThan keeps the newest by push time and sinceImagePushed expires those older than the count, with rules applied in priority order and none marking an image a higher rule selected. A platform image of a held manifest list is kept until the list goes, and an artifact naming a subject expires with that image. Get and DeleteLifecyclePolicy report lastEvaluatedAt, and the delete echoes the policy it removed. Closes #5874.
This commit is contained in:
1 parent
365bad3dde
commit
ddad3ca1df
19 files changed
+1652
-53
No files matched your search
@@ -3518,6 +3518,22 @@ public interface EmulatorConfig {
|
||||
boolean preferLocalImages();
|
||||
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
/**
|
||||
* Run the background sweep that applies repository lifecycle policies, expiring the images their rules
|
||||
* select. When off, policies are checked and stored but nothing expires.
|
||||
* Env: FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_ENABLED
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean lifecycleSweepEnabled();
|
||||
|
||||
/**
|
||||
* How often the lifecycle sweep runs, in seconds. ECR expires an image within 24 hours of it meeting a
|
||||
* rule, so the interval only bounds how late Floci is.
|
||||
* Env: FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_INTERVAL_SECONDS
|
||||
*/
|
||||
@WithDefault("60")
|
||||
long lifecycleSweepIntervalSeconds();
|
||||
}
|
||||
|
||||
interface LambdaServiceConfig {
|
||||
|
||||
@@ -22,6 +22,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -617,27 +618,39 @@ public class EcrJsonHandler {
|
||||
String repo = request.path("repositoryName").asText(null);
|
||||
String registryId = request.path("registryId").asText(null);
|
||||
Repository r = service.getLifecyclePolicy(repo, registryId, region);
|
||||
return lifecycleResponse(r);
|
||||
ObjectNode response = lifecycleBody(r.getRegistryId(), r.getRepositoryName(), r.getLifecyclePolicyText());
|
||||
putLastEvaluatedAt(response, service.lifecyclePolicyEvaluatedAt(r, region));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteLifecyclePolicy(JsonNode request, String region) {
|
||||
String repo = request.path("repositoryName").asText(null);
|
||||
String registryId = request.path("registryId").asText(null);
|
||||
Repository r = service.deleteLifecyclePolicy(repo, registryId, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("registryId", r.getRegistryId());
|
||||
response.put("repositoryName", r.getRepositoryName());
|
||||
EcrService.DeletedLifecyclePolicy deleted = service.deleteLifecyclePolicy(repo, registryId, region);
|
||||
ObjectNode response = lifecycleBody(deleted.registryId(), deleted.repositoryName(),
|
||||
deleted.lifecyclePolicyText());
|
||||
putLastEvaluatedAt(response, deleted.lastEvaluatedAt());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response lifecycleResponse(Repository r) {
|
||||
return Response.ok(lifecycleBody(r.getRegistryId(), r.getRepositoryName(), r.getLifecyclePolicyText()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private ObjectNode lifecycleBody(String registryId, String repositoryName, String lifecyclePolicyText) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("registryId", r.getRegistryId());
|
||||
response.put("repositoryName", r.getRepositoryName());
|
||||
if (r.getLifecyclePolicyText() != null) {
|
||||
response.put("lifecyclePolicyText", r.getLifecyclePolicyText());
|
||||
response.put("registryId", registryId);
|
||||
response.put("repositoryName", repositoryName);
|
||||
if (lifecyclePolicyText != null) {
|
||||
response.put("lifecyclePolicyText", lifecyclePolicyText);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
return response;
|
||||
}
|
||||
|
||||
/** ECR answers with a time stamp before the policy is first applied, as Floci does with the epoch. */
|
||||
private static void putLastEvaluatedAt(ObjectNode response, Instant lastEvaluatedAt) {
|
||||
response.put("lastEvaluatedAt", lastEvaluatedAt != null ? lastEvaluatedAt.getEpochSecond() : 0L);
|
||||
}
|
||||
|
||||
private Response handleSetRepositoryPolicy(JsonNode request, String region) {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package io.floci.aws.services.ecr;
|
||||
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.ActionType;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.Rule;
|
||||
import io.floci.aws.services.ecr.EcrLifecyclePolicy.StorageClass;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Decides which images a lifecycle policy expires, by the evaluation rules of the ECR user guide: every rule selects
|
||||
* the images its tag filter matches and marks those its count rule finds, oldest first, and rules apply in
|
||||
* {@code rulePriority} order, a rule never marking an image a higher-priority rule selected.
|
||||
*
|
||||
* <p>Floci keeps every image in standard storage and records no pulls, so a rule selecting archived images selects
|
||||
* none, and {@code sinceImagePulled} and {@code transition} rules mark nothing for expiry while still keeping
|
||||
* lower-priority rules off the images they select.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html">Lifecycle policy
|
||||
* evaluation rules</a>
|
||||
*/
|
||||
final class EcrLifecycleEvaluator {
|
||||
|
||||
/**
|
||||
* An image of the repository: its manifest digest, its tags, when it was pushed, and whether a manifest list the
|
||||
* repository holds names it, which keeps it from expiring.
|
||||
*/
|
||||
record Image(String digest, List<String> tags, Instant pushedAt, boolean inManifestList) {}
|
||||
|
||||
/** An image the policy expires, with the priority of the rule that marked it. */
|
||||
record Expiry(String digest, int rulePriority) {}
|
||||
|
||||
/** Newest first, as {@code imageCountMoreThan} keeps the newest; the digest settles a tie. */
|
||||
private static final Comparator<Image> NEWEST_FIRST = Comparator.comparing(Image::pushedAt).reversed()
|
||||
.thenComparing(Image::digest);
|
||||
|
||||
private EcrLifecycleEvaluator() {
|
||||
}
|
||||
|
||||
static List<Expiry> expiries(EcrLifecyclePolicy policy, List<Image> images, Instant now) {
|
||||
List<Rule> rules = new ArrayList<>(policy.rules());
|
||||
rules.sort(Comparator.comparingInt(Rule::priority));
|
||||
Set<String> selectedByHigherRules = new HashSet<>();
|
||||
List<Expiry> expiries = new ArrayList<>();
|
||||
for (Rule rule : rules) {
|
||||
List<Image> selected = images.stream().filter(image -> selects(rule, image)).sorted(NEWEST_FIRST).toList();
|
||||
for (Image marked : marked(rule, selected, now)) {
|
||||
if (!selectedByHigherRules.contains(marked.digest()) && !marked.inManifestList()
|
||||
&& rule.action() == ActionType.EXPIRE) {
|
||||
expiries.add(new Expiry(marked.digest(), rule.priority()));
|
||||
}
|
||||
}
|
||||
selected.forEach(image -> selectedByHigherRules.add(image.digest()));
|
||||
}
|
||||
return expiries;
|
||||
}
|
||||
|
||||
private static boolean selects(Rule rule, Image image) {
|
||||
if (rule.storageClass() != StorageClass.STANDARD) {
|
||||
return false;
|
||||
}
|
||||
return switch (rule.tagStatus()) {
|
||||
case ANY -> true;
|
||||
case UNTAGGED -> image.tags().isEmpty();
|
||||
case TAGGED -> !image.tags().isEmpty() && (rule.tagPatterns().isEmpty()
|
||||
? rule.tagPrefixes().stream().allMatch(prefix -> image.tags().stream().anyMatch(
|
||||
tag -> tag.startsWith(prefix)))
|
||||
: rule.tagPatterns().stream().map(EcrLifecycleEvaluator::wildcard).allMatch(
|
||||
pattern -> image.tags().stream().anyMatch(tag -> pattern.matcher(tag).matches())));
|
||||
};
|
||||
}
|
||||
|
||||
/** The images, newest first, that the rule's count finds among those it selects. */
|
||||
private static List<Image> marked(Rule rule, List<Image> selected, Instant now) {
|
||||
return switch (rule.countType()) {
|
||||
case IMAGE_COUNT_MORE_THAN -> selected.subList(Math.min(rule.countNumber(), selected.size()),
|
||||
selected.size());
|
||||
case SINCE_IMAGE_PUSHED -> {
|
||||
Instant cutoff = now.minus(Duration.ofDays(rule.countNumber()));
|
||||
yield selected.stream().filter(image -> image.pushedAt().isBefore(cutoff)).toList();
|
||||
}
|
||||
case SINCE_IMAGE_PULLED, SINCE_IMAGE_TRANSITIONED -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
/** A tag pattern, where {@code *} matches any run of characters, none included. */
|
||||
private static Pattern wildcard(String pattern) {
|
||||
return Pattern.compile(Arrays.stream(pattern.split("\\*", -1)).map(Pattern::quote)
|
||||
.collect(Collectors.joining(".*")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.floci.aws.services.ecr;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.SweepScheduler;
|
||||
import io.floci.aws.core.common.SweepWorker;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
/**
|
||||
* Applies repository lifecycle policies in the background. ECR expires an image within a day of it meeting a rule
|
||||
* rather than on any request, so a sweep on a fixed interval matches that and leaves nothing to reconcile after a
|
||||
* restart.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EcrLifecycleScheduler extends SweepScheduler {
|
||||
|
||||
@Inject
|
||||
public EcrLifecycleScheduler(EcrService service, EmulatorConfig config) {
|
||||
super(new SweepWorker("ecr-lifecycle-sweep",
|
||||
config.services().ecr().enabled() && config.services().ecr().lifecycleSweepEnabled(),
|
||||
config.services().ecr().lifecycleSweepIntervalSeconds(), false, service::applyLifecyclePolicies));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.PaginatedResult;
|
||||
import io.floci.aws.core.common.Pagination;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.core.common.concurrent.KeyedWriteLocks;
|
||||
import io.floci.aws.core.resource.ExplorerResource;
|
||||
@@ -45,12 +46,15 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -112,6 +116,23 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
// Held while a repository's tags are copied, changed and put in place of the map it held, which is never changed.
|
||||
// The copy is put one entry at a time, as the map always was, so ListTagsForResource keeps the order it listed.
|
||||
private final Object tagLock = new Object();
|
||||
// When the sweep last applied each repository's lifecycle policy, with the text it applied, so a policy put since
|
||||
// reads as never applied. Kept in memory: a restart only delays the next report by one sweep.
|
||||
private final Map<String, LifecycleEvaluation> lifecycleEvaluations = new ConcurrentHashMap<>();
|
||||
// Held, per repository, by the lifecycle sweep while it applies the policy, and by every change to the policy or
|
||||
// to the repository's existence, so the sweep applies a policy only to the repository that still holds it.
|
||||
private final KeyedWriteLocks<String> lifecycleLocks = new KeyedWriteLocks<>();
|
||||
// Counts the writes each backing registry repository has had, so the sweep, which reads the images without the
|
||||
// write lock, can tell that none was written before it takes the lock to expire some.
|
||||
private final Map<String, AtomicLong> repositoryWrites = new ConcurrentHashMap<>();
|
||||
// What each repository's manifests say about manifest lists and subjects, by digest: a manifest's content never
|
||||
// changes, so the sweep reads only the manifests it has not read before.
|
||||
private final Map<String, Map<String, ManifestReferences>> manifestReferences = new ConcurrentHashMap<>();
|
||||
|
||||
private record LifecycleEvaluation(String policyText, Instant evaluatedAt) {}
|
||||
|
||||
/** The images a manifest list names, and the image an artifact names as its subject, null for none. */
|
||||
private record ManifestReferences(Set<String> listed, String subject) {}
|
||||
|
||||
@Inject
|
||||
public EcrService(StorageFactory factory,
|
||||
@@ -670,6 +691,17 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
String registryId,
|
||||
boolean force,
|
||||
String region) {
|
||||
String lifecycleKey = key(region, effectiveAccount(registryId), repositoryName);
|
||||
lockLifecycle(lifecycleKey);
|
||||
try {
|
||||
return deleteRepositoryUnderLifecycleLock(repositoryName, registryId, force, region);
|
||||
} finally {
|
||||
unlockLifecycle(lifecycleKey);
|
||||
}
|
||||
}
|
||||
|
||||
private Repository deleteRepositoryUnderLifecycleLock(String repositoryName, String registryId, boolean force,
|
||||
String region) {
|
||||
String account = effectiveAccount(registryId);
|
||||
String key = key(region, account, repositoryName);
|
||||
Repository repo = repoStore.get(key).orElseThrow(() -> notFound(repositoryName, account));
|
||||
@@ -721,6 +753,7 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
}
|
||||
|
||||
repoStore.delete(key);
|
||||
lifecycleEvaluations.remove(key);
|
||||
// Drop cached image metadata for this repo.
|
||||
String metaPrefix = key + "::";
|
||||
synchronized (imageMetaStore) {
|
||||
@@ -1393,9 +1426,30 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
* {@link #lockRepositoryWrites}.
|
||||
*/
|
||||
public void unlockRepositoryWrites(String storageRepositoryName) {
|
||||
repositoryWrites.computeIfAbsent(storageRepositoryName, ignored -> new AtomicLong()).incrementAndGet();
|
||||
repositoryWriteLocks.release(storageRepositoryName);
|
||||
}
|
||||
|
||||
/** How many holds of the repository's write lock have ended, each a write the repository may have had. */
|
||||
private long repositoryWriteCount(String storageRepositoryName) {
|
||||
return repositoryWrites.computeIfAbsent(storageRepositoryName, ignored -> new AtomicLong()).get();
|
||||
}
|
||||
|
||||
/** See {@code lifecycleLocks}; an interruption surfaces as a {@code ServerException}. */
|
||||
private void lockLifecycle(String repositoryKey) {
|
||||
try {
|
||||
lifecycleLocks.acquire(repositoryKey);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AwsException("ServerException",
|
||||
"Interrupted while waiting for the lifecycle lock on " + repositoryKey, 500);
|
||||
}
|
||||
}
|
||||
|
||||
private void unlockLifecycle(String repositoryKey) {
|
||||
lifecycleLocks.release(repositoryKey);
|
||||
}
|
||||
|
||||
/** The repository write lock entries still counting writers, for tests. */
|
||||
int liveRepositoryWriteLocks() {
|
||||
return repositoryWriteLocks.size();
|
||||
@@ -1824,10 +1878,16 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
|
||||
public Repository putLifecyclePolicy(String repoName, String registryId, String policyText, String region) {
|
||||
validateLifecyclePolicyDocument(policyText);
|
||||
Repository repo = requireRepo(repoName, registryId, region);
|
||||
repo.setLifecyclePolicyText(policyText);
|
||||
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
|
||||
return repo;
|
||||
String lifecycleKey = key(region, effectiveAccount(registryId), repoName);
|
||||
lockLifecycle(lifecycleKey);
|
||||
try {
|
||||
Repository repo = requireRepo(repoName, registryId, region);
|
||||
repo.setLifecyclePolicyText(policyText);
|
||||
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
|
||||
return repo;
|
||||
} finally {
|
||||
unlockLifecycle(lifecycleKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1852,16 +1912,255 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
Repository repo = requireRepo(repoName, registryId, region);
|
||||
if (repo.getLifecyclePolicyText() == null) {
|
||||
throw new AwsException("LifecyclePolicyNotFoundException",
|
||||
"No lifecycle policy associated with repository " + repoName, 400);
|
||||
"Lifecycle policy does not exist for the repository with name '" + repoName
|
||||
+ "' in the registry with id '" + repo.getRegistryId() + "'", 400);
|
||||
}
|
||||
return repo;
|
||||
}
|
||||
|
||||
public Repository deleteLifecyclePolicy(String repoName, String registryId, String region) {
|
||||
Repository repo = getLifecyclePolicy(repoName, registryId, region);
|
||||
repo.setLifecyclePolicyText(null);
|
||||
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
|
||||
return repo;
|
||||
/** The policy a repository held when it was deleted, with the time Floci last applied it, null if never. */
|
||||
public record DeletedLifecyclePolicy(String registryId, String repositoryName, String lifecyclePolicyText,
|
||||
Instant lastEvaluatedAt) {}
|
||||
|
||||
public DeletedLifecyclePolicy deleteLifecyclePolicy(String repoName, String registryId, String region) {
|
||||
String lifecycleKey = key(region, effectiveAccount(registryId), repoName);
|
||||
lockLifecycle(lifecycleKey);
|
||||
try {
|
||||
Repository repo = getLifecyclePolicy(repoName, registryId, region);
|
||||
String text = repo.getLifecyclePolicyText();
|
||||
Instant lastEvaluatedAt = lifecyclePolicyEvaluatedAt(repo, region);
|
||||
repo.setLifecyclePolicyText(null);
|
||||
repoStore.put(key(region, repo.getRegistryId(), repoName), repo);
|
||||
lifecycleEvaluations.remove(key(region, repo.getRegistryId(), repoName));
|
||||
return new DeletedLifecyclePolicy(repo.getRegistryId(), repoName, text, lastEvaluatedAt);
|
||||
} finally {
|
||||
unlockLifecycle(lifecycleKey);
|
||||
}
|
||||
}
|
||||
|
||||
/** When the lifecycle sweep last applied the repository's current policy; null until it has. */
|
||||
public Instant lifecyclePolicyEvaluatedAt(Repository repo, String region) {
|
||||
LifecycleEvaluation evaluation = lifecycleEvaluations.get(
|
||||
key(region, repo.getRegistryId(), repo.getRepositoryName()));
|
||||
return evaluation != null && evaluation.policyText().equals(repo.getLifecyclePolicyText())
|
||||
? evaluation.evaluatedAt() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the lifecycle policy of every repository that has one, in every account and Region, as ECR does in the
|
||||
* background. Nothing is done while the backing registry is not running: the sweep never starts it. A repository
|
||||
* that fails is retried by the next sweep, after the others have been applied.
|
||||
*/
|
||||
void applyLifecyclePolicies(Instant now) {
|
||||
if (isDisabled() || !registryManager.isStarted() || registryManager.httpClient() == null) {
|
||||
return;
|
||||
}
|
||||
List<AccountAwareStorageBackend.AccountEntry<Repository>> withPolicies = new ArrayList<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Repository> entry : repositoriesInEveryAccount()) {
|
||||
if (entry.key().split("::", 3).length == 3 && entry.value().getLifecyclePolicyText() != null) {
|
||||
withPolicies.add(entry);
|
||||
}
|
||||
}
|
||||
if (withPolicies.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> catalog;
|
||||
try {
|
||||
catalog = registryManager.httpClient().catalogStrict();
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("ECR lifecycle sweep could not read the registry catalog", e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("ECR lifecycle sweep was interrupted reading the registry catalog", e);
|
||||
}
|
||||
List<String> failedRepositories = new ArrayList<>();
|
||||
List<RuntimeException> failures = new ArrayList<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Repository> entry : withPolicies) {
|
||||
String[] scope = entry.key().split("::", 3);
|
||||
String region = scope[0];
|
||||
String account = scope[1];
|
||||
String name = scope[2];
|
||||
try {
|
||||
RequestScopes.runAs(account, region, () -> applyLifecyclePolicy(account, region, name, catalog, now));
|
||||
} catch (RuntimeException e) {
|
||||
failedRepositories.add(entry.key());
|
||||
failures.add(e);
|
||||
}
|
||||
}
|
||||
if (!failures.isEmpty()) {
|
||||
IllegalStateException failure = new IllegalStateException(
|
||||
"ECR lifecycle sweep failed for repositories " + failedRepositories);
|
||||
failures.forEach(failure::addSuppressed);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private List<AccountAwareStorageBackend.AccountEntry<Repository>> repositoriesInEveryAccount() {
|
||||
if (repoStore instanceof AccountAwareStorageBackend<Repository> aware) {
|
||||
return aware.scanAllAccountEntries(key -> true);
|
||||
}
|
||||
List<AccountAwareStorageBackend.AccountEntry<Repository>> repositories = new ArrayList<>();
|
||||
for (String key : repoStore.keys()) {
|
||||
repoStore.get(key).ifPresent(repo -> repositories.add(
|
||||
new AccountAwareStorageBackend.AccountEntry<>(repo.getRegistryId(), key, repo)));
|
||||
}
|
||||
return repositories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one repository's policy under its lifecycle lock, so neither the policy nor the repository changes while
|
||||
* it is applied. The images are read and evaluated without the repository's write lock, which is taken only to
|
||||
* expire what the policy selects, and only if the repository had no write since the images were read; otherwise
|
||||
* the next sweep applies the policy. A policy stored before PutLifecyclePolicy checked every rule, and that it now
|
||||
* refuses, is left unapplied.
|
||||
*/
|
||||
private void applyLifecyclePolicy(String account, String region, String name, List<String> catalog, Instant now) {
|
||||
String key = key(region, account, name);
|
||||
lockLifecycle(key);
|
||||
try {
|
||||
String text = repoStore.get(key).map(Repository::getLifecyclePolicyText).orElse(null);
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
EcrLifecyclePolicy policy;
|
||||
try {
|
||||
policy = EcrLifecyclePolicy.parse(text);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Not applying the lifecycle policy of ECR repository {0}/{1}/{2}, which PutLifecyclePolicy "
|
||||
+ "refuses: {3}", region, account, name, e.getMessage());
|
||||
return;
|
||||
}
|
||||
String internal = resolveRegistryRepoName(account, region, name, catalog);
|
||||
long writes = repositoryWriteCount(internal);
|
||||
Map<String, String> expired = imagesToExpire(account, region, name, internal, policy, now);
|
||||
if (!expired.isEmpty() && !expire(account, region, name, internal, expired, writes)) {
|
||||
return;
|
||||
}
|
||||
lifecycleEvaluations.put(key, new LifecycleEvaluation(text, now));
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new IllegalStateException("Could not apply the lifecycle policy of ECR repository " + region + "/"
|
||||
+ account + "/" + name + ": " + e.getMessage(), e);
|
||||
} finally {
|
||||
unlockLifecycle(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the expired manifests, subjects before the artifacts naming them, under the repository's write lock;
|
||||
* false, deleting nothing, when the repository had a write since its images were read. A registry error stops the
|
||||
* deletes, so no artifact goes while the image it names is still there.
|
||||
*/
|
||||
private boolean expire(String account, String region, String name, String internal, Map<String, String> expired,
|
||||
long writesWhenRead) throws IOException, InterruptedException {
|
||||
RegistryHttpClient http = registryManager.httpClient();
|
||||
lockRepositoryWrites(internal);
|
||||
try {
|
||||
if (repositoryWriteCount(internal) != writesWhenRead) {
|
||||
LOG.debugv("ECR repository {0}/{1}/{2} was written while its lifecycle policy was evaluated; the next "
|
||||
+ "sweep applies it", region, account, name);
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, String> image : expired.entrySet()) {
|
||||
if (http.deleteManifestStrict(internal, image.getKey())) {
|
||||
removeImagePush(account, region, name, image.getKey());
|
||||
LOG.infov("ECR lifecycle policy expired image {0} of repository {1}/{2}/{3} ({4})",
|
||||
image.getKey(), region, account, name, image.getValue());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
unlockRepositoryWrites(internal);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the policy expires among the images the registry holds for the repository, each tagged digest with its
|
||||
* tags and every other manifest untagged, with why. A digest a held manifest list names is kept until the list
|
||||
* goes. An artifact naming another image as its {@code subject} is selected by no rule while that image is held,
|
||||
* and expires once it is gone, whether the policy expires it now or it was deleted, as ECR expires reference
|
||||
* artifacts.
|
||||
*/
|
||||
private Map<String, String> imagesToExpire(String account, String region, String name, String internal,
|
||||
EcrLifecyclePolicy policy, Instant now)
|
||||
throws IOException, InterruptedException {
|
||||
RegistryHttpClient http = registryManager.httpClient();
|
||||
Map<String, List<String>> tagsByDigest = new LinkedHashMap<>();
|
||||
for (String tag : http.listTagsStrict(internal)) {
|
||||
String digest = http.headManifestDigestStrict(internal, tag, null);
|
||||
if (digest != null) {
|
||||
tagsByDigest.computeIfAbsent(digest, ignored -> new ArrayList<>()).add(tag);
|
||||
}
|
||||
}
|
||||
for (String digest : registryManager.heldManifestDigests(internal)) {
|
||||
tagsByDigest.putIfAbsent(digest, List.of());
|
||||
}
|
||||
|
||||
Map<String, ManifestReferences> known = manifestReferences.getOrDefault(internal, Map.of());
|
||||
Map<String, ManifestReferences> references = new HashMap<>();
|
||||
Set<String> listed = new HashSet<>();
|
||||
Map<String, String> subjects = new LinkedHashMap<>();
|
||||
for (String digest : tagsByDigest.keySet()) {
|
||||
ManifestReferences read = known.get(digest);
|
||||
if (read == null) {
|
||||
read = readReferences(http, internal, digest);
|
||||
}
|
||||
references.put(digest, read);
|
||||
listed.addAll(read.listed());
|
||||
if (read.subject() != null) {
|
||||
subjects.put(digest, read.subject());
|
||||
}
|
||||
}
|
||||
manifestReferences.put(internal, references);
|
||||
|
||||
List<EcrLifecycleEvaluator.Image> images = new ArrayList<>();
|
||||
for (Map.Entry<String, List<String>> image : tagsByDigest.entrySet()) {
|
||||
String digest = image.getKey();
|
||||
String subject = subjects.get(digest);
|
||||
if (subject == null || !tagsByDigest.containsKey(subject)) {
|
||||
Instant pushedAt = describeImagePush(account, region, name, digest).getPushedAt();
|
||||
images.add(new EcrLifecycleEvaluator.Image(digest, image.getValue(),
|
||||
pushedAt != null ? pushedAt : now, listed.contains(digest)));
|
||||
}
|
||||
}
|
||||
Map<String, String> expired = new LinkedHashMap<>();
|
||||
for (EcrLifecycleEvaluator.Expiry expiry : EcrLifecycleEvaluator.expiries(policy, images, now)) {
|
||||
expired.put(expiry.digest(), "rule " + expiry.rulePriority());
|
||||
}
|
||||
boolean added = true;
|
||||
while (added) {
|
||||
added = false;
|
||||
for (Map.Entry<String, String> referrer : subjects.entrySet()) {
|
||||
String subject = referrer.getValue();
|
||||
if (!expired.containsKey(referrer.getKey())
|
||||
&& (!tagsByDigest.containsKey(subject) || expired.containsKey(subject))) {
|
||||
expired.put(referrer.getKey(), "an artifact of image " + subject + ", which is gone");
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return expired;
|
||||
}
|
||||
|
||||
private static ManifestReferences readReferences(RegistryHttpClient http, String internal, String digest)
|
||||
throws IOException, InterruptedException {
|
||||
RegistryHttpClient.ManifestResult manifest = http.getManifest(internal, digest, null);
|
||||
if (manifest == null || manifest.body() == null) {
|
||||
throw new IOException("the registry did not return manifest " + digest);
|
||||
}
|
||||
JsonNode body = MAPPER.readTree(manifest.body());
|
||||
Set<String> listed = new HashSet<>();
|
||||
for (JsonNode child : body.path("manifests")) {
|
||||
if (child.path("digest").isTextual()) {
|
||||
listed.add(child.path("digest").asText());
|
||||
}
|
||||
}
|
||||
JsonNode subject = body.path("subject").path("digest");
|
||||
return new ManifestReferences(Set.copyOf(listed), subject.isTextual() ? subject.asText() : null);
|
||||
}
|
||||
|
||||
public Repository setRepositoryPolicy(String repoName, String registryId, String policyText, String region) {
|
||||
@@ -1979,6 +2278,8 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
synchronized (imageMetaStore) {
|
||||
pendingImagePushes.clear();
|
||||
}
|
||||
lifecycleEvaluations.clear();
|
||||
manifestReferences.clear();
|
||||
}
|
||||
|
||||
private static String imageMetaKey(String region, String account, String repoName, String digest) {
|
||||
@@ -2143,8 +2444,12 @@ public class EcrService implements ResourceProvider, Resettable {
|
||||
}
|
||||
|
||||
private String resolveRegistryRepoNameStrict(String account, String region, String repoName) throws Exception {
|
||||
return resolveRegistryRepoName(account, region, repoName, registryManager.httpClient().catalogStrict());
|
||||
}
|
||||
|
||||
/** {@link #resolveRegistryRepoNameStrict} against a catalog already read. */
|
||||
private String resolveRegistryRepoName(String account, String region, String repoName, List<String> catalog) {
|
||||
String internal = registryManager.internalRepoName(account, region, repoName);
|
||||
List<String> catalog = registryManager.httpClient().catalogStrict();
|
||||
if (catalog.contains(internal)) {
|
||||
return internal;
|
||||
}
|
||||
|
||||
@@ -36,10 +36,12 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -65,6 +67,7 @@ public class EcrRegistryManager {
|
||||
private static final int REPOSITORY_DELETION_KILL_GRACE_SECONDS = 1;
|
||||
private static final String NAMED_VOLUME = "ecr-registry-data";
|
||||
private static final String REPOSITORIES_PATH = "/var/lib/registry/docker/registry/v2/repositories/";
|
||||
private static final Pattern REVISION_LINK = Pattern.compile(".*/_manifests/revisions/sha256/([a-f0-9]{64})/link");
|
||||
private static final int GC_KILL_GRACE_SECONDS = 2;
|
||||
static final long RECONCILE_RETRY_MILLIS = 30_000;
|
||||
|
||||
@@ -840,13 +843,47 @@ public class EcrRegistryManager {
|
||||
throw new IllegalStateException("ECR registry is not started");
|
||||
}
|
||||
String path = repositoryStoragePath(internalRepoName);
|
||||
execInRegistry(containerId, "repository deletion", "rm", "-rf",
|
||||
path + "/_layers", path + "/_manifests", path + "/_uploads");
|
||||
}
|
||||
|
||||
/**
|
||||
* The digests of every manifest the registry holds for one repository, untagged ones included, read from the
|
||||
* revision links of its storage, since the distribution API lists tags only. A deleted manifest's link is gone,
|
||||
* and a repository the registry never stored holds none.
|
||||
*/
|
||||
public Set<String> heldManifestDigests(String internalRepoName) {
|
||||
String id = containerId;
|
||||
if (!started || id == null) {
|
||||
throw new IllegalStateException("ECR registry is not started");
|
||||
}
|
||||
String revisions = repositoryStoragePath(internalRepoName) + "/_manifests/revisions/sha256";
|
||||
String output = execInRegistry(id, "manifest listing", "sh", "-c",
|
||||
"[ -d '" + revisions + "' ] || exit 0; find '" + revisions + "' -mindepth 2 -maxdepth 2 -name link");
|
||||
Set<String> digests = new LinkedHashSet<>();
|
||||
for (String line : output.split("\n")) {
|
||||
Matcher revision = REVISION_LINK.matcher(line.trim());
|
||||
if (revision.matches()) {
|
||||
digests.add("sha256:" + revision.group(1));
|
||||
}
|
||||
}
|
||||
return digests;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code command} in the registry container under a bounded {@code timeout}, returning its output; one that
|
||||
* times out, is interrupted or exits non-zero fails as {@code what}.
|
||||
*/
|
||||
private String execInRegistry(String container, String what, String... command) {
|
||||
List<String> bounded = new ArrayList<>(List.of("timeout", "-k",
|
||||
String.valueOf(REPOSITORY_DELETION_KILL_GRACE_SECONDS),
|
||||
String.valueOf(REPOSITORY_DELETION_TIMEOUT_SECONDS)));
|
||||
bounded.addAll(List.of(command));
|
||||
StringBuilder output = new StringBuilder();
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
ExecCreateCmdResponse exec = dockerClient
|
||||
.execCreateCmd(containerId)
|
||||
.withCmd("timeout", "-k", String.valueOf(REPOSITORY_DELETION_KILL_GRACE_SECONDS),
|
||||
String.valueOf(REPOSITORY_DELETION_TIMEOUT_SECONDS), "rm", "-rf",
|
||||
path + "/_layers", path + "/_manifests", path + "/_uploads")
|
||||
.execCreateCmd(container)
|
||||
.withCmd(bounded.toArray(String[]::new))
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(true)
|
||||
.exec();
|
||||
@@ -861,16 +898,17 @@ public class EcrRegistryManager {
|
||||
.awaitCompletion(REPOSITORY_DELETION_TIMEOUT_SECONDS
|
||||
+ REPOSITORY_DELETION_KILL_GRACE_SECONDS + 1, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
throw new RuntimeException("repository deletion timed out");
|
||||
throw new RuntimeException(what + " timed out");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("repository deletion interrupted", e);
|
||||
throw new RuntimeException(what + " interrupted", e);
|
||||
}
|
||||
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
|
||||
if (exitCode == null || exitCode != 0) {
|
||||
throw new RuntimeException("repository deletion failed: " + output);
|
||||
throw new RuntimeException(what + " failed: " + output);
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/** Stops the container if {@code keepRunningOnShutdown=false}. Called from EmulatorLifecycle hooks. */
|
||||
|
||||
@@ -193,6 +193,26 @@ public class RegistryHttpClient {
|
||||
return new ManifestResult(digest, resp.body(), mediaType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict DELETE of a manifest by digest: true once deleted, false when the registry does not hold it, and an
|
||||
* {@link IOException} for any other answer, so a caller can tell a failed delete from a missing manifest.
|
||||
*/
|
||||
public boolean deleteManifestStrict(String name, String digest) throws IOException, InterruptedException {
|
||||
HttpResponse<Void> resp = http.send(
|
||||
HttpRequest.newBuilder(URI.create(baseUrl + "/v2/" + name + "/manifests/" + digest))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.DELETE()
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
if (resp.statusCode() == 404) {
|
||||
return false;
|
||||
}
|
||||
if (resp.statusCode() >= 400) {
|
||||
throw new IOException("Registry DELETE manifest " + name + "/" + digest + " returned " + resp.statusCode());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** DELETE a manifest by digest. Returns true on 202/200, false on 404. */
|
||||
public boolean deleteManifest(String name, String digest) throws IOException, InterruptedException {
|
||||
HttpResponse<Void> resp = http.send(
|
||||
|
||||
Reference in new issue
Block a user