mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(s3): track archived object restore state (#8166)
* feat(s3): track archived object restore state * fix(s3): validate restore options and report version restore status
This commit is contained in:
1 parent
c3551d351e
commit
1686f29e04
11 files changed
+777
-15
No files matched your search
@@ -1553,6 +1553,10 @@ public interface EmulatorConfig {
|
||||
@WithDefault("false")
|
||||
boolean globalBucketNamespace();
|
||||
|
||||
/** Seconds before RestoreObject reports a completed temporary copy. */
|
||||
@WithDefault("0")
|
||||
long restoreCompletionDelaySeconds();
|
||||
|
||||
/**
|
||||
* Run the background sweep that applies bucket lifecycle expiration rules: Expiration,
|
||||
* NoncurrentVersionExpiration and AbortIncompleteMultipartUpload. When off, rules are
|
||||
|
||||
@@ -61,6 +61,7 @@ import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
|
||||
import javax.xml.stream.XMLStreamConstants;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
@@ -633,7 +634,7 @@ public class S3Controller {
|
||||
if (params.has("versions")) {
|
||||
s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization);
|
||||
return handleListObjectVersions(bucket, prefix, delimiter, maxKeys, keyMarker, versionIdMarker,
|
||||
encodingType);
|
||||
encodingType, httpHeaders);
|
||||
}
|
||||
if (params.has("location")) {
|
||||
s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization);
|
||||
@@ -776,6 +777,7 @@ public class S3Controller {
|
||||
List<S3Object> objects = result.objects();
|
||||
List<String> commonPrefixes = result.commonPrefixes();
|
||||
boolean v2 = "2".equals(listType);
|
||||
boolean includeRestoreStatus = includesRestoreStatus(httpHeaders);
|
||||
String bucketOwnerAccount = (v1 || Boolean.parseBoolean(params.first("fetch-owner")))
|
||||
? s3Service.getBucketOwnerAccountId(bucket) : null;
|
||||
boolean ownershipEnforced = bucketOwnerAccount != null && s3Service.bucketOwnershipIsEnforced(bucket);
|
||||
@@ -805,6 +807,9 @@ public class S3Controller {
|
||||
.elem("ETag", obj.getETag())
|
||||
.elem("Size", obj.getSize())
|
||||
.elem("StorageClass", obj.getStorageClass());
|
||||
if (includeRestoreStatus) {
|
||||
appendRestoreStatus(xml, obj);
|
||||
}
|
||||
if (bucketOwnerAccount != null) {
|
||||
xml.start("Owner")
|
||||
.elem("ID", AwsCanonicalUserId.forAccount(S3Service.effectiveObjectOwnerAccount(
|
||||
@@ -1729,8 +1734,9 @@ public class S3Controller {
|
||||
if (hasQueryParam(uriInfo, "restore")) {
|
||||
checkVersionId(bucket, ResteasyRequests.queryParameters(uriInfo).getFirst("versionId"));
|
||||
s3Service.authorizeObjectWrite(bucket, key, "s3:RestoreObject", authorization);
|
||||
s3Service.restoreObject(bucket, key, versionId, new String(body, StandardCharsets.UTF_8));
|
||||
return Response.accepted().build();
|
||||
boolean started = s3Service.restoreObject(bucket, key, versionId,
|
||||
new String(body, StandardCharsets.UTF_8));
|
||||
return started ? Response.accepted().build() : Response.ok().build();
|
||||
}
|
||||
|
||||
if (hasQueryParam(uriInfo, "select")) {
|
||||
@@ -2181,7 +2187,8 @@ public class S3Controller {
|
||||
}
|
||||
|
||||
private Response handleListObjectVersions(String bucket, String prefix, String delimiter, String maxKeys,
|
||||
String keyMarker, String versionIdMarker, String encodingType) {
|
||||
String keyMarker, String versionIdMarker, String encodingType,
|
||||
HttpHeaders httpHeaders) {
|
||||
if (hasText(versionIdMarker) && !hasText(keyMarker)) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"A version-id marker cannot be specified without a key marker.", 400);
|
||||
@@ -2189,6 +2196,7 @@ public class S3Controller {
|
||||
int max = resolveMaxKeys(maxKeys);
|
||||
S3Service.ListVersionsResult result =
|
||||
s3Service.listObjectVersions(bucket, prefix, delimiter, max, keyMarker, versionIdMarker);
|
||||
boolean includeRestoreStatus = includesRestoreStatus(httpHeaders);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
|
||||
.start("ListVersionsResult", AwsNamespaces.S3)
|
||||
@@ -2222,8 +2230,11 @@ public class S3Controller {
|
||||
.elem("LastModified", ISO_FORMAT.format(obj.getLastModified()))
|
||||
.elem("ETag", obj.getETag())
|
||||
.elem("Size", obj.getSize())
|
||||
.elem("StorageClass", obj.getStorageClass())
|
||||
.end("Version");
|
||||
.elem("StorageClass", obj.getStorageClass());
|
||||
if (includeRestoreStatus) {
|
||||
appendRestoreStatus(xml, obj);
|
||||
}
|
||||
xml.end("Version");
|
||||
}
|
||||
}
|
||||
for (String cp : result.commonPrefixes()) {
|
||||
@@ -2238,6 +2249,24 @@ public class S3Controller {
|
||||
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
|
||||
private static boolean includesRestoreStatus(HttpHeaders httpHeaders) {
|
||||
String optionalAttributes = httpHeaders.getHeaderString("x-amz-optional-object-attributes");
|
||||
return optionalAttributes != null && Arrays.stream(optionalAttributes.split(","))
|
||||
.map(String::trim).anyMatch("RestoreStatus"::equals);
|
||||
}
|
||||
|
||||
private void appendRestoreStatus(XmlBuilder xml, S3Object obj) {
|
||||
S3Service.RestoreStatus restore = s3Service.restoreStatus(obj);
|
||||
if (restore != null) {
|
||||
xml.start("RestoreStatus")
|
||||
.elem("IsRestoreInProgress", restore.inProgress());
|
||||
if (restore.expiryDate() != null) {
|
||||
xml.elem("RestoreExpiryDate", DateTimeFormatter.ISO_INSTANT.format(restore.expiryDate()));
|
||||
}
|
||||
xml.end("RestoreStatus");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Notification Configuration ---
|
||||
|
||||
private Response handleGetBucketNotification(String bucket) {
|
||||
@@ -3176,6 +3205,14 @@ public class S3Controller {
|
||||
if (obj.getStorageClass() != null) {
|
||||
resp.header("x-amz-storage-class", obj.getStorageClass());
|
||||
}
|
||||
S3Service.RestoreStatus restore = s3Service.restoreStatus(obj);
|
||||
if (restore != null) {
|
||||
String header = "ongoing-request=\"" + restore.inProgress() + "\"";
|
||||
if (restore.expiryDate() != null) {
|
||||
header += ", expiry-date=\"" + rfc822(restore.expiryDate()) + "\"";
|
||||
}
|
||||
resp.header("x-amz-restore", header);
|
||||
}
|
||||
String contentEncoding = overrides.contentEncoding() != null ? overrides.contentEncoding() : obj.getContentEncoding();
|
||||
if (contentEncoding != null) {
|
||||
resp.header("Content-Encoding", contentEncoding);
|
||||
|
||||
@@ -67,6 +67,8 @@ import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Clock;
|
||||
import java.time.DateTimeException;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -286,6 +288,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
private final IamService iamService;
|
||||
private final boolean globalBucketNamespace;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
private final Clock clock;
|
||||
private final long restoreCompletionDelaySeconds;
|
||||
|
||||
@Inject
|
||||
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
|
||||
@@ -295,7 +299,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
IamService iamService) {
|
||||
IamService iamService, Clock clock) {
|
||||
this(
|
||||
storageFactory.create("s3", "s3-buckets.json",
|
||||
new TypeReference<Map<String, Bucket>>() {
|
||||
@@ -316,10 +320,23 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
regionResolver,
|
||||
config.effectiveBaseUrl(), objectMapper,
|
||||
config.services().s3().enforceAuth(), config.services().iam().enforcementEnabled(), iamService,
|
||||
config.services().s3().globalBucketNamespace()
|
||||
config.services().s3().globalBucketNamespace(), clock,
|
||||
config.services().s3().restoreCompletionDelaySeconds()
|
||||
);
|
||||
}
|
||||
|
||||
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
|
||||
SqsService sqsService, SnsService snsService,
|
||||
Instance<LambdaService> lambdaServiceProvider,
|
||||
EventBridgeService eventBridgeService,
|
||||
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
IamService iamService) {
|
||||
this(storageFactory, config, sqsService, snsService, lambdaServiceProvider,
|
||||
eventBridgeService, s3UpdatedEvent, regionResolver, objectMapper, iamService, Clock.systemUTC());
|
||||
}
|
||||
|
||||
/**
|
||||
* Package-private constructor for testing.
|
||||
*/
|
||||
@@ -331,6 +348,15 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
|
||||
}
|
||||
|
||||
S3Service(StorageBackend<String, Bucket> bucketStore,
|
||||
StorageBackend<String, S3Object> objectStore,
|
||||
Path dataRoot, boolean inMemory, Clock clock, long restoreCompletionDelaySeconds) {
|
||||
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
|
||||
dataRoot, inMemory, null, null, null, null, null, null, null,
|
||||
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false,
|
||||
clock, restoreCompletionDelaySeconds);
|
||||
}
|
||||
|
||||
S3Service(StorageBackend<String, Bucket> bucketStore,
|
||||
StorageBackend<String, S3Object> objectStore,
|
||||
Path dataRoot, boolean inMemory,
|
||||
@@ -402,6 +428,26 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
|
||||
boolean enforceAuth, boolean enforceIam, IamService iamService,
|
||||
boolean globalBucketNamespace) {
|
||||
this(bucketStore, objectStore, annotationStore, accountPublicAccessBlockStore,
|
||||
dataRoot, inMemory, sqsService, snsService, lambdaService, lambdaServiceProvider,
|
||||
lambdaInvoker, eventBridgeService, s3UpdatedEvent, regionResolver, baseUrl,
|
||||
objectMapper, enforceAuth, enforceIam, iamService, globalBucketNamespace,
|
||||
Clock.systemUTC(), 0);
|
||||
}
|
||||
|
||||
private S3Service(StorageBackend<String, Bucket> bucketStore,
|
||||
StorageBackend<String, S3Object> objectStore,
|
||||
AccountAwareStorageBackend<ObjectAnnotation> annotationStore,
|
||||
AccountAwareStorageBackend<String> accountPublicAccessBlockStore,
|
||||
Path dataRoot, boolean inMemory, SqsService sqsService, SnsService snsService,
|
||||
LambdaService lambdaService,
|
||||
Instance<LambdaService> lambdaServiceProvider,
|
||||
LambdaInvoker lambdaInvoker,
|
||||
EventBridgeService eventBridgeService,
|
||||
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
|
||||
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
|
||||
boolean enforceAuth, boolean enforceIam, IamService iamService,
|
||||
boolean globalBucketNamespace, Clock clock, long restoreCompletionDelaySeconds) {
|
||||
this.bucketStore = bucketStore;
|
||||
this.objectStore = objectStore;
|
||||
this.annotationStore = annotationStore;
|
||||
@@ -423,6 +469,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
this.iamService = iamService;
|
||||
this.globalBucketNamespace = globalBucketNamespace;
|
||||
this.policyEvaluator = new IamPolicyEvaluator(objectMapper);
|
||||
this.clock = clock;
|
||||
this.restoreCompletionDelaySeconds = Math.max(0, restoreCompletionDelaySeconds);
|
||||
if (!inMemory) {
|
||||
try {
|
||||
Files.createDirectories(dataRoot);
|
||||
@@ -6798,10 +6846,116 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
.build();
|
||||
}
|
||||
|
||||
public void restoreObject(String bucketName, String key, String versionId, String restoreXml) {
|
||||
// Validation only - stub implementation
|
||||
getObject(bucketName, key, versionId);
|
||||
LOG.infov("Restored object: {0}/{1} (stub)", bucketName, key);
|
||||
public record RestoreStatus(boolean inProgress, Instant expiryDate) { }
|
||||
|
||||
public RestoreStatus restoreStatus(S3Object object) {
|
||||
return restoreStatus(object, clock.instant());
|
||||
}
|
||||
|
||||
private static RestoreStatus restoreStatus(S3Object object, Instant now) {
|
||||
Instant completedAt = object.getRestoreCompletionAt();
|
||||
Instant expiresAt = object.getRestoreExpiryAt();
|
||||
if (completedAt == null || expiresAt == null || !now.isBefore(expiresAt)) {
|
||||
return null;
|
||||
}
|
||||
return now.isBefore(completedAt)
|
||||
? new RestoreStatus(true, null)
|
||||
: new RestoreStatus(false, expiresAt);
|
||||
}
|
||||
|
||||
/** Returns true for a newly started restore, false when extending a completed restore. */
|
||||
public boolean restoreObject(String bucketName, String key, String versionId, String restoreXml) {
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
synchronized (ownedBucket.value()) {
|
||||
S3Object object = copyObject(requireStoredObject(ownedBucket, bucketName, key, versionId));
|
||||
int days = restoreDays(restoreXml, object.getStorageClass());
|
||||
if (!"GLACIER".equals(object.getStorageClass()) && !"DEEP_ARCHIVE".equals(object.getStorageClass())) {
|
||||
throw new AwsException("ObjectAlreadyInActiveTierError",
|
||||
"This operation is not valid for objects in the active storage tier.", 403);
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
RestoreStatus status = restoreStatus(object, now);
|
||||
if (status != null && status.inProgress()) {
|
||||
throw new AwsException("RestoreAlreadyInProgress", "Object restore is already in progress.", 409);
|
||||
}
|
||||
boolean started = status == null;
|
||||
try {
|
||||
Instant completedAt = started ? now.plusSeconds(restoreCompletionDelaySeconds) : now;
|
||||
Instant expiration = completedAt.plus(days, ChronoUnit.DAYS);
|
||||
Instant midnight = expiration.truncatedTo(ChronoUnit.DAYS);
|
||||
object.setRestoreCompletionAt(completedAt);
|
||||
// S3 rounds the temporary copy's expiry up to the next UTC midnight.
|
||||
object.setRestoreExpiryAt(expiration.equals(midnight)
|
||||
? midnight : midnight.plus(1, ChronoUnit.DAYS));
|
||||
} catch (DateTimeException | ArithmeticException e) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
putObjectMetadataForAccount(ownedBucket.account(), bucketName, key, object);
|
||||
return started;
|
||||
}
|
||||
}
|
||||
|
||||
private static int restoreDays(String restoreXml, String storageClass) {
|
||||
XmlParser.XmlElement root = XmlParser.parseDocumentElementTree(restoreXml);
|
||||
if (root == null || !"RestoreRequest".equals(root.name()) || !root.text().isEmpty()
|
||||
|| root.count("Days") != 1
|
||||
|| root.count("Type") != 0 || root.count("SelectParameters") != 0
|
||||
|| root.count("OutputLocation") != 0 || root.count("Tier") > 1
|
||||
|| root.count("GlacierJobParameters") > 1 || root.count("Description") > 1
|
||||
|| root.children().stream().anyMatch(child -> !Set.of("Days", "Tier",
|
||||
"GlacierJobParameters", "Description").contains(child.name()))) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
XmlParser.XmlElement daysElement = root.child("Days");
|
||||
if (!daysElement.children().isEmpty()) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
XmlParser.XmlElement tier = root.child("Tier");
|
||||
boolean expedited = tier != null && "Expedited".equals(tier.text());
|
||||
if (tier != null) {
|
||||
validateRestoreTier(tier);
|
||||
}
|
||||
XmlParser.XmlElement glacierJobParameters = root.child("GlacierJobParameters");
|
||||
if (glacierJobParameters != null) {
|
||||
if (!glacierJobParameters.text().isEmpty() || glacierJobParameters.children().size() != 1
|
||||
|| glacierJobParameters.count("Tier") != 1) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
XmlParser.XmlElement glacierTier = glacierJobParameters.child("Tier");
|
||||
validateRestoreTier(glacierTier);
|
||||
expedited |= "Expedited".equals(glacierTier.text());
|
||||
}
|
||||
XmlParser.XmlElement description = root.child("Description");
|
||||
if (description != null && !description.children().isEmpty()) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
if ("DEEP_ARCHIVE".equals(storageClass) && expedited) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"Expedited retrievals are not supported for S3 Glacier Deep Archive.", 400);
|
||||
}
|
||||
try {
|
||||
int days = Integer.parseInt(daysElement.text());
|
||||
if (days > 0) {
|
||||
return days;
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Fall through to the same protocol error as non-positive Days.
|
||||
}
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
|
||||
private static void validateRestoreTier(XmlParser.XmlElement tier) {
|
||||
if (!tier.children().isEmpty() || !Set.of("Standard", "Bulk", "Expedited").contains(tier.text())) {
|
||||
throw malformedRestoreRequest();
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException malformedRestoreRequest() {
|
||||
return new AwsException("MalformedXML",
|
||||
"The XML you provided was not well-formed or did not validate against our published schema.", 400);
|
||||
}
|
||||
|
||||
private static String defaultAclXml(String ownerAccount, String displayName) {
|
||||
|
||||
@@ -34,6 +34,8 @@ public class S3Object {
|
||||
private Instant lastModified;
|
||||
private String eTag;
|
||||
private String storageClass;
|
||||
private Instant restoreCompletionAt;
|
||||
private Instant restoreExpiryAt;
|
||||
private S3Checksum checksum;
|
||||
private List<Part> parts;
|
||||
private String versionId;
|
||||
@@ -110,6 +112,8 @@ public class S3Object {
|
||||
this.lastModified = source.lastModified;
|
||||
this.eTag = source.eTag;
|
||||
this.storageClass = source.storageClass;
|
||||
this.restoreCompletionAt = source.restoreCompletionAt;
|
||||
this.restoreExpiryAt = source.restoreExpiryAt;
|
||||
this.checksum = source.checksum == null ? null : source.checksum.copy();
|
||||
this.parts = Part.copyAll(source.parts);
|
||||
this.versionId = source.versionId;
|
||||
@@ -173,6 +177,12 @@ public class S3Object {
|
||||
public String getStorageClass() { return storageClass; }
|
||||
public void setStorageClass(String storageClass) { this.storageClass = storageClass; }
|
||||
|
||||
public Instant getRestoreCompletionAt() { return restoreCompletionAt; }
|
||||
public void setRestoreCompletionAt(Instant restoreCompletionAt) { this.restoreCompletionAt = restoreCompletionAt; }
|
||||
|
||||
public Instant getRestoreExpiryAt() { return restoreExpiryAt; }
|
||||
public void setRestoreExpiryAt(Instant restoreExpiryAt) { this.restoreExpiryAt = restoreExpiryAt; }
|
||||
|
||||
public S3Checksum getChecksum() { return checksum; }
|
||||
public void setChecksum(S3Checksum checksum) { this.checksum = checksum; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user