From ddad3ca1df2a6cb628ca740a064368a78928f7d1 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:54:39 -0400 Subject: [PATCH] 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. --- .../configuration/advanced/application-yml.md | 2 + docs/configuration/environment-variables.md | 2 + docs/services/ecr.md | 77 +- .../io/floci/aws/config/EmulatorConfig.java | 16 + .../aws/services/ecr/EcrJsonHandler.java | 33 +- .../services/ecr/EcrLifecycleEvaluator.java | 99 +++ .../services/ecr/EcrLifecycleScheduler.java | 23 + .../io/floci/aws/services/ecr/EcrService.java | 327 ++++++++- .../ecr/registry/EcrRegistryManager.java | 52 +- .../ecr/registry/RegistryHttpClient.java | 20 + src/main/resources/application.yml | 2 + .../ecr/EcrLifecycleEvaluatorTest.java | 208 ++++++ ...ecyclePolicyValidationIntegrationTest.java | 23 + ...crLifecycleSweepDockerIntegrationTest.java | 112 +++ .../services/ecr/EcrLifecycleSweepTest.java | 658 ++++++++++++++++++ .../aws/services/ecr/EcrServiceTest.java | 2 + .../ecr/registry/EcrRegistryManagerTest.java | 42 ++ .../io/floci/aws/testing/EcrTestImages.java | 6 +- src/test/resources/application.yml | 1 + 19 files changed, 1652 insertions(+), 53 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/ecr/EcrLifecycleEvaluator.java create mode 100644 src/main/java/io/floci/aws/services/ecr/EcrLifecycleScheduler.java create mode 100644 src/test/java/io/floci/aws/services/ecr/EcrLifecycleEvaluatorTest.java create mode 100644 src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepDockerIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepTest.java diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index 10e69d0ff4..62a984cb38 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -352,6 +352,8 @@ floci: keep-running-on-shutdown: true uri-style: hostname # hostname | path prefer-local-images: true + lifecycle-sweep-enabled: true # apply repository lifecycle policies in the background + lifecycle-sweep-interval-seconds: 60 ``` ### Initialization hooks diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index acd2bdaebe..f21c83c409 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -586,6 +586,8 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | Repository URI style: `hostname` (`.dkr.ecr..localhost`) or `path` | | `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry | | `FLOCI_SERVICES_ECR_DOCKER_NETWORK` | _(none)_ | Docker network for the ECR registry container | +| `FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_ENABLED` | `true` | Apply repository lifecycle policies in the background, expiring the images their rules select | +| `FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_INTERVAL_SECONDS` | `60` | How often the lifecycle sweep runs | ### EKS (Elastic Kubernetes Service) diff --git a/docs/services/ecr.md b/docs/services/ecr.md index 3d8e659baf..7cdb64b8ef 100644 --- a/docs/services/ecr.md +++ b/docs/services/ecr.md @@ -37,33 +37,13 @@ | `PutImageScanningConfiguration` | Set a repository's `scanOnPush` flag and return the updated configuration; a non-boolean value is rejected | | `BatchGetRepositoryScanningConfiguration` | Report each repository's `scanOnPush` setting with a derived `scanFrequency` (`SCAN_ON_PUSH` or `MANUAL`); a missing repository fails the whole batch instead of appearing in `failures` | | `TagResource` / `UntagResource` / `ListTagsForResource` | Resource tagging | -| `PutLifecyclePolicy` / `GetLifecyclePolicy` / `DeleteLifecyclePolicy` | Lifecycle policy round-trip (stored, not enforced) | +| `PutLifecyclePolicy` / `GetLifecyclePolicy` / `DeleteLifecyclePolicy` | Lifecycle policies, applied by a background sweep (see [Lifecycle policies](#lifecycle-policies)) | | `SetRepositoryPolicy` / `GetRepositoryPolicy` / `DeleteRepositoryPolicy` | Repository policy round-trip (stored, not enforced) | | `PutRegistryPolicy` / `GetRegistryPolicy` / `DeleteRegistryPolicy` | Registry policy round-trip (stored, not enforced) | | `PutReplicationConfiguration` / `DescribeRegistry` | Store the registry's replication rules and return them with the registry ID (stored, not acted on) | | `PutRegistryScanningConfiguration` / `GetRegistryScanningConfiguration` | Store the registry's scan type and scanning rules (stored, not acted on) | | `GetAccountSetting` / `PutAccountSetting` | Read and store account settings for the registry (stored, not acted on) | -`PutLifecyclePolicy`, and an `AWS::ECR::Repository` in CloudFormation, check the document -as ECR does, against the rules in the ECR user guide: - -- The text is 100 to 30720 characters, as the API model bounds it. -- One to 50 rules, each with a unique positive `rulePriority`, a `selection` and an `action`. -- `tagStatus` is `tagged`, `untagged` or `any`. A `tagged` rule needs exactly one of `tagPrefixList` (at most 10 prefixes) and `tagPatternList`, and the other two statuses allow neither. A pattern can have at most four `*` wildcards. -- `countType` is `imageCountMoreThan`, `sinceImagePushed`, `sinceImagePulled` or `sinceImageTransitioned`. The three `since` types need `countUnit` `days`, and `imageCountMoreThan` takes no `countUnit`. `countNumber` is a positive integer, at least 90 for `sinceImageTransitioned`. -- `storageClass` is `standard`, the default, except for `sinceImageTransitioned`, which needs `archive`. -- `action.type` is `expire` or `transition`. An `expire` action carries nothing else, a `transition` needs `targetStorageClass` `archive`, and `sinceImageTransitioned` allows only `expire`. -- Among the rules selecting one storage class, an `any` rule has the highest `rulePriority`, so there is one at most, only one rule selects untagged images, and no tag prefix appears in two rules. - -Values are matched exactly as the guide spells them, and a selection member the guide does not -list is refused. A refused document returns `InvalidParameterException` in ECR's message form, -`Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: '...'`, with the prior -policy kept. As on ECR, malformed JSON, or a document that does not map onto ECR's rule types, -gives `Lifecycle policy parsing failure: ...`, a document breaking the JSON schema gives the schema -validator's own text after `Lifecycle policy validation failure: `, and a broken rule gives a sentence -naming it. Where ECR's wording is known, from refusals quoted publicly and replays recorded against -ECR, Floci uses it. Expiration and registry garbage collection remain unimplemented. - `GetAccountSetting` and `PutAccountSetting` keep values per account and Region. Supported names are `BASIC_SCAN_TYPE_VERSION` (`AWS_NATIVE`), `REGISTRY_POLICY_SCOPE` (`V2`), and `BLOB_MOUNTING` (`ENABLED` or `DISABLED`). Floci defaults to `AWS_NATIVE`, @@ -126,6 +106,54 @@ is refused with the model's message, as AWS does. `imageStatus` and `DescribeIma - **Lambda, ECS and EMR Serverless integration.** Image-backed Lambda functions (`PackageType=Image`), ECS task containers and the custom images of EMR Serverless applications (in its `docker` runner mode) reference the same loopback `repositoryUri`. Floci rewrites real-AWS-shaped `.dkr.ecr..amazonaws.com/...` URIs to the loopback registry at pull time, path style on `localhost` (`localhost:///`) in either URI style and with or without TLS, an address a Linux Docker daemon pulls from over plain HTTP. On Docker Desktop the rewrite is `.dkr.ecr..localhost:/` instead: Desktop's daemon runs in a VM and dials `localhost` there, where a host port Docker chose for Floci is not bound, while it sends `*.localhost` through its host proxy to the port Floci publishes. Floci asks the daemon once whether it is Docker Desktop. CDK's `DockerImageFunction` (which generates AWS-shaped URIs in CloudFormation templates) works without any user-side rewriting. With `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set, the rewritten reference, and a loopback `repositoryUri` named directly, are still pulled from Floci's registry: the base goes in front of the images a mirror holds, never of one on `localhost`. - **Locally built images win.** An AWS-shaped URI that names an image already present on the Docker daemon is used as-is instead of being rewritten (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`, default `true`). Build the image under the exact URI your function or task definition declares (`docker build -t .dkr.ecr..amazonaws.com/: .`) and it runs without a push to the emulated registry, and without the registry container being started. The check uses the reference Floci would launch, so with `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` set the image must be present as `/.dkr.ecr..amazonaws.com/:`. +## Lifecycle policies + +`PutLifecyclePolicy`, and an `AWS::ECR::Repository` in CloudFormation, check the document +as ECR does, against the rules in the ECR user guide: + +- The text is 100 to 30720 characters, as the API model bounds it. +- One to 50 rules, each with a unique positive `rulePriority`, a `selection` and an `action`. +- `tagStatus` is `tagged`, `untagged` or `any`. A `tagged` rule needs exactly one of `tagPrefixList` (at most 10 prefixes) and `tagPatternList`, and the other two statuses allow neither. A pattern can have at most four `*` wildcards. +- `countType` is `imageCountMoreThan`, `sinceImagePushed`, `sinceImagePulled` or `sinceImageTransitioned`. The three `since` types need `countUnit` `days`, and `imageCountMoreThan` takes no `countUnit`. `countNumber` is a positive integer, at least 90 for `sinceImageTransitioned`. +- `storageClass` is `standard`, the default, except for `sinceImageTransitioned`, which needs `archive`. +- `action.type` is `expire` or `transition`. An `expire` action carries nothing else, a `transition` needs `targetStorageClass` `archive`, and `sinceImageTransitioned` allows only `expire`. +- Among the rules selecting one storage class, an `any` rule has the highest `rulePriority`, so there is one at most, only one rule selects untagged images, and no tag prefix appears in two rules. + +Values are matched exactly as the guide spells them, and a selection member the guide does not +list is refused. A refused document returns `InvalidParameterException` in ECR's message form, +`Invalid parameter at 'LifecyclePolicyText' failed to satisfy constraint: '...'`, with the prior +policy kept. As on ECR, malformed JSON, or a document that does not map onto ECR's rule types, +gives `Lifecycle policy parsing failure: ...`, a document breaking the JSON schema gives the schema +validator's own text after `Lifecycle policy validation failure: `, and a broken rule gives a sentence +naming it. Where ECR's wording is known, from refusals quoted publicly and replays recorded against +ECR, Floci uses it. + +A background sweep applies every repository's policy every +`FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_INTERVAL_SECONDS` (60 by default). ECR expires an image within +24 hours of it meeting a rule, so the interval only bounds how late Floci is. The sweep follows the +evaluation rules in the user guide: + +- The images are every manifest the registry holds for the repository, read from its storage: each tagged one with its tags, and the rest untagged. One pushed before Floci recorded push times counts as pushed when the sweep first sees it. +- Rules apply in `rulePriority` order. Each selects the images its tag filter matches. `imageCountMoreThan` marks all but the newest `countNumber` of them, and `sinceImagePushed` marks those pushed more than `countNumber` days ago. The push time is the `imagePushedAt` that `DescribeImages` reports. +- A rule never marks an image that a higher-priority rule selected, so one rule at most expires an image. +- An image named by a manifest list in the repository, such as one platform of a multi-arch image, is kept until the list is gone. A later sweep expires it if a rule still marks it. +- An artifact naming another image as its `subject`, such as a signature or an SBOM, is protected from the rules while the repository holds that image. It expires once the image is gone, whether the policy expired it or it was deleted with `BatchDeleteImage`. +- Floci keeps every image in standard storage, so a rule selecting `archive` storage selects nothing, and a `transition` rule moves nothing. The images a transition rule selects are still off-limits to lower-priority rules. +- Floci records no pull times, so a `sinceImagePulled` rule marks nothing. The images it selects are still off-limits to lower-priority rules. + +`GetLifecyclePolicy` and `DeleteLifecyclePolicy` return `lastEvaluatedAt`, the time the sweep last +applied the current policy, or the epoch before it has. Floci keeps that time in memory, so after a +restart it reads as the epoch until the next sweep. `DeleteLifecyclePolicy` also returns the +policy it deleted. A policy stored before `PutLifecyclePolicy` +checked every rule, and that it now refuses, is not applied, and the sweep logs a warning for it. +The sweep reads a repository's images without holding up pushes to it, and takes the repository's +write lock only to expire what its policy selects. A push in between puts the expiry off to the next +sweep, and a policy put or deleted while the sweep applies the old one waits for it. The sweep +never starts the backing registry, so nothing expires while the registry is not running. +Blobs of expired images stay on disk until garbage collection runs; see +[Troubleshooting](#troubleshooting). Set `FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_ENABLED=false` to keep +policies without applying them. + ## Pull-time update exclusions Exclusions are stored per account and Region, with up to 100 registered IAM role or @@ -148,6 +176,8 @@ changing image pull-time tracking. | `FLOCI_SERVICES_ECR_DATA_PATH` | `./data/ecr` | Bind-mount root for the registry data directory | | `FLOCI_SERVICES_ECR_KEEP_RUNNING_ON_SHUTDOWN` | `true` | Leave the registry container running so the next Floci start adopts it | | `FLOCI_SERVICES_ECR_DOCKER_NETWORK` | Inherit Floci's container network | Docker network shared by Floci and the backing registry when running in Docker | +| `FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_ENABLED` | `true` | Apply repository lifecycle policies in the background (see [Lifecycle policies](#lifecycle-policies)) | +| `FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_INTERVAL_SECONDS` | `60` | How often the lifecycle sweep runs | | `FLOCI_SERVICES_ECR_URI_STYLE` | `hostname` | `hostname` = `*.dkr.ecr..localhost`; `path` = `localhost:///` | | `FLOCI_SERVICES_ECR_TLS_URI` | `false` | Report `localhost.floci.io` registry addresses and an HTTPS login endpoint when global `FLOCI_TLS_ENABLED` is also `true` | | `FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES` | `true` | Use an AWS-shaped ECR image URI as-is when the Docker daemon already has that image, instead of rewriting it to the loopback registry | @@ -325,13 +355,12 @@ new lambda.DockerImageFunction(this, 'MyFn', { ## Not Implemented -The following ECR features are **not** implemented. Stored values for policies and lifecycle rules round-trip via the API but are not enforced at runtime: +The following ECR features are **not** implemented. Stored values for these policies round-trip via the API but are not enforced at runtime: - Replication and registry scanning (the configurations are stored, but images are not copied or scanned) - Pull-through cache image proxying and population. Rule configuration APIs are supported, but pulls are not routed to upstream registries - Image scanning (`StartImageScan`, `DescribeImageScanFindings`) - Image signing and notary attachments -- Lifecycle policy enforcement (the policy text is stored but not applied) - Applying repository creation templates (they are stored, but Floci never creates repositories through replication, pull through cache or create-on-push) - Repository policy enforcement (no IAM evaluation against repository-level policies) - TLS via emulated ACM @@ -351,6 +380,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.** 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). +**Disk not reclaimed after deleting images.** Deleting the last tag of an image, deleting by digest, or a lifecycle policy expiring an image 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:///` URIs. On Docker Desktop the rewrite of AWS-shaped Lambda, ECS and EMR Serverless images keeps `.dkr.ecr..localhost`; there, build the image under the AWS-shaped URI the function or task definition names, and Floci uses it as-is (`FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES`). diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 7bc26aab07..4a977a9d00 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -3518,6 +3518,22 @@ public interface EmulatorConfig { boolean preferLocalImages(); Optional 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 { diff --git a/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java b/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java index e0bfd7074a..f2c0daf1ba 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrJsonHandler.java @@ -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) { diff --git a/src/main/java/io/floci/aws/services/ecr/EcrLifecycleEvaluator.java b/src/main/java/io/floci/aws/services/ecr/EcrLifecycleEvaluator.java new file mode 100644 index 0000000000..e55b0489ef --- /dev/null +++ b/src/main/java/io/floci/aws/services/ecr/EcrLifecycleEvaluator.java @@ -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. + * + *

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 Lifecycle policy + * evaluation rules + */ +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 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 NEWEST_FIRST = Comparator.comparing(Image::pushedAt).reversed() + .thenComparing(Image::digest); + + private EcrLifecycleEvaluator() { + } + + static List expiries(EcrLifecyclePolicy policy, List images, Instant now) { + List rules = new ArrayList<>(policy.rules()); + rules.sort(Comparator.comparingInt(Rule::priority)); + Set selectedByHigherRules = new HashSet<>(); + List expiries = new ArrayList<>(); + for (Rule rule : rules) { + List 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 marked(Rule rule, List 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(".*"))); + } +} diff --git a/src/main/java/io/floci/aws/services/ecr/EcrLifecycleScheduler.java b/src/main/java/io/floci/aws/services/ecr/EcrLifecycleScheduler.java new file mode 100644 index 0000000000..2fb78a54ea --- /dev/null +++ b/src/main/java/io/floci/aws/services/ecr/EcrLifecycleScheduler.java @@ -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)); + } +} diff --git a/src/main/java/io/floci/aws/services/ecr/EcrService.java b/src/main/java/io/floci/aws/services/ecr/EcrService.java index 2820abc332..c2c29b4ae6 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrService.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrService.java @@ -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 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 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 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> 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 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> withPolicies = new ArrayList<>(); + for (AccountAwareStorageBackend.AccountEntry entry : repositoriesInEveryAccount()) { + if (entry.key().split("::", 3).length == 3 && entry.value().getLifecyclePolicyText() != null) { + withPolicies.add(entry); + } + } + if (withPolicies.isEmpty()) { + return; + } + List 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 failedRepositories = new ArrayList<>(); + List failures = new ArrayList<>(); + for (AccountAwareStorageBackend.AccountEntry 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> repositoriesInEveryAccount() { + if (repoStore instanceof AccountAwareStorageBackend aware) { + return aware.scanAllAccountEntries(key -> true); + } + List> 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 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 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 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 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 imagesToExpire(String account, String region, String name, String internal, + EcrLifecyclePolicy policy, Instant now) + throws IOException, InterruptedException { + RegistryHttpClient http = registryManager.httpClient(); + Map> 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 known = manifestReferences.getOrDefault(internal, Map.of()); + Map references = new HashMap<>(); + Set listed = new HashSet<>(); + Map 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 images = new ArrayList<>(); + for (Map.Entry> 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 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 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 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 catalog) { String internal = registryManager.internalRepoName(account, region, repoName); - List catalog = registryManager.httpClient().catalogStrict(); if (catalog.contains(internal)) { return internal; } diff --git a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java index 5bf92360b3..ce7d573573 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/EcrRegistryManager.java @@ -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 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 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 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. */ diff --git a/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java b/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java index 59ce9ba940..41210ed527 100644 --- a/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java +++ b/src/main/java/io/floci/aws/services/ecr/registry/RegistryHttpClient.java @@ -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 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 resp = http.send( diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ad2f91ce10..147750298d 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -920,6 +920,8 @@ floci: uri-style: hostname tls-uri: false prefer-local-images: true + lifecycle-sweep-enabled: true # FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_ENABLED - apply repository lifecycle policies in the background + lifecycle-sweep-interval-seconds: 60 # FLOCI_SERVICES_ECR_LIFECYCLE_SWEEP_INTERVAL_SECONDS ui: enabled: true image: "floci/floci-ui:0.7.0" diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecycleEvaluatorTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleEvaluatorTest.java new file mode 100644 index 0000000000..82bdae28bf --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleEvaluatorTest.java @@ -0,0 +1,208 @@ +package io.floci.aws.services.ecr; + +import io.floci.aws.services.ecr.EcrLifecycleEvaluator.Expiry; +import io.floci.aws.services.ecr.EcrLifecycleEvaluator.Image; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The worked examples of the ECR user guide's lifecycle policy examples page, each with the images it lists and the + * result it states, then what Floci adds: manifest lists, and the rules it applies no action for. + */ +class EcrLifecycleEvaluatorTest { + + private static final Instant NOW = Instant.parse("2026-11-23T12:00:00Z"); + private static final String EXPIRE = "{\"type\":\"expire\"}"; + private static final String TRANSITION = "{\"type\":\"transition\",\"targetStorageClass\":\"archive\"}"; + + @Test + void multipleRulesLowerPriorityRuleSkipsAnImageAHigherOneSelected() { + List images = List.of(image("A", 10, "beta-1", "prod-1"), image("B", 9, "beta-2", "prod-2"), + image("C", 8, "beta-3")); + + assertEquals(List.of("A"), expired(policy(rule(1, tagged("prod*", 1), EXPIRE), + rule(2, tagged("beta*", 1), EXPIRE)), images)); + assertEquals(List.of("B", "A"), expired(policy(rule(1, tagged("beta*", 1), EXPIRE), + rule(2, tagged("prod*", 1), EXPIRE)), images)); + } + + @Test + void multipleTagsInOneRuleSelectOnlyImagesMatchingEveryPattern() { + List byAge = List.of(image("A", 12, "alpha-1"), image("B", 11, "beta-1"), + image("C", 10, "alpha-2", "beta-2"), image("D", 4, "alpha-3"), image("E", 3, "beta-3"), + image("F", 2, "alpha-4", "beta-4")); + assertEquals(List.of("C"), expired(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":" + + "[\"alpha*\",\"beta*\"],\"countType\":\"sinceImagePushed\",\"countNumber\":5,\"countUnit\":\"days\"}", + EXPIRE)), byAge)); + + List byCount = List.of(image("A", 10, "alpha-1", "beta-1", "gamma-1"), + image("B", 9, "alpha-2", "beta-2"), image("C", 8, "alpha-3", "beta-3", "gamma-2")); + assertEquals(List.of("B", "A"), expired(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":" + + "[\"alpha*\",\"beta*\"],\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), byCount)); + } + + @Test + void anAnyRuleKeepsOnlyTheNewestImages() { + List images = List.of(image("A", 4, "alpha-1"), image("B", 3, "beta-1"), image("C", 2), + image("D", 1, "alpha-2")); + + assertEquals(List.of("C", "B", "A"), expired(policy(rule(1, any(1), EXPIRE)), images)); + } + + /** "Images A, B, and D are expired": the last rule can mark only D, the one image no earlier rule selected. */ + @Test + void anAnyRuleAfterTaggedAndUntaggedRulesMarksOnlyWhatTheySkipped() { + List images = List.of(image("A", Duration.ofDays(4), "alpha-1", "beta-1"), + image("B", Duration.ofDays(3)), image("C", Duration.ofDays(2), "alpha-2"), + image("D", Duration.ofDays(1), "git hash"), image("E", Duration.ofDays(1).minusMinutes(1))); + + assertEquals(List.of("A", "B", "D"), expired(policy(rule(1, tagged("alpha*", 1), EXPIRE), + rule(2, "{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\"," + + "\"countNumber\":1}", EXPIRE), + rule(3, any(1), EXPIRE)), images)); + } + + @Test + void anUntaggedRuleKeepsOneUntaggedImage() { + List images = List.of(image("A", 3), image("B", 2), image("C", 1), image("T", 5, "latest")); + + assertEquals(List.of("B", "A"), expired(policy(rule(1, "{\"tagStatus\":\"untagged\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), images)); + } + + @Test + void aPrefixListSelectsImagesWithATagStartingWithEachPrefix() { + List images = List.of(image("A", 5, "prod-1", "v1"), image("B", 4, "prod-2"), image("C", 3, "v2-prod"), + image("D", 2, "prod-3", "v3")); + + assertEquals(List.of("A"), expired(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPrefixList\":" + + "[\"prod\",\"v\"],\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), images)); + } + + @Test + void aWildcardMatchesAnyRunOfCharactersIncludingNone() { + List images = List.of(image("A", 5, "prod"), image("B", 4, "repo-production"), image("C", 3, "dev"), + image("D", 2, "prod-team")); + + assertEquals(List.of("B", "A"), expired(policy(rule(1, tagged("*prod*", 1), EXPIRE)), images)); + } + + /** "Older than" the count: an image pushed exactly that many days ago stays. */ + @Test + void sinceImagePushedExpiresOnlyImagesOlderThanTheCount() { + List images = List.of(image("A", Duration.ofDays(7).plusSeconds(1)), image("B", Duration.ofDays(7)), + image("C", Duration.ofDays(1))); + + assertEquals(List.of("A"), expired(policy(rule(1, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\"," + + "\"countUnit\":\"days\",\"countNumber\":7}", EXPIRE)), images)); + } + + @Test + void imagesPushedAtOnceAreKeptInDigestOrder() { + List images = List.of(image("B", 1), image("A", 1), image("C", 1)); + + assertEquals(List.of("C"), expired(policy(rule(1, any(2), EXPIRE)), images)); + } + + /** + * "If an image is referenced by a manifest list, it cannot be expired or archived without the manifest list being + * deleted or archived first." + */ + @Test + void anImageAManifestListNamesStillCountsButNeverExpires() { + List images = List.of(new Image("child-1", List.of(), NOW.minus(Duration.ofDays(1)), true), + new Image("child-2", List.of(), NOW.minus(Duration.ofDays(1)), true), image("orphan-1", 8), + image("orphan-2", 7), image("index", 1, "v1")); + + assertEquals(List.of("orphan-2", "orphan-1"), expired(policy(rule(1, "{\"tagStatus\":\"untagged\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1}", EXPIRE)), images)); + } + + /** Floci has no archive storage: a transition rule moves nothing, but lower rules still cannot take its images. */ + @Test + void aTransitionRuleExpiresNothingAndKeepsLowerRulesOffWhatItSelects() { + List images = List.of(image("A", 40, "prod-1"), image("B", 35, "dev-1"), image("C", 1, "prod-2")); + + assertEquals(List.of("B"), expired(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"prod*\"]," + + "\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":30}", TRANSITION), + rule(2, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\"," + + "\"countNumber\":30}", EXPIRE)), images)); + } + + /** Floci records no pulls, so a pull-age rule marks nothing, yet keeps lower rules off what it selects. */ + @Test + void aSinceImagePulledRuleExpiresNothingAndKeepsLowerRulesOffWhatItSelects() { + List images = List.of(image("A", 100, "prod-1"), image("B", 100, "dev-1")); + + assertEquals(List.of("B"), expired(policy(rule(1, "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"prod*\"]," + + "\"countType\":\"sinceImagePulled\",\"countUnit\":\"days\",\"countNumber\":1}", EXPIRE), + rule(2, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\"," + + "\"countNumber\":1}", EXPIRE)), images)); + } + + /** Every image is in standard storage, so an archive rule selects none and keeps no later rule off them. */ + @Test + void anArchiveRuleSelectsNoImage() { + List images = List.of(image("A", 400), image("B", 500, "v1")); + + assertEquals(List.of("A", "B"), expired(policy(rule(1, "{\"tagStatus\":\"any\",\"storageClass\":\"archive\"," + + "\"countType\":\"sinceImageTransitioned\",\"countUnit\":\"days\",\"countNumber\":365}", + EXPIRE), + rule(2, "{\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\"," + + "\"countNumber\":30}", EXPIRE)), images)); + } + + @Test + void aPatternMatchesTheWholeTag() { + List images = List.of(image("A", 5, "preprod"), image("B", 4, "prod-1"), image("C", 3, "prod-2")); + + assertEquals(List.of("B"), expired(policy(rule(1, tagged("prod*", 1), EXPIRE)), images)); + } + + /** Rules apply in priority order whatever order the document lists them in. */ + @Test + void anExpiryNamesTheRuleThatMarkedIt() { + List images = List.of(image("A", 5, "prod-1"), image("B", 4, "prod-2"), image("C", 3), + image("D", 10, "dev")); + + assertEquals(List.of(new Expiry("A", 4), new Expiry("D", 9)), EcrLifecycleEvaluator.expiries( + EcrLifecyclePolicy.parse(policy(rule(9, any(2), EXPIRE), rule(4, tagged("prod*", 1), EXPIRE), + rule(6, "{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\"," + + "\"countUnit\":\"days\",\"countNumber\":30}", EXPIRE))), images, NOW)); + } + + private static List expired(String policy, List images) { + return EcrLifecycleEvaluator.expiries(EcrLifecyclePolicy.parse(policy), images, NOW).stream() + .map(Expiry::digest).toList(); + } + + private static Image image(String digest, int pushedDaysAgo, String... tags) { + return image(digest, Duration.ofDays(pushedDaysAgo), tags); + } + + private static Image image(String digest, Duration pushedAgo, String... tags) { + return new Image(digest, List.of(tags), NOW.minus(pushedAgo), false); + } + + private static String policy(String... rules) { + return "{\"rules\":[" + String.join(",", rules) + "]}"; + } + + private static String rule(int priority, String selection, String action) { + return "{\"rulePriority\":" + priority + ",\"selection\":" + selection + ",\"action\":" + action + "}"; + } + + private static String tagged(String pattern, int count) { + return "{\"tagStatus\":\"tagged\",\"tagPatternList\":[\"" + pattern + + "\"],\"countType\":\"imageCountMoreThan\",\"countNumber\":" + count + "}"; + } + + private static String any(int count) { + return "{\"tagStatus\":\"any\",\"countType\":\"imageCountMoreThan\",\"countNumber\":" + count + "}"; + } +} diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java index 961c332ab5..a134fb744c 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecyclePolicyValidationIntegrationTest.java @@ -13,10 +13,12 @@ import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; import software.amazon.awssdk.services.ecr.EcrClient; +import software.amazon.awssdk.services.ecr.model.DeleteLifecyclePolicyResponse; import software.amazon.awssdk.services.ecr.model.InvalidParameterException; import software.amazon.awssdk.services.ecr.model.LifecyclePolicyNotFoundException; import software.amazon.awssdk.services.ecr.model.RepositoryNotFoundException; +import java.time.Instant; import java.util.UUID; import java.util.stream.Stream; @@ -128,6 +130,27 @@ class EcrLifecyclePolicyValidationIntegrationTest { } } + /** ECR answers with a time stamp before the sweep first applies the policy, and deleting it echoes it. */ + @Test + void getAndDeleteSayWhenThePolicyWasLastApplied() { + String repository = "lifecycle-validation/" + UUID.randomUUID(); + try (EcrClient client = AwsTestClients.create(EcrClient.builder(), "test", Region.US_EAST_1)) { + client.createRepository(r -> r.repositoryName(repository)); + try { + client.putLifecyclePolicy(r -> r.repositoryName(repository).lifecyclePolicyText(VALID_POLICY)); + + assertEquals(Instant.EPOCH, client.getLifecyclePolicy(r -> r.repositoryName(repository)) + .lastEvaluatedAt()); + DeleteLifecyclePolicyResponse deleted = client.deleteLifecyclePolicy( + r -> r.repositoryName(repository)); + assertEquals(VALID_POLICY, deleted.lifecyclePolicyText()); + assertEquals(Instant.EPOCH, deleted.lastEvaluatedAt()); + } finally { + client.deleteRepository(r -> r.repositoryName(repository)); + } + } + } + /** ECR's validator ends its text with a newline, which the message keeps inside the closing quote. */ @Test void aRefusedDocumentCarriesEcrsMessage() { diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepDockerIntegrationTest.java new file mode 100644 index 0000000000..dc245a15fe --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepDockerIntegrationTest.java @@ -0,0 +1,112 @@ +package io.floci.aws.services.ecr; + +import io.floci.aws.core.common.Digests; +import io.floci.aws.testing.EcrTestImages; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.SidecarContainersProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; + +/** + * A repository's lifecycle policy applied by the sweep against the real backing registry: images pushed through the + * registry API as {@code docker push} sends them, the sweep run, and the expired image gone from the registry and from + * {@code DescribeImages}. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class EcrLifecycleSweepDockerIntegrationTest { + + private static final String DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json"; + private static final String KEEP_ONE = "{\"rules\":[{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"any\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":{\"type\":\"expire\"}}]}"; + + @Inject + EcrLifecycleScheduler scheduler; + + private final String repo = "lifecycle/" + UUID.randomUUID().toString().substring(0, 8); + + @BeforeAll + static void requireDocker() { + SidecarContainersProfile.requireDockerAndImage("floci.services.ecr.registry-image"); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void deleteRepository() { + call("DeleteRepository", "{\"repositoryName\":\"" + repo + "\",\"force\":true}"); + } + + @Test + void theSweepExpiresTheImagesTheRepositorysPolicySelects() { + call("CreateRepository", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200); + String host = "000000000000.dkr.ecr.us-east-1.localhost:" + RestAssured.port; + byte[] layer = ("layer " + repo).getBytes(StandardCharsets.UTF_8); + String layerDigest = "sha256:" + Digests.sha256Hex(layer); + EcrTestImages.uploadBlob(host, repo, layerDigest, layer); + for (String tag : List.of("v1", "v2", "v3")) { + push(host, tag, layer.length, layerDigest); + } + call("PutLifecyclePolicy", "{\"repositoryName\":\"" + repo + "\",\"lifecyclePolicyText\":" + + quoted(KEEP_ONE) + "}").statusCode(200); + call("GetLifecyclePolicy", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200) + .body("lastEvaluatedAt", equalTo(0)); + + scheduler.tick(Instant.now()); + + call("DescribeImages", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200) + .body("imageDetails", hasSize(1)) + .body("imageDetails[0].imageTags", equalTo(List.of("v3"))); + given().header("Host", host).accept(DOCKER_MANIFEST) + .when().get("/v2/" + repo + "/manifests/v1") + .then().statusCode(404); + call("GetLifecyclePolicy", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200) + .body("lastEvaluatedAt", greaterThan(0)); + call("DeleteLifecyclePolicy", "{\"repositoryName\":\"" + repo + "\"}").statusCode(200) + .body("lifecyclePolicyText", equalTo(KEEP_ONE)) + .body("lastEvaluatedAt", greaterThan(0)); + } + + /** One image per tag: each has its own config blob over the shared layer, so each has its own digest. */ + private void push(String host, String tag, int layerSize, String layerDigest) { + byte[] config = ("{\"architecture\":\"amd64\",\"os\":\"linux\",\"config\":{\"Labels\":{\"tag\":\"" + tag + + "\"}},\"rootfs\":{\"type\":\"layers\",\"diff_ids\":[]}}").getBytes(StandardCharsets.UTF_8); + String configDigest = "sha256:" + Digests.sha256Hex(config); + EcrTestImages.uploadBlob(host, repo, configDigest, config); + String manifest = """ + {"schemaVersion":2,"mediaType":"%s", + "config":{"mediaType":"application/vnd.docker.container.image.v1+json","size":%d,"digest":"%s"}, + "layers":[{"mediaType":"application/vnd.docker.image.rootfs.diff.tar.gzip","size":%d,"digest":"%s"}]} + """.formatted(DOCKER_MANIFEST, config.length, configDigest, layerSize, layerDigest); + given().header("Host", host).contentType(DOCKER_MANIFEST).body(manifest) + .when().put("/v2/" + repo + "/manifests/" + tag) + .then().statusCode(201); + } + + private static String quoted(String json) { + return "\"" + json.replace("\"", "\\\"") + "\""; + } + + private static ValidatableResponse call(String action, String body) { + return given().header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921." + action) + .contentType("application/x-amz-json-1.1") + .body(body) + .when().post("/") + .then(); + } +} diff --git a/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepTest.java b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepTest.java new file mode 100644 index 0000000000..fe2f341e56 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecr/EcrLifecycleSweepTest.java @@ -0,0 +1,658 @@ +package io.floci.aws.services.ecr; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.ecr.model.ImageMetadata; +import io.floci.aws.services.ecr.model.Repository; +import io.floci.aws.services.ecr.registry.EcrRegistryManager; +import io.floci.aws.services.ecr.registry.RegistryHttpClient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.Mockito; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +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.AtomicInteger; +import java.util.concurrent.locks.LockSupport; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +/** {@link EcrService#applyLifecyclePolicies} against an in-memory registry speaking the distribution API. */ +class EcrLifecycleSweepTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String REPO = "app"; + private static final Instant NOW = Instant.parse("2026-11-23T12:00:00Z"); + private static final String KEEP_TWO = policy("{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"any\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":2},\"action\":{\"type\":\"expire\"}}"); + private static final String OLDER_THAN_FIVE_DAYS = policy("{\"rulePriority\":1,\"selection\":{" + + "\"tagStatus\":\"any\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":5}," + + "\"action\":{\"type\":\"expire\"}}"); + + private FakeRegistry registry; + private EcrRegistryManager registryManager; + private InMemoryStorage repositories; + private InMemoryStorage pushRecords; + private EcrService service; + private EmulatorConfig config; + + @BeforeEach + void setUp() throws IOException { + registry = new FakeRegistry(); + registryManager = Mockito.mock(EcrRegistryManager.class); + when(registryManager.getRepositoryUri(anyString(), anyString(), anyString())).thenReturn("uri"); + when(registryManager.internalRepoName(anyString(), anyString(), anyString())) + .thenAnswer(inv -> inv.getArgument(0) + "/" + inv.getArgument(1) + "/" + inv.getArgument(2)); + when(registryManager.isStarted()).thenReturn(true); + when(registryManager.httpClient()).thenReturn(new RegistryHttpClient("http://127.0.0.1:" + registry.port())); + when(registryManager.heldManifestDigests(anyString())).thenAnswer(inv -> registry.digests(inv.getArgument(0))); + config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS); + when(config.services().ecr().enabled()).thenReturn(true); + repositories = new InMemoryStorage<>(); + pushRecords = new InMemoryStorage<>(); + service = new EcrService(repositories, pushRecords, new InMemoryStorage<>(), registryManager, config, + new RegionResolver(REGION, ACCOUNT)); + } + + @AfterEach + void tearDown() { + registry.close(); + } + + @Test + void theSweepExpiresWhatThePolicySelectsAndRecordsWhenItRan() { + Repository repo = repository(REPO, KEEP_TWO); + String v1 = push(REGION, REPO, "v1", image("v1"), 4); + String v2 = push(REGION, REPO, "v2", image("v2"), 3); + String v3 = push(REGION, REPO, "v3", image("v3"), 2); + String v4 = push(REGION, REPO, "v4", image("v4"), 1); + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(v3, v4), registry.digests(internal(REGION, REPO))); + assertEquals(Set.of(v3, v4), recordedDigests(REGION, REPO)); + assertEquals(NOW, service.lifecyclePolicyEvaluatedAt(repo, REGION)); + assertEquals(Set.of(v1, v2), Set.copyOf(registry.deleted)); + } + + /** + * Untagged images are every manifest the registry holds without a tag: one with no push record is taken as pushed + * when the sweep first sees it, as DescribeImages does, and a push record of a manifest that is gone names nothing. + */ + @Test + void untaggedImagesAreTheManifestsTheRegistryHoldsWithoutATag() { + repository(REPO, policy("{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"untagged\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":{\"type\":\"expire\"}}")); + String tagged = push(REGION, REPO, "latest", image("tagged"), 9); + String oldest = push(REGION, REPO, null, image("u1"), 8); + String older = push(REGION, REPO, null, image("u2"), 7); + String unrecorded = registry.put(internal(REGION, REPO), null, image("u3")); + service.recordImagePush(ACCOUNT, REGION, REPO, digest(image("gone")), NOW.minus(Duration.ofDays(20))); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(tagged, unrecorded), registry.digests(internal(REGION, REPO))); + assertEquals(Set.of(oldest, older), Set.copyOf(registry.deleted)); + } + + /** + * "If an image is referenced by a manifest list, it cannot be expired or archived without the manifest list being + * deleted or archived first." + */ + @Test + void anImageAManifestListNamesExpiresOnlyOnceTheListIsGone() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String amd64 = push(REGION, REPO, null, image("amd64"), 10); + String arm64 = push(REGION, REPO, null, image("arm64"), 10); + String index = push(REGION, REPO, "v1", "{\"schemaVersion\":2,\"mediaType\":" + + "\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"digest\":\"" + amd64 + "\"}," + + "{\"digest\":\"" + arm64 + "\"}]}", 10); + + service.applyLifecyclePolicies(NOW); + assertEquals(List.of(index), registry.deleted); + + service.applyLifecyclePolicies(NOW); + assertEquals(Set.of(), registry.digests(internal(REGION, REPO))); + } + + /** + * "When reference artifacts are present in a repository, Amazon ECR lifecycle policies automatically expire or + * archive those artifacts within 24 hours of the deletion or archival of the subject image." + */ + @Test + void anArtifactExpiresWithItsSubjectAndIsSelectedByNoRule() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "old", image("old"), 10); + String current = push(REGION, REPO, "current", image("current"), 1); + String oldSignature = push(REGION, REPO, null, referrer(old, "old-sig"), 1); + String currentSignature = push(REGION, REPO, null, referrer(current, "current-sig"), 10); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(current, currentSignature), registry.digests(internal(REGION, REPO))); + assertEquals(Set.of(old, oldSignature), Set.copyOf(registry.deleted)); + } + + /** The subject's "deletion", in the user guide's words, whatever deleted it: here a BatchDeleteImage before. */ + /** An image the registry holds counts as held whether or not Floci recorded its push. */ + @Test + void anArtifactOfAnImageWithNoPushRecordIsKept() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String subject = registry.put(internal(REGION, REPO), null, image("unrecorded")); + String signature = push(REGION, REPO, null, referrer(subject, "sig"), 10); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(subject, signature), registry.digests(internal(REGION, REPO))); + } + + @Test + void aManifestListWithNoPushRecordStillKeepsItsImages() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String amd64 = push(REGION, REPO, null, image("amd64"), 10); + String index = registry.put(internal(REGION, REPO), null, "{\"schemaVersion\":2,\"mediaType\":" + + "\"application/vnd.oci.image.index.v1+json\",\"manifests\":[{\"digest\":\"" + amd64 + "\"}]}"); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(amd64, index), registry.digests(internal(REGION, REPO))); + } + + /** A delete the registry refuses stops the sweep: no artifact goes while the image it names is still there. */ + @Test + void aDeleteTheRegistryRefusesStopsTheSweepOfThatRepository() { + Repository repo = repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "old", image("old"), 10); + String signature = push(REGION, REPO, null, referrer(old, "sig"), 1); + registry.refusedDeletes.add(old); + + assertThrows(IllegalStateException.class, () -> service.applyLifecyclePolicies(NOW)); + + assertEquals(Set.of(old, signature), registry.digests(internal(REGION, REPO))); + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + } + + @Test + void anArtifactWhoseSubjectIsAlreadyGoneExpires() { + repository(REPO, KEEP_TWO); + String kept = push(REGION, REPO, "v1", image("v1"), 1); + String orphan = push(REGION, REPO, null, referrer(digest(image("deleted")), "sig"), 1); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(kept), registry.digests(internal(REGION, REPO))); + assertEquals(List.of(orphan), registry.deleted); + } + + @Test + void eachRepositoryIsSweptInItsOwnRegion() { + repository(REPO, KEEP_TWO); + repository("eu-west-1", "other", OLDER_THAN_FIVE_DAYS); + repository("plain", null); + String here = push(REGION, REPO, "v1", image("here"), 30); + String there = push("eu-west-1", "other", "v1", image("there"), 30); + String untouched = push(REGION, "plain", "v1", image("plain"), 30); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(here), registry.digests(internal(REGION, REPO))); + assertEquals(Set.of(), registry.digests(internal("eu-west-1", "other"))); + assertEquals(Set.of(untouched), registry.digests(internal(REGION, "plain"))); + assertEquals(List.of(there), registry.deleted); + } + + @Test + void nothingIsSweptWhileTheRegistryIsNotRunning() { + Repository repo = repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + when(registryManager.isStarted()).thenReturn(false); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(old), registry.digests(internal(REGION, REPO))); + assertEquals(0, registry.requests.get()); + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + } + + /** A policy stored before every rule was checked, which PutLifecyclePolicy now refuses, is left unapplied. */ + @Test + void aStoredPolicyThatIsNowRefusedIsNotApplied() { + Repository repo = repository(REPO, null); + repo.setLifecyclePolicyText(policy("{\"rulePriority\":1,\"selection\":{\"tagStatus\":\"tagged\"," + + "\"countType\":\"imageCountMoreThan\",\"countNumber\":1},\"action\":{\"type\":\"expire\"}}")); + repositories.put(REGION + "::" + ACCOUNT + "::" + REPO, repo); + String v1 = push(REGION, REPO, "v1", image("v1"), 30); + String v2 = push(REGION, REPO, "v2", image("v2"), 20); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(v1, v2), registry.digests(internal(REGION, REPO))); + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + } + + @Test + void aRepositoryTheRegistryFailsForIsRetriedLaterWhileTheOthersAreSwept() { + repository("broken", OLDER_THAN_FIVE_DAYS); + repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + push(REGION, "broken", "v1", image("broken"), 30); + registry.failing.add(internal(REGION, "broken")); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> service.applyLifecyclePolicies(NOW)); + + assertTrue(failure.getMessage().contains(REGION + "::" + ACCOUNT + "::broken"), failure.getMessage()); + assertEquals(List.of(old), registry.deleted); + } + + @Test + void aPolicyPutSinceTheSweepReadsAsNeverApplied() { + Repository repo = repository(REPO, KEEP_TWO); + service.applyLifecyclePolicies(NOW); + assertEquals(NOW, service.lifecyclePolicyEvaluatedAt(repo, REGION)); + + service.putLifecyclePolicy(REPO, null, OLDER_THAN_FIVE_DAYS, REGION); + + assertNull(service.lifecyclePolicyEvaluatedAt(service.getLifecyclePolicy(REPO, null, REGION), REGION)); + } + + @Test + void deletingThePolicyAnswersWithItAndWhenItWasLastApplied() { + repository(REPO, KEEP_TWO); + service.applyLifecyclePolicies(NOW); + + EcrService.DeletedLifecyclePolicy deleted = service.deleteLifecyclePolicy(REPO, null, REGION); + + assertEquals(new EcrService.DeletedLifecyclePolicy(ACCOUNT, REPO, KEEP_TWO, NOW), deleted); + service.putLifecyclePolicy(REPO, null, KEEP_TWO, REGION); + assertNull(service.lifecyclePolicyEvaluatedAt(service.getLifecyclePolicy(REPO, null, REGION), REGION)); + } + + /** + * The images are read without the repository's write lock, so a push is never held up by the reads. A write that + * ends between the reads and the deletes puts the expiry off to the next sweep, which reads the images again. + */ + @Test + void aWriteWhileThePolicyIsEvaluatedPutsTheExpiryOffToTheNextSweep() throws InterruptedException { + Repository repo = repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + service.lockRepositoryWrites(internal(REGION, REPO)); + Thread sweep = new Thread(() -> service.applyLifecyclePolicies(NOW)); + try { + sweep.start(); + awaitParkedOnALock(sweep); + assertEquals(1, registry.tagListings.get()); + assertEquals(List.of(), registry.deleted); + } finally { + service.unlockRepositoryWrites(internal(REGION, REPO)); + } + sweep.join(Duration.ofSeconds(10).toMillis()); + + assertEquals(List.of(), registry.deleted); + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + service.applyLifecyclePolicies(NOW); + assertEquals(List.of(old), registry.deleted); + } + + @Test + void aSweepThatExpiresNothingNeverTakesTheWriteLock() throws InterruptedException { + Repository repo = repository(REPO, OLDER_THAN_FIVE_DAYS); + push(REGION, REPO, "v1", image("v1"), 1); + service.lockRepositoryWrites(internal(REGION, REPO)); + try { + Thread sweep = new Thread(() -> service.applyLifecyclePolicies(NOW)); + sweep.start(); + sweep.join(Duration.ofSeconds(10).toMillis()); + + assertEquals(NOW, service.lifecyclePolicyEvaluatedAt(repo, REGION)); + } finally { + service.unlockRepositoryWrites(internal(REGION, REPO)); + } + } + + /** + * The policy is applied as it stood when the sweep came to the repository: a policy put meanwhile waits for the + * sweep, then reads as never applied. + */ + @Test + void aPolicyPutWhileTheSweepAppliesTheOldOneWaitsForIt() throws InterruptedException { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + CountDownLatch gate = registry.holdTagListings(); + Thread sweep = new Thread(() -> service.applyLifecyclePolicies(NOW)); + Thread put = new Thread(() -> service.putLifecyclePolicy(REPO, null, KEEP_TWO, REGION)); + try { + sweep.start(); + registry.awaitHeldTagListing(); + put.start(); + awaitParkedOnALock(put); + } finally { + gate.countDown(); + } + sweep.join(Duration.ofSeconds(10).toMillis()); + put.join(Duration.ofSeconds(10).toMillis()); + + assertEquals(List.of(old), registry.deleted); + assertEquals(KEEP_TWO, service.getLifecyclePolicy(REPO, null, REGION).getLifecyclePolicyText()); + assertNull(service.lifecyclePolicyEvaluatedAt(service.getLifecyclePolicy(REPO, null, REGION), REGION)); + } + + @Test + void aPolicyDeletedWhileTheSweepAppliesItWaitsForIt() throws InterruptedException { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + CountDownLatch gate = registry.holdTagListings(); + Thread sweep = new Thread(() -> service.applyLifecyclePolicies(NOW)); + Thread delete = new Thread(() -> service.deleteLifecyclePolicy(REPO, null, REGION)); + try { + sweep.start(); + registry.awaitHeldTagListing(); + delete.start(); + awaitParkedOnALock(delete); + } finally { + gate.countDown(); + } + sweep.join(Duration.ofSeconds(10).toMillis()); + delete.join(Duration.ofSeconds(10).toMillis()); + + assertEquals(List.of(old), registry.deleted); + assertThrows(AwsException.class, () -> service.getLifecyclePolicy(REPO, null, REGION)); + } + + /** A repository deleted while the sweep applies its policy waits for it, and a new one by its name starts afresh. */ + @Test + void aRepositoryDeletedWhileTheSweepAppliesItsPolicyWaitsForIt() throws InterruptedException { + repository(REPO, KEEP_TWO); + CountDownLatch gate = registry.holdTagListings(); + Thread sweep = new Thread(() -> service.applyLifecyclePolicies(NOW)); + Thread delete = new Thread(() -> service.deleteRepository(REPO, null, true, REGION)); + try { + sweep.start(); + registry.awaitHeldTagListing(); + delete.start(); + awaitParkedOnALock(delete); + } finally { + gate.countDown(); + } + sweep.join(Duration.ofSeconds(10).toMillis()); + delete.join(Duration.ofSeconds(10).toMillis()); + + assertNull(service.lifecyclePolicyEvaluatedAt(repository(REPO, KEEP_TWO), REGION)); + } + + @Test + void aResetForgetsWhenEachPolicyWasApplied() { + Repository repo = repository(REPO, KEEP_TWO); + service.applyLifecyclePolicies(NOW); + + service.clear(); + + assertNull(service.lifecyclePolicyEvaluatedAt(repo, REGION)); + } + + /** A manifest's content never changes, so each is read once; the catalog is read once a sweep. */ + @Test + void eachManifestIsReadOnceAndTheCatalogOnceASweep() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + repository("other", OLDER_THAN_FIVE_DAYS); + push(REGION, REPO, "v1", image("v1"), 1); + push(REGION, REPO, null, image("u1"), 1); + push(REGION, "other", "v1", image("other"), 1); + + service.applyLifecyclePolicies(NOW); + service.applyLifecyclePolicies(NOW); + + assertEquals(3, registry.manifestReads.get()); + assertEquals(2, registry.catalogReads.get()); + } + + private static void awaitParkedOnALock(Thread thread) { + long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (!parkedOnALock(thread) && System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + assertTrue(parkedOnALock(thread), thread.getName() + " should wait for a repository lock"); + } + + /** Both repository locks are a semaphore per repository, which a waiting thread parks on; a registry call is not. */ + private static boolean parkedOnALock(Thread thread) { + Object blocker = LockSupport.getBlocker(thread); + return blocker != null && blocker.getClass().getEnclosingClass() == Semaphore.class; + } + + @Test + void nothingIsSweptWhileEcrIsDisabled() { + repository(REPO, OLDER_THAN_FIVE_DAYS); + String old = push(REGION, REPO, "v1", image("v1"), 30); + int before = registry.requests.get(); + when(config.services().ecr().enabled()).thenReturn(false); + + service.applyLifecyclePolicies(NOW); + + assertEquals(Set.of(old), registry.digests(internal(REGION, REPO))); + assertEquals(before, registry.requests.get()); + } + + @Test + void aRepositoryCreatedAgainUnderTheSameNameStartsNeverApplied() { + repository(REPO, KEEP_TWO); + service.applyLifecyclePolicies(NOW); + + service.deleteRepository(REPO, null, true, REGION); + Repository again = repository(REPO, KEEP_TWO); + + assertNull(service.lifecyclePolicyEvaluatedAt(again, REGION)); + } + + private Repository repository(String name, String policy) { + return repository(REGION, name, policy); + } + + private Repository repository(String region, String name, String policy) { + service.createRepository(name, null, null, null, null, null, null, region); + registry.create(internal(region, name)); + if (policy != null) { + service.putLifecyclePolicy(name, null, policy, region); + } + return service.describeRepositories(List.of(name), null, region).get(0); + } + + private String push(String region, String repo, String tag, String manifest, int pushedDaysAgo) { + String digest = registry.put(internal(region, repo), tag, manifest); + service.recordImagePush(ACCOUNT, region, repo, digest, NOW.minus(Duration.ofDays(pushedDaysAgo))); + return digest; + } + + private Set recordedDigests(String region, String repo) { + String prefix = region + "::" + ACCOUNT + "::" + repo + "::"; + Set digests = new HashSet<>(); + pushRecords.scan(key -> key.startsWith(prefix)).forEach(record -> digests.add(record.getDigest())); + return digests; + } + + private static String internal(String region, String repo) { + return ACCOUNT + "/" + region + "/" + repo; + } + + private static String policy(String... rules) { + return "{\"rules\":[" + String.join(",", rules) + "]}"; + } + + private static String image(String name) { + return "{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"config\":{}," + + "\"layers\":[],\"annotations\":{\"name\":\"" + name + "\"}}"; + } + + private static String referrer(String subject, String name) { + return "{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\"," + + "\"artifactType\":\"application/vnd.example.signature\",\"config\":{},\"layers\":[]," + + "\"subject\":{\"digest\":\"" + subject + "\"},\"annotations\":{\"name\":\"" + name + "\"}}"; + } + + private static String digest(String manifest) { + return "sha256:" + Digests.sha256Hex(manifest.getBytes(StandardCharsets.UTF_8)); + } + + /** The distribution API calls the sweep makes: catalog, tag list, manifest HEAD, GET and DELETE. */ + private static final class FakeRegistry implements AutoCloseable { + private final HttpServer server; + private final Map> manifests = new ConcurrentHashMap<>(); + private final Map> tags = new ConcurrentHashMap<>(); + private final Set failing = ConcurrentHashMap.newKeySet(); + private final List deleted = new ArrayList<>(); + private final AtomicInteger requests = new AtomicInteger(); + private final AtomicInteger tagListings = new AtomicInteger(); + private final AtomicInteger manifestReads = new AtomicInteger(); + private final AtomicInteger catalogReads = new AtomicInteger(); + private final Set refusedDeletes = ConcurrentHashMap.newKeySet(); + private final CountDownLatch tagListingHeld = new CountDownLatch(1); + private volatile CountDownLatch tagListingGate; + + private FakeRegistry() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/v2/", this::handle); + server.start(); + } + + private int port() { + return server.getAddress().getPort(); + } + + private void create(String repo) { + manifests.put(repo, new TreeMap<>()); + tags.put(repo, new TreeMap<>()); + } + + private String put(String repo, String tag, String manifest) { + String digest = digest(manifest); + manifests.get(repo).put(digest, manifest); + if (tag != null) { + tags.get(repo).put(tag, digest); + } + return digest; + } + + private Set digests(String repo) { + return Set.copyOf(manifests.getOrDefault(repo, Map.of()).keySet()); + } + + /** Holds every tag listing until the returned gate opens. */ + private CountDownLatch holdTagListings() { + tagListingGate = new CountDownLatch(1); + return tagListingGate; + } + + private void awaitHeldTagListing() throws InterruptedException { + assertTrue(tagListingHeld.await(10, TimeUnit.SECONDS), "no tag listing reached the registry"); + } + + private synchronized void handle(HttpExchange exchange) throws IOException { + requests.incrementAndGet(); + String path = exchange.getRequestURI().getPath().substring("/v2/".length()); + String method = exchange.getRequestMethod(); + if (path.equals("_catalog")) { + catalogReads.incrementAndGet(); + send(exchange, 200, "{\"repositories\":[\"" + String.join("\",\"", manifests.keySet()) + "\"]}", + "application/json"); + return; + } + if (path.endsWith("/tags/list")) { + tagListings.incrementAndGet(); + CountDownLatch gate = tagListingGate; + if (gate != null) { + tagListingHeld.countDown(); + try { + gate.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + String repo = path.substring(0, path.length() - "/tags/list".length()); + if (failing.contains(repo)) { + send(exchange, 500, "{}", "application/json"); + return; + } + send(exchange, 200, "{\"name\":\"" + repo + "\",\"tags\":[" + (tags.get(repo).isEmpty() ? "" + : "\"" + String.join("\",\"", tags.get(repo).keySet()) + "\"") + "]}", "application/json"); + return; + } + int split = path.lastIndexOf("/manifests/"); + String repo = path.substring(0, split); + String reference = path.substring(split + "/manifests/".length()); + String digest = reference.startsWith("sha256:") ? reference : tags.get(repo).get(reference); + String manifest = digest == null ? null : manifests.get(repo).get(digest); + if (manifest == null) { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + return; + } + switch (method) { + case "DELETE" -> { + if (refusedDeletes.contains(digest)) { + exchange.sendResponseHeaders(500, -1); + exchange.close(); + return; + } + manifests.get(repo).remove(digest); + tags.get(repo).values().removeIf(digest::equals); + deleted.add(digest); + exchange.sendResponseHeaders(202, -1); + exchange.close(); + } + case "HEAD" -> { + exchange.getResponseHeaders().add("Docker-Content-Digest", digest); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + } + default -> { + manifestReads.incrementAndGet(); + exchange.getResponseHeaders().add("Docker-Content-Digest", digest); + send(exchange, 200, manifest, "application/vnd.oci.image.manifest.v1+json"); + } + } + } + + private static void send(HttpExchange exchange, int status, String body, String contentType) + throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", contentType); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + + @Override + public void close() { + server.stop(0); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java index 0a9404dc45..2a9f8c319e 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java @@ -1605,6 +1605,8 @@ class EcrServiceTest { AwsException ex = assertThrows(AwsException.class, () -> service.getLifecyclePolicy(REPO, null, REGION)); assertEquals("LifecyclePolicyNotFoundException", ex.getErrorCode()); + assertEquals("Lifecycle policy does not exist for the repository with name '" + REPO + + "' in the registry with id '" + ACCOUNT + "'", ex.getMessage()); } // ------------------------------------------------------------ diff --git a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java index 9059f25615..5dfd9dab55 100644 --- a/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java +++ b/src/test/java/io/floci/aws/services/ecr/registry/EcrRegistryManagerTest.java @@ -18,6 +18,7 @@ import com.github.dockerjava.api.model.ContainerNetworkSettings; import com.github.dockerjava.api.model.ContainerPort; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.Info; +import com.github.dockerjava.api.model.StreamType; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.docker.ContainerBuilder; @@ -45,6 +46,7 @@ import org.mockito.Mockito; import java.io.Closeable; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -52,6 +54,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -1112,6 +1115,45 @@ class EcrRegistryManagerTest { "/var/lib/registry/docker/registry/v2/repositories/000000000000/us-east-1/team/app/_uploads"); } + /** The registry's API lists tags only; untagged manifests are read from the revision links of its storage. */ + @Test + void heldManifestDigestsAreReadFromTheRevisionLinks() { + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerLifecycleManager.ContainerInfo("container-id", Map.of())); + String revisions = "/var/lib/registry/docker/registry/v2/repositories/000000000000/us-east-1/team/app" + + "/_manifests/revisions/sha256"; + String first = "a".repeat(64); + String second = "0123456789abcdef".repeat(4); + DockerClient dockerClient = Mockito.mock(DockerClient.class); + ExecCreateCmd execCreate = Mockito.mock(ExecCreateCmd.class, Mockito.RETURNS_SELF); + ExecCreateCmdResponse exec = Mockito.mock(ExecCreateCmdResponse.class); + when(exec.getId()).thenReturn("exec-id"); + when(execCreate.exec()).thenReturn(exec); + when(dockerClient.execCreateCmd("container-id")).thenReturn(execCreate); + ExecStartCmd execStart = Mockito.mock(ExecStartCmd.class); + when(execStart.exec(any())).thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + ResultCallback callback = invocation.getArgument(0); + callback.onNext(new Frame(StreamType.STDOUT, (revisions + "/" + first + "/link\n" + revisions + "/" + + second + "/link\n" + revisions + "/not-a-digest/link\n").getBytes(StandardCharsets.UTF_8))); + callback.onComplete(); + return callback; + }); + when(dockerClient.execStartCmd("exec-id")).thenReturn(execStart); + InspectExecCmd inspect = Mockito.mock(InspectExecCmd.class); + InspectExecResponse result = Mockito.mock(InspectExecResponse.class); + when(result.getExitCodeLong()).thenReturn(0L); + when(inspect.exec()).thenReturn(result); + when(dockerClient.inspectExecCmd("exec-id")).thenReturn(inspect); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + manager.ensureStarted(); + + assertEquals(Set.of("sha256:" + first, "sha256:" + second), + manager.heldManifestDigests("000000000000/us-east-1/team/app")); + verify(execCreate).withCmd("timeout", "-k", "1", "10", "sh", "-c", "[ -d '" + revisions + "' ] || exit 0; " + + "find '" + revisions + "' -mindepth 2 -maxdepth 2 -name link"); + } + @Test @SuppressWarnings("unchecked") void runGarbageCollectTimeoutWithExecStillRunningKeepsAdmissionClosed() throws Exception { diff --git a/src/test/java/io/floci/aws/testing/EcrTestImages.java b/src/test/java/io/floci/aws/testing/EcrTestImages.java index c7614c70d4..786b470421 100644 --- a/src/test/java/io/floci/aws/testing/EcrTestImages.java +++ b/src/test/java/io/floci/aws/testing/EcrTestImages.java @@ -163,7 +163,11 @@ public final class EcrTestImages { return buf.array(); } - private static void uploadBlob(String host, String repo, String digest, byte[] content) { + /** + * Uploads {@code content} to {@code repo} as one monolithic blob upload, sending {@code host}, one of Floci's + * repository hosts, as the {@code Host} header. + */ + public static void uploadBlob(String host, String repo, String digest, byte[] content) { String location = given().header("Host", host) .when().post("/v2/" + repo + "/blobs/uploads/") .then().statusCode(202) diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index a6f471d732..fcba5cd001 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -395,6 +395,7 @@ floci: ecr: enabled: true tls-uri: false + lifecycle-sweep-enabled: false # tests run the sweep themselves, so no repository's policy applies behind another test's back ui: enabled: true bedrock: