Refactor complex admin and storage methods

This commit is contained in:
admin committed 2026-11-07 11:00:16 +01:00
1 parent 5304dfc047
commit 3c739deb09
13 files changed
+1434 -950

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar clo
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.RequestDiagnosticsTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.RequestDiagnosticsTest
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.BucketActivityTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.BucketActivityTest
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminOperationsTest RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminOperationsTest
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminBulkJobsTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.FeatureTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.FeatureTest
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.NodeHttpTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.NodeHttpTest
+1
View File
@@ -26,6 +26,7 @@ The script compiles the source and test programs into `out/classes`, then runs:
| `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. | | `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. |
| `AdminConsoleTest` | Admin sign-in, CSRF and origin checks, bucket and object changes, public-access confirmations, live metrics, encrypted managed-key persistence, scoped reads and listings, and key revocation. | | `AdminConsoleTest` | Admin sign-in, CSRF and origin checks, bucket and object changes, public-access confirmations, live metrics, encrypted managed-key persistence, scoped reads and listings, and key revocation. |
| `AdminOperationsTest` | Persisted admin events, effective access checks, stale editor conflicts, and paged copy, tag, inventory, and delete jobs; private copy ACLs, checksum verification, and tag validation. | | `AdminOperationsTest` | Persisted admin events, effective access checks, stale editor conflicts, and paged copy, tag, inventory, and delete jobs; private copy ACLs, checksum verification, and tag validation. |
| `AdminBulkJobsTest` | Exact job limits, truncated and stalled pagination, cancellation, and bounded per-object error reports. |
| `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. | | `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. |
| `NodeHttpTest` | Total node response deadlines, stalled-body cancellation, response-size limits, and interruption. | | `NodeHttpTest` | Total node response deadlines, stalled-body cancellation, response-size limits, and interruption. |
| `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. | | `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. |
+74 -51
View File
@@ -72,63 +72,86 @@
? history.filter(point => point.cpu !== null) : history; ? history.filter(point => point.cpu !== null) : history;
} }
function showMemory(sample) {
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
if (sample.rssBytes < 0 && !memoryFallback) {
memoryFallback = true;
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
charts[3].series = [
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
];
}
show('perf-ram', bytes(rss));
return rss;
}
function cpuUsage(sample, before, seconds) {
if (!(sample.cpuNanos >= 0 && before.cpuNanos >= 0)) return null;
return Math.max(0, Math.min(100,
(sample.cpuNanos - before.cpuNanos) /
(seconds * 1e9 * Math.max(1, sample.processors)) * 100));
}
function samplePoint(sample, before, seconds, rss) {
const errors = counterDelta(sample, before, 'failures4xx') +
counterDelta(sample, before, 'failures5xx');
return {
time: new Date().toLocaleTimeString(),
requests: counterDelta(sample, before, 'requests') / seconds,
errors: errors / seconds,
inbound: counterDelta(sample, before, 'inboundBytes') / seconds / 1024,
outbound: counterDelta(sample, before, 'outboundBytes') / seconds / 1024,
cpu: cpuUsage(sample, before, seconds),
memory: rss / 1048576,
heap: sample.heapBytes / 1048576,
seconds
};
}
function showCpuAverage() {
const cpuPoints = history.filter(entry => entry.cpu !== null);
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
show('perf-cpu', cpuSeconds ?
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
cpuSeconds).toFixed(1) + '%' : '—');
}
function showInterval(sample, before, point) {
const requests = counterDelta(sample, before, 'requests');
show('perf-rps', rate(point.requests));
show('perf-latency', requests ?
(counterDelta(sample, before, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
showCpuAverage();
updateCharts();
}
function recordSample(sample, now, rss) {
if (!previous) return;
const before = previous.sample;
if (sample.requests < before.requests) {
history.length = 0;
updateCharts();
}
if (!(sample.requests >= before.requests)) return;
const seconds = (now - previous.at) / 1000;
if (!(seconds > 0.1)) return;
const point = samplePoint(sample, before, seconds, rss);
history.push(point);
if (history.length > 60) history.shift();
showInterval(sample, before, point);
}
function accept(sample) { function accept(sample) {
if (!active || document.hidden) return; if (!active || document.hidden) return;
try { try {
const now = performance.now(); const now = performance.now();
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes; const rss = showMemory(sample);
if (sample.rssBytes < 0 && !memoryFallback) {
memoryFallback = true;
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
charts[3].series = [
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
];
}
show('perf-ram', bytes(rss));
show('perf-gc', Number(sample.gcCount).toLocaleString()); show('perf-gc', Number(sample.gcCount).toLocaleString());
show('perf-inflight', Number(sample.inFlight).toLocaleString()); show('perf-inflight', Number(sample.inFlight).toLocaleString());
if (previous && sample.requests < previous.sample.requests) { recordSample(sample, now, rss);
history.length = 0;
updateCharts();
}
if (previous && sample.requests >= previous.sample.requests) {
const seconds = (now - previous.at) / 1000;
if (seconds > 0.1) {
const requests = counterDelta(sample, previous.sample, 'requests');
const errors = counterDelta(sample, previous.sample, 'failures4xx') +
counterDelta(sample, previous.sample, 'failures5xx');
const cpu = sample.cpuNanos >= 0 && previous.sample.cpuNanos >= 0
? Math.max(0, Math.min(100,
(sample.cpuNanos - previous.sample.cpuNanos) /
(seconds * 1e9 * Math.max(1, sample.processors)) * 100))
: null;
const point = {
time: new Date().toLocaleTimeString(),
requests: requests / seconds,
errors: errors / seconds,
inbound: counterDelta(sample, previous.sample, 'inboundBytes') / seconds / 1024,
outbound: counterDelta(sample, previous.sample, 'outboundBytes') / seconds / 1024,
cpu,
memory: rss / 1048576,
heap: sample.heapBytes / 1048576,
seconds
};
history.push(point);
if (history.length > 60) history.shift();
show('perf-rps', rate(point.requests));
show('perf-latency', requests ?
(counterDelta(sample, previous.sample, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
const cpuPoints = history.filter(entry => entry.cpu !== null);
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
show('perf-cpu', cpuSeconds ?
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
cpuSeconds).toFixed(1) + '%' : '—');
updateCharts();
}
}
previous = { sample, at: now }; previous = { sample, at: now };
showState(history.length ? 'Live · one-second samples' : showState(history.length ? 'Live · one-second samples' :
'Collecting a second sample…', history.length ? 'live' : 'loading'); 'Collecting a second sample…', history.length ? 'live' : 'loading');
+1
View File
@@ -18,6 +18,7 @@ java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.RequestDiagnosticsTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.RequestDiagnosticsTest
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.BucketActivityTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.BucketActivityTest
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminOperationsTest java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminOperationsTest
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminBulkJobsTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.FeatureTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.FeatureTest
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.NodeHttpTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.NodeHttpTest
+44 -28
View File
@@ -26,6 +26,17 @@ final class AdminAccessCheck {
Result check(String principal, String operation, String bucket, String key) throws IOException { Result check(String principal, String operation, String bucket, String key) throws IOException {
if (principal == null || !identities.contains(principal)) if (principal == null || !identities.contains(principal))
return new Result(false, "Authentication", "Access key is unknown or disabled"); 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)) if (operation == null || !Set.of("list", "read", "write", "delete").contains(operation))
throw new StoreException(400, "InvalidArgument", "Choose a supported 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]")) 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"); throw new StoreException(400, "InvalidArgument", "Object key or prefix is too long");
if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024)) if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024))
throw new StoreException(400, "InvalidArgument", "Enter an object key"); 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) { String method = switch (operation) {
case "read" -> "GET";
case "write" -> "PUT"; case "write" -> "PUT";
case "delete" -> "DELETE"; case "delete" -> "DELETE";
default -> "GET"; default -> "GET";
}; };
try { if (managed != null && managed.contains(principal))
if (operation.equals("list")) { managed.checkObject(principal, bucket, key, method, Map.of(), new Headers());
Map<String, String> query = Map.of("list-type", "2", "prefix", key == null ? "" : key); else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers());
if (managed != null && managed.contains(principal)) }
managed.checkBucket(principal, bucket, method, query);
else scopes.checkBucket(principal, bucket, method, query); private Result inspectAccess(String principal, String operation, String bucket, String key)
} else { throws IOException {
if (managed != null && managed.contains(principal)) return switch (operation) {
managed.checkObject(principal, bucket, key, method, Map.of(), new Headers()); case "list" -> policyResult(access.inspectBucket(bucket, principal));
else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers()); case "read" -> inspectRead(principal, bucket, key);
} case "delete" -> policyResult(access.inspectWrite(bucket, key, principal, "s3:DeleteObject"));
} catch (StoreException denied) { default -> policyResult(access.inspectWrite(bucket, key, principal, "s3:PutObject"));
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; private Result inspectRead(String principal, String bucket, String key) throws IOException {
if (operation.equals("list")) { ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null);
decision = access.inspectBucket(bucket, principal); if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key()))
} else if (operation.equals("read")) { return new Result(false, "Object", "Current object does not exist");
ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null); return policyResult(access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal));
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); private static Result policyResult(S3Access.Decision decision) {
} else {
decision = access.inspectWrite(bucket, key, principal,
operation.equals("delete") ? "s3:DeleteObject" : "s3:PutObject");
}
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason()); return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
} }
} }
+175 -130
View File
@@ -12,143 +12,188 @@ final class AdminActions {
static String apply(ObjectStorage store, String action, Map<String, String> form, static String apply(ObjectStorage store, String action, Map<String, String> form,
Set<String> identities, ManagedCredentials managed) throws IOException { Set<String> identities, ManagedCredentials managed) throws IOException {
String bucket = form.get("bucket"); String bucket = required(form, "bucket", 63);
if (action.equals("create-bucket")) { return switch (action) {
bucket = required(form, "bucket", 63); case "create-bucket" -> createBucket(store, bucket, form);
boolean wizard = "wizard".equals(form.get("setup")); case "rename-bucket" -> renameBucket(store, bucket, form, managed);
String versioning = form.getOrDefault("versioning", "off"); case "delete-bucket" -> deleteBucket(store, bucket, form);
if (wizard && !versioning.equals("off") && !versioning.equals("enabled")) default -> updateBucket(store, bucket, action, form, identities);
invalid("Invalid initial versioning setting"); };
ObjectStorage.ObjectOwnership ownership = wizard ? }
BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED; private static String createBucket(ObjectStorage store, String bucket, Map<String, String> form)
ObjectStorage.PublicAccessBlock publicBlock = wizard ? new ObjectStorage.PublicAccessBlock( throws IOException {
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"), boolean wizard = "wizard".equals(form.get("setup"));
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")) : String versioning = form.getOrDefault("versioning", "off");
ObjectStorage.PublicAccessBlock.secure(); if (wizard && !versioning.equals("off") && !versioning.equals("enabled"))
if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) && invalid("Invalid initial versioning setting");
!"yes".equals(form.get("acknowledgePublic"))) ObjectStorage.ObjectOwnership ownership = wizard ?
invalid("Confirm that relaxing public access controls may expose this bucket"); BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
store.createBucket(bucket); ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
if (wizard) { ObjectStorage.PublicAccessBlock publicBlock = wizard ? publicAccessBlock(form) :
if (versioning.equals("enabled")) ObjectStorage.PublicAccessBlock.secure();
store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED); if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) &&
if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) !"yes".equals(form.get("acknowledgePublic")))
store.setBucketOwnership(bucket, ownership); invalid("Confirm that relaxing public access controls may expose this bucket");
if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure())) store.createBucket(bucket);
store.setPublicAccessBlock(bucket, publicBlock); if (wizard) configureCreatedBucket(store, bucket, versioning, ownership, publicBlock);
} return AdminBrowser.bucketUrl(bucket, "", null);
return AdminBrowser.bucketUrl(bucket, "", null); }
}
bucket = required(form, "bucket", 63); private static void configureCreatedBucket(ObjectStorage store, String bucket, String versioning,
if (action.equals("rename-bucket")) { ObjectStorage.ObjectOwnership ownership, ObjectStorage.PublicAccessBlock publicBlock)
confirm(form, bucket); throws IOException {
String newName = required(form, "newName", 63); if (versioning.equals("enabled"))
String currentName = bucket; store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(currentName))) if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
throw new StoreException(409, "BucketHasScopedKeys", store.setBucketOwnership(bucket, ownership);
"Move or remove scoped access keys for this bucket before renaming it"); if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()))
store.renameBucket(bucket, newName); store.setPublicAccessBlock(bucket, publicBlock);
return AdminBrowser.bucketUrl(newName, "", null); }
}
if (action.equals("delete-bucket")) { private static String renameBucket(ObjectStorage store, String bucket, Map<String, String> form,
confirm(form, bucket); ManagedCredentials managed) throws IOException {
store.deleteBucket(bucket); confirm(form, bucket);
return AdminConsole.PATH + "/buckets"; 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); ObjectStorage.Bucket current = store.bucket(bucket);
switch (action) { switch (action) {
case "delete-object" -> { case "delete-object" -> { return deleteObject(store, bucket, form); }
String key = required(form, "key", 1024); case "versioning" -> setVersioning(store, bucket, form);
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm"); case "ownership" -> setOwnership(store, bucket, form);
String version = form.getOrDefault("version", ""); case "public-access" -> setPublicAccess(store, bucket, current, form);
if (version.length() > 256) invalid("Invalid object version"); case "policy" -> setPolicy(store, bucket, current, form);
if (!version.isEmpty() && !version.equals(form.get("confirmVersion"))) case "bucket-grant" -> setBucketGrant(store, bucket, current, form, identities);
invalid("Type the version ID to confirm permanent deletion"); case "object-grant" -> { return setObjectGrant(store, bucket, current, form, identities); }
store.delete(bucket, key, version.isEmpty() ? null : version); case "object-tag" -> { return setObjectTag(store, bucket, form); }
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));
}
default -> invalid("Unknown admin action"); default -> invalid("Unknown admin action");
} }
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings"; 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, private static Map<String, String> updateGrants(Map<String, String> current,
Map<String, String> form, Set<String> identities) { Map<String, String> form, Set<String> identities) {
String principal = required(form, "principal", 128); String principal = required(form, "principal", 128);
+44 -33
View File
@@ -119,39 +119,7 @@ final class AdminBulkJobs {
private void run(Job job) { private void run(Job job) {
try { try {
String after = null; processPages(job);
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);
job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed"; job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed";
} catch (Exception error) { } catch (Exception error) {
job.state = "Failed"; 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 { private ObjectStorage.ListPage list(Job job, String after) throws IOException {
return operations.readValue(() -> return operations.readValue(() ->
store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after)); store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after));
@@ -138,6 +138,13 @@ final class AdminOperationsPages {
return page(content.toString(), true); return page(content.toString(), true);
} }
ClusterStore.ClusterStatus status = cluster.status(); 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 healthy = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable).count();
long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable) long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable)
.map(node -> node.node().hostId()).distinct().count(); .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("</strong></biscuit-cardview><biscuit-cardview><small>Reachable nodes</small><strong>")
.append(healthy).append(" / ").append(status.nodes().size()) .append(healthy).append(" / ").append(status.nodes().size())
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>") .append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>")
.append(hosts).append("</strong></biscuit-cardview></div>") .append(hosts).append("</strong></biscuit-cardview></div>");
.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>") }
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("<strong>Metadata primary</strong><p>")
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only") .append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
.append("</p></div><div class=cluster-connect aria-hidden=true></div><div class=cluster-nodes>"); .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>Host ").append(node.node().hostId())
.append("</code><code>").append(escape(node.node().url().toString())) .append("</code><code>").append(escape(node.node().url().toString()))
.append("</code><small>Verified replicas at last repair: ") .append("</code><small>Verified replicas at last repair: ")
.append(status.repair() == null || !status.repair().state().equals("completed") || .append(!replicasMeasured(status) ?
status.repair().report().scanned() > 0 && status.verifiedReplicas().isEmpty() ?
"Not measured" : "Not measured" :
Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L))) Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L)))
.append("</small></div>"); .append("</small></div>");
@@ -174,33 +183,48 @@ final class AdminOperationsPages {
"Multiple nodes on one host do not provide host-level redundancy.</p>"); "Multiple nodes on one host do not provide host-level redundancy.</p>");
if (status.omittedNodes() > 0) content.append("<p class=rename-warning>") if (status.omittedNodes() > 0) content.append("<p class=rename-warning>")
.append(status.omittedNodes()).append(" additional nodes are not probed in this view.</p>"); .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(); 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>"); 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>"); if (repair == null) content.append("<p class=muted>No repair report has been recorded yet.</p>");
else { else {
ClusterStore.RepairReport report = repair.report(); appendRepairReport(content, repair);
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>");
} }
content.append("<p class=muted>Repair is run by the separate cluster maintenance service. " + 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>"); "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";
} }
} }
+65 -47
View File
@@ -576,65 +576,83 @@ final class DiskStore implements ObjectStorage {
synchronized (lock(destination)) { synchronized (lock(destination)) {
synchronized (this) { synchronized (this) {
Bucket configured = buckets.get(metadata.bucket()); Bucket configured = buckets.get(metadata.bucket());
if (expected != null) { checkExpectedVersion(configured, metadata, expected);
Metadata current = index.get(indexKey(metadata.bucket(), metadata.key())); if (isVersioned(configured))
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)
return installVersionedPending(destination, pending, metadata, createOnly, return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning()); configured.versioning());
} }
long previous = 0; Metadata previous = previousMetadata(destination, createOnly);
boolean existed = Files.exists(destination); long previousLength = previous == null ? 0 : previous.length();
boolean legacy = false; long additional = Math.max(0, metadata.length() - previousLength);
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);
synchronized (this) { synchronized (this) {
Bucket configured = buckets.get(metadata.bucket()); Bucket configured = buckets.get(metadata.bucket());
if (configured != null && configured.versioning() != VersioningState.NEVER) if (isVersioned(configured))
return installVersionedPending(destination, pending, metadata, createOnly, return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning()); configured.versioning());
if (Files.exists(catalog) && configured == null) reservePublication(metadata.bucket(), configured, additional);
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();
}
} }
publishUnversioned(destination, pending, metadata, previous, additional);
return metadata; 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, private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata,
boolean createOnly, VersioningState state) throws IOException { boolean createOnly, VersioningState state) throws IOException {
String bucket = metadata.bucket(); String bucket = metadata.bucket();
@@ -46,20 +46,23 @@ final class RequestDiagnostics {
void record(String requestId, String operation, String bucket, int status, long elapsedNanos, void record(String requestId, String operation, String bucket, int status, long elapsedNanos,
String principal) { String principal) {
if (operation == null) operation = "Service";
long now = System.currentTimeMillis(); 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()); int slot = (int) Math.floorMod(minute, windows.length());
Window window; while (true) {
do { Window window = windows.get(slot);
window = windows.get(slot); if (window != null && window.minute == minute) return window;
if (window != null && window.minute == minute) break;
Window fresh = new Window(minute); Window fresh = new Window(minute);
if (windows.compareAndSet(slot, window, fresh)) { if (windows.compareAndSet(slot, window, fresh)) return fresh;
window = fresh; }
break; }
}
} while (true); private static void recordWindow(Window window, int status, long elapsedNanos) {
window.requests.increment(); window.requests.increment();
if (status >= 500) window.serverErrors.increment(); if (status >= 500) window.serverErrors.increment();
else if (status >= 400) window.clientErrors.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]) while (latencySlot < LATENCY_BOUNDS_MS.length && millis > LATENCY_BOUNDS_MS[latencySlot])
latencySlot++; latencySlot++;
window.latency[latencySlot].increment(); window.latency[latencySlot].increment();
if (principal != null && principal.length() <= 128) { }
KeyCounters counters = keys.get(principal);
if (counters == null && keys.size() < 128) private void recordKey(String principal, int status, long now) {
counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters()); if (principal == null || principal.length() > 128) return;
if (counters != null) { KeyCounters counters = keys.get(principal);
counters.requests.increment(); if (counters == null && keys.size() < 128)
if (status >= 400) counters.failures.increment(); counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters());
counters.lastSeen.set(now); if (counters == null) return;
} counters.requests.increment();
} if (status >= 400) counters.failures.increment();
if (status >= 400) { counters.lastSeen.set(now);
if (operation.length() > 32) operation = "Other"; }
if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—";
long sequence = failureSequence.getAndIncrement(); private void recordFailure(String requestId, String operation, String bucket, int status, long now) {
failures.set((int) (sequence % failures.length()), if (operation == null) operation = "Service";
new Failure(sequence, now, requestId, operation, bucket, status)); 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() { List<KeyActivity> keyActivity() {
@@ -0,0 +1,137 @@
package cloud.lunarsky.store;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public final class AdminBulkJobsTest {
private static final String BUCKET = "test-bucket";
private static final ObjectStorage.Metadata METADATA = new ObjectStorage.Metadata(
4, 0, "etag", new byte[32], BUCKET, "", "text/plain");
@FunctionalInterface
private interface Listing {
ObjectStorage.ListPage get(int count, String after) throws Exception;
}
@FunctionalInterface
private interface Deletion {
void delete(String key) throws Exception;
}
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
private static ObjectStorage storage(Listing listing, Deletion deletion) {
return (ObjectStorage) Proxy.newProxyInstance(ObjectStorage.class.getClassLoader(),
new Class<?>[]{ObjectStorage.class}, (proxy, method, arguments) -> switch (method.getName()) {
case "bucket" -> new ObjectStorage.Bucket(BUCKET, 0);
case "list" -> listing.get((int) arguments[3], (String) arguments[4]);
case "delete" -> {
deletion.delete((String) arguments[1]);
yield null;
}
default -> throw new AssertionError("Unexpected storage operation: " + method.getName());
});
}
private static ObjectStorage.ListPage page(int start, int end, String next, boolean truncated) {
List<ObjectStorage.ListedObject> objects = IntStream.range(start, end)
.mapToObj(index -> new ObjectStorage.ListedObject(Integer.toString(index), METADATA)).toList();
return new ObjectStorage.ListPage(objects, List.of(), next, truncated);
}
private static AdminBulkJobs.Spec spec(String operation) {
return new AdminBulkJobs.Spec(operation, BUCKET, "", "", "", "", "");
}
private static AdminBulkJobs.Snapshot finished(ArrayBlockingQueue<AdminBulkJobs.Snapshot> results)
throws InterruptedException {
AdminBulkJobs.Snapshot result = results.poll(10, TimeUnit.SECONDS);
if (result == null) throw new AssertionError("Bulk job did not finish");
return result;
}
private static void itemLimit(int total, boolean oversizedPage) throws Exception {
ObjectStorage store = storage((count, after) -> {
int start = after == null ? 0 : Integer.parseInt(after) + 1;
int end = oversizedPage ? total : Math.min(start + count, total);
return page(start, end, Integer.toString(end - 1), end < total);
}, key -> { });
var results = new ArrayBlockingQueue<AdminBulkJobs.Snapshot>(2);
AdminBulkJobs jobs = new AdminBulkJobs(store, results::add);
jobs.start(spec("inventory"));
AdminBulkJobs.Snapshot result = finished(results);
boolean capped = total > AdminBulkJobs.MAX_ITEMS;
check(result.capped() == capped, "Incorrect cap at the item boundary");
check(result.state().equals(capped ? "Capped" : "Completed"), "Incorrect completion state");
check(result.processed() == AdminBulkJobs.MAX_ITEMS && result.succeeded() == result.processed(),
"Item limit lost or overran entries");
check(!jobs.hasActiveJob(), "Finished job is still active");
}
private static void cancellation() throws Exception {
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicInteger deletes = new AtomicInteger();
ObjectStorage store = storage((count, after) -> page(0, 3, null, false), key -> {
deletes.incrementAndGet();
entered.countDown();
if (!release.await(10, TimeUnit.SECONDS)) throw new AssertionError("Delete was not released");
});
var results = new ArrayBlockingQueue<AdminBulkJobs.Snapshot>(2);
AdminBulkJobs jobs = new AdminBulkJobs(store, results::add);
AdminBulkJobs.Snapshot started = jobs.start(spec("delete"));
try {
check(entered.await(10, TimeUnit.SECONDS), "Delete did not start");
jobs.cancel(started.id());
} finally {
release.countDown();
}
AdminBulkJobs.Snapshot result = finished(results);
check(result.state().equals("Cancelled") && result.processed() == 1 && result.succeeded() == 1,
"Cancellation did not finish the in-progress entry");
check(deletes.get() == 1, "Cancellation started another entry");
}
private static void stalledPagination() throws Exception {
ObjectStorage store = storage((count, after) -> page(0, 1, "0", true), key -> { });
var results = new ArrayBlockingQueue<AdminBulkJobs.Snapshot>(2);
AdminBulkJobs jobs = new AdminBulkJobs(store, results::add);
jobs.start(spec("inventory"));
AdminBulkJobs.Snapshot result = finished(results);
check(result.state().equals("Failed") && result.processed() == 2,
"A repeated pagination marker did not stop the job");
check(jobs.report(result.id()).contains("IOException"), "Listing failure missing from report");
}
private static void entryFailure() throws Exception {
ObjectStorage store = storage((count, after) -> page(0, 3, null, false), key -> {
if (key.equals("1")) throw new StoreException(403, "AccessDenied", "x".repeat(300));
});
var results = new ArrayBlockingQueue<AdminBulkJobs.Snapshot>(2);
AdminBulkJobs jobs = new AdminBulkJobs(store, results::add);
jobs.start(spec("delete"));
AdminBulkJobs.Snapshot result = finished(results);
check(result.state().equals("Completed") && result.processed() == 3 &&
result.succeeded() == 2 && result.failed() == 1, "Entry failure aborted or miscounted the job");
String report = jobs.report(result.id());
check(report.contains("AccessDenied: ") && !report.contains("x".repeat(201)),
"Entry failure detail was missing or unbounded");
}
public static void main(String[] args) throws Exception {
itemLimit(AdminBulkJobs.MAX_ITEMS, false);
itemLimit(AdminBulkJobs.MAX_ITEMS + 1, false);
itemLimit(AdminBulkJobs.MAX_ITEMS + 1, true);
cancellation();
stalledPagination();
entryFailure();
System.out.println("Admin bulk job tests passed: cap, cancellation, pagination, errors");
}
}
File diff suppressed because it is too large. Load diff
@@ -3,6 +3,14 @@ package cloud.lunarsky.store;
public final class RequestDiagnosticsTest { public final class RequestDiagnosticsTest {
public static void main(String[] args) { public static void main(String[] args) {
RequestDiagnostics diagnostics = new RequestDiagnostics(); RequestDiagnostics diagnostics = new RequestDiagnostics();
rollingCounts(diagnostics);
boundedFailures(diagnostics);
keyCounters();
failureLabelsAndLatency();
System.out.println("Request diagnostics tests passed");
}
private static void rollingCounts(RequestDiagnostics diagnostics) {
diagnostics.record("request-1", "Object GET", "photos", 200, 4_000_000); diagnostics.record("request-1", "Object GET", "photos", 200, 4_000_000);
diagnostics.record("request-2", "Object PUT", "photos", 403, 16_000_000); diagnostics.record("request-2", "Object PUT", "photos", 403, 16_000_000);
diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000); diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000);
@@ -14,6 +22,9 @@ public final class RequestDiagnosticsTest {
!result.recentFailures().get(0).bucket().equals("—") || !result.recentFailures().get(0).bucket().equals("—") ||
!result.recentFailures().get(1).bucket().equals("photos")) !result.recentFailures().get(1).bucket().equals("photos"))
throw new AssertionError("Rolling request diagnostics changed"); throw new AssertionError("Rolling request diagnostics changed");
}
private static void boundedFailures(RequestDiagnostics diagnostics) {
for (int index = 0; index < 70; index++) for (int index = 0; index < 70; index++)
diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000); diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000);
RequestDiagnostics.Snapshot bounded = diagnostics.snapshot(); RequestDiagnostics.Snapshot bounded = diagnostics.snapshot();
@@ -21,6 +32,33 @@ public final class RequestDiagnosticsTest {
!bounded.recentFailures().get(0).requestId().equals("bounded-69") || !bounded.recentFailures().get(0).requestId().equals("bounded-69") ||
!bounded.recentFailures().get(63).requestId().equals("bounded-6")) !bounded.recentFailures().get(63).requestId().equals("bounded-6"))
throw new AssertionError("Recent failure history is not bounded"); throw new AssertionError("Recent failure history is not bounded");
System.out.println("Request diagnostics tests passed"); }
private static void keyCounters() {
RequestDiagnostics diagnostics = new RequestDiagnostics();
diagnostics.record("key-ok", "Object GET", "photos", 200, 1_000_000, "reader");
diagnostics.record("key-error", "Object GET", "photos", 403, 1_000_000, "reader");
diagnostics.record("anonymous", "Object GET", "photos", 200, 1_000_000, null);
diagnostics.record("invalid-key", "Object GET", "photos", 403, 1_000_000, "x".repeat(129));
var activity = diagnostics.keyActivity();
if (activity.size() != 1) throw new AssertionError("Invalid principals entered key counters");
var reader = activity.getFirst();
if (!reader.principal().equals("reader") || reader.requests() != 2 ||
reader.failures() != 1 || reader.lastSeenMillis() <= 0)
throw new AssertionError("Authenticated key activity changed");
}
private static void failureLabelsAndLatency() {
RequestDiagnostics diagnostics = new RequestDiagnostics();
diagnostics.record("missing-label", null, "invalid/bucket", 404, -1);
diagnostics.record("long-label", "x".repeat(33), "photos", 503, 10_001_000_000L);
var result = diagnostics.snapshot();
var newest = result.recentFailures().getFirst();
var oldest = result.recentFailures().getLast();
if (!newest.operation().equals("Other") || !newest.bucket().equals("photos") ||
!oldest.operation().equals("Service") || !oldest.bucket().equals("—"))
throw new AssertionError("Failure labels were not normalized");
if (result.p50Millis() != 1 || result.p95Millis() != -1 || result.p99Millis() != -1)
throw new AssertionError("Latency underflow or overflow bucket changed");
} }
} }