mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(s3): apply lifecycle expiration rules (#5158)
A bucket's lifecycle configuration was stored and returned but never evaluated. A background sweep now applies its expiration actions: - Expiration (Days, Date) deletes the current version of a matching object, or adds a delete marker in a versioning-enabled bucket. Day counts run from the last-modified time and round up to the next midnight UTC, as on S3. - ExpiredObjectDeleteMarker, and a Days or Date expiration once the marker is old enough, remove a delete marker with no other versions. - NoncurrentVersionExpiration (NoncurrentDays, NewerNoncurrentVersions) permanently deletes noncurrent versions, counting from when the next newer version was written. - AbortIncompleteMultipartUpload (DaysAfterInitiation) aborts uploads under a prefix-only filter. Filters are Prefix, Tag, ObjectSizeGreaterThan, ObjectSizeLessThan, an And of them, or the older rule-level Prefix. Disabled rules are skipped, versions under Object Lock retention or a legal hold are never deleted, and each bucket is swept in its owning account. Lifecycle deletions are notified as s3:LifecycleExpiration:* rather than s3:ObjectRemoved:*, with S3 itself as the requester, and their EventBridge reason is "Lifecycle Expiration". A rule S3 would have refused on put, such as Days 0, a size bound that is not a number or a Tag without a Value, is skipped as a whole, so a bad value never widens what a rule deletes. A body that is not one well-formed LifecycleConfiguration document has no rules. Each key is planned from one pass over its account's objects, then read again by its known store keys and applied under the bucket monitor. Lifecycle configuration changes and tagging now change under that monitor too, and a multipart upload is aborted only while its bucket and the rules are still the ones the sweep started on. Versions written in the same millisecond keep the order they were written in, for ListObjectVersions as well as for lifecycle. PutObject, GetObject and HeadObject on a current version that an Expiration rule matches return x-amz-expiration with the expiry date and the URL-encoded rule id. The sweep runs every 60 seconds by default, configured with floci.services.s3.lifecycle-sweep-enabled and floci.services.s3.lifecycle-sweep-interval-seconds. Transition actions are still not applied. Closes #5137
This commit is contained in:
1 parent
fea7d7b0b1
commit
cbd2f61dc4
18 files changed
+1846
-33
No files matched your search
@@ -1379,6 +1379,23 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean globalBucketNamespace();
|
||||
|
||||
/**
|
||||
* Run the background sweep that applies bucket lifecycle expiration rules: Expiration,
|
||||
* NoncurrentVersionExpiration and AbortIncompleteMultipartUpload. When off, rules are
|
||||
* stored and reported in {@code x-amz-expiration} but nothing expires.
|
||||
* Env: FLOCI_SERVICES_S3_LIFECYCLE_SWEEP_ENABLED
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean lifecycleSweepEnabled();
|
||||
|
||||
/**
|
||||
* How often the lifecycle sweep runs. S3 itself applies lifecycle about once a day, to
|
||||
* expiry times rounded to midnight UTC, so the interval only bounds how late Floci is.
|
||||
* Env: FLOCI_SERVICES_S3_LIFECYCLE_SWEEP_INTERVAL_SECONDS
|
||||
*/
|
||||
@WithDefault("60")
|
||||
long lifecycleSweepIntervalSeconds();
|
||||
}
|
||||
|
||||
interface DynamoDbServiceConfig {
|
||||
|
||||
@@ -454,6 +454,37 @@ public final class XmlParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a whole document into its document element's tree, or returns {@code null} when the
|
||||
* document is empty or not well-formed anywhere, after its document element included.
|
||||
*
|
||||
* <p>For a stored document whose every part has effect, where {@link #extractElementTree}
|
||||
* would return a complete element followed by content that never parsed.
|
||||
*/
|
||||
public static XmlElement parseDocumentElementTree(String xml) {
|
||||
if (xml == null || xml.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
|
||||
try {
|
||||
XmlElement root = null;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (root == null && event == XMLStreamConstants.START_ELEMENT) {
|
||||
root = readElementTree(r);
|
||||
}
|
||||
}
|
||||
return root;
|
||||
} finally {
|
||||
r.close();
|
||||
}
|
||||
} catch (XMLStreamException e) {
|
||||
LOG.debugv("Ignoring malformed XML document: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static XmlElement readElementTree(XMLStreamReader r) throws XMLStreamException {
|
||||
String name = r.getLocalName();
|
||||
StringBuilder text = new StringBuilder();
|
||||
|
||||
@@ -111,7 +111,7 @@ public class S3Controller {
|
||||
private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
.withZone(ZoneId.of("UTC"));
|
||||
private static final DateTimeFormatter RFC_822 = DateTimeFormatter
|
||||
static final DateTimeFormatter RFC_822 = DateTimeFormatter
|
||||
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
|
||||
.withZone(ZoneId.of("GMT"));
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
@@ -2939,6 +2939,7 @@ public class S3Controller {
|
||||
appendSseCustomerHeaders(resp, obj);
|
||||
appendChecksumHeaders(resp, obj.getChecksum());
|
||||
appendLockHeaders(resp, obj);
|
||||
appendExpirationHeader(resp, obj);
|
||||
}
|
||||
|
||||
// includeChecksum must be false for a range the stored checksum does not describe:
|
||||
@@ -2983,6 +2984,14 @@ public class S3Controller {
|
||||
appendChecksumHeaders(resp, obj.getChecksum());
|
||||
}
|
||||
appendLockHeaders(resp, obj);
|
||||
appendExpirationHeader(resp, obj);
|
||||
}
|
||||
|
||||
private void appendExpirationHeader(Response.ResponseBuilder resp, S3Object obj) {
|
||||
String expiration = s3Service.expirationHeader(obj);
|
||||
if (expiration != null) {
|
||||
resp.header("x-amz-expiration", expiration);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendSseCustomerHeaders(Response.ResponseBuilder resp, S3Object obj) {
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser.XmlElement;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The expiration actions of a bucket's lifecycle configuration, read the way S3 applies them.
|
||||
*
|
||||
* <p>PutBucketLifecycleConfiguration stores the body verbatim, so this is parsed when it is used,
|
||||
* and a body or rule S3 would have refused is ignored rather than failing the request or the
|
||||
* sweep that reads it (see {@link #parse}). Disabled rules are dropped. Transition actions are not
|
||||
* modelled.
|
||||
*/
|
||||
record S3LifecycleConfiguration(List<Rule> rules) {
|
||||
|
||||
static final S3LifecycleConfiguration EMPTY = new S3LifecycleConfiguration(List.of());
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(S3LifecycleConfiguration.class);
|
||||
|
||||
/** NewerNoncurrentVersions: "You can specify up to 100 noncurrent versions to retain." */
|
||||
private static final int MAX_NEWER_NONCURRENT_VERSIONS = 100;
|
||||
|
||||
// Date is ISO 8601 on the wire. The leniency covers bodies Floci writes itself, such as a
|
||||
// CloudFormation ExpirationDate passed through as the template spelled it.
|
||||
private static final List<Function<String, Instant>> DATE_PARSERS = List.of(
|
||||
text -> OffsetDateTime.parse(text).toInstant(),
|
||||
text -> LocalDateTime.parse(text).toInstant(ZoneOffset.UTC),
|
||||
text -> LocalDate.parse(text).atStartOfDay(ZoneOffset.UTC).toInstant());
|
||||
|
||||
record Rule(String id, Filter filter, Expiration expiration,
|
||||
NoncurrentVersionExpiration noncurrentVersionExpiration, Integer abortDaysAfterInitiation) {
|
||||
}
|
||||
|
||||
/** A rule's filter: every condition that is set must hold. An empty filter matches everything. */
|
||||
record Filter(String prefix, Map<String, String> tags, Long objectSizeGreaterThan, Long objectSizeLessThan) {
|
||||
|
||||
boolean matches(String key, Map<String, String> objectTags, long size) {
|
||||
if (!key.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, String> tag : tags.entrySet()) {
|
||||
String value = objectTags == null ? null : objectTags.get(tag.getKey());
|
||||
if (!tag.getValue().equals(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Both size bounds are exclusive.
|
||||
return (objectSizeGreaterThan == null || size > objectSizeGreaterThan)
|
||||
&& (objectSizeLessThan == null || size < objectSizeLessThan);
|
||||
}
|
||||
|
||||
/**
|
||||
* An in-progress multipart upload has no tags or size to test, and S3 refuses
|
||||
* AbortIncompleteMultipartUpload under a tag filter, so only a prefix selects uploads.
|
||||
*/
|
||||
boolean selectsUpload(String key) {
|
||||
return tags.isEmpty() && objectSizeGreaterThan == null && objectSizeLessThan == null
|
||||
&& key.startsWith(prefix);
|
||||
}
|
||||
}
|
||||
|
||||
record Expiration(Integer days, Instant date, boolean expiredObjectDeleteMarker) {
|
||||
|
||||
/** When something created at {@code created} expires under this action, or null if it sets no age. */
|
||||
Instant expiresAt(Instant created) {
|
||||
if (days != null) {
|
||||
return afterDays(created, days);
|
||||
}
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
record NoncurrentVersionExpiration(Integer noncurrentDays, Integer newerNoncurrentVersions) {
|
||||
}
|
||||
|
||||
/** The earliest current-version expiration that applies to an object, and the rule that sets it. */
|
||||
record Expiry(Instant date, String ruleId) {
|
||||
|
||||
/**
|
||||
* The {@code x-amz-expiration} header value, in the shape the S3 API reference shows,
|
||||
* {@code expiry-date="Fri, 23 Dec 2012 00:00:00 GMT", rule-id="1"}, with the rule id
|
||||
* URL-encoded as the reference requires.
|
||||
*/
|
||||
String header() {
|
||||
return "expiry-date=\"" + S3Controller.RFC_822.format(date) + "\", rule-id=\""
|
||||
+ SigV4Canonicalization.uriEncode(ruleId == null ? "" : ruleId) + "\"";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Day-based lifecycle times run from a start time: "Amazon S3 calculates the time by adding
|
||||
* the number of days specified in the rule to the object creation time and rounding up the
|
||||
* resulting time to the next day at midnight UTC."
|
||||
*/
|
||||
static Instant afterDays(Instant start, int days) {
|
||||
return start.plus(days, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* The earliest Days or Date expiration among the rules that match a current object version,
|
||||
* or null when none does.
|
||||
*/
|
||||
Expiry currentVersionExpiry(String key, Map<String, String> tags, long size, Instant created) {
|
||||
Expiry earliest = null;
|
||||
for (Rule rule : rules) {
|
||||
if (rule.expiration() == null || !rule.filter().matches(key, tags, size)) {
|
||||
continue;
|
||||
}
|
||||
Instant at = rule.expiration().expiresAt(created);
|
||||
if (at != null && (earliest == null || at.isBefore(earliest.date()))) {
|
||||
earliest = new Expiry(at, rule.id());
|
||||
}
|
||||
}
|
||||
return earliest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a delete marker that is the only version of its key, an expired object delete
|
||||
* marker, is due for removal. ExpiredObjectDeleteMarker removes it at once; a Days or Date
|
||||
* expiration removes it once the marker itself is old enough.
|
||||
*/
|
||||
boolean removesExpiredObjectDeleteMarker(String key, Instant markerCreated, Instant now) {
|
||||
for (Rule rule : rules) {
|
||||
Expiration expiration = rule.expiration();
|
||||
if (expiration == null || !rule.filter().matches(key, Map.of(), 0)) {
|
||||
continue;
|
||||
}
|
||||
if (expiration.expiredObjectDeleteMarker()) {
|
||||
return true;
|
||||
}
|
||||
Instant at = expiration.expiresAt(markerCreated);
|
||||
if (at != null && !now.isBefore(at)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a noncurrent version is due for permanent deletion: it has been noncurrent, counted
|
||||
* from when its successor was created, for NoncurrentDays, and at least
|
||||
* NewerNoncurrentVersions newer noncurrent versions are retained ahead of it.
|
||||
*/
|
||||
boolean expiresNoncurrentVersion(String key, Map<String, String> tags, long size,
|
||||
Instant becameNoncurrent, int newerNoncurrentVersions, Instant now) {
|
||||
for (Rule rule : rules) {
|
||||
NoncurrentVersionExpiration action = rule.noncurrentVersionExpiration();
|
||||
if (action == null || !rule.filter().matches(key, tags, size)) {
|
||||
continue;
|
||||
}
|
||||
if (action.noncurrentDays() == null && action.newerNoncurrentVersions() == null) {
|
||||
continue;
|
||||
}
|
||||
boolean oldEnough = action.noncurrentDays() == null
|
||||
|| !now.isBefore(afterDays(becameNoncurrent, action.noncurrentDays()));
|
||||
boolean beyondRetained = action.newerNoncurrentVersions() == null
|
||||
|| newerNoncurrentVersions >= action.newerNoncurrentVersions();
|
||||
if (oldEnough && beyondRetained) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether an incomplete multipart upload for {@code key} initiated at {@code initiated} is due to be aborted. */
|
||||
boolean abortsUpload(String key, Instant initiated, Instant now) {
|
||||
for (Rule rule : rules) {
|
||||
Integer days = rule.abortDaysAfterInitiation();
|
||||
if (days != null && rule.filter().selectsUpload(key) && !now.isBefore(afterDays(initiated, days))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a stored configuration. A body that is not one well-formed LifecycleConfiguration
|
||||
* document has no rules. A rule that S3 would have refused on put, such as {@code Days} 0 or a
|
||||
* size bound that is not a number, is dropped whole rather than read without the bad value, so
|
||||
* a bad value never widens what the rule deletes. The other rules still apply.
|
||||
*/
|
||||
static S3LifecycleConfiguration parse(String xml) {
|
||||
XmlElement root = XmlParser.parseDocumentElementTree(xml);
|
||||
if (root == null || !"LifecycleConfiguration".equals(root.name())) {
|
||||
return EMPTY;
|
||||
}
|
||||
List<Rule> rules = new ArrayList<>();
|
||||
for (XmlElement element : root.children()) {
|
||||
if (!"Rule".equals(element.name()) || "Disabled".equals(text(element, "Status"))) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
rules.add(rule(element));
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("Ignoring lifecycle rule {0}: {1}", text(element, "ID"), e.getMessage());
|
||||
}
|
||||
}
|
||||
return new S3LifecycleConfiguration(List.copyOf(rules));
|
||||
}
|
||||
|
||||
private static Rule rule(XmlElement rule) {
|
||||
String status = text(rule, "Status");
|
||||
if (!"Enabled".equals(status)) {
|
||||
throw new IllegalArgumentException("Status is " + status + ", not Enabled or Disabled");
|
||||
}
|
||||
NoncurrentVersionExpiration noncurrent = noncurrentVersionExpiration(rule.child("NoncurrentVersionExpiration"));
|
||||
if (noncurrent != null && noncurrent.newerNoncurrentVersions() != null && rule.child("Filter") == null) {
|
||||
// The user guide: "If you don't specify a <Filter> element, Amazon S3 generates an
|
||||
// InvalidRequest error when you specify the number of noncurrent versions to retain."
|
||||
throw new IllegalArgumentException("NewerNoncurrentVersions needs a Filter");
|
||||
}
|
||||
return new Rule(text(rule, "ID"), filter(rule), expiration(rule.child("Expiration")), noncurrent,
|
||||
abortDaysAfterInitiation(rule.child("AbortIncompleteMultipartUpload")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule's Filter, or the deprecated rule-level Prefix that predates it: "Filter is required
|
||||
* if the LifecycleRule does not contain a Prefix element." An empty Filter applies to the whole
|
||||
* bucket.
|
||||
*/
|
||||
private static Filter filter(XmlElement rule) {
|
||||
XmlElement filter = rule.child("Filter");
|
||||
if (filter == null) {
|
||||
String prefix = text(rule, "Prefix");
|
||||
if (prefix == null) {
|
||||
throw new IllegalArgumentException("a rule needs a Filter or a Prefix");
|
||||
}
|
||||
return new Filter(prefix, Map.of(), null, null);
|
||||
}
|
||||
XmlElement and = filter.child("And");
|
||||
XmlElement conditions = and != null ? and : filter;
|
||||
String prefix = text(conditions, "Prefix");
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (XmlElement tag : conditions.children()) {
|
||||
if ("Tag".equals(tag.name())) {
|
||||
String key = text(tag, "Key");
|
||||
String value = text(tag, "Value");
|
||||
if (key == null || value == null) {
|
||||
throw new IllegalArgumentException("a Tag needs both a Key and a Value");
|
||||
}
|
||||
// "When you specify multiple tags in a filter, each tag key must be unique."
|
||||
if (tags.put(key, value) != null) {
|
||||
throw new IllegalArgumentException("tag key " + key + " appears twice");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Filter(prefix == null ? "" : prefix, Map.copyOf(tags),
|
||||
size(conditions, "ObjectSizeGreaterThan"), size(conditions, "ObjectSizeLessThan"));
|
||||
}
|
||||
|
||||
private static Expiration expiration(XmlElement element) {
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
Integer days = positiveInteger(element, "Days");
|
||||
String dateText = text(element, "Date");
|
||||
Instant date = dateText == null ? null : date(dateText);
|
||||
String deleteMarkerText = text(element, "ExpiredObjectDeleteMarker");
|
||||
if (deleteMarkerText != null && (days != null || date != null)) {
|
||||
throw new IllegalArgumentException("ExpiredObjectDeleteMarker cannot be specified with Days or Date");
|
||||
}
|
||||
boolean deleteMarker = deleteMarkerText != null && bool(deleteMarkerText, "ExpiredObjectDeleteMarker");
|
||||
if (days == null && date == null && !deleteMarker) {
|
||||
return null;
|
||||
}
|
||||
return new Expiration(days, date, deleteMarker);
|
||||
}
|
||||
|
||||
private static NoncurrentVersionExpiration noncurrentVersionExpiration(XmlElement element) {
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
Integer newer = integer(element, "NewerNoncurrentVersions");
|
||||
if (newer != null && (newer < 1 || newer > MAX_NEWER_NONCURRENT_VERSIONS)) {
|
||||
throw new IllegalArgumentException("NewerNoncurrentVersions " + newer + " is not between 1 and 100");
|
||||
}
|
||||
return new NoncurrentVersionExpiration(positiveInteger(element, "NoncurrentDays"), newer);
|
||||
}
|
||||
|
||||
private static Integer abortDaysAfterInitiation(XmlElement element) {
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
Integer days = integer(element, "DaysAfterInitiation");
|
||||
if (days != null && days < 0) {
|
||||
throw new IllegalArgumentException("DaysAfterInitiation " + days + " is negative");
|
||||
}
|
||||
return days;
|
||||
}
|
||||
|
||||
private static String text(XmlElement parent, String childName) {
|
||||
XmlElement child = parent.child(childName);
|
||||
return child == null ? null : child.text();
|
||||
}
|
||||
|
||||
/** Days and NoncurrentDays: "The value must be a non-zero positive integer." */
|
||||
private static Integer positiveInteger(XmlElement parent, String childName) {
|
||||
Integer value = integer(parent, childName);
|
||||
if (value != null && value < 1) {
|
||||
throw new IllegalArgumentException(childName + " " + value + " is not a positive integer");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** An absent element is null; one whose text is not an integer makes the rule invalid. */
|
||||
private static Integer integer(XmlElement parent, String childName) {
|
||||
String text = text(parent, childName);
|
||||
return text == null ? null : Integer.valueOf(text);
|
||||
}
|
||||
|
||||
private static Long size(XmlElement parent, String childName) {
|
||||
String text = text(parent, childName);
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
long value = Long.parseLong(text);
|
||||
if (value < 0) {
|
||||
throw new IllegalArgumentException(childName + " " + value + " is negative");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static boolean bool(String text, String name) {
|
||||
if ("true".equalsIgnoreCase(text)) {
|
||||
return true;
|
||||
}
|
||||
if ("false".equalsIgnoreCase(text)) {
|
||||
return false;
|
||||
}
|
||||
throw new IllegalArgumentException(name + " " + text + " is not true or false");
|
||||
}
|
||||
|
||||
private static Instant date(String text) {
|
||||
for (Function<String, Instant> parser : DATE_PARSERS) {
|
||||
try {
|
||||
return parser.apply(text);
|
||||
} catch (DateTimeParseException ignored) {
|
||||
// Not this shape; try the next one.
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Date " + text + " is not an ISO 8601 date");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Applies bucket lifecycle expiration rules from one background thread. S3 evaluates lifecycle
|
||||
* asynchronously rather than on each request, so a sweep over every bucket with a lifecycle
|
||||
* configuration on a fixed interval matches that, and leaves nothing to reconcile after a restart.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class S3LifecycleSweeper {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(S3LifecycleSweeper.class);
|
||||
|
||||
/** Used when the configured interval is not a positive number of seconds. */
|
||||
static final long DEFAULT_INTERVAL_SECONDS = 60L;
|
||||
|
||||
private final S3Service s3Service;
|
||||
private final Clock clock;
|
||||
private final boolean enabled;
|
||||
private final long intervalSeconds;
|
||||
private final ScheduledExecutorService executor;
|
||||
|
||||
/**
|
||||
* S3 stamps objects with {@code Instant.now()}, so the sweep reads the same system clock, not
|
||||
* the injectable {@link Clock} that tests pin to a fixed date.
|
||||
*/
|
||||
@Inject
|
||||
public S3LifecycleSweeper(S3Service s3Service, EmulatorConfig config) {
|
||||
this(s3Service, config, Clock.systemUTC());
|
||||
}
|
||||
|
||||
S3LifecycleSweeper(S3Service s3Service, EmulatorConfig config, Clock clock) {
|
||||
this.s3Service = s3Service;
|
||||
this.clock = clock;
|
||||
this.enabled = config.services().s3().enabled() && config.services().s3().lifecycleSweepEnabled();
|
||||
this.intervalSeconds = resolveInterval(config.services().s3().lifecycleSweepIntervalSeconds());
|
||||
this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable, "s3-lifecycle-sweeper");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
/** A non-positive interval would throw from the startup observer and keep the emulator from becoming ready. */
|
||||
private static long resolveInterval(long configured) {
|
||||
if (configured > 0) {
|
||||
return configured;
|
||||
}
|
||||
LOG.warnv("Ignoring S3 lifecycle-sweep interval {0}s: must be a positive number of seconds, "
|
||||
+ "falling back to {1}s", configured, DEFAULT_INTERVAL_SECONDS);
|
||||
return DEFAULT_INTERVAL_SECONDS;
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent event) {
|
||||
if (!enabled) {
|
||||
LOG.debug("S3 lifecycle sweeper disabled");
|
||||
return;
|
||||
}
|
||||
executor.scheduleWithFixedDelay(this::sweep, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
|
||||
LOG.debugv("S3 lifecycle sweeper started, interval {0}s", intervalSeconds);
|
||||
}
|
||||
|
||||
void onStop(@Observes ShutdownEvent event) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
|
||||
void sweep() {
|
||||
try {
|
||||
s3Service.applyLifecycleExpiration(clock.instant());
|
||||
} catch (RuntimeException e) {
|
||||
// A sweep failure must not kill the scheduled task. The next run retries.
|
||||
LOG.error("S3 lifecycle sweep failed", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
@@ -72,6 +73,7 @@ import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
@@ -81,6 +83,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
@@ -1936,7 +1939,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// so a concurrent overwrite cannot land between the check and the delete.
|
||||
synchronized (bucket) {
|
||||
checkDeletePrecondition(bucketName, key, ifMatch);
|
||||
return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance);
|
||||
return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance, OBJECT_REMOVED_EVENT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1989,8 +1992,13 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes as DeleteObject does. {@code removalEvent} is the notification event family the
|
||||
* deletion is reported under: {@code ObjectRemoved} for a request, {@code LifecycleExpiration}
|
||||
* when a lifecycle rule expires the object.
|
||||
*/
|
||||
private S3Object deleteObjectLocked(Bucket bucket, String bucketName, String key,
|
||||
String versionId, boolean bypassGovernance) {
|
||||
String versionId, boolean bypassGovernance, String removalEvent) {
|
||||
if (bucket.isVersioningEnabled() && versionId == null) {
|
||||
// Check lock on current latest before placing a delete marker
|
||||
objectStore.get(objectKey(bucketName, key)).ifPresent(prev -> {
|
||||
@@ -2005,6 +2013,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
deleteMarker.setVersionId(markerId);
|
||||
deleteMarker.setDeleteMarker(true);
|
||||
deleteMarker.setLatest(true);
|
||||
deleteMarker.setEventSequencer(nextEventSequencer());
|
||||
|
||||
// Mark previous latest as not latest
|
||||
objectStore.get(objectKey(bucketName, key)).ifPresent(prev -> {
|
||||
@@ -2022,7 +2031,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
objectStore.put(versionedKey(bucketName, key, markerId), deleteMarker);
|
||||
objectStore.put(objectKey(bucketName, key), deleteMarker);
|
||||
LOG.debugv("Created delete marker: {0}/{1} v={2}", bucketName, key, markerId);
|
||||
fireNotifications(bucketName, key, "ObjectRemoved:DeleteMarkerCreated", deleteMarker);
|
||||
fireNotifications(bucketName, key, removalEvent + ":DeleteMarkerCreated", deleteMarker);
|
||||
return deleteMarker;
|
||||
} else if ("null".equals(versionId)) {
|
||||
// A null version is stored at the plain object key until a versioned write replaces it.
|
||||
@@ -2037,7 +2046,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
deleteFile(bucketName, key);
|
||||
deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null));
|
||||
LOG.debugv("Permanently deleted null version: {0}/{1}", bucketName, key);
|
||||
fireNotifications(bucketName, key, "ObjectRemoved:Delete", null);
|
||||
fireNotifications(bucketName, key, removalEvent + ":Delete", null);
|
||||
return existing;
|
||||
} else if (versionId != null) {
|
||||
// Get the specific version before permanent deletion
|
||||
@@ -2061,7 +2070,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
deleteFile(bucketName, key);
|
||||
} else {
|
||||
S3Object newLatest = remaining.stream()
|
||||
.max(Comparator.comparing(S3Object::getLastModified))
|
||||
.max(WRITE_ORDER)
|
||||
.orElseThrow();
|
||||
// The promoted version's body becomes current before its metadata is
|
||||
// published, the order storeObjectInternal writes in, so a concurrent GET
|
||||
@@ -2080,7 +2089,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
});
|
||||
if (toDelete != null) {
|
||||
fireNotifications(bucketName, key, "ObjectRemoved:Delete", toDelete);
|
||||
fireNotifications(bucketName, key, removalEvent + ":Delete", toDelete);
|
||||
}
|
||||
return toDelete;
|
||||
} else {
|
||||
@@ -2094,7 +2103,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
deleteFile(bucketName, key);
|
||||
deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null));
|
||||
LOG.debugv("Deleted object: {0}/{1}", bucketName, key);
|
||||
fireNotifications(bucketName, key, "ObjectRemoved:Delete", null);
|
||||
fireNotifications(bucketName, key, removalEvent + ":Delete", null);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2652,11 +2661,11 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
Collections.sort(commonPrefixes);
|
||||
}
|
||||
|
||||
// Sort by key, then by lastModified descending
|
||||
// Sort by key, then newest first
|
||||
versions.sort((a, b) -> {
|
||||
int keyCompare = a.getKey().compareTo(b.getKey());
|
||||
if (keyCompare != 0) return keyCompare;
|
||||
return b.getLastModified().compareTo(a.getLastModified());
|
||||
return WRITE_ORDER.compare(b, a);
|
||||
});
|
||||
|
||||
// Apply the marker filter. Without a version-id-marker the marker is an exclusive lower bound on the
|
||||
@@ -2791,11 +2800,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// --- Object Tagging ---
|
||||
|
||||
public void putObjectTagging(String bucketName, String key, Map<String, String> tags) {
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, null);
|
||||
S3Object obj = ownedObject.value();
|
||||
obj.setTags(tags != null ? tags : new java.util.HashMap<>());
|
||||
putObjectMetadataForAccount(ownedObject.account(), bucketName, key, obj);
|
||||
setCurrentObjectTags(bucketName, key, tags != null ? tags : new HashMap<>());
|
||||
LOG.debugv("Put tags on object: {0}/{1}", bucketName, key);
|
||||
}
|
||||
|
||||
@@ -2810,11 +2815,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteObjectTagging(String bucketName, String key) {
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, null);
|
||||
S3Object obj = ownedObject.value();
|
||||
obj.setTags(new java.util.HashMap<>());
|
||||
putObjectMetadataForAccount(ownedObject.account(), bucketName, key, obj);
|
||||
setCurrentObjectTags(bucketName, key, new HashMap<>());
|
||||
LOG.debugv("Deleted tags from object: {0}/{1}", bucketName, key);
|
||||
}
|
||||
|
||||
@@ -4919,24 +4920,348 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
return new LifecycleConfigurationResult(bucket.getLifecycleConfiguration(), size);
|
||||
}
|
||||
|
||||
/**
|
||||
* The lifecycle configuration changes under the bucket monitor the lifecycle sweep applies rules
|
||||
* under, so a sweep never expires an object by a rule that was replaced or removed before it acted.
|
||||
*/
|
||||
public String putBucketLifecycle(String bucketName, String lifecycle, String transitionDefaultMinimumObjectSize) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
bucket.setLifecycleConfiguration(lifecycle);
|
||||
String size = (transitionDefaultMinimumObjectSize == null || transitionDefaultMinimumObjectSize.isBlank())
|
||||
? DEFAULT_TRANSITION_DEFAULT_MIN_OBJECT_SIZE
|
||||
: transitionDefaultMinimumObjectSize;
|
||||
bucket.setTransitionDefaultMinimumObjectSize(size);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
synchronized (bucket) {
|
||||
bucket.setLifecycleConfiguration(lifecycle);
|
||||
bucket.setTransitionDefaultMinimumObjectSize(size);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
public void deleteBucketLifecycle(String bucketName) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
bucket.setLifecycleConfiguration(null);
|
||||
bucket.setTransitionDefaultMinimumObjectSize(null);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
synchronized (bucket) {
|
||||
bucket.setLifecycleConfiguration(null);
|
||||
bucket.setTransitionDefaultMinimumObjectSize(null);
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
}
|
||||
|
||||
private static final String OBJECT_REMOVED_EVENT = "ObjectRemoved";
|
||||
private static final String LIFECYCLE_EXPIRATION_EVENT = "LifecycleExpiration";
|
||||
|
||||
/**
|
||||
* The versions of one key in the order they were written: by last-modified time, then by the
|
||||
* sequencer each write takes under the bucket lock, so versions stored within one millisecond
|
||||
* keep their order. The sequencer is not persisted, so across a restart such versions fall back
|
||||
* to version id order, which is at least the same on every read.
|
||||
*/
|
||||
private static final Comparator<S3Object> WRITE_ORDER = Comparator
|
||||
.comparing(S3Object::getLastModified)
|
||||
.thenComparing(S3Object::getEventSequencer, Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||
.thenComparing(S3Object::getVersionId, Comparator.nullsFirst(Comparator.naturalOrder()));
|
||||
|
||||
/**
|
||||
* The {@code x-amz-expiration} header for an object being returned or just written: the
|
||||
* earliest expiration an enabled rule's Days or Date sets for it, and that rule's id. Null
|
||||
* when no rule applies. Only the current version carries the header.
|
||||
*/
|
||||
public String expirationHeader(S3Object object) {
|
||||
if (object == null || object.getBucketName() == null || object.isDeleteMarker() || !object.isLatest()) {
|
||||
return null;
|
||||
}
|
||||
String lifecycle = resolveBucket(object.getBucketName()).map(Bucket::getLifecycleConfiguration).orElse(null);
|
||||
if (lifecycle == null) {
|
||||
return null;
|
||||
}
|
||||
S3LifecycleConfiguration.Expiry expiry = S3LifecycleConfiguration.parse(lifecycle).currentVersionExpiry(
|
||||
object.getKey(), object.getTags(), object.getSize(), object.getLastModified());
|
||||
return expiry == null ? null : expiry.header();
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the expiration actions of every bucket's lifecycle configuration as they stand at
|
||||
* {@code now}, each bucket in its owning account. S3 runs lifecycle asynchronously, so this is
|
||||
* driven by {@link S3LifecycleSweeper} rather than by requests. A bucket that fails does not
|
||||
* hold back the others, and the run then fails with every bucket's error, so a sweep that went
|
||||
* wrong never looks like one that completed.
|
||||
*/
|
||||
void applyLifecycleExpiration(Instant now) {
|
||||
Map<String, List<AccountAwareStorageBackend.AccountEntry<Bucket>>> byAccount = new LinkedHashMap<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Bucket> entry : bucketsInEveryAccount()) {
|
||||
if (entry.value().getLifecycleConfiguration() != null) {
|
||||
byAccount.computeIfAbsent(entry.accountId(), accountId -> new ArrayList<>()).add(entry);
|
||||
}
|
||||
}
|
||||
List<String> failedBuckets = new ArrayList<>();
|
||||
List<RuntimeException> failures = new ArrayList<>();
|
||||
byAccount.forEach((accountId, buckets) -> {
|
||||
Set<String> bucketNames = new HashSet<>();
|
||||
buckets.forEach(entry -> bucketNames.add(entry.key()));
|
||||
Map<String, Map<String, KeyHistory>> histories;
|
||||
try {
|
||||
histories = RequestScopes.callAs(accountId, () -> keyHistories(bucketNames));
|
||||
} catch (RuntimeException e) {
|
||||
failedBuckets.addAll(bucketNames);
|
||||
failures.add(e);
|
||||
return;
|
||||
}
|
||||
for (AccountAwareStorageBackend.AccountEntry<Bucket> entry : buckets) {
|
||||
try {
|
||||
RequestScopes.runAs(accountId, entry.value().getRegion(), () -> applyLifecycleExpiration(
|
||||
entry.key(), histories.getOrDefault(entry.key(), Map.of()), now));
|
||||
} catch (RuntimeException e) {
|
||||
failedBuckets.add(entry.key());
|
||||
failures.add(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!failures.isEmpty()) {
|
||||
IllegalStateException failure = new IllegalStateException(
|
||||
"S3 lifecycle sweep failed for buckets " + failedBuckets);
|
||||
failures.forEach(failure::addSuppressed);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private List<AccountAwareStorageBackend.AccountEntry<Bucket>> bucketsInEveryAccount() {
|
||||
if (bucketStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<Bucket> typed = (AccountAwareStorageBackend<Bucket>) aware;
|
||||
return typed.scanAllAccountEntries(bucketName -> true);
|
||||
}
|
||||
List<AccountAwareStorageBackend.AccountEntry<Bucket>> buckets = new ArrayList<>();
|
||||
for (String bucketName : bucketStore.keys()) {
|
||||
bucketStore.get(bucketName).ifPresent(bucket ->
|
||||
buckets.add(new AccountAwareStorageBackend.AccountEntry<>(null, bucketName, bucket)));
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
/** One key's stored entries: the entry at the plain key, null when there is none, and every versioned entry. */
|
||||
private record KeyHistory(S3Object current, List<S3Object> versions) { }
|
||||
|
||||
/** What a sweep does to one key: permanently delete these versions, then expire the current one or not. */
|
||||
private record LifecyclePlan(List<String> versionsToDelete, boolean expireCurrent) {
|
||||
boolean isEmpty() {
|
||||
return versionsToDelete.isEmpty() && !expireCurrent;
|
||||
}
|
||||
}
|
||||
|
||||
/** A bucket's lifecycle rules, parsed again only when its stored configuration has changed. */
|
||||
private static final class LifecycleRules {
|
||||
private String xml;
|
||||
private S3LifecycleConfiguration rules = S3LifecycleConfiguration.EMPTY;
|
||||
|
||||
S3LifecycleConfiguration of(Bucket bucket) {
|
||||
String stored = bucket.getLifecycleConfiguration();
|
||||
if (!Objects.equals(stored, xml)) {
|
||||
xml = stored;
|
||||
rules = S3LifecycleConfiguration.parse(stored);
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
}
|
||||
|
||||
private void applyLifecycleExpiration(String bucketName, Map<String, KeyHistory> histories, Instant now) {
|
||||
Bucket bucket = bucketStore.get(bucketName).orElse(null);
|
||||
LifecycleRules rules = new LifecycleRules();
|
||||
if (bucket == null || rules.of(bucket).rules().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// Each key is planned from the unlocked snapshot, then read again, planned again and applied
|
||||
// under the bucket monitor. Writes, tagging, Object Lock changes and lifecycle configuration
|
||||
// changes hold the same monitor, so what is applied is what the key and the rules are now.
|
||||
for (Map.Entry<String, KeyHistory> entry : histories.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
if (planLifecycle(rules.of(bucket), key, entry.getValue(), now).isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
synchronized (bucket) {
|
||||
if (bucketStore.get(bucketName).orElse(null) != bucket) {
|
||||
return;
|
||||
}
|
||||
KeyHistory history = rereadKeyHistory(bucketName, key, entry.getValue());
|
||||
if (history == null) {
|
||||
continue;
|
||||
}
|
||||
LifecyclePlan plan = planLifecycle(rules.of(bucket), key, history, now);
|
||||
for (String versionId : plan.versionsToDelete()) {
|
||||
expireByLifecycle(bucket, bucketName, key, versionId);
|
||||
}
|
||||
if (plan.expireCurrent()) {
|
||||
expireByLifecycle(bucket, bucketName, key, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
abortIncompleteMultipartUploads(bucket, bucketName, rules, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every key of the named buckets in the current account, from one pass over the object store.
|
||||
* A key with versions but no plain-key entry is included: a versioning-suspended bucket leaves
|
||||
* one after DeleteObject.
|
||||
*/
|
||||
private Map<String, Map<String, KeyHistory>> keyHistories(Set<String> bucketNames) {
|
||||
Map<String, Map<String, S3Object>> currents = new HashMap<>();
|
||||
Map<String, Map<String, List<S3Object>>> versions = new HashMap<>();
|
||||
for (String storeKey : objectStore.keys()) {
|
||||
int slash = storeKey.indexOf('/');
|
||||
String bucketName = slash < 0 ? null : storeKey.substring(0, slash);
|
||||
if (!bucketNames.contains(bucketName)) {
|
||||
continue;
|
||||
}
|
||||
S3Object stored = objectStore.get(storeKey).orElse(null);
|
||||
if (stored == null) {
|
||||
continue;
|
||||
}
|
||||
if (storeKey.equals(objectKey(bucketName, stored.getKey()))) {
|
||||
currents.computeIfAbsent(bucketName, name -> new HashMap<>()).put(stored.getKey(), stored);
|
||||
} else {
|
||||
versions.computeIfAbsent(bucketName, name -> new HashMap<>())
|
||||
.computeIfAbsent(stored.getKey(), key -> new ArrayList<>()).add(stored);
|
||||
}
|
||||
}
|
||||
Map<String, Map<String, KeyHistory>> histories = new HashMap<>();
|
||||
for (String bucketName : bucketNames) {
|
||||
Map<String, S3Object> bucketCurrents = currents.getOrDefault(bucketName, Map.of());
|
||||
Map<String, List<S3Object>> bucketVersions = versions.getOrDefault(bucketName, Map.of());
|
||||
Set<String> keys = new HashSet<>(bucketCurrents.keySet());
|
||||
keys.addAll(bucketVersions.keySet());
|
||||
Map<String, KeyHistory> bucketHistories = new TreeMap<>();
|
||||
for (String key : keys) {
|
||||
bucketHistories.put(key, new KeyHistory(bucketCurrents.get(key), bucketVersions.getOrDefault(key, List.of())));
|
||||
}
|
||||
histories.put(bucketName, bucketHistories);
|
||||
}
|
||||
return histories;
|
||||
}
|
||||
|
||||
/**
|
||||
* One key's entries as they are now, read directly at the store keys the snapshot saw, or null
|
||||
* when the key has been written since. Every write replaces the plain-key entry, so while it is
|
||||
* unchanged the key's versions are the snapshot's, less any deleted since.
|
||||
*/
|
||||
private KeyHistory rereadKeyHistory(String bucketName, String key, KeyHistory snapshot) {
|
||||
S3Object current = objectStore.get(objectKey(bucketName, key)).orElse(null);
|
||||
if (!sameWrite(current, snapshot.current())) {
|
||||
return null;
|
||||
}
|
||||
List<S3Object> versions = new ArrayList<>();
|
||||
for (S3Object version : snapshot.versions()) {
|
||||
objectStore.get(versionedKey(bucketName, key, version.getVersionId())).ifPresent(versions::add);
|
||||
}
|
||||
return new KeyHistory(current, versions);
|
||||
}
|
||||
|
||||
private static boolean sameWrite(S3Object stored, S3Object seen) {
|
||||
if (stored == null || seen == null) {
|
||||
return stored == seen;
|
||||
}
|
||||
return stored == seen
|
||||
|| (Objects.equals(stored.getVersionId(), seen.getVersionId())
|
||||
&& Objects.equals(stored.getDataGeneration(), seen.getDataGeneration())
|
||||
&& Objects.equals(stored.getLastModified(), seen.getLastModified())
|
||||
&& stored.isDeleteMarker() == seen.isDeleteMarker());
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides which lifecycle actions are due on one key. A noncurrent version has been noncurrent
|
||||
* since its successor, the next newer version, was created. Versions under Object Lock
|
||||
* retention or a legal hold are never planned for deletion.
|
||||
*
|
||||
* <p>A key with no plain-key entry has only noncurrent versions. The newest of them stopped
|
||||
* being current when its successor was deleted, a time Floci does not record, so it is not
|
||||
* aged by NoncurrentDays; it still counts as a newer version for the ones below it.
|
||||
*/
|
||||
private LifecyclePlan planLifecycle(S3LifecycleConfiguration lifecycle, String key, KeyHistory history,
|
||||
Instant now) {
|
||||
S3Object current = history.current();
|
||||
String currentVersionId = current == null ? null : current.getVersionId();
|
||||
List<S3Object> noncurrent = history.versions().stream()
|
||||
.filter(version -> current == null || !Objects.equals(version.getVersionId(), currentVersionId))
|
||||
.sorted(WRITE_ORDER.reversed())
|
||||
.toList();
|
||||
List<String> deletions = new ArrayList<>();
|
||||
Instant successorCreated = current == null ? null : current.getLastModified();
|
||||
for (int newer = 0; newer < noncurrent.size(); newer++) {
|
||||
S3Object version = noncurrent.get(newer);
|
||||
if (successorCreated != null && !lockedAgainstDeletion(version)
|
||||
&& lifecycle.expiresNoncurrentVersion(key, version.getTags(), version.getSize(),
|
||||
successorCreated, newer, now)) {
|
||||
deletions.add(version.getVersionId());
|
||||
}
|
||||
successorCreated = version.getLastModified();
|
||||
}
|
||||
if (current == null) {
|
||||
return new LifecyclePlan(deletions, false);
|
||||
}
|
||||
if (current.isDeleteMarker()) {
|
||||
if (currentVersionId != null && noncurrent.isEmpty()
|
||||
&& lifecycle.removesExpiredObjectDeleteMarker(key, current.getLastModified(), now)) {
|
||||
deletions.add(currentVersionId);
|
||||
}
|
||||
return new LifecyclePlan(deletions, false);
|
||||
}
|
||||
S3LifecycleConfiguration.Expiry expiry = lifecycle.currentVersionExpiry(
|
||||
key, current.getTags(), current.getSize(), current.getLastModified());
|
||||
return new LifecyclePlan(deletions, expiry != null && !now.isBefore(expiry.date()));
|
||||
}
|
||||
|
||||
private boolean lockedAgainstDeletion(S3Object version) {
|
||||
try {
|
||||
checkLockProtection(version, false);
|
||||
return false;
|
||||
} catch (AwsException expected) {
|
||||
// Lifecycle cannot bypass retention, so a version DeleteObject would refuse is left alone.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Expires as DeleteObject would, reported as a lifecycle expiration: a null {@code versionId}
|
||||
* expires the current version, a delete marker in a versioning-enabled bucket and a deletion
|
||||
* otherwise, and a version id deletes that version permanently.
|
||||
*/
|
||||
private void expireByLifecycle(Bucket bucket, String bucketName, String key, String versionId) {
|
||||
try {
|
||||
deleteObjectLocked(bucket, bucketName, key, versionId, false, LIFECYCLE_EXPIRATION_EVENT);
|
||||
LOG.debugv("Lifecycle expired {0}/{1} v={2}", bucketName, key, versionId);
|
||||
} catch (AwsException e) {
|
||||
// Object Lock protects the object; lifecycle leaves it in place, as on S3.
|
||||
LOG.debugv("Lifecycle left {0}/{1} v={2} in place: {3}", bucketName, key, versionId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the bucket's incomplete multipart uploads that an AbortIncompleteMultipartUpload rule
|
||||
* has made due. Each abort holds the upload's lock and then the bucket monitor, the order
|
||||
* DeleteBucket takes them in, and is applied only while the bucket is still the one the sweep
|
||||
* started on and the rules still make it due, so an upload in a bucket deleted and created again
|
||||
* under the same name is never aborted under the old bucket's rules.
|
||||
*/
|
||||
private void abortIncompleteMultipartUploads(Bucket bucket, String bucketName, LifecycleRules rules, Instant now) {
|
||||
String ownerAccountId = ownerId();
|
||||
for (MultipartUpload upload : List.copyOf(multipartUploads.values())) {
|
||||
if (!bucketName.equals(upload.getBucket())
|
||||
|| (upload.getOwnerAccountId() != null && !ownerAccountId.equals(upload.getOwnerAccountId()))
|
||||
|| upload.getInitiated() == null
|
||||
|| !rules.of(bucket).abortsUpload(upload.getKey(), upload.getInitiated(), now)) {
|
||||
continue;
|
||||
}
|
||||
withMultipartOperationLock(bucketName, upload.getUploadId(), () -> {
|
||||
synchronized (bucket) {
|
||||
if (bucketStore.get(bucketName).orElse(null) == bucket
|
||||
&& multipartUploads.get(upload.getUploadId()) == upload
|
||||
&& rules.of(bucket).abortsUpload(upload.getKey(), upload.getInitiated(), now)) {
|
||||
cleanupMultipart(upload.getUploadId());
|
||||
LOG.debugv("Lifecycle aborted multipart upload {0}/{1}, uploadId={2}",
|
||||
bucketName, upload.getKey(), upload.getUploadId());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public String getBucketAcl(String bucketName) {
|
||||
@@ -5807,9 +6132,15 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
objectNode.put("version-id", obj.getVersionId());
|
||||
}
|
||||
detail.put("request-id", UUID.randomUUID().toString());
|
||||
detail.put("requester", "aws:emulator");
|
||||
detail.put("source-ip-address", "127.0.0.1");
|
||||
detail.put("reason", eventName);
|
||||
// A lifecycle deletion is S3's own: "source-ip-address - ... Only present for events
|
||||
// triggered by an S3 request."
|
||||
if (isLifecycleEvent(eventName)) {
|
||||
detail.put("requester", ServicePrincipals.of("s3"));
|
||||
} else {
|
||||
detail.put("requester", "aws:emulator");
|
||||
detail.put("source-ip-address", "127.0.0.1");
|
||||
}
|
||||
detail.put("reason", eventBridgeReason(eventName));
|
||||
String deletionType = eventBridgeDeletionType(eventName);
|
||||
if (deletionType != null) {
|
||||
detail.put("deletion-type", deletionType);
|
||||
@@ -5820,10 +6151,19 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The EventBridge {@code reason}: {@code Lifecycle Expiration} for a deletion by a lifecycle rule. */
|
||||
private static String eventBridgeReason(String eventName) {
|
||||
return isLifecycleEvent(eventName) ? "Lifecycle Expiration" : eventName;
|
||||
}
|
||||
|
||||
private static boolean isLifecycleEvent(String eventName) {
|
||||
return eventName.startsWith(LIFECYCLE_EXPIRATION_EVENT + ":");
|
||||
}
|
||||
|
||||
private static String eventBridgeDeletionType(String eventName) {
|
||||
return switch (eventName) {
|
||||
case "ObjectRemoved:Delete" -> "Permanently Deleted";
|
||||
case "ObjectRemoved:DeleteMarkerCreated" -> "Delete Marker Created";
|
||||
case "ObjectRemoved:Delete", "LifecycleExpiration:Delete" -> "Permanently Deleted";
|
||||
case "ObjectRemoved:DeleteMarkerCreated", "LifecycleExpiration:DeleteMarkerCreated" -> "Delete Marker Created";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
@@ -5913,8 +6253,11 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
record.put("awsRegion", region);
|
||||
record.put("eventTime", eventTime);
|
||||
record.put("eventName", eventName);
|
||||
record.putObject("userIdentity").put("principalId", "AWS:EMULATOR");
|
||||
record.putObject("requestParameters").put("sourceIPAddress", "127.0.0.1");
|
||||
// The user guide's s3:LifecycleExpiration:Delete example names S3 itself as both.
|
||||
boolean lifecycle = isLifecycleEvent(eventName);
|
||||
record.putObject("userIdentity").put("principalId", lifecycle ? ServicePrincipals.of("s3") : "AWS:EMULATOR");
|
||||
record.putObject("requestParameters")
|
||||
.put("sourceIPAddress", lifecycle ? ServicePrincipals.of("s3") : "127.0.0.1");
|
||||
record.putObject("responseElements").put("x-amz-request-id", requestId);
|
||||
record.set("s3", s3Node);
|
||||
|
||||
@@ -6232,6 +6575,23 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* still refers to this object, checked under the bucket lock that puts and deletes hold, so a
|
||||
* concurrent overwrite or delete marker is never replaced by the object it superseded.
|
||||
*/
|
||||
/**
|
||||
* Replaces the current version's tags under the bucket monitor that writes, deletes and the
|
||||
* lifecycle sweep hold, so the object is resolved and rewritten in one step: the sweep never
|
||||
* sees the tags it matched a rule against change before it acts.
|
||||
*/
|
||||
private void setCurrentObjectTags(String bucketName, String key, Map<String, String> tags) {
|
||||
Bucket bucket = resolveBucket(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
synchronized (bucket) {
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, null);
|
||||
ownedObject.value().setTags(tags);
|
||||
putObjectMetadataForAccount(ownedObject.account(), bucketName, key, ownedObject.value());
|
||||
}
|
||||
}
|
||||
|
||||
private void putObjectMetadataForAccount(String accountId, String bucketName, String key, S3Object object) {
|
||||
Bucket bucket = resolveBucket(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
|
||||
Reference in new issue
Block a user