Refactor complex admin and storage methods
This commit is contained in:
1 parent
5304dfc047
commit
3c739deb09
13 files changed
+1434
-950
No files matched your search
@@ -26,6 +26,17 @@ final class AdminAccessCheck {
|
||||
Result check(String principal, String operation, String bucket, String key) throws IOException {
|
||||
if (principal == null || !identities.contains(principal))
|
||||
return new Result(false, "Authentication", "Access key is unknown or disabled");
|
||||
validateRequest(operation, bucket, key);
|
||||
try {
|
||||
checkScope(principal, operation, bucket, key);
|
||||
} catch (StoreException denied) {
|
||||
if (denied.status != 403) throw denied;
|
||||
return new Result(false, "Key scope", "Key scope does not allow this bucket, prefix, or operation");
|
||||
}
|
||||
return inspectAccess(principal, operation, bucket, key);
|
||||
}
|
||||
|
||||
private static void validateRequest(String operation, String bucket, String key) {
|
||||
if (operation == null || !Set.of("list", "read", "write", "delete").contains(operation))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported operation");
|
||||
if (bucket == null || !bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
|
||||
@@ -34,39 +45,44 @@ final class AdminAccessCheck {
|
||||
throw new StoreException(400, "InvalidArgument", "Object key or prefix is too long");
|
||||
if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024))
|
||||
throw new StoreException(400, "InvalidArgument", "Enter an object key");
|
||||
}
|
||||
|
||||
private void checkScope(String principal, String operation, String bucket, String key) {
|
||||
if (operation.equals("list")) {
|
||||
Map<String, String> query = Map.of("list-type", "2", "prefix", key == null ? "" : key);
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkBucket(principal, bucket, "GET", query);
|
||||
else scopes.checkBucket(principal, bucket, "GET", query);
|
||||
return;
|
||||
}
|
||||
String method = switch (operation) {
|
||||
case "read" -> "GET";
|
||||
case "write" -> "PUT";
|
||||
case "delete" -> "DELETE";
|
||||
default -> "GET";
|
||||
};
|
||||
try {
|
||||
if (operation.equals("list")) {
|
||||
Map<String, String> query = Map.of("list-type", "2", "prefix", key == null ? "" : key);
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkBucket(principal, bucket, method, query);
|
||||
else scopes.checkBucket(principal, bucket, method, query);
|
||||
} else {
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
}
|
||||
} catch (StoreException denied) {
|
||||
if (denied.status != 403) throw denied;
|
||||
return new Result(false, "Key scope", "Key scope does not allow this bucket, prefix, or operation");
|
||||
}
|
||||
S3Access.Decision decision;
|
||||
if (operation.equals("list")) {
|
||||
decision = access.inspectBucket(bucket, principal);
|
||||
} else if (operation.equals("read")) {
|
||||
ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null);
|
||||
if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key()))
|
||||
return new Result(false, "Object", "Current object does not exist");
|
||||
decision = access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal);
|
||||
} else {
|
||||
decision = access.inspectWrite(bucket, key, principal,
|
||||
operation.equals("delete") ? "s3:DeleteObject" : "s3:PutObject");
|
||||
}
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
}
|
||||
|
||||
private Result inspectAccess(String principal, String operation, String bucket, String key)
|
||||
throws IOException {
|
||||
return switch (operation) {
|
||||
case "list" -> policyResult(access.inspectBucket(bucket, principal));
|
||||
case "read" -> inspectRead(principal, bucket, key);
|
||||
case "delete" -> policyResult(access.inspectWrite(bucket, key, principal, "s3:DeleteObject"));
|
||||
default -> policyResult(access.inspectWrite(bucket, key, principal, "s3:PutObject"));
|
||||
};
|
||||
}
|
||||
|
||||
private Result inspectRead(String principal, String bucket, String key) throws IOException {
|
||||
ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null);
|
||||
if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key()))
|
||||
return new Result(false, "Object", "Current object does not exist");
|
||||
return policyResult(access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal));
|
||||
}
|
||||
|
||||
private static Result policyResult(S3Access.Decision decision) {
|
||||
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
|
||||
}
|
||||
}
|
||||
@@ -12,143 +12,188 @@ final class AdminActions {
|
||||
|
||||
static String apply(ObjectStorage store, String action, Map<String, String> form,
|
||||
Set<String> identities, ManagedCredentials managed) throws IOException {
|
||||
String bucket = form.get("bucket");
|
||||
if (action.equals("create-bucket")) {
|
||||
bucket = required(form, "bucket", 63);
|
||||
boolean wizard = "wizard".equals(form.get("setup"));
|
||||
String versioning = form.getOrDefault("versioning", "off");
|
||||
if (wizard && !versioning.equals("off") && !versioning.equals("enabled"))
|
||||
invalid("Invalid initial versioning setting");
|
||||
ObjectStorage.ObjectOwnership ownership = wizard ?
|
||||
BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
ObjectStorage.PublicAccessBlock publicBlock = wizard ? new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")) :
|
||||
ObjectStorage.PublicAccessBlock.secure();
|
||||
if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) &&
|
||||
!"yes".equals(form.get("acknowledgePublic")))
|
||||
invalid("Confirm that relaxing public access controls may expose this bucket");
|
||||
store.createBucket(bucket);
|
||||
if (wizard) {
|
||||
if (versioning.equals("enabled"))
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
|
||||
if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucket, ownership);
|
||||
if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()))
|
||||
store.setPublicAccessBlock(bucket, publicBlock);
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null);
|
||||
}
|
||||
bucket = required(form, "bucket", 63);
|
||||
if (action.equals("rename-bucket")) {
|
||||
confirm(form, bucket);
|
||||
String newName = required(form, "newName", 63);
|
||||
String currentName = bucket;
|
||||
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(currentName)))
|
||||
throw new StoreException(409, "BucketHasScopedKeys",
|
||||
"Move or remove scoped access keys for this bucket before renaming it");
|
||||
store.renameBucket(bucket, newName);
|
||||
return AdminBrowser.bucketUrl(newName, "", null);
|
||||
}
|
||||
if (action.equals("delete-bucket")) {
|
||||
confirm(form, bucket);
|
||||
store.deleteBucket(bucket);
|
||||
return AdminConsole.PATH + "/buckets";
|
||||
}
|
||||
String bucket = required(form, "bucket", 63);
|
||||
return switch (action) {
|
||||
case "create-bucket" -> createBucket(store, bucket, form);
|
||||
case "rename-bucket" -> renameBucket(store, bucket, form, managed);
|
||||
case "delete-bucket" -> deleteBucket(store, bucket, form);
|
||||
default -> updateBucket(store, bucket, action, form, identities);
|
||||
};
|
||||
}
|
||||
|
||||
private static String createBucket(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
boolean wizard = "wizard".equals(form.get("setup"));
|
||||
String versioning = form.getOrDefault("versioning", "off");
|
||||
if (wizard && !versioning.equals("off") && !versioning.equals("enabled"))
|
||||
invalid("Invalid initial versioning setting");
|
||||
ObjectStorage.ObjectOwnership ownership = wizard ?
|
||||
BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
ObjectStorage.PublicAccessBlock publicBlock = wizard ? publicAccessBlock(form) :
|
||||
ObjectStorage.PublicAccessBlock.secure();
|
||||
if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) &&
|
||||
!"yes".equals(form.get("acknowledgePublic")))
|
||||
invalid("Confirm that relaxing public access controls may expose this bucket");
|
||||
store.createBucket(bucket);
|
||||
if (wizard) configureCreatedBucket(store, bucket, versioning, ownership, publicBlock);
|
||||
return AdminBrowser.bucketUrl(bucket, "", null);
|
||||
}
|
||||
|
||||
private static void configureCreatedBucket(ObjectStorage store, String bucket, String versioning,
|
||||
ObjectStorage.ObjectOwnership ownership, ObjectStorage.PublicAccessBlock publicBlock)
|
||||
throws IOException {
|
||||
if (versioning.equals("enabled"))
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
|
||||
if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucket, ownership);
|
||||
if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()))
|
||||
store.setPublicAccessBlock(bucket, publicBlock);
|
||||
}
|
||||
|
||||
private static String renameBucket(ObjectStorage store, String bucket, Map<String, String> form,
|
||||
ManagedCredentials managed) throws IOException {
|
||||
confirm(form, bucket);
|
||||
String newName = required(form, "newName", 63);
|
||||
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(bucket)))
|
||||
throw new StoreException(409, "BucketHasScopedKeys",
|
||||
"Move or remove scoped access keys for this bucket before renaming it");
|
||||
store.renameBucket(bucket, newName);
|
||||
return AdminBrowser.bucketUrl(newName, "", null);
|
||||
}
|
||||
|
||||
private static String deleteBucket(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
confirm(form, bucket);
|
||||
store.deleteBucket(bucket);
|
||||
return AdminConsole.PATH + "/buckets";
|
||||
}
|
||||
|
||||
private static String updateBucket(ObjectStorage store, String bucket, String action,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
switch (action) {
|
||||
case "delete-object" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm");
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
if (!version.isEmpty() && !version.equals(form.get("confirmVersion")))
|
||||
invalid("Type the version ID to confirm permanent deletion");
|
||||
store.delete(bucket, key, version.isEmpty() ? null : version);
|
||||
return AdminBrowser.bucketUrl(bucket, key.contains("/") ?
|
||||
key.substring(0, key.lastIndexOf('/') + 1) : "", null);
|
||||
}
|
||||
case "versioning" -> {
|
||||
String state = required(form, "state", 16);
|
||||
if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state");
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state));
|
||||
}
|
||||
case "ownership" -> {
|
||||
confirm(form, bucket);
|
||||
String value = required(form, "ownership", 32);
|
||||
store.setBucketOwnership(bucket, BucketSecurity.ownership(value));
|
||||
}
|
||||
case "public-access" -> {
|
||||
ObjectStorage.PublicAccessBlock block = new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets"));
|
||||
ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock();
|
||||
if (previous.blockPublicAcls() && !block.blockPublicAcls() ||
|
||||
previous.ignorePublicAcls() && !block.ignorePublicAcls() ||
|
||||
previous.blockPublicPolicy() && !block.blockPublicPolicy() ||
|
||||
previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket);
|
||||
store.setPublicAccessBlock(bucket, block);
|
||||
}
|
||||
case "policy" -> {
|
||||
String policy = form.getOrDefault("policy", "").trim();
|
||||
if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large");
|
||||
if (!policy.isEmpty()) {
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucket);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
if (parsed.publicAllow()) confirm(form, bucket);
|
||||
}
|
||||
store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy);
|
||||
}
|
||||
case "bucket-grant" -> {
|
||||
Map<String, String> acl = updateGrants(current.acl(), form, identities);
|
||||
if (newPublicGrant(current.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setBucketAcl(bucket, acl);
|
||||
}
|
||||
case "object-grant" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
String versionId = version.isEmpty() ? null : version;
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, versionId)) {
|
||||
metadata = opened.metadata();
|
||||
}
|
||||
Map<String, String> acl = updateGrants(metadata.acl(), form, identities);
|
||||
if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setObjectAcl(bucket, key, versionId, acl);
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId));
|
||||
}
|
||||
case "object-tag" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
String tag = required(form, "tag", 128);
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
String versionId = version.isEmpty() ? null : version;
|
||||
Map<String, String> tags = new HashMap<>(store.tags(bucket, key, versionId));
|
||||
if ("remove".equals(form.get("operation"))) tags.remove(tag);
|
||||
else if ("add".equals(form.get("operation"))) {
|
||||
String value = form.get("value");
|
||||
if (value == null || value.length() > 256) invalid("Invalid value");
|
||||
tags.put(tag, value);
|
||||
}
|
||||
else invalid("Invalid tag operation");
|
||||
ObjectAttributes.validateTags(tags);
|
||||
store.setTags(bucket, key, versionId, Map.copyOf(tags));
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId));
|
||||
}
|
||||
case "delete-object" -> { return deleteObject(store, bucket, form); }
|
||||
case "versioning" -> setVersioning(store, bucket, form);
|
||||
case "ownership" -> setOwnership(store, bucket, form);
|
||||
case "public-access" -> setPublicAccess(store, bucket, current, form);
|
||||
case "policy" -> setPolicy(store, bucket, current, form);
|
||||
case "bucket-grant" -> setBucketGrant(store, bucket, current, form, identities);
|
||||
case "object-grant" -> { return setObjectGrant(store, bucket, current, form, identities); }
|
||||
case "object-tag" -> { return setObjectTag(store, bucket, form); }
|
||||
default -> invalid("Unknown admin action");
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
|
||||
}
|
||||
|
||||
private static String deleteObject(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm");
|
||||
String version = version(form);
|
||||
if (version != null && !version.equals(form.get("confirmVersion")))
|
||||
invalid("Type the version ID to confirm permanent deletion");
|
||||
store.delete(bucket, key, version);
|
||||
return AdminBrowser.bucketUrl(bucket, key.contains("/") ?
|
||||
key.substring(0, key.lastIndexOf('/') + 1) : "", null);
|
||||
}
|
||||
|
||||
private static void setVersioning(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String state = required(form, "state", 16);
|
||||
if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state");
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state));
|
||||
}
|
||||
|
||||
private static void setOwnership(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
confirm(form, bucket);
|
||||
String value = required(form, "ownership", 32);
|
||||
store.setBucketOwnership(bucket, BucketSecurity.ownership(value));
|
||||
}
|
||||
|
||||
private static void setPublicAccess(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form) throws IOException {
|
||||
ObjectStorage.PublicAccessBlock block = publicAccessBlock(form);
|
||||
ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock();
|
||||
if (previous.blockPublicAcls() && !block.blockPublicAcls() ||
|
||||
previous.ignorePublicAcls() && !block.ignorePublicAcls() ||
|
||||
previous.blockPublicPolicy() && !block.blockPublicPolicy() ||
|
||||
previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket);
|
||||
store.setPublicAccessBlock(bucket, block);
|
||||
}
|
||||
|
||||
private static ObjectStorage.PublicAccessBlock publicAccessBlock(Map<String, String> form) {
|
||||
return new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets"));
|
||||
}
|
||||
|
||||
private static void setPolicy(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form) throws IOException {
|
||||
String policy = form.getOrDefault("policy", "").trim();
|
||||
if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large");
|
||||
if (!policy.isEmpty()) {
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucket);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
if (parsed.publicAllow()) confirm(form, bucket);
|
||||
}
|
||||
store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy);
|
||||
}
|
||||
|
||||
private static void setBucketGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
Map<String, String> acl = updateGrants(current.acl(), form, identities);
|
||||
if (newPublicGrant(current.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setBucketAcl(bucket, acl);
|
||||
}
|
||||
|
||||
private static String setObjectGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
String version = version(form);
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) {
|
||||
metadata = opened.metadata();
|
||||
}
|
||||
Map<String, String> acl = updateGrants(metadata.acl(), form, identities);
|
||||
if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setObjectAcl(bucket, key, version, acl);
|
||||
return objectUrl(bucket, key, version);
|
||||
}
|
||||
|
||||
private static String setObjectTag(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
String tag = required(form, "tag", 128);
|
||||
String version = version(form);
|
||||
Map<String, String> tags = new HashMap<>(store.tags(bucket, key, version));
|
||||
if ("remove".equals(form.get("operation"))) tags.remove(tag);
|
||||
else if ("add".equals(form.get("operation"))) {
|
||||
String value = form.get("value");
|
||||
if (value == null || value.length() > 256) invalid("Invalid value");
|
||||
tags.put(tag, value);
|
||||
} else invalid("Invalid tag operation");
|
||||
ObjectAttributes.validateTags(tags);
|
||||
store.setTags(bucket, key, version, Map.copyOf(tags));
|
||||
return objectUrl(bucket, key, version);
|
||||
}
|
||||
|
||||
private static String version(Map<String, String> form) {
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
return version.isEmpty() ? null : version;
|
||||
}
|
||||
|
||||
private static String objectUrl(String bucket, String key, String version) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(version == null ? "" : "&version=" + AdminBrowser.encoded(version));
|
||||
}
|
||||
|
||||
private static Map<String, String> updateGrants(Map<String, String> current,
|
||||
Map<String, String> form, Set<String> identities) {
|
||||
String principal = required(form, "principal", 128);
|
||||
|
||||
@@ -119,39 +119,7 @@ final class AdminBulkJobs {
|
||||
|
||||
private void run(Job job) {
|
||||
try {
|
||||
String after = null;
|
||||
do {
|
||||
if (job.cancel) break;
|
||||
ObjectStorage.ListPage page = list(job, after);
|
||||
int remaining = MAX_ITEMS - job.processed;
|
||||
for (ObjectStorage.ListedObject entry : page.objects()) {
|
||||
if (job.cancel || job.processed >= MAX_ITEMS) break;
|
||||
try {
|
||||
operations.read(() -> process(job.spec, entry));
|
||||
job.succeeded++;
|
||||
String detail = job.spec.operation().equals("inventory") ?
|
||||
"bytes=" + entry.metadata().length() + " etag=" + entry.metadata().etag() :
|
||||
job.spec.operation();
|
||||
append(job, "ok", entry.key(), detail);
|
||||
} catch (Exception error) {
|
||||
job.failed++;
|
||||
String detail = error instanceof StoreException storeError ?
|
||||
storeError.code + ": " + storeError.getMessage() :
|
||||
error.getClass().getSimpleName();
|
||||
append(job, "error", entry.key(), detail.length() > 200 ?
|
||||
detail.substring(0, 200) : detail);
|
||||
}
|
||||
job.processed++;
|
||||
}
|
||||
if (job.processed >= MAX_ITEMS) {
|
||||
job.capped = page.truncated() || page.objects().size() > remaining;
|
||||
break;
|
||||
}
|
||||
if (!page.truncated()) break;
|
||||
if (page.nextKey() == null || page.nextKey().equals(after))
|
||||
throw new IOException("Storage listing did not advance");
|
||||
after = page.nextKey();
|
||||
} while (true);
|
||||
processPages(job);
|
||||
job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed";
|
||||
} catch (Exception error) {
|
||||
job.state = "Failed";
|
||||
@@ -162,6 +130,49 @@ final class AdminBulkJobs {
|
||||
}
|
||||
}
|
||||
|
||||
private void processPages(Job job) throws IOException {
|
||||
String after = null;
|
||||
while (!job.cancel) {
|
||||
ObjectStorage.ListPage page = list(job, after);
|
||||
if (processPage(job, page) || !page.truncated()) return;
|
||||
if (page.nextKey() == null || page.nextKey().equals(after))
|
||||
throw new IOException("Storage listing did not advance");
|
||||
after = page.nextKey();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean processPage(Job job, ObjectStorage.ListPage page) {
|
||||
int remaining = MAX_ITEMS - job.processed;
|
||||
for (ObjectStorage.ListedObject entry : page.objects()) {
|
||||
if (job.cancel || job.processed >= MAX_ITEMS) break;
|
||||
processEntry(job, entry);
|
||||
}
|
||||
if (job.processed < MAX_ITEMS) return false;
|
||||
job.capped = page.truncated() || page.objects().size() > remaining;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void processEntry(Job job, ObjectStorage.ListedObject entry) {
|
||||
try {
|
||||
operations.read(() -> process(job.spec, entry));
|
||||
job.succeeded++;
|
||||
String detail = job.spec.operation().equals("inventory") ?
|
||||
"bytes=" + entry.metadata().length() + " etag=" + entry.metadata().etag() :
|
||||
job.spec.operation();
|
||||
append(job, "ok", entry.key(), detail);
|
||||
} catch (Exception error) {
|
||||
job.failed++;
|
||||
append(job, "error", entry.key(), errorDetail(error));
|
||||
}
|
||||
job.processed++;
|
||||
}
|
||||
|
||||
private static String errorDetail(Exception error) {
|
||||
String detail = error instanceof StoreException storeError ?
|
||||
storeError.code + ": " + storeError.getMessage() : error.getClass().getSimpleName();
|
||||
return detail.length() > 200 ? detail.substring(0, 200) : detail;
|
||||
}
|
||||
|
||||
private ObjectStorage.ListPage list(Job job, String after) throws IOException {
|
||||
return operations.readValue(() ->
|
||||
store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after));
|
||||
|
||||
@@ -138,6 +138,13 @@ final class AdminOperationsPages {
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
ClusterStore.ClusterStatus status = cluster.status();
|
||||
appendClusterSummary(content, status);
|
||||
appendClusterTopology(content, status);
|
||||
appendRepairProgress(content, status.repair());
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
private static void appendClusterSummary(StringBuilder content, ClusterStore.ClusterStatus status) {
|
||||
long healthy = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable).count();
|
||||
long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable)
|
||||
.map(node -> node.node().hostId()).distinct().count();
|
||||
@@ -150,8 +157,11 @@ final class AdminOperationsPages {
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable nodes</small><strong>")
|
||||
.append(healthy).append(" / ").append(status.nodes().size())
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>")
|
||||
.append(hosts).append("</strong></biscuit-cardview></div>")
|
||||
.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>")
|
||||
.append(hosts).append("</strong></biscuit-cardview></div>");
|
||||
}
|
||||
|
||||
private static void appendClusterTopology(StringBuilder content, ClusterStore.ClusterStatus status) {
|
||||
content.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>")
|
||||
.append("<strong>Metadata primary</strong><p>")
|
||||
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
|
||||
.append("</p></div><div class=cluster-connect aria-hidden=true></div><div class=cluster-nodes>");
|
||||
@@ -163,8 +173,7 @@ final class AdminOperationsPages {
|
||||
.append("</code><code>Host ").append(node.node().hostId())
|
||||
.append("</code><code>").append(escape(node.node().url().toString()))
|
||||
.append("</code><small>Verified replicas at last repair: ")
|
||||
.append(status.repair() == null || !status.repair().state().equals("completed") ||
|
||||
status.repair().report().scanned() > 0 && status.verifiedReplicas().isEmpty() ?
|
||||
.append(!replicasMeasured(status) ?
|
||||
"Not measured" :
|
||||
Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L)))
|
||||
.append("</small></div>");
|
||||
@@ -174,33 +183,48 @@ final class AdminOperationsPages {
|
||||
"Multiple nodes on one host do not provide host-level redundancy.</p>");
|
||||
if (status.omittedNodes() > 0) content.append("<p class=rename-warning>")
|
||||
.append(status.omittedNodes()).append(" additional nodes are not probed in this view.</p>");
|
||||
}
|
||||
|
||||
private static boolean replicasMeasured(ClusterStore.ClusterStatus status) {
|
||||
ClusterStore.RepairStatus repair = status.repair();
|
||||
if (repair == null || !repair.state().equals("completed")) return false;
|
||||
return repair.report().scanned() <= 0 || !status.verifiedReplicas().isEmpty();
|
||||
}
|
||||
|
||||
private static void appendRepairProgress(StringBuilder content, ClusterStore.RepairStatus repair) {
|
||||
content.append("<section class=insight><h3>Repair progress</h3>");
|
||||
if (repair == null) content.append("<p class=muted>No repair report has been recorded yet.</p>");
|
||||
else {
|
||||
ClusterStore.RepairReport report = repair.report();
|
||||
boolean stale = repair.state().equals("running") &&
|
||||
System.currentTimeMillis() - repair.updatedAt() > 300_000;
|
||||
content.append("<p><strong>").append(stale ? "May be interrupted" :
|
||||
repair.state().equals("running") ? "Running" :
|
||||
repair.state().equals("failed") ? "Failed" : "Completed")
|
||||
.append("</strong> · Started ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.startedAt()))
|
||||
.append(" UTC · Last update ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.updatedAt()))
|
||||
.append(" UTC</p><p class=muted>These counts are from this repair pass, " +
|
||||
"not a live replica inventory.</p><div class=grid>")
|
||||
.append("<biscuit-cardview><small>Segments scanned</small><strong>")
|
||||
.append(report.scanned()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Replicas restored</small><strong>")
|
||||
.append(report.restored()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Under-replicated</small><strong>")
|
||||
.append(report.underReplicated()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Unrecoverable</small><strong>")
|
||||
.append(report.unrecoverable()).append("</strong></biscuit-cardview></div>");
|
||||
appendRepairReport(content, repair);
|
||||
}
|
||||
content.append("<p class=muted>Repair is run by the separate cluster maintenance service. " +
|
||||
"This panel does not trigger repair or change placement.</p></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
private static void appendRepairReport(StringBuilder content, ClusterStore.RepairStatus repair) {
|
||||
ClusterStore.RepairReport report = repair.report();
|
||||
content.append("<p><strong>").append(repairLabel(repair))
|
||||
.append("</strong> · Started ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.startedAt()))
|
||||
.append(" UTC · Last update ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.updatedAt()))
|
||||
.append(" UTC</p><p class=muted>These counts are from this repair pass, " +
|
||||
"not a live replica inventory.</p><div class=grid>")
|
||||
.append("<biscuit-cardview><small>Segments scanned</small><strong>")
|
||||
.append(report.scanned()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Replicas restored</small><strong>")
|
||||
.append(report.restored()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Under-replicated</small><strong>")
|
||||
.append(report.underReplicated()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Unrecoverable</small><strong>")
|
||||
.append(report.unrecoverable()).append("</strong></biscuit-cardview></div>");
|
||||
}
|
||||
|
||||
private static String repairLabel(ClusterStore.RepairStatus repair) {
|
||||
if (repair.state().equals("running")) {
|
||||
return System.currentTimeMillis() - repair.updatedAt() > 300_000
|
||||
? "May be interrupted" : "Running";
|
||||
}
|
||||
return repair.state().equals("failed") ? "Failed" : "Completed";
|
||||
}
|
||||
}
|
||||
@@ -576,65 +576,83 @@ final class DiskStore implements ObjectStorage {
|
||||
synchronized (lock(destination)) {
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (expected != null) {
|
||||
Metadata current = index.get(indexKey(metadata.bucket(), metadata.key()));
|
||||
if (configured == null || configured.versioning() != VersioningState.ENABLED ||
|
||||
current == null || !expected.versionId().equals(
|
||||
current.versionId() == null ? "null" : current.versionId()) ||
|
||||
!MessageDigest.isEqual(expected.sha256(), current.sha256()) ||
|
||||
!expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl()))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
|
||||
}
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
checkExpectedVersion(configured, metadata, expected);
|
||||
if (isVersioned(configured))
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
}
|
||||
long previous = 0;
|
||||
boolean existed = Files.exists(destination);
|
||||
boolean legacy = false;
|
||||
if (existed) {
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
Metadata old = readRecord(in).metadata();
|
||||
previous = old.length();
|
||||
legacy = old.key() == null;
|
||||
}
|
||||
}
|
||||
long additional = Math.max(0, metadata.length() - previous);
|
||||
Metadata previous = previousMetadata(destination, createOnly);
|
||||
long previousLength = previous == null ? 0 : previous.length();
|
||||
long additional = Math.max(0, metadata.length() - previousLength);
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
if (isVersioned(configured))
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
if (Files.exists(catalog) && configured == null)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (maxTotal - used - reservedBytes < additional)
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
reservedBytes += additional;
|
||||
publishingByBucket.merge(metadata.bucket(), 1, Integer::sum);
|
||||
}
|
||||
boolean moved = false;
|
||||
try {
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
moved = true;
|
||||
syncDirectory(destination.getParent());
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
if (moved) {
|
||||
used = used - previous + metadata.length();
|
||||
if (!existed) objectCount++;
|
||||
if (legacy) legacyCount--;
|
||||
index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
reservePublication(metadata.bucket(), configured, additional);
|
||||
}
|
||||
publishUnversioned(destination, pending, metadata, previous, additional);
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
|
||||
private void checkExpectedVersion(Bucket configured, Metadata metadata, Metadata expected) {
|
||||
if (expected == null) return;
|
||||
Metadata current = index.get(indexKey(metadata.bucket(), metadata.key()));
|
||||
if (configured == null || configured.versioning() != VersioningState.ENABLED ||
|
||||
current == null || !expected.versionId().equals(
|
||||
current.versionId() == null ? "null" : current.versionId()) ||
|
||||
!MessageDigest.isEqual(expected.sha256(), current.sha256()) ||
|
||||
!expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl()))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
|
||||
}
|
||||
|
||||
private static boolean isVersioned(Bucket configured) {
|
||||
return configured != null && configured.versioning() != VersioningState.NEVER;
|
||||
}
|
||||
|
||||
private Metadata previousMetadata(Path destination, boolean createOnly) throws IOException {
|
||||
if (!Files.exists(destination)) return null;
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
return readRecord(in).metadata();
|
||||
}
|
||||
}
|
||||
|
||||
private void reservePublication(String bucket, Bucket configured, long additional) {
|
||||
if (Files.exists(catalog) && configured == null)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (maxTotal - used - reservedBytes < additional)
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
reservedBytes += additional;
|
||||
publishingByBucket.merge(bucket, 1, Integer::sum);
|
||||
}
|
||||
|
||||
private void publishUnversioned(Path destination, Path pending, Metadata metadata,
|
||||
Metadata previous, long additional) throws IOException {
|
||||
boolean moved = false;
|
||||
try {
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
moved = true;
|
||||
syncDirectory(destination.getParent());
|
||||
} finally {
|
||||
finishPublication(metadata, previous, additional, moved);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void finishPublication(Metadata metadata, Metadata previous,
|
||||
long additional, boolean moved) {
|
||||
if (moved) {
|
||||
used = used - (previous == null ? 0 : previous.length()) + metadata.length();
|
||||
if (previous == null) objectCount++;
|
||||
else if (previous.key() == null) legacyCount--;
|
||||
index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
|
||||
private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly, VersioningState state) throws IOException {
|
||||
String bucket = metadata.bucket();
|
||||
|
||||
@@ -46,20 +46,23 @@ final class RequestDiagnostics {
|
||||
|
||||
void record(String requestId, String operation, String bucket, int status, long elapsedNanos,
|
||||
String principal) {
|
||||
if (operation == null) operation = "Service";
|
||||
long now = System.currentTimeMillis();
|
||||
long minute = now / MINUTE_MILLIS;
|
||||
recordWindow(currentWindow(now / MINUTE_MILLIS), status, elapsedNanos);
|
||||
recordKey(principal, status, now);
|
||||
if (status >= 400) recordFailure(requestId, operation, bucket, status, now);
|
||||
}
|
||||
|
||||
private Window currentWindow(long minute) {
|
||||
int slot = (int) Math.floorMod(minute, windows.length());
|
||||
Window window;
|
||||
do {
|
||||
window = windows.get(slot);
|
||||
if (window != null && window.minute == minute) break;
|
||||
while (true) {
|
||||
Window window = windows.get(slot);
|
||||
if (window != null && window.minute == minute) return window;
|
||||
Window fresh = new Window(minute);
|
||||
if (windows.compareAndSet(slot, window, fresh)) {
|
||||
window = fresh;
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
if (windows.compareAndSet(slot, window, fresh)) return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
private static void recordWindow(Window window, int status, long elapsedNanos) {
|
||||
window.requests.increment();
|
||||
if (status >= 500) window.serverErrors.increment();
|
||||
else if (status >= 400) window.clientErrors.increment();
|
||||
@@ -68,23 +71,26 @@ final class RequestDiagnostics {
|
||||
while (latencySlot < LATENCY_BOUNDS_MS.length && millis > LATENCY_BOUNDS_MS[latencySlot])
|
||||
latencySlot++;
|
||||
window.latency[latencySlot].increment();
|
||||
if (principal != null && principal.length() <= 128) {
|
||||
KeyCounters counters = keys.get(principal);
|
||||
if (counters == null && keys.size() < 128)
|
||||
counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters());
|
||||
if (counters != null) {
|
||||
counters.requests.increment();
|
||||
if (status >= 400) counters.failures.increment();
|
||||
counters.lastSeen.set(now);
|
||||
}
|
||||
}
|
||||
if (status >= 400) {
|
||||
if (operation.length() > 32) operation = "Other";
|
||||
if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—";
|
||||
long sequence = failureSequence.getAndIncrement();
|
||||
failures.set((int) (sequence % failures.length()),
|
||||
new Failure(sequence, now, requestId, operation, bucket, status));
|
||||
}
|
||||
}
|
||||
|
||||
private void recordKey(String principal, int status, long now) {
|
||||
if (principal == null || principal.length() > 128) return;
|
||||
KeyCounters counters = keys.get(principal);
|
||||
if (counters == null && keys.size() < 128)
|
||||
counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters());
|
||||
if (counters == null) return;
|
||||
counters.requests.increment();
|
||||
if (status >= 400) counters.failures.increment();
|
||||
counters.lastSeen.set(now);
|
||||
}
|
||||
|
||||
private void recordFailure(String requestId, String operation, String bucket, int status, long now) {
|
||||
if (operation == null) operation = "Service";
|
||||
if (operation.length() > 32) operation = "Other";
|
||||
if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—";
|
||||
long sequence = failureSequence.getAndIncrement();
|
||||
failures.set((int) (sequence % failures.length()),
|
||||
new Failure(sequence, now, requestId, operation, bucket, status));
|
||||
}
|
||||
|
||||
List<KeyActivity> keyActivity() {
|
||||
|
||||
Reference in new issue
Block a user