Expand admin tools and harden storage operations
This commit is contained in:
1 parent
fbec6694df
commit
5304dfc047
86 files changed
+8111
-1102
No files matched your search
@@ -0,0 +1,72 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminAccessCheck {
|
||||
record Result(boolean allowed, String stage, String explanation) { }
|
||||
|
||||
private final ObjectStorage store;
|
||||
private final S3Access access;
|
||||
private final KeyScopes scopes;
|
||||
private final Set<String> identities;
|
||||
private final ManagedCredentials managed;
|
||||
|
||||
AdminAccessCheck(ObjectStorage store, S3Access access, KeyScopes scopes,
|
||||
Set<String> identities, ManagedCredentials managed) {
|
||||
this.store = store;
|
||||
this.access = access;
|
||||
this.scopes = scopes;
|
||||
this.identities = identities;
|
||||
this.managed = managed;
|
||||
}
|
||||
|
||||
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");
|
||||
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]"))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a valid bucket");
|
||||
if (key != null && key.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1024)
|
||||
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");
|
||||
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");
|
||||
}
|
||||
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminActions {
|
||||
private 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";
|
||||
}
|
||||
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));
|
||||
}
|
||||
default -> invalid("Unknown admin action");
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
|
||||
}
|
||||
|
||||
private static Map<String, String> updateGrants(Map<String, String> current,
|
||||
Map<String, String> form, Set<String> identities) {
|
||||
String principal = required(form, "principal", 128);
|
||||
if (principal.equals("AllUsers")) principal = Acl.ALL_USERS;
|
||||
if (principal.equals("AuthenticatedUsers")) principal = Acl.AUTHENTICATED_USERS;
|
||||
Map<String, String> updated = new HashMap<>(current);
|
||||
if ("remove".equals(form.get("operation"))) updated.remove(principal);
|
||||
else if ("add".equals(form.get("operation"))) {
|
||||
int bits = switch (required(form, "permission", 16)) {
|
||||
case "READ" -> Acl.READ;
|
||||
case "WRITE" -> Acl.WRITE;
|
||||
case "READ_ACP" -> Acl.READ_ACP;
|
||||
case "WRITE_ACP" -> Acl.WRITE_ACP;
|
||||
case "FULL_CONTROL" -> Acl.FULL_CONTROL;
|
||||
default -> throw new StoreException(400, "InvalidArgument", "Invalid ACL permission");
|
||||
};
|
||||
int existing = Integer.parseInt(updated.getOrDefault(principal, "0"));
|
||||
updated.put(principal, Integer.toString(existing | bits));
|
||||
} else invalid("Invalid grant operation");
|
||||
return Acl.validate(updated, identities);
|
||||
}
|
||||
|
||||
private static boolean newPublicGrant(Map<String, String> before, Map<String, String> after) {
|
||||
return java.util.List.of(Acl.ALL_USERS, Acl.AUTHENTICATED_USERS).stream().anyMatch(
|
||||
principal -> !before.getOrDefault(principal, "0").equals(after.getOrDefault(principal, "0")) &&
|
||||
Integer.parseInt(after.getOrDefault(principal, "0")) != 0);
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> form, String field, int maxLength) {
|
||||
String value = form.get(field);
|
||||
if (value == null || value.isBlank() || value.length() > maxLength || value.indexOf('\0') >= 0)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid " + field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void confirm(Map<String, String> form, String bucket) {
|
||||
if (!bucket.equals(form.get("confirm")))
|
||||
throw new StoreException(400, "InvalidArgument", "Type the bucket name to confirm");
|
||||
}
|
||||
|
||||
private static void invalid(String message) {
|
||||
throw new StoreException(400, "InvalidArgument", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminHttp.*;
|
||||
|
||||
final class AdminAssets {
|
||||
private record Asset(byte[] content, String type, boolean authenticated) { }
|
||||
|
||||
private final Map<String, Asset> assets;
|
||||
|
||||
AdminAssets() throws IOException {
|
||||
Map<String, Asset> loaded = new HashMap<>();
|
||||
add(loaded, "/style.css", "admin.css", "text/css", false);
|
||||
add(loaded, "/logo.png", "objectstore-logo.png", "image/png", false);
|
||||
add(loaded, "/workspace.js", "workspace.js", "text/javascript", false);
|
||||
add(loaded, "/biscuit.js", "biscuit.js", "text/javascript", true);
|
||||
add(loaded, "/performance.js", "performance.js", "text/javascript", true);
|
||||
for (String icon : AdminLayout.ICONS) {
|
||||
add(loaded, "/icons/" + icon + ".svg", "icons/" + icon + ".svg", "image/svg+xml", true);
|
||||
}
|
||||
assets = Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
boolean handle(HttpExchange exchange, boolean signedIn) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
Asset asset = assets.get(path);
|
||||
boolean icon = path.startsWith(PATH + "/icons/") && path.endsWith(".svg");
|
||||
if (asset == null && !icon) return false;
|
||||
if (!exchange.getRequestMethod().equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
} else if ((icon || asset.authenticated()) && !signedIn) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
} else if (asset == null) {
|
||||
send(exchange, 404, "Not found", "text/plain; charset=utf-8");
|
||||
} else {
|
||||
exchange.getResponseHeaders().set("Content-Type", asset.type());
|
||||
exchange.sendResponseHeaders(200, asset.content().length);
|
||||
exchange.getResponseBody().write(asset.content());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void add(Map<String, Asset> assets, String route, String file, String type,
|
||||
boolean authenticated) throws IOException {
|
||||
String contentType = type.equals("image/png") ? type : type + "; charset=" + StandardCharsets.UTF_8;
|
||||
assets.put(PATH + route, new Asset(Files.readAllBytes(Path.of("admin-ui", file)),
|
||||
contentType, authenticated));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminAuditTrail {
|
||||
private static final long MAX_BYTES = 4L * 1024 * 1024;
|
||||
private final Path file;
|
||||
private final Path previous;
|
||||
|
||||
record Entry(long timeMillis, String action, String target, String result, String peer) { }
|
||||
|
||||
AdminAuditTrail(Path dataDirectory) throws IOException {
|
||||
Files.createDirectories(dataDirectory);
|
||||
file = dataDirectory.resolve("admin-audit.tsv");
|
||||
previous = dataDirectory.resolve("admin-audit.previous.tsv");
|
||||
if (!Files.exists(file)) Files.createFile(file);
|
||||
privateFile(file);
|
||||
}
|
||||
|
||||
synchronized void record(String action, String target, String result, String peer) throws IOException {
|
||||
String line = System.currentTimeMillis() + "\t" + safe(action, 48) + "\t" +
|
||||
safe(target, 256) + "\t" + safe(result, 48) + "\t" + safe(peer, 64) + "\n";
|
||||
byte[] bytes = line.getBytes(StandardCharsets.UTF_8);
|
||||
if (Files.size(file) + bytes.length > MAX_BYTES) {
|
||||
Files.move(file, previous, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.createFile(file);
|
||||
privateFile(previous);
|
||||
privateFile(file);
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized List<Entry> recent(int limit) throws IOException {
|
||||
int wanted = Math.min(200, Math.max(0, limit));
|
||||
List<Entry> found = new ArrayList<>();
|
||||
for (Path path : List.of(file, previous)) {
|
||||
if (!Files.exists(path)) continue;
|
||||
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
|
||||
for (int i = lines.size() - 1; i >= 0 && found.size() < wanted; i--) {
|
||||
String[] fields = lines.get(i).split("\t", -1);
|
||||
if (fields.length != 5) continue;
|
||||
try {
|
||||
found.add(new Entry(Long.parseLong(fields[0]), fields[1], fields[2],
|
||||
fields[3], fields[4]));
|
||||
} catch (NumberFormatException ignored) { }
|
||||
}
|
||||
if (found.size() >= wanted) break;
|
||||
}
|
||||
return List.copyOf(found);
|
||||
}
|
||||
|
||||
private static String safe(String input, int limit) {
|
||||
if (input == null) return "—";
|
||||
String value = input.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');
|
||||
return value.length() <= limit ? value : value.substring(0, limit);
|
||||
}
|
||||
|
||||
private static void privateFile(Path path) throws IOException {
|
||||
try {
|
||||
Files.setPosixFilePermissions(path, Set.of(PosixFilePermission.OWNER_READ,
|
||||
PosixFilePermission.OWNER_WRITE));
|
||||
} catch (UnsupportedOperationException ignored) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
|
||||
final class AdminAuthentication {
|
||||
private static final long SESSION_MILLIS = Duration.ofMinutes(30).toMillis();
|
||||
private static final long ATTEMPT_WINDOW_MILLIS = Duration.ofMinutes(5).toMillis();
|
||||
private static final int MAX_SESSIONS = 128;
|
||||
private static final int MAX_CLIENTS = 1024;
|
||||
private final byte[] passwordHash;
|
||||
private final URI publicOrigin;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final LinkedHashMap<String, Session> sessions = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Long> loginTokens = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Attempt> attempts = new LinkedHashMap<>();
|
||||
|
||||
private record Attempt(long started, int failures) { }
|
||||
record Session(long expires, String csrf) { }
|
||||
|
||||
private AdminAuthentication(byte[] passwordHash, URI publicOrigin) {
|
||||
this.passwordHash = passwordHash;
|
||||
this.publicOrigin = publicOrigin;
|
||||
}
|
||||
|
||||
static AdminAuthentication fromEnvironment(Map<String, String> env) throws IOException {
|
||||
return new AdminAuthentication(passwordHash(env.get("ADMIN_UI_PASSWORD_FILE")), configuredOrigin(env));
|
||||
}
|
||||
|
||||
private static byte[] passwordHash(String file) throws IOException {
|
||||
if (file == null || file.isBlank())
|
||||
throw new IllegalArgumentException("ADMIN_UI_PASSWORD_FILE is required when the admin UI is enabled");
|
||||
byte[] password = Files.readAllBytes(Path.of(file));
|
||||
int length = password.length;
|
||||
if (length > 0 && password[length - 1] == '\n') length--;
|
||||
if (length > 0 && password[length - 1] == '\r') length--;
|
||||
if (length < 16 || length > 1024)
|
||||
throw new IllegalArgumentException("Admin password must contain 16 to 1024 bytes");
|
||||
for (int i = 0; i < length; i++) {
|
||||
if (password[i] == '\n' || password[i] == '\r' || password[i] == 0)
|
||||
throw new IllegalArgumentException("Admin password must be a single line");
|
||||
}
|
||||
byte[] trimmed = java.util.Arrays.copyOf(password, length);
|
||||
byte[] hash = SigV4.hash(trimmed);
|
||||
java.util.Arrays.fill(trimmed, (byte) 0);
|
||||
java.util.Arrays.fill(password, (byte) 0);
|
||||
return hash;
|
||||
}
|
||||
|
||||
private static URI configuredOrigin(Map<String, String> env) {
|
||||
String privateOrigin = env.get("ADMIN_UI_PRIVATE_ORIGIN");
|
||||
String publicOrigin = env.get("ADMIN_UI_ORIGIN");
|
||||
if (privateOrigin != null && !privateOrigin.isBlank() &&
|
||||
publicOrigin != null && !publicOrigin.isBlank())
|
||||
throw new IllegalArgumentException("Configure only one admin UI origin");
|
||||
String configured = privateOrigin != null && !privateOrigin.isBlank() ? privateOrigin : publicOrigin;
|
||||
URI origin = null;
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
try { origin = URI.create(configured); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid ADMIN_UI_ORIGIN", error);
|
||||
}
|
||||
boolean privateHttp = privateOrigin != null && !privateOrigin.isBlank();
|
||||
if (!(privateHttp ? "http".equals(origin.getScheme()) &&
|
||||
privateIpv4(origin.getHost()) && origin.getPort() > 0 && origin.getPort() <= 65535 :
|
||||
"https".equals(origin.getScheme()) && origin.getHost() != null) ||
|
||||
origin.getUserInfo() != null || origin.getRawQuery() != null || origin.getRawFragment() != null ||
|
||||
!(origin.getRawPath().isEmpty() || origin.getRawPath().equals("/")))
|
||||
throw new IllegalArgumentException(privateHttp ?
|
||||
"ADMIN_UI_PRIVATE_ORIGIN must be an HTTP origin with a private IPv4 address and port" :
|
||||
"ADMIN_UI_ORIGIN must be an HTTPS origin");
|
||||
origin = URI.create(origin.toString().replaceFirst("/$", ""));
|
||||
}
|
||||
return origin;
|
||||
}
|
||||
|
||||
boolean matchesPassword(String password) {
|
||||
byte[] candidate = SigV4.hash((password == null ? "" : password).getBytes(StandardCharsets.UTF_8));
|
||||
return MessageDigest.isEqual(candidate, passwordHash);
|
||||
}
|
||||
|
||||
synchronized String signIn(String client) {
|
||||
String token = randomToken();
|
||||
attempts.remove(client);
|
||||
long now = System.currentTimeMillis();
|
||||
sessions.entrySet().removeIf(entry -> entry.getValue().expires() <= now);
|
||||
if (sessions.size() >= MAX_SESSIONS) sessions.remove(sessions.keySet().iterator().next());
|
||||
sessions.put(token, new Session(now + SESSION_MILLIS, randomToken()));
|
||||
return token;
|
||||
}
|
||||
|
||||
synchronized void signOut(HttpExchange exchange) {
|
||||
sessions.remove(sessionCookie(exchange));
|
||||
}
|
||||
|
||||
synchronized String issueLoginToken() {
|
||||
long now = System.currentTimeMillis();
|
||||
loginTokens.entrySet().removeIf(entry -> entry.getValue() <= now);
|
||||
if (loginTokens.size() >= MAX_SESSIONS) loginTokens.remove(loginTokens.keySet().iterator().next());
|
||||
String token = randomToken();
|
||||
loginTokens.put(token, now + Duration.ofMinutes(10).toMillis());
|
||||
return token;
|
||||
}
|
||||
|
||||
synchronized boolean consumeLoginToken(String token) {
|
||||
if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) return false;
|
||||
Long until = loginTokens.remove(token);
|
||||
return until != null && until > System.currentTimeMillis();
|
||||
}
|
||||
|
||||
String randomToken() {
|
||||
byte[] value = new byte[32];
|
||||
random.nextBytes(value);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
|
||||
}
|
||||
|
||||
synchronized boolean throttled(String client) {
|
||||
Attempt attempt = attempts.get(client);
|
||||
return attempt != null && System.currentTimeMillis() - attempt.started < ATTEMPT_WINDOW_MILLIS &&
|
||||
attempt.failures >= 5;
|
||||
}
|
||||
|
||||
synchronized void failed(String client) {
|
||||
long now = System.currentTimeMillis();
|
||||
Attempt attempt = attempts.get(client);
|
||||
if (attempt == null || now - attempt.started >= ATTEMPT_WINDOW_MILLIS)
|
||||
attempts.put(client, new Attempt(now, 1));
|
||||
else attempts.put(client, new Attempt(attempt.started, attempt.failures + 1));
|
||||
if (attempts.size() > MAX_CLIENTS) {
|
||||
Iterator<String> oldest = attempts.keySet().iterator();
|
||||
oldest.next();
|
||||
oldest.remove();
|
||||
}
|
||||
}
|
||||
|
||||
synchronized Session session(HttpExchange exchange) {
|
||||
String token = sessionCookie(exchange);
|
||||
Session session = sessions.get(token);
|
||||
if (session == null) return null;
|
||||
if (session.expires() > System.currentTimeMillis()) return session;
|
||||
sessions.remove(token);
|
||||
return null;
|
||||
}
|
||||
|
||||
String sessionCookie(HttpExchange exchange) {
|
||||
String header = exchange.getRequestHeaders().getFirst("Cookie");
|
||||
if (header == null || header.length() > 8192) return "";
|
||||
String name = secureOrigin() ? "__Host-objectstore_admin=" : "objectstore_admin=";
|
||||
for (String field : header.split(";")) {
|
||||
String value = field.trim();
|
||||
if (value.startsWith(name) && value.substring(name.length()).matches("[A-Za-z0-9_-]{43}"))
|
||||
return value.substring(name.length());
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String cookie(String token, int seconds) {
|
||||
String name = secureOrigin() ? "__Host-objectstore_admin" : "objectstore_admin";
|
||||
String path = secureOrigin() ? "/" : PATH;
|
||||
return name + "=" + token + "; Path=" + path + "; HttpOnly; SameSite=Strict; Max-Age=" + seconds +
|
||||
(secureOrigin() ? "; Secure" : "");
|
||||
}
|
||||
|
||||
boolean secureOrigin() {
|
||||
return publicOrigin != null && "https".equals(publicOrigin.getScheme());
|
||||
}
|
||||
|
||||
static boolean privateIpv4(String host) {
|
||||
if (host == null || !host.matches("[0-9]+(?:\\.[0-9]+){3}")) return false;
|
||||
String[] fields = host.split("\\.");
|
||||
int[] octets = new int[4];
|
||||
for (int i = 0; i < octets.length; i++) {
|
||||
if (fields[i].length() > 3 || (fields[i].length() > 1 && fields[i].startsWith("0"))) return false;
|
||||
octets[i] = Integer.parseInt(fields[i]);
|
||||
if (octets[i] > 255) return false;
|
||||
}
|
||||
return octets[0] == 10 ||
|
||||
(octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
|
||||
(octets[0] == 192 && octets[1] == 168);
|
||||
}
|
||||
|
||||
String requestOrigin(HttpExchange exchange) {
|
||||
String host = exchange.getRequestHeaders().getFirst("Host");
|
||||
if (host == null || exchange.getRequestHeaders().get("Host").size() != 1) return null;
|
||||
if (publicOrigin != null)
|
||||
return host.equalsIgnoreCase(publicOrigin.getRawAuthority()) ? publicOrigin.toString() : null;
|
||||
if (!host.matches("(?i)(localhost|127\\.0\\.0\\.1|\\[::1\\])(?::[0-9]{1,5})?")) return null;
|
||||
return "http://" + host.toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
static boolean adminOriginAllowed(HttpExchange exchange, String expected) {
|
||||
String submitted = exchange.getRequestHeaders().getFirst("Origin");
|
||||
if (submitted == null || submitted.equals(expected) || submitted.equals("null")) return true;
|
||||
return "same-origin".equals(exchange.getRequestHeaders().getFirst("Sec-Fetch-Site"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Base64;
|
||||
|
||||
final class AdminBranding {
|
||||
static final String DEFAULT_NAME = "ObjectStore admin";
|
||||
static final String DEFAULT_THEME = "deep-dark";
|
||||
static final int MAX_ICON_BYTES = 128 * 1024;
|
||||
private static final int MAX_FILE_BYTES = 180 * 1024;
|
||||
private final Path file;
|
||||
private volatile State state;
|
||||
|
||||
record State(String name, String mime, byte[] icon, String defaultTheme) { }
|
||||
|
||||
AdminBranding(Path file) throws IOException {
|
||||
this.file = file.toAbsolutePath().normalize();
|
||||
State loaded = new State(DEFAULT_NAME, "", new byte[0], DEFAULT_THEME);
|
||||
try {
|
||||
if (Files.exists(this.file)) loaded = decode(Files.readAllBytes(this.file));
|
||||
} catch (IOException error) {
|
||||
System.err.println("Could not load admin branding; using defaults: " + error.getMessage());
|
||||
}
|
||||
this.state = loaded;
|
||||
}
|
||||
|
||||
State state() {
|
||||
State current = state;
|
||||
return new State(current.name(), current.mime(), current.icon().clone(), current.defaultTheme());
|
||||
}
|
||||
|
||||
synchronized void setName(String name) throws IOException {
|
||||
String value = name == null ? "" : name.trim();
|
||||
if (value.isEmpty() || value.length() > 40 || value.chars().anyMatch(Character::isISOControl))
|
||||
throw new StoreException(400, "InvalidArgument", "Use a display name of 1 to 40 characters");
|
||||
persist(new State(value, state.mime(), state.icon(), state.defaultTheme()));
|
||||
}
|
||||
|
||||
synchronized void setIcon(byte[] icon) throws IOException {
|
||||
if (icon.length == 0 || icon.length > MAX_ICON_BYTES)
|
||||
throw new StoreException(413, "InvalidArgument", "Icon must be at most 128 KiB");
|
||||
String mime = mime(icon);
|
||||
if (mime == null)
|
||||
throw new StoreException(415, "InvalidArgument", "Use a PNG, JPEG, or WebP icon");
|
||||
persist(new State(state.name(), mime, icon.clone(), state.defaultTheme()));
|
||||
}
|
||||
|
||||
synchronized void setDefaultTheme(String theme) throws IOException {
|
||||
if (!validTheme(theme))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported Biscuit theme");
|
||||
persist(new State(state.name(), state.mime(), state.icon(), theme));
|
||||
}
|
||||
|
||||
synchronized void reset() throws IOException {
|
||||
persist(new State(DEFAULT_NAME, "", new byte[0], state.defaultTheme()));
|
||||
}
|
||||
|
||||
String json() {
|
||||
State current = state;
|
||||
String name = current.name().replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
return "{\"name\":\"" + name + "\",\"icon\":\"" +
|
||||
(current.icon().length == 0 ? AdminConsole.PATH + "/logo.png" :
|
||||
AdminConsole.PATH + "/branding-icon?v=" +
|
||||
Integer.toHexString(java.util.Arrays.hashCode(current.icon()))) +
|
||||
"\",\"defaultTheme\":\"" + current.defaultTheme() + "\"}";
|
||||
}
|
||||
|
||||
private void persist(State next) throws IOException {
|
||||
Path parent = file.getParent();
|
||||
Files.createDirectories(parent);
|
||||
Path temporary = Files.createTempFile(parent, "admin-branding-", ".part");
|
||||
try {
|
||||
byte[] bytes = ("ObjectStoreBranding 2\n" +
|
||||
Base64.getEncoder().encodeToString(next.name().getBytes(StandardCharsets.UTF_8)) + "\n" +
|
||||
next.mime() + "\n" + Base64.getEncoder().encodeToString(next.icon()) + "\n" +
|
||||
next.defaultTheme() + "\n")
|
||||
.getBytes(StandardCharsets.US_ASCII);
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(parent, StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
state = next;
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private static State decode(byte[] bytes) throws IOException {
|
||||
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Admin branding file is too large");
|
||||
try {
|
||||
String[] lines = new String(bytes, StandardCharsets.US_ASCII).split("\\n", -1);
|
||||
boolean oldFormat = lines.length == 5 && lines[0].equals("ObjectStoreBranding 1") &&
|
||||
lines[4].isEmpty();
|
||||
boolean newFormat = lines.length == 6 && lines[0].equals("ObjectStoreBranding 2") &&
|
||||
lines[5].isEmpty();
|
||||
if (!oldFormat && !newFormat)
|
||||
throw new IllegalArgumentException();
|
||||
String name = new String(Base64.getDecoder().decode(lines[1]), StandardCharsets.UTF_8);
|
||||
byte[] icon = Base64.getDecoder().decode(lines[3]);
|
||||
if (name.isBlank() || name.length() > 40 || name.chars().anyMatch(Character::isISOControl) ||
|
||||
icon.length > MAX_ICON_BYTES ||
|
||||
!(icon.length == 0 && lines[2].isEmpty() || lines[2].equals(mime(icon))))
|
||||
throw new IllegalArgumentException();
|
||||
String theme = oldFormat ? DEFAULT_THEME : lines[4];
|
||||
if (!validTheme(theme)) throw new IllegalArgumentException();
|
||||
return new State(name, lines[2], icon, theme);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid admin branding file", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean validTheme(String theme) {
|
||||
return "auto".equals(theme) || "light".equals(theme) ||
|
||||
"dark".equals(theme) || "deep-dark".equals(theme);
|
||||
}
|
||||
|
||||
private static String mime(byte[] bytes) {
|
||||
if (bytes.length >= 8 && (bytes[0] & 255) == 137 && bytes[1] == 80 && bytes[2] == 78 &&
|
||||
bytes[3] == 71 && bytes[4] == 13 && bytes[5] == 10 && bytes[6] == 26 && bytes[7] == 10)
|
||||
return "image/png";
|
||||
if (bytes.length >= 3 && (bytes[0] & 255) == 255 && (bytes[1] & 255) == 216 &&
|
||||
(bytes[2] & 255) == 255) return "image/jpeg";
|
||||
if (bytes.length >= 12 && bytes[0] == 'R' && bytes[1] == 'I' && bytes[2] == 'F' &&
|
||||
bytes[3] == 'F' && bytes[8] == 'W' && bytes[9] == 'E' && bytes[10] == 'B' &&
|
||||
bytes[11] == 'P') return "image/webp";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -4,75 +4,97 @@ import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminBrowserView.*;
|
||||
|
||||
final class AdminBrowser {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private AdminBrowser() { }
|
||||
|
||||
record EditorDraft(String value, String error) { }
|
||||
|
||||
static String index(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("filter", "after"));
|
||||
Map<String, String> query = query(rawQuery, Set.of("filter", "after", "page"));
|
||||
String filter = query.getOrDefault("filter", "").trim();
|
||||
String after = query.get("after");
|
||||
String pageQuery = query.get("page");
|
||||
if (filter.length() > 256 || after != null && after.length() > 255)
|
||||
throw invalidQuery();
|
||||
if (after != null && pageQuery != null) throw invalidQuery();
|
||||
List<ObjectStorage.Bucket> matches = store.buckets().stream()
|
||||
.filter(bucket -> bucket.name().toLowerCase(Locale.ROOT).contains(filter.toLowerCase(Locale.ROOT)))
|
||||
.sorted(Comparator.comparing(ObjectStorage.Bucket::name)).toList();
|
||||
List<ObjectStorage.Bucket> page = matches.stream()
|
||||
.filter(bucket -> after == null || bucket.name().compareTo(after) > 0)
|
||||
.limit(PAGE_SIZE + 1).toList();
|
||||
boolean next = page.size() > PAGE_SIZE;
|
||||
if (next) page = page.subList(0, PAGE_SIZE);
|
||||
int pageNumber = 1;
|
||||
if (pageQuery != null) {
|
||||
try { pageNumber = Integer.parseInt(pageQuery); }
|
||||
catch (NumberFormatException error) { throw invalidQuery(); }
|
||||
if (pageNumber < 1 || pageNumber > Math.max(1, (matches.size() + PAGE_SIZE - 1) / PAGE_SIZE))
|
||||
throw invalidQuery();
|
||||
} else if (after != null) {
|
||||
pageNumber = 1 + (int) matches.stream()
|
||||
.filter(bucket -> bucket.name().compareTo(after) <= 0).count() / PAGE_SIZE;
|
||||
}
|
||||
int offset = (pageNumber - 1) * PAGE_SIZE;
|
||||
List<ObjectStorage.Bucket> page = after == null ?
|
||||
matches.stream().skip(offset).limit(PAGE_SIZE).toList() :
|
||||
matches.stream().filter(bucket -> bucket.name().compareTo(after) > 0)
|
||||
.limit(PAGE_SIZE).toList();
|
||||
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/overview'>Overview</a><span>/</span><span>Buckets</span></nav>")
|
||||
.append("<div class=intro><div><h2>Buckets</h2><p>")
|
||||
.append(matches.size()).append(" matching buckets · read-only</p></div></div>")
|
||||
.append(matches.size()).append(" matching buckets</p></div>")
|
||||
.append("<button type=button class=primary-action data-open-dialog=create-bucket-dialog>")
|
||||
.append(AdminConsole.icon("plus")).append("New bucket</button></div>")
|
||||
.append("<div class=toolbar><form method=get action='").append(AdminConsole.PATH)
|
||||
.append("/buckets'><div class=field><label for=bucket-filter>Find a bucket</label>")
|
||||
.append("<input id=bucket-filter name=filter value='").append(AdminConsole.escape(filter))
|
||||
.append("' placeholder='Bucket name'></div><button type=submit>Search</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/overview'>Overview</a></div>");
|
||||
.append("/overview'>Overview</a></div>")
|
||||
.append(AdminBucketForms.create(csrf));
|
||||
if (page.isEmpty()) {
|
||||
html.append("<div class='table-wrap empty'>No buckets match this search.</div>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>")
|
||||
.append("<th>Ownership</th><th>Created</th></tr></thead><tbody>");
|
||||
.append("<th>Access</th><th>Ownership</th><th>Created</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : page) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(bucket.name(), "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioning(bucket.versioning())).append("</td><td>")
|
||||
.append(versioningBadge(bucket.versioning())).append("</td><td>")
|
||||
.append(accessBadge(bucket)).append("</td><td>")
|
||||
.append(ownership(bucket.ownership())).append("</td><td>")
|
||||
.append(time(bucket.created())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (after != null || next) {
|
||||
html.append("<nav class=pagination aria-label='Bucket pages'><a class=button-link href='")
|
||||
.append(indexUrl(filter, null)).append("'>First page</a>");
|
||||
if (next) html.append("<a class=button-link href='")
|
||||
.append(indexUrl(filter, page.getLast().name())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
if (matches.size() > PAGE_SIZE)
|
||||
html.append("<biscuit-paginationview class=bucket-pagination theme=deep-dark page=")
|
||||
.append(pageNumber).append(" total=").append(matches.size())
|
||||
.append(" page-size=").append(PAGE_SIZE).append(" data-filter='")
|
||||
.append(AdminConsole.escape(filter)).append("'></biscuit-paginationview>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return bucket(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf, EditorDraft policyDraft)
|
||||
throws IOException {
|
||||
return bucket(store, rawQuery, csrf, policyDraft, null);
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf, EditorDraft policyDraft,
|
||||
BucketActivity activity) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("name", "prefix", "after"));
|
||||
String name = required(query, "name", 255);
|
||||
String prefix = query.getOrDefault("prefix", "");
|
||||
@@ -87,13 +109,33 @@ final class AdminBrowser {
|
||||
html.append(breadcrumbs(name, prefix));
|
||||
html.append("<div class=intro><div><h2>").append(AdminConsole.escape(name))
|
||||
.append("</h2><p>Browse prefixes and inspect object metadata.</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Read-only</biscuit-badgeview></div>")
|
||||
.append("<div class=bucket-badges>")
|
||||
.append(versioningBadge(bucket.versioning()))
|
||||
.append(accessBadge(bucket))
|
||||
.append("</div></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Entries on this page</small><strong>")
|
||||
.append(page.keyCount()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Object bytes on this page</small><strong>")
|
||||
.append(AdminConsole.formatBytes(visibleBytes)).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Versioning</small><strong>")
|
||||
.append(versioning(bucket.versioning())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<biscuit-tablayout theme=deep-dark orientation=horizontal variant=underline ")
|
||||
.append("aria-label='Bucket panels' value='")
|
||||
.append(policyDraft == null ? "objects" : "settings").append("'>");
|
||||
objectsPanel(html, store.limits().maxObjectBytes(), name, prefix, after, page, csrf);
|
||||
html.append("<biscuit-tab label=Activity value=activity>")
|
||||
.append(activityPanel(name, activity));
|
||||
largestObjects(html, page, prefix);
|
||||
html.append("</biscuit-tab><biscuit-tab label=Settings value=settings>");
|
||||
bucketSummary(html, bucket);
|
||||
AdminBucketForms.settings(html, bucket, csrf, policyDraft);
|
||||
html.append("</biscuit-tab></biscuit-tablayout>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static void objectsPanel(StringBuilder html, long maxObjectBytes, String name,
|
||||
String prefix, String after, ObjectStorage.ListPage page, String csrf) {
|
||||
html.append("<biscuit-tab label=Objects value=objects>")
|
||||
.append("<section class=buckets id=objects><h2>Objects</h2>")
|
||||
.append("<p>Showing up to ").append(PAGE_SIZE)
|
||||
.append(" entries in this prefix. Counts and chart data describe this page only.</p>")
|
||||
@@ -103,24 +145,55 @@ final class AdminBrowser {
|
||||
.append("<input id=prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/2026/'></div><button type=submit>Browse</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/buckets'>All buckets</a></div>");
|
||||
.append("/buckets'>All buckets</a><a class=button-link href='")
|
||||
.append(versionsUrl(name, prefix, null, null)).append("'>")
|
||||
.append(AdminConsole.icon("version-history")).append("Versions</a></div>")
|
||||
.append("<form class='settings-form upload-form' data-bucket='")
|
||||
.append(AdminConsole.escape(name)).append("' data-prefix='")
|
||||
.append(AdminConsole.escape(prefix)).append("' data-max-bytes='")
|
||||
.append(maxObjectBytes).append("'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<h3>Upload file</h3><div class=upload-fields><label>Choose file")
|
||||
.append("<input type=file name=file required></label><label>Object key")
|
||||
.append("<input name=key value='").append(AdminConsole.escape(prefix))
|
||||
.append("' required placeholder='Path and file name'></label></div>")
|
||||
.append("<label class=check><input type=checkbox name=overwrite>Replace existing object")
|
||||
.append(" <small>(requires versioning)</small></label>")
|
||||
.append("<button type=submit>").append(AdminConsole.icon("upload"))
|
||||
.append("Upload</button><p class=upload-status role=status>")
|
||||
.append("JavaScript is required for uploads. Maximum file size: ")
|
||||
.append(AdminConsole.formatBytes(maxObjectBytes))
|
||||
.append(".</p></form>");
|
||||
objectTable(html, name, prefix, page);
|
||||
if (after != null || page.truncated()) {
|
||||
html.append("<nav class=pagination aria-label='Object pages'><a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, null)).append("'>First page</a>");
|
||||
if (page.truncated()) html.append("<a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, page.nextKey())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
html.append("</section></biscuit-tab>");
|
||||
}
|
||||
|
||||
private static void objectTable(StringBuilder html, String name, String prefix,
|
||||
ObjectStorage.ListPage page) {
|
||||
if (page.keyCount() == 0) {
|
||||
html.append("<div class='table-wrap empty'>Nothing in this prefix.</div>");
|
||||
if (!prefix.isEmpty()) html.append("<nav class=pagination><a class=button-link href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null)).append("'>← Parent folder</a></nav>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Kind</th>")
|
||||
.append("<th>Size</th><th>Modified</th></tr></thead><tbody>");
|
||||
.append("<th>Size</th><th>Modified</th><th>Actions</th></tr></thead><tbody>");
|
||||
if (!prefix.isEmpty()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null))
|
||||
.append("'>../</a></td><td class=kind>Parent</td><td>—</td><td>—</td></tr>");
|
||||
.append("'>../</a></td><td class=kind>Parent</td><td>—</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (String folder : page.prefixes()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, folder, null)).append("'>▸ ")
|
||||
.append(AdminConsole.escape(folder.substring(prefix.length())))
|
||||
.append("</a></td><td class=kind>Folder</td><td>—</td><td>—</td></tr>");
|
||||
.append("</a></td><td class=kind>Folder</td><td>—</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (ObjectStorage.ListedObject object : page.objects()) {
|
||||
ObjectStorage.Metadata meta = object.metadata();
|
||||
@@ -130,20 +203,18 @@ final class AdminBrowser {
|
||||
.append(objectUrl(name, object.key())).append("'>")
|
||||
.append(AdminConsole.escape(label)).append("</a></td><td class=kind>Object</td><td>")
|
||||
.append(AdminConsole.formatBytes(meta.length())).append("</td><td>")
|
||||
.append(time(meta.modified())).append("</td></tr>");
|
||||
.append(time(meta.modified())).append("</td><td><a href='")
|
||||
.append(downloadUrl(name, object.key(), null))
|
||||
.append("'>").append(AdminConsole.icon("download"))
|
||||
.append("Download</a></td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (after != null || page.truncated()) {
|
||||
html.append("<nav class=pagination aria-label='Object pages'><a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, null)).append("'>First page</a>");
|
||||
if (page.truncated()) html.append("<a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, page.nextKey())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
html.append("</section>");
|
||||
}
|
||||
|
||||
private static void largestObjects(StringBuilder html, ObjectStorage.ListPage page, String prefix) {
|
||||
if (!page.objects().isEmpty()) {
|
||||
html.append("<section class=insight><biscuit-chartview type=bar theme=dark ")
|
||||
html.append("<section class=insight><biscuit-chartview type=bar theme=deep-dark ")
|
||||
.append("name='Largest objects on this page' height=300>")
|
||||
.append("<biscuit-series type=bar x=label y=bytes name='Size in bytes'>");
|
||||
page.objects().stream().sorted(Comparator.comparingLong((ObjectStorage.ListedObject object) ->
|
||||
@@ -155,6 +226,9 @@ final class AdminBrowser {
|
||||
});
|
||||
html.append("</biscuit-series></biscuit-chartview></section>");
|
||||
}
|
||||
}
|
||||
|
||||
private static void bucketSummary(StringBuilder html, ObjectStorage.Bucket bucket) {
|
||||
html.append("<section class=buckets id=configuration><h2>Bucket settings</h2>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Access</h3>")
|
||||
.append(fact("Ownership", ownership(bucket.ownership())))
|
||||
@@ -173,143 +247,62 @@ final class AdminBrowser {
|
||||
if (!bucket.acl().isEmpty())
|
||||
html.append(attributes("Bucket grants", bucket.acl()));
|
||||
html.append("</section>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static String activityPanel(String bucket, BucketActivity activity) {
|
||||
if (activity == null)
|
||||
return "<section class=insight><h2>Daily activity</h2><p>Activity is unavailable.</p></section>";
|
||||
List<BucketActivity.Day> days = activity.days(bucket);
|
||||
long reads = days.stream().mapToLong(BucketActivity.Day::reads).sum();
|
||||
long writes = days.stream().mapToLong(BucketActivity.Day::writes).sum();
|
||||
StringBuilder html = new StringBuilder("<section class='insight activity-panel'><h2>Daily activity</h2>")
|
||||
.append("<p>Successful S3 requests observed by this server, in UTC. ")
|
||||
.append("The latest activity may take up to a minute to survive a sudden power loss.</p>")
|
||||
.append("<p class=activity-summary><strong>").append(reads + writes)
|
||||
.append(" requests</strong><span>").append(reads).append(" reads · ")
|
||||
.append(writes).append(" writes over 365 days</span></p>")
|
||||
.append("<biscuit-activity-chart theme=deep-dark name='Daily S3 requests' ")
|
||||
.append("calendar-range=rolling calendar-color='#9d73d5' ")
|
||||
.append("color-scale=steps gradient=subtle>")
|
||||
.append("<biscuit-series type=calendar x=date y=count name=Requests>");
|
||||
for (BucketActivity.Day day : days) {
|
||||
if (day.total() > 0)
|
||||
html.append("<biscuit-point x='").append(day.date()).append("' y='")
|
||||
.append(day.total()).append("'></biscuit-point>");
|
||||
}
|
||||
return html.append("</biscuit-series></biscuit-activity-chart>")
|
||||
.append("<p class=muted>Each square is one UTC day. Counts include reads and writes.</p></section>")
|
||||
.toString();
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "key"));
|
||||
String bucketName = required(query, "bucket", 255);
|
||||
String key = required(query, "key", 1024);
|
||||
store.bucket(bucketName);
|
||||
ObjectStorage.Metadata meta;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucketName, key)) {
|
||||
meta = opened.metadata();
|
||||
}
|
||||
int slash = key.lastIndexOf('/');
|
||||
String prefix = slash < 0 ? "" : key.substring(0, slash + 1);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucketName, prefix))
|
||||
.append("<div class=intro><div><h2 class=name-cell>")
|
||||
.append(AdminConsole.escape(key.endsWith("/") ? "(folder marker)" : key.substring(prefix.length())))
|
||||
.append("</h2><p>Object metadata · content is not loaded in this view</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Object</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Size</small><strong>")
|
||||
.append(AdminConsole.formatBytes(meta.length()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Content type</small><strong>")
|
||||
.append(AdminConsole.escape(meta.contentType() == null ? "Unknown" : meta.contentType()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Modified</small><strong>")
|
||||
.append(time(meta.modified())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Identity</h3>")
|
||||
.append(fact("Bucket", bucketName)).append(fact("Key", key))
|
||||
.append(fact("Version ID", meta.versionId() == null ? "Unversioned" : meta.versionId()))
|
||||
.append("</div><div class=detail-card><h3>Integrity</h3>")
|
||||
.append(fact("ETag", meta.etag() == null ? "—" : meta.etag()))
|
||||
.append(fact("SHA-256", meta.sha256() == null ? "—" :
|
||||
java.util.HexFormat.of().formatHex(meta.sha256())))
|
||||
.append("</div></div>")
|
||||
.append(attributes("User metadata", meta.userMetadata()))
|
||||
.append(attributes("Tags", meta.tags()))
|
||||
.append(attributes("Checksums", meta.checksums()))
|
||||
.append(attributes("ACL grants", meta.acl()));
|
||||
return html.toString();
|
||||
return AdminObjectPages.object(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf, EditorDraft contentDraft)
|
||||
throws IOException {
|
||||
return AdminObjectPages.object(store, rawQuery, csrf, contentDraft);
|
||||
}
|
||||
|
||||
static String versions(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return AdminObjectPages.versions(store, rawQuery, csrf);
|
||||
}
|
||||
|
||||
static String bucketUrl(String name, String prefix, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/bucket?name=" + encoded(name));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
return AdminBrowserView.bucketUrl(name, prefix, after);
|
||||
}
|
||||
|
||||
private static String objectUrl(String bucket, String key) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + encoded(bucket) + "&key=" + encoded(key);
|
||||
}
|
||||
|
||||
private static String indexUrl(String filter, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/buckets?filter=" + encoded(filter));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private static String breadcrumbs(String bucket, String prefix) {
|
||||
StringBuilder html = new StringBuilder("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/buckets'>Buckets</a><span>/</span>");
|
||||
if (prefix.isEmpty()) {
|
||||
html.append("<span>").append(AdminConsole.escape(bucket)).append("</span>");
|
||||
} else {
|
||||
html.append("<a href='").append(bucketUrl(bucket, "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket)).append("</a>");
|
||||
int from = 0;
|
||||
while (from < prefix.length()) {
|
||||
int slash = prefix.indexOf('/', from);
|
||||
if (slash < 0) break;
|
||||
String current = prefix.substring(0, slash + 1);
|
||||
String label = prefix.substring(from, slash + 1);
|
||||
html.append("<span>/</span><a href='").append(bucketUrl(bucket, current, null))
|
||||
.append("'>").append(AdminConsole.escape(label)).append("</a>");
|
||||
from = slash + 1;
|
||||
}
|
||||
}
|
||||
return html.append("</nav>").toString();
|
||||
}
|
||||
|
||||
private static String parentPrefix(String prefix) {
|
||||
int last = prefix.lastIndexOf('/', prefix.length() - 2);
|
||||
return last < 0 ? "" : prefix.substring(0, last + 1);
|
||||
}
|
||||
|
||||
private static String attributes(String title, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
StringBuilder html = new StringBuilder("<details><summary>")
|
||||
.append(AdminConsole.escape(title)).append(" (" + values.size() + ")</summary>")
|
||||
.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>");
|
||||
values.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
html.append("<tr><td class=name-cell>").append(AdminConsole.escape(entry.getKey()))
|
||||
.append("</td><td class=name-cell>").append(AdminConsole.escape(entry.getValue() == null ? "" : entry.getValue()))
|
||||
.append("</td></tr>"));
|
||||
return html.append("</tbody></table></div></details>").toString();
|
||||
}
|
||||
|
||||
private static String fact(String name, String value) {
|
||||
return "<div class=fact><span>" + AdminConsole.escape(name) + "</span><strong>" +
|
||||
AdminConsole.escape(value) + "</strong></div>";
|
||||
}
|
||||
|
||||
private static String versioning(ObjectStorage.VersioningState state) {
|
||||
return switch (state) {
|
||||
case NEVER -> "Off";
|
||||
case ENABLED -> "Enabled";
|
||||
case SUSPENDED -> "Suspended";
|
||||
};
|
||||
}
|
||||
|
||||
private static String ownership(ObjectStorage.ObjectOwnership value) {
|
||||
return switch (value) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
}
|
||||
|
||||
private static String yesNo(boolean value) {
|
||||
return value ? "On" : "Off";
|
||||
}
|
||||
|
||||
private static String time(long epochMillis) {
|
||||
return TIME.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
private static String encoded(String value) {
|
||||
static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> values, String name, int limit) {
|
||||
static String required(Map<String, String> values, String name, int limit) {
|
||||
String value = values.get(name);
|
||||
if (value == null || value.isEmpty() || value.length() > limit) throw invalidQuery();
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Map<String, String> query(String raw, Set<String> allowed) {
|
||||
static Map<String, String> query(String raw, Set<String> allowed) {
|
||||
if (raw == null || raw.isEmpty()) return Map.of();
|
||||
if (raw.length() > 8192) throw invalidQuery();
|
||||
Map<String, String> values = new HashMap<>();
|
||||
@@ -328,7 +321,7 @@ final class AdminBrowser {
|
||||
return values;
|
||||
}
|
||||
|
||||
private static StoreException invalidQuery() {
|
||||
static StoreException invalidQuery() {
|
||||
return new StoreException(400, "InvalidArgument", "Invalid browser link or search");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminBrowser.encoded;
|
||||
|
||||
final class AdminBrowserView {
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private AdminBrowserView() { }
|
||||
|
||||
static String bucketUrl(String name, String prefix, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/bucket?name=" + encoded(name));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
static String objectUrl(String bucket, String key) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + encoded(bucket) + "&key=" + encoded(key);
|
||||
}
|
||||
|
||||
static String downloadUrl(String bucket, String key, String version) {
|
||||
return AdminConsole.PATH + "/download?bucket=" + encoded(bucket) +
|
||||
"&key=" + encoded(key) +
|
||||
(version == null ? "" : "&version=" + encoded(version));
|
||||
}
|
||||
|
||||
static String versionsUrl(String bucket, String prefix, String keyMarker, String versionMarker) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/versions?bucket=" + encoded(bucket));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (keyMarker != null) url.append("&keyMarker=").append(encoded(keyMarker));
|
||||
if (versionMarker != null) url.append("&versionMarker=").append(encoded(versionMarker));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
static String breadcrumbs(String bucket, String prefix) {
|
||||
StringBuilder html = new StringBuilder("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/buckets'>Buckets</a><span>/</span>");
|
||||
if (prefix.isEmpty()) {
|
||||
html.append("<span>").append(AdminConsole.escape(bucket)).append("</span>");
|
||||
} else {
|
||||
html.append("<a href='").append(bucketUrl(bucket, "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket)).append("</a>");
|
||||
int from = 0;
|
||||
while (from < prefix.length()) {
|
||||
int slash = prefix.indexOf('/', from);
|
||||
if (slash < 0) break;
|
||||
String current = prefix.substring(0, slash + 1);
|
||||
String label = prefix.substring(from, slash + 1);
|
||||
html.append("<span>/</span><a href='").append(bucketUrl(bucket, current, null))
|
||||
.append("'>").append(AdminConsole.escape(label)).append("</a>");
|
||||
from = slash + 1;
|
||||
}
|
||||
}
|
||||
return html.append("</nav>").toString();
|
||||
}
|
||||
|
||||
static String parentPrefix(String prefix) {
|
||||
int last = prefix.lastIndexOf('/', prefix.length() - 2);
|
||||
return last < 0 ? "" : prefix.substring(0, last + 1);
|
||||
}
|
||||
|
||||
static String attributes(String title, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
StringBuilder html = new StringBuilder("<details><summary>")
|
||||
.append(AdminConsole.escape(title)).append(" (" + values.size() + ")</summary>")
|
||||
.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>");
|
||||
values.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
html.append("<tr><td class=name-cell>").append(AdminConsole.escape(entry.getKey()))
|
||||
.append("</td><td class=name-cell>").append(AdminConsole.escape(entry.getValue() == null ? "" : entry.getValue()))
|
||||
.append("</td></tr>"));
|
||||
return html.append("</tbody></table></div></details>").toString();
|
||||
}
|
||||
|
||||
static String fact(String name, String value) {
|
||||
return "<div class=fact><span>" + AdminConsole.escape(name) + "</span><strong>" +
|
||||
AdminConsole.escape(value) + "</strong></div>";
|
||||
}
|
||||
|
||||
static String versioning(ObjectStorage.VersioningState state) {
|
||||
return switch (state) {
|
||||
case NEVER -> "Off";
|
||||
case ENABLED -> "Enabled";
|
||||
case SUSPENDED -> "Suspended";
|
||||
};
|
||||
}
|
||||
|
||||
static String versioningBadge(ObjectStorage.VersioningState state) {
|
||||
String variant = state == ObjectStorage.VersioningState.ENABLED ? "success" :
|
||||
state == ObjectStorage.VersioningState.SUSPENDED ? "warning" : "accent";
|
||||
return badge(variant, "Versioning " + versioning(state));
|
||||
}
|
||||
|
||||
static String accessBadge(ObjectStorage.Bucket bucket) {
|
||||
ObjectStorage.PublicAccessBlock block = bucket.publicAccessBlock();
|
||||
boolean blocked = block.blockPublicAcls() && block.ignorePublicAcls() &&
|
||||
block.blockPublicPolicy() && block.restrictPublicBuckets();
|
||||
return badge(blocked ? "success" : "warning",
|
||||
blocked ? "Public access blocked" : "Public controls relaxed");
|
||||
}
|
||||
|
||||
static String badge(String variant, String text) {
|
||||
return "<biscuit-badgeview theme=deep-dark variant=" + variant + " size=small>" +
|
||||
AdminConsole.escape(text) + "</biscuit-badgeview>";
|
||||
}
|
||||
|
||||
static String ownership(ObjectStorage.ObjectOwnership value) {
|
||||
return switch (value) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
}
|
||||
|
||||
static String yesNo(boolean value) {
|
||||
return value ? "On" : "Off";
|
||||
}
|
||||
|
||||
static String time(long epochMillis) {
|
||||
return TIME.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
final class AdminBucketForms {
|
||||
private AdminBucketForms() { }
|
||||
|
||||
static String create(String csrf) {
|
||||
StringBuilder html = new StringBuilder();
|
||||
html.append("<biscuit-dialogview id=create-bucket-dialog theme=deep-dark label='Create bucket'>")
|
||||
.append("<form class='settings-form dialog-form bucket-wizard-form' method=post action='")
|
||||
.append(AdminConsole.PATH)
|
||||
.append("/action/create-bucket'><input type=hidden name=csrf value='").append(csrf)
|
||||
.append("'><input type=hidden name=setup value=wizard>")
|
||||
.append("<biscuit-formwizardview id=create-bucket-wizard theme=deep-dark>")
|
||||
.append("<biscuit-formstep label=Name value=name>")
|
||||
.append("<label for=new-bucket>Bucket name</label>")
|
||||
.append("<input id=new-bucket name=bucket required minlength=3 maxlength=63 ")
|
||||
.append("pattern='[a-z0-9][a-z0-9-]*[a-z0-9]' placeholder='e.g. media-archive'>")
|
||||
.append("<small>Bucket URLs and presigned links use this name.</small>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Storage value=storage>")
|
||||
.append("<label for=new-versioning>Versioning</label>")
|
||||
.append("<select id=new-versioning name=versioning><option value=off>Off</option>")
|
||||
.append("<option value=enabled>Enabled · retain old versions</option></select>")
|
||||
.append("<label for=new-ownership>Object ownership</label>")
|
||||
.append("<select id=new-ownership name=ownership>")
|
||||
.append("<option value=BucketOwnerEnforced>Bucket owner enforced · ACLs disabled</option>")
|
||||
.append("<option value=BucketOwnerPreferred>Bucket owner preferred</option>")
|
||||
.append("<option value=ObjectWriter>Object writer</option></select>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Access value=access>")
|
||||
.append("<p>Block public access by default. Turn off only the controls you need.</p>")
|
||||
.append("<div class=check-grid>")
|
||||
.append("<label class=check><input type=checkbox name=blockPublicAcls checked>Block public ACLs</label>")
|
||||
.append("<label class=check><input type=checkbox name=ignorePublicAcls checked>Ignore public ACLs</label>")
|
||||
.append("<label class=check><input type=checkbox name=blockPublicPolicy checked>Block public policies</label>")
|
||||
.append("<label class=check><input type=checkbox name=restrictPublicBuckets checked>Restrict public buckets</label>")
|
||||
.append("</div><label class=check id=public-ack-row hidden>")
|
||||
.append("<input type=checkbox name=acknowledgePublic value=yes>")
|
||||
.append("I understand that relaxing these controls can expose data</label>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Review value=review>")
|
||||
.append("<p id=bucket-wizard-review role=status></p>")
|
||||
.append("<small>Settings can be changed later in the bucket panel.</small>")
|
||||
.append("</biscuit-formstep></biscuit-formwizardview>")
|
||||
.append("<div class=dialog-actions><button type=button data-close-dialog>Cancel</button>")
|
||||
.append("</div></form></biscuit-dialogview>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static void settings(StringBuilder html, ObjectStorage.Bucket bucket, String csrf,
|
||||
AdminBrowser.EditorDraft policyDraft) {
|
||||
String name = bucket.name();
|
||||
html.append("<section class=buckets><h2>Manage bucket</h2>")
|
||||
.append("<p>Changes take effect immediately. Type the bucket name to confirm access changes.</p>")
|
||||
.append("<div class=settings-grid><form class=settings-form method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/versioning'>").append(hidden(csrf, name))
|
||||
.append("<h3>Versioning</h3><select name=state>")
|
||||
.append(option("ENABLED", bucket.versioning() == ObjectStorage.VersioningState.ENABLED))
|
||||
.append(option("SUSPENDED", bucket.versioning() == ObjectStorage.VersioningState.SUSPENDED))
|
||||
.append("</select><button>Save versioning</button></form>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/ownership'>").append(hidden(csrf, name))
|
||||
.append("<h3>Object Ownership</h3><select name=ownership>")
|
||||
.append(option("BucketOwnerEnforced", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED))
|
||||
.append(option("BucketOwnerPreferred", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED))
|
||||
.append(option("ObjectWriter", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.OBJECT_WRITER))
|
||||
.append("</select><input name=confirm placeholder='Type bucket name' required>")
|
||||
.append("<button>Save ownership</button></form></div>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/public-access'>").append(hidden(csrf, name))
|
||||
.append("<h3>Block Public Access</h3><div class=check-grid>")
|
||||
.append(checkbox("blockPublicAcls", "Block new public ACLs", bucket.publicAccessBlock().blockPublicAcls()))
|
||||
.append(checkbox("ignorePublicAcls", "Ignore existing public ACLs", bucket.publicAccessBlock().ignorePublicAcls()))
|
||||
.append(checkbox("blockPublicPolicy", "Block public policies", bucket.publicAccessBlock().blockPublicPolicy()))
|
||||
.append(checkbox("restrictPublicBuckets", "Restrict public buckets", bucket.publicAccessBlock().restrictPublicBuckets()))
|
||||
.append("</div><input name=confirm placeholder='Type bucket name if reducing protection'>")
|
||||
.append("<button>Save public access</button></form>")
|
||||
.append("<form class='settings-form code-form' id=policy-editor method=post action='")
|
||||
.append(AdminConsole.PATH)
|
||||
.append("/action/policy'>").append(hidden(csrf, name))
|
||||
.append("<h3>Bucket policy</h3><p class=muted>Edit the policy JSON for this bucket.</p>")
|
||||
.append("<biscuit-codeview class=policy-editor id=policy-code language=json ")
|
||||
.append("aria-label='Bucket policy JSON' value='")
|
||||
.append(AdminConsole.escape(policyDraft == null ?
|
||||
bucket.policy() == null ? "" : bucket.policy() : policyDraft.value()))
|
||||
.append("'></biscuit-codeview><textarea class='code-fallback policy-fallback' ")
|
||||
.append("name=policy rows=9 spellcheck=false placeholder='No policy configured'>")
|
||||
.append(AdminConsole.escape(policyDraft == null ?
|
||||
bucket.policy() == null ? "" : bucket.policy() : policyDraft.value()))
|
||||
.append("</textarea><p class=editor-diagnostics data-editor=policy-code data-state=")
|
||||
.append(policyDraft == null ? "hint" : "error")
|
||||
.append(" role=status>")
|
||||
.append(AdminConsole.escape(policyDraft == null ? "JSON syntax is checked before saving." :
|
||||
policyDraft.error()))
|
||||
.append("</p><input name=confirm placeholder='Type bucket name for public policy'>")
|
||||
.append("<button>Save policy</button></form>");
|
||||
if (bucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
grantForm(html, "bucket-grant", name, null, null, csrf);
|
||||
else html.append("<p class=muted>ACL editing is disabled while Bucket owner enforced is active.</p>");
|
||||
html.append("<biscuit-accordionview theme=deep-dark class=bucket-renamer>")
|
||||
.append("<biscuit-accordionitem label='Rename bucket'>")
|
||||
.append("<form class='settings-form rename-form' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/rename-bucket'>")
|
||||
.append(hidden(csrf, name))
|
||||
.append("<p class=rename-warning role=note><strong>Renaming changes the bucket URL.</strong> ")
|
||||
.append("Clients using the old name or presigned links will stop working. Update application ")
|
||||
.append("configuration and any external access policies. Stored objects, versions, and ")
|
||||
.append("multipart uploads remain in this bucket. Scoped access keys must be moved first. ")
|
||||
.append("If S3_BUCKET names this bucket, update it before restarting the service.</p>")
|
||||
.append("<label for=rename-target>New bucket name</label>")
|
||||
.append("<input id=rename-target name=newName required minlength=3 maxlength=63 ")
|
||||
.append("pattern='[a-z0-9][a-z0-9-]*[a-z0-9]' placeholder='New name'>")
|
||||
.append("<label for=rename-confirm>Type the current name to confirm</label>")
|
||||
.append("<input id=rename-confirm name=confirm required autocomplete=off>")
|
||||
.append("<button type=submit>Rename bucket</button></form>")
|
||||
.append("</biscuit-accordionitem></biscuit-accordionview>");
|
||||
html.append("<form class='settings-form danger-zone' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/delete-bucket'>")
|
||||
.append(hidden(csrf, name)).append("<h3>Delete bucket</h3>")
|
||||
.append("<p>Only an empty bucket can be deleted. Type its name to confirm.</p>")
|
||||
.append("<div class=form-row><input name=confirm required placeholder='Type bucket name'>")
|
||||
.append("<button>Delete bucket</button></div></form></section>");
|
||||
}
|
||||
|
||||
static void grantForm(StringBuilder html, String action, String bucket,
|
||||
String key, String version, String csrf) {
|
||||
html.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/").append(action).append("'>").append(hidden(csrf, bucket));
|
||||
if (key != null) html.append("<input type=hidden name=key value='")
|
||||
.append(AdminConsole.escape(key)).append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<h3>ACL grants</h3><p class=muted>Use an access key ID, AllUsers, or AuthenticatedUsers.</p>")
|
||||
.append("<div class=form-row><input name=principal required placeholder='Grantee'>")
|
||||
.append("<select name=permission><option>READ</option><option>WRITE</option>")
|
||||
.append("<option>READ_ACP</option><option>WRITE_ACP</option>")
|
||||
.append("<option>FULL_CONTROL</option></select>")
|
||||
.append("<select name=operation><option value=add>Add grant</option>")
|
||||
.append("<option value=remove>Remove grantee</option></select>")
|
||||
.append("<input name=confirm placeholder='Bucket name for public grant'>")
|
||||
.append("<button>Save grant</button></div></form>");
|
||||
}
|
||||
|
||||
static String hidden(String csrf, String bucket) {
|
||||
return "<input type=hidden name=csrf value='" + csrf +
|
||||
"'><input type=hidden name=bucket value='" + AdminConsole.escape(bucket) + "'>";
|
||||
}
|
||||
|
||||
private static String option(String name, boolean selected) {
|
||||
return "<option" + (selected ? " selected" : "") + ">" + name + "</option>";
|
||||
}
|
||||
|
||||
private static String checkbox(String name, String label, boolean checked) {
|
||||
return "<label class=check><input type=checkbox name='" + name + "'" +
|
||||
(checked ? " checked" : "") + ">" + label + "</label>";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminBulkJobs {
|
||||
static final int MAX_ITEMS = 10_000;
|
||||
private static final int MAX_REPORT_CHARS = 2_000_000;
|
||||
record Spec(String operation, String bucket, String prefix, String targetBucket,
|
||||
String targetPrefix, String tag, String value) { }
|
||||
record Snapshot(String id, Spec spec, String state, int processed, int succeeded,
|
||||
int failed, boolean capped, boolean reportTruncated, long started, long finished) { }
|
||||
|
||||
static final class Job {
|
||||
final String id;
|
||||
final Spec spec;
|
||||
final long started = System.currentTimeMillis();
|
||||
final StringBuilder report = new StringBuilder("status,bucket,key,detail\n");
|
||||
volatile String state = "Running";
|
||||
volatile int processed, succeeded, failed;
|
||||
volatile boolean capped, cancel, reportTruncated;
|
||||
volatile long finished;
|
||||
|
||||
Job(String id, Spec spec) {
|
||||
this.id = id;
|
||||
this.spec = spec;
|
||||
}
|
||||
Snapshot snapshot() {
|
||||
return new Snapshot(id, spec, state, processed, succeeded, failed, capped,
|
||||
reportTruncated, started, finished);
|
||||
}
|
||||
}
|
||||
|
||||
private final ObjectStorage store;
|
||||
private final java.util.function.Consumer<Snapshot> onFinish;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final ArrayDeque<Job> history = new ArrayDeque<>();
|
||||
private volatile StoreOperations operations = new StoreOperations();
|
||||
private Job active;
|
||||
|
||||
AdminBulkJobs(ObjectStorage store) { this(store, ignored -> { }); }
|
||||
|
||||
AdminBulkJobs(ObjectStorage store, java.util.function.Consumer<Snapshot> onFinish) {
|
||||
this.store = store;
|
||||
this.onFinish = onFinish;
|
||||
}
|
||||
|
||||
void setOperations(StoreOperations operations) { this.operations = operations; }
|
||||
|
||||
synchronized boolean hasActiveJob() { return active != null && active.finished == 0; }
|
||||
|
||||
Snapshot start(Spec spec) throws IOException {
|
||||
return operations.readValue(() -> startJob(spec));
|
||||
}
|
||||
|
||||
private synchronized Snapshot startJob(Spec spec) throws IOException {
|
||||
if (hasActiveJob())
|
||||
throw new StoreException(409, "JobInProgress", "Wait for or cancel the current job");
|
||||
validate(spec);
|
||||
byte[] id = new byte[12];
|
||||
random.nextBytes(id);
|
||||
Job job = new Job(Base64.getUrlEncoder().withoutPadding().encodeToString(id), spec);
|
||||
active = job;
|
||||
history.addFirst(job);
|
||||
while (history.size() > 10) history.removeLast();
|
||||
Thread.ofVirtual().name("objectstore-admin-job").start(() -> run(job));
|
||||
return job.snapshot();
|
||||
}
|
||||
|
||||
synchronized List<Snapshot> list() {
|
||||
return history.stream().map(Job::snapshot).toList();
|
||||
}
|
||||
|
||||
synchronized Snapshot get(String id) {
|
||||
Job job = find(id);
|
||||
return job.snapshot();
|
||||
}
|
||||
|
||||
synchronized String report(String id) {
|
||||
Job job = find(id);
|
||||
synchronized (job.report) { return job.report.toString(); }
|
||||
}
|
||||
|
||||
synchronized void cancel(String id) {
|
||||
Job job = find(id);
|
||||
if (job.finished == 0) job.cancel = true;
|
||||
}
|
||||
|
||||
private Job find(String id) {
|
||||
return history.stream().filter(job -> job.id.equals(id)).findFirst()
|
||||
.orElseThrow(() -> new StoreException(404, "NoSuchJob", "Job not found"));
|
||||
}
|
||||
|
||||
private void validate(Spec spec) throws IOException {
|
||||
if (!List.of("inventory", "copy", "delete", "tag").contains(spec.operation()))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported bulk operation");
|
||||
store.bucket(spec.bucket());
|
||||
if (spec.prefix() == null || spec.prefix().getBytes(StandardCharsets.UTF_8).length > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid prefix");
|
||||
if (spec.operation().equals("copy")) {
|
||||
store.bucket(spec.targetBucket());
|
||||
if (spec.bucket().equals(spec.targetBucket()))
|
||||
throw new StoreException(400, "InvalidArgument", "Bulk copy requires a different destination bucket");
|
||||
if (spec.targetPrefix() == null || spec.targetPrefix().getBytes(StandardCharsets.UTF_8).length > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid destination prefix");
|
||||
}
|
||||
if (spec.operation().equals("tag") && (spec.tag() == null || spec.tag().isBlank() ||
|
||||
spec.tag().length() > 128 || spec.value() == null || spec.value().length() > 256))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid tag key or value");
|
||||
if (spec.operation().equals("tag"))
|
||||
ObjectAttributes.validateTags(Map.of(spec.tag(), spec.value()));
|
||||
}
|
||||
|
||||
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);
|
||||
job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed";
|
||||
} catch (Exception error) {
|
||||
job.state = "Failed";
|
||||
append(job, "error", "", error.getClass().getSimpleName());
|
||||
} finally {
|
||||
job.finished = System.currentTimeMillis();
|
||||
onFinish.accept(job.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectStorage.ListPage list(Job job, String after) throws IOException {
|
||||
return operations.readValue(() ->
|
||||
store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after));
|
||||
}
|
||||
|
||||
private void process(Spec spec, ObjectStorage.ListedObject entry) throws IOException {
|
||||
String key = entry.key();
|
||||
switch (spec.operation()) {
|
||||
case "inventory" -> { }
|
||||
case "delete" -> store.delete(spec.bucket(), key);
|
||||
case "tag" -> {
|
||||
Map<String, String> tags = new HashMap<>(store.tags(spec.bucket(), key));
|
||||
tags.put(spec.tag(), spec.value());
|
||||
ObjectAttributes.validateTags(tags);
|
||||
store.setTags(spec.bucket(), key, Map.copyOf(tags));
|
||||
}
|
||||
case "copy" -> {
|
||||
try (ObjectStorage.OpenObject source = store.open(spec.bucket(), key)) {
|
||||
ObjectStorage.Metadata meta = source.metadata();
|
||||
String suffix = key.substring(spec.prefix().length());
|
||||
store.put(spec.targetBucket(), spec.targetPrefix() + suffix, source.stream(),
|
||||
meta.length(), SigV4.hex(meta.sha256()), null, true, meta.contentType(),
|
||||
meta.userMetadata(), meta.tags(), meta::checksums, Map.of());
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
private static void append(Job job, String status, String key, String detail) {
|
||||
synchronized (job.report) {
|
||||
if (job.report.length() >= MAX_REPORT_CHARS) {
|
||||
if (!job.reportTruncated) job.report.append("report-truncated,,,See job counters for totals\n");
|
||||
job.reportTruncated = true;
|
||||
return;
|
||||
}
|
||||
job.report.append(csv(status)).append(',').append(csv(job.spec.bucket())).append(',')
|
||||
.append(csv(key)).append(',').append(csv(detail)).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
private static String csv(String value) {
|
||||
String safe = value.replace("\r", " ").replace("\n", " ").replace("\t", " ");
|
||||
if (!safe.isEmpty() && "=+-@".indexOf(safe.charAt(0)) >= 0) safe = "'" + safe;
|
||||
return '"' + safe.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,67 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminFileTransfer {
|
||||
private AdminFileTransfer() { }
|
||||
|
||||
static String upload(ObjectStorage store, HttpExchange exchange) throws IOException {
|
||||
Map<String, String> query = AdminBrowser.query(exchange.getRequestURI().getRawQuery(),
|
||||
Set.of("bucket", "key", "overwrite"));
|
||||
String bucket = required(query, "bucket", 63);
|
||||
String key = required(query, "key", 1024);
|
||||
boolean overwrite = "1".equals(query.get("overwrite"));
|
||||
if (query.containsKey("overwrite") && !overwrite)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid overwrite option");
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
if (overwrite && current.versioning() != ObjectStorage.VersioningState.ENABLED)
|
||||
throw new StoreException(409, "InvalidBucketState", "Enable versioning before replacing an object");
|
||||
String lengthHeader = exchange.getRequestHeaders().getFirst("Content-Length");
|
||||
long length;
|
||||
try { length = Long.parseLong(lengthHeader); }
|
||||
catch (NumberFormatException | NullPointerException error) {
|
||||
throw new StoreException(411, "MissingContentLength", "Upload size is required");
|
||||
}
|
||||
if (length < 0 || length > store.limits().maxObjectBytes())
|
||||
throw new StoreException(413, "EntityTooLarge", "File exceeds the configured object limit");
|
||||
String type = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (type == null || type.isBlank()) type = "application/octet-stream";
|
||||
if (type.length() > 255 || type.chars().anyMatch(character -> character < 32 || character == 127))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid content type");
|
||||
store.put(bucket, key, exchange.getRequestBody(), length, null, null, !overwrite, type);
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key);
|
||||
}
|
||||
|
||||
static void download(ObjectStorage store, HttpExchange exchange) throws IOException {
|
||||
Map<String, String> query = AdminBrowser.query(exchange.getRequestURI().getRawQuery(),
|
||||
Set.of("bucket", "key", "version"));
|
||||
String bucket = required(query, "bucket", 63);
|
||||
String key = required(query, "key", 1024);
|
||||
String version = query.get("version");
|
||||
if (version != null && (version.isEmpty() || version.length() > 256))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object version");
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) {
|
||||
String filename = key.substring(key.lastIndexOf('/') + 1);
|
||||
if (filename.isEmpty()) filename = "object";
|
||||
String encoded = java.net.URLEncoder.encode(filename, StandardCharsets.UTF_8)
|
||||
.replace("+", "%20").replace("*", "%2A");
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/octet-stream");
|
||||
exchange.getResponseHeaders().set("Content-Disposition",
|
||||
"attachment; filename=\"download\"; filename*=UTF-8''" + encoded);
|
||||
exchange.sendResponseHeaders(200, opened.metadata().length());
|
||||
opened.stream().transferTo(exchange.getResponseBody());
|
||||
}
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> query, String name, int maxLength) {
|
||||
String value = query.get(name);
|
||||
if (value == null || value.isEmpty() || value.getBytes(StandardCharsets.UTF_8).length > maxLength)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object path");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminHttp {
|
||||
private static final int MAX_FORM_BYTES = 128 * 1024;
|
||||
|
||||
private AdminHttp() { }
|
||||
|
||||
static Map<String, String> readForm(HttpExchange exchange) throws IOException {
|
||||
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (contentType == null || !contentType.split(";", 2)[0].trim()
|
||||
.equalsIgnoreCase("application/x-www-form-urlencoded")) {
|
||||
throw new StoreException(415, "InvalidRequest", "Expected a form submission");
|
||||
}
|
||||
byte[] body = exchange.getRequestBody().readNBytes(MAX_FORM_BYTES + 1);
|
||||
if (body.length > MAX_FORM_BYTES) {
|
||||
throw new StoreException(413, "InvalidRequest", "Form is too large");
|
||||
}
|
||||
Map<String, String> values = new java.util.HashMap<>();
|
||||
try {
|
||||
for (String field : new String(body, StandardCharsets.UTF_8).split("&", -1)) {
|
||||
int split = field.indexOf('=');
|
||||
if (split < 0) continue;
|
||||
String key = URLDecoder.decode(field.substring(0, split), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(field.substring(split + 1), StandardCharsets.UTF_8);
|
||||
if (values.putIfAbsent(key, value) != null)
|
||||
throw new IllegalArgumentException("Duplicate form field");
|
||||
}
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new StoreException(400, "InvalidRequest", "Invalid form submission");
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
static void securityHeaders(HttpExchange exchange) {
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.getResponseHeaders().set("Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'self'; style-src-elem 'self' 'unsafe-inline'; " +
|
||||
"style-src-attr 'none'; script-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; " +
|
||||
"frame-ancestors 'none'; base-uri 'none'");
|
||||
exchange.getResponseHeaders().set("Referrer-Policy", "no-referrer");
|
||||
exchange.getResponseHeaders().set("X-Frame-Options", "DENY");
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
}
|
||||
|
||||
static void methodNotAllowed(HttpExchange exchange, String methods) throws IOException {
|
||||
exchange.getResponseHeaders().set("Allow", methods);
|
||||
send(exchange, 405, "Method not allowed", "text/plain; charset=utf-8");
|
||||
}
|
||||
|
||||
static void redirect(HttpExchange exchange, String path) throws IOException {
|
||||
exchange.getResponseHeaders().set("Location", path);
|
||||
exchange.sendResponseHeaders(303, -1);
|
||||
}
|
||||
|
||||
static void send(HttpExchange exchange, int status, String body, String contentType) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", contentType);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
|
||||
final class AdminLayout {
|
||||
static final Set<String> ICONS = Set.of("folder", "file", "refresh", "code-file",
|
||||
"search", "chevron-right", "objects", "bucket", "access-key", "activity", "sliders",
|
||||
"plus", "upload", "download", "version-history", "edit", "trash");
|
||||
|
||||
private AdminLayout() { }
|
||||
|
||||
static String page(String content) {
|
||||
return page(content, false);
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets) {
|
||||
return page(content, widgets, false);
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets, boolean performance) {
|
||||
boolean workspace = content.startsWith("<!--admin-shell-->");
|
||||
return "<!doctype html><html lang=en><head><meta charset=utf-8>" +
|
||||
"<meta name=viewport content='width=device-width,initial-scale=1'><title>ObjectStore admin</title>" +
|
||||
"<link rel=stylesheet href='" + PATH + "/style.css'>" +
|
||||
(widgets || workspace ? "<script defer src='" + PATH + "/biscuit.js'></script>" : "") +
|
||||
"<script defer src='" + PATH + "/workspace.js'></script>" +
|
||||
(performance ? "<script defer src='" + PATH + "/performance.js'></script>" : "") +
|
||||
"</head><body data-admin-theme=deep-dark" + (workspace ? " class=workspace-body" : "") + "><main>" +
|
||||
content + (workspace ? "</div><biscuit-toastview id=admin-toast theme=deep-dark></biscuit-toastview>" +
|
||||
"<biscuit-footerview theme=deep-dark brand='ObjectStore admin' " +
|
||||
"description='Private service controls' copyright='ObjectStore v" + Version.VALUE + "'>" +
|
||||
"<a href='https://lunarsky.cloud/objectstore/' data-footer-group=Resources>Documentation</a>" +
|
||||
"</biscuit-footerview></div></div>" : "") + "</main></body></html>";
|
||||
}
|
||||
|
||||
static String consoleHeader(String csrf) {
|
||||
return "<!--admin-shell--><div class=app-shell>" +
|
||||
"<biscuit-sidebarview theme=deep-dark label='Navigation' aria-label='Admin sections' sticky>" +
|
||||
"<div class=sidebar-brand>" + logoMark() +
|
||||
"<span><strong>ObjectStore</strong><small>ADMIN · v" + Version.VALUE + "</small></span></div>" +
|
||||
"<div class=sidebar-group>WORKSPACE</div>" +
|
||||
navLink("overview", "objects", "Overview") +
|
||||
navLink("buckets", "bucket", "Buckets") +
|
||||
"<div class=sidebar-group>OPERATIONS</div>" +
|
||||
navLink("credentials", "access-key", "Access keys") +
|
||||
navLink("performance", "activity", "Performance") +
|
||||
navLink("diagnostics", "search", "Diagnostics") +
|
||||
navLink("health", "refresh", "Health & recovery") +
|
||||
navLink("audit", "access-key", "Audit & access") +
|
||||
navLink("jobs", "refresh", "Bulk jobs") +
|
||||
navLink("cluster", "objects", "Cluster") +
|
||||
"<div class=sidebar-group>PREFERENCES</div>" +
|
||||
navLink("settings", "sliders", "Settings") +
|
||||
"</biscuit-sidebarview><div class=workspace>" +
|
||||
"<biscuit-pageloaderview id=page-loading mode=page theme=deep-dark open " +
|
||||
"message='Loading page…'><div class=loader-skeletons>" +
|
||||
"<biscuit-skeletonview width=220px height=18px></biscuit-skeletonview>" +
|
||||
"<biscuit-skeletonview width=160px height=12px></biscuit-skeletonview>" +
|
||||
"</div></biscuit-pageloaderview>" +
|
||||
"<biscuit-navbarview theme=deep-dark sticky brand='ObjectStore admin' brand-href='" + PATH +
|
||||
"/overview' aria-label='Admin toolbar'>" +
|
||||
mobileNavLink("overview", "objects", "Overview") +
|
||||
mobileNavLink("buckets", "bucket", "Buckets") +
|
||||
mobileNavLink("credentials", "access-key", "Access keys") +
|
||||
mobileNavLink("performance", "activity", "Performance") +
|
||||
mobileNavLink("diagnostics", "search", "Diagnostics") +
|
||||
mobileNavLink("health", "refresh", "Health & recovery") +
|
||||
mobileNavLink("audit", "access-key", "Audit & access") +
|
||||
mobileNavLink("jobs", "refresh", "Bulk jobs") +
|
||||
mobileNavLink("cluster", "objects", "Cluster") +
|
||||
mobileNavLink("settings", "sliders", "Settings") +
|
||||
"<form slot=actions method=post action='" + PATH +
|
||||
"/logout'><input type=hidden name=csrf value='" + csrf +
|
||||
"'><button type=submit>Sign out</button></form></biscuit-navbarview>" +
|
||||
"<div class=workspace-content>";
|
||||
}
|
||||
|
||||
static String navLink(String path, String icon, String label) {
|
||||
return "<a class=sidebar-link href='" + PATH + "/" + path + "'><img alt='' src='" + PATH +
|
||||
"/icons/" + icon + ".svg' width=18 height=18><span>" + label + "</span></a>";
|
||||
}
|
||||
|
||||
static String icon(String name) {
|
||||
if (!ICONS.contains(name)) throw new IllegalArgumentException("Unknown admin icon");
|
||||
return "<img class=action-icon src='" + PATH + "/icons/" + name +
|
||||
".svg' alt='' width=16 height=16>";
|
||||
}
|
||||
|
||||
static String mobileNavLink(String path, String icon, String label) {
|
||||
return "<a class=mobile-nav-link href='" + PATH + "/" + path +
|
||||
"'><img alt='' src='" + PATH + "/icons/" + icon +
|
||||
".svg' width=16 height=16>" + label + "</a>";
|
||||
}
|
||||
|
||||
static String logoMark() {
|
||||
return "<span class=mark aria-hidden=true><img src='" + PATH +
|
||||
"/logo.png' alt='' width=56 height=56></span>";
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
static String formatBytes(long bytes) {
|
||||
if (bytes == Long.MAX_VALUE) return "Unlimited";
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
String[] units = { "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
|
||||
double value = bytes;
|
||||
int unit = -1;
|
||||
do {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
} while (value >= 1024 && unit < units.length - 1);
|
||||
return String.format(java.util.Locale.ROOT, "%.1f %s", value, units[unit]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminBrowser.*;
|
||||
import static cloud.lunarsky.store.AdminBrowserView.*;
|
||||
import static cloud.lunarsky.store.AdminBucketForms.*;
|
||||
|
||||
final class AdminObjectPages {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
|
||||
private AdminObjectPages() { }
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return object(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf, AdminBrowser.EditorDraft contentDraft)
|
||||
throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "key", "version"));
|
||||
String bucketName = required(query, "bucket", 255);
|
||||
String key = required(query, "key", 1024);
|
||||
String version = query.get("version");
|
||||
if (version != null && (version.isEmpty() || version.length() > 256)) throw invalidQuery();
|
||||
ObjectStorage.Bucket bucket = store.bucket(bucketName);
|
||||
ObjectStorage.Metadata meta;
|
||||
String text = null;
|
||||
String previewError = null;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucketName, key, version)) {
|
||||
meta = opened.metadata();
|
||||
if (AdminTextEditor.supports(meta)) {
|
||||
try { text = AdminTextEditor.read(opened); }
|
||||
catch (StoreException error) { previewError = error.getMessage(); }
|
||||
}
|
||||
}
|
||||
int slash = key.lastIndexOf('/');
|
||||
String prefix = slash < 0 ? "" : key.substring(0, slash + 1);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucketName, prefix))
|
||||
.append("<div class=intro><div><h2 class=name-cell>")
|
||||
.append(AdminConsole.escape(key.endsWith("/") ? "(folder marker)" : key.substring(prefix.length())))
|
||||
.append("</h2><p>Inspect, download, or edit this object.</p></div>")
|
||||
.append("<biscuit-badgeview theme=deep-dark variant=accent>Object</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Size</small><strong>")
|
||||
.append(AdminConsole.formatBytes(meta.length()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Content type</small><strong>")
|
||||
.append(AdminConsole.escape(meta.contentType() == null ? "Unknown" : meta.contentType()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Modified</small><strong>")
|
||||
.append(time(meta.modified())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<p class=object-actions><a class=button-link href='")
|
||||
.append(downloadUrl(bucketName, key, version)).append("'>")
|
||||
.append(AdminConsole.icon("download")).append("Download file</a></p>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Identity</h3>")
|
||||
.append(fact("Bucket", bucketName)).append(fact("Key", key))
|
||||
.append(fact("Version ID", meta.versionId() == null ? "Unversioned" : meta.versionId()))
|
||||
.append("</div><div class=detail-card><h3>Integrity</h3>")
|
||||
.append(fact("ETag", meta.etag() == null ? "—" : meta.etag()))
|
||||
.append(fact("SHA-256", meta.sha256() == null ? "—" :
|
||||
java.util.HexFormat.of().formatHex(meta.sha256())))
|
||||
.append("</div></div>")
|
||||
.append(attributes("User metadata", meta.userMetadata()))
|
||||
.append(attributes("Tags", meta.tags()))
|
||||
.append(attributes("Checksums", meta.checksums()))
|
||||
.append(attributes("ACL grants", meta.acl()));
|
||||
if (text != null) {
|
||||
textEditor(html, bucket, meta, version, text, csrf, contentDraft);
|
||||
} else if (previewError != null) {
|
||||
html.append("<p class=muted>").append(AdminConsole.escape(previewError)).append("</p>");
|
||||
}
|
||||
if (bucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
grantForm(html, "object-grant", bucketName, key, version, csrf);
|
||||
objectActions(html, bucketName, key, version, csrf);
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static void textEditor(StringBuilder html, ObjectStorage.Bucket bucket,
|
||||
ObjectStorage.Metadata meta, String version, String text,
|
||||
String csrf, AdminBrowser.EditorDraft draft) {
|
||||
boolean versioningEnabled = bucket.versioning() ==
|
||||
ObjectStorage.VersioningState.ENABLED;
|
||||
boolean editable = version == null && versioningEnabled &&
|
||||
meta.versionId() != null && meta.sha256() != null;
|
||||
String value = draft == null ? text : draft.value();
|
||||
html.append("<section class=editor-section id=text-editor><div class=intro><div><h2>Text object</h2>")
|
||||
.append("<p>").append(editable ? "Saving creates a new object version." :
|
||||
version != null ? "Older versions are read-only." :
|
||||
!versioningEnabled ? "Enable bucket versioning to edit this object safely." :
|
||||
"This object has no version or integrity token and is read-only here.")
|
||||
.append("</p></div><biscuit-badgeview theme=deep-dark variant=accent>")
|
||||
.append(AdminConsole.escape(AdminTextEditor.language(meta)))
|
||||
.append("</biscuit-badgeview></div>");
|
||||
if (editable) html.append("<form class='settings-form code-form' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/edit-object'>")
|
||||
.append(hidden(csrf, bucket.name()))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(meta.key()))
|
||||
.append("'><input type=hidden name=originalVersion value='")
|
||||
.append(AdminConsole.escape(meta.versionId() == null ? "" : meta.versionId()))
|
||||
.append("'><input type=hidden name=originalSha256 value='")
|
||||
.append(meta.sha256() == null ? "" : SigV4.hex(meta.sha256())).append("'>");
|
||||
else html.append("<div class=settings-form>");
|
||||
html.append("<label for=object-code>Content</label><biscuit-codeview id=object-code ")
|
||||
.append("class=text-editor language='")
|
||||
.append(AdminConsole.escape(AdminTextEditor.language(meta)))
|
||||
.append("' aria-label='Object content'")
|
||||
.append(editable ? "" : " readonly")
|
||||
.append(" value='").append(AdminConsole.escape(value)).append("'></biscuit-codeview>")
|
||||
.append("<textarea class='code-fallback text-fallback' id=object-content rows=12 ")
|
||||
.append(editable ? "name=content" : "readonly")
|
||||
.append(">").append(AdminConsole.escape(value)).append("</textarea>")
|
||||
.append("<p class=editor-diagnostics data-editor=object-code data-state=")
|
||||
.append(draft == null ? "hint" : "error")
|
||||
.append(" role=status>")
|
||||
.append(AdminConsole.escape(draft == null ? "UTF-8 text · 32 KiB maximum" :
|
||||
draft.error())).append("</p>");
|
||||
if (editable) html.append("<button type=submit>")
|
||||
.append(AdminConsole.icon("edit")).append("Save new version</button></form>");
|
||||
else html.append("</div>");
|
||||
html.append("</section>");
|
||||
}
|
||||
|
||||
private static void objectActions(StringBuilder html, String bucketName, String key,
|
||||
String version, String csrf) {
|
||||
html.append("<section class=buckets><h2>Tags</h2>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/object-tag'>").append(hidden(csrf, bucketName))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(key))
|
||||
.append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<div class=form-row><input name=tag placeholder='Tag name' required maxlength=128>")
|
||||
.append("<input name=value placeholder='Value' maxlength=256>")
|
||||
.append("<select name=operation><option value=add>Save</option>")
|
||||
.append("<option value=remove>Remove</option></select><button>Apply tag</button></div></form></section>")
|
||||
.append("<form class='settings-form danger-zone' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/delete-object'>")
|
||||
.append(hidden(csrf, bucketName))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(key)).append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<h3>Delete object</h3><p>Type the full object key to confirm. ")
|
||||
.append(version == null ? "A versioned bucket may create a delete marker." :
|
||||
"This deletes the selected version permanently.")
|
||||
.append("</p><input name=confirm required placeholder='Full object key'>");
|
||||
if (version != null) html.append("<input name=confirmVersion required placeholder='Version ID'>");
|
||||
html.append("<button type=submit>").append(AdminConsole.icon("trash"))
|
||||
.append("Delete object</button></form>");
|
||||
}
|
||||
|
||||
static String versions(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "prefix", "keyMarker", "versionMarker"));
|
||||
String bucket = required(query, "bucket", 255);
|
||||
String prefix = query.getOrDefault("prefix", "");
|
||||
String keyMarker = query.get("keyMarker");
|
||||
String versionMarker = query.get("versionMarker");
|
||||
if (prefix.length() > 1024 || keyMarker != null && keyMarker.length() > 1024 ||
|
||||
versionMarker != null && (versionMarker.isEmpty() || versionMarker.length() > 256))
|
||||
throw invalidQuery();
|
||||
ObjectStorage.VersionPage page = store.listVersions(bucket, prefix, keyMarker, versionMarker, PAGE_SIZE);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucket, prefix))
|
||||
.append("<div class=intro><div><h2>Object versions</h2><p>Retained versions and delete markers")
|
||||
.append("</p></div></div><div class=toolbar><form method=get action='")
|
||||
.append(AdminConsole.PATH).append("/versions'><input type=hidden name=bucket value='")
|
||||
.append(AdminConsole.escape(bucket)).append("'><div class=field><label for=version-prefix>Prefix</label>")
|
||||
.append("<input id=version-prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/'></div><button type=submit>Browse</button></form></div>");
|
||||
if (page.entries().isEmpty()) {
|
||||
html.append("<div class='table-wrap empty'>No versions in this prefix.</div>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Key</th><th>Version</th>")
|
||||
.append("<th>State</th><th>Modified</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.VersionEntry entry : page.entries()) {
|
||||
html.append("<tr><td class=name-cell>");
|
||||
if (entry.deleteMarker()) html.append(AdminConsole.escape(entry.key()));
|
||||
else html.append("<a href='").append(objectUrl(bucket, entry.key()))
|
||||
.append("&version=").append(encoded(entry.versionId())).append("'>")
|
||||
.append(AdminConsole.escape(entry.key())).append("</a>");
|
||||
html.append("</td><td class=name-cell><code>").append(AdminConsole.escape(entry.versionId()))
|
||||
.append("</code></td><td>").append(entry.deleteMarker() ? "Delete marker" : "Object")
|
||||
.append(entry.latest() ? " · latest" : "").append("</td><td>")
|
||||
.append(time(entry.modified())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (page.truncated()) html.append("<nav class=pagination><a class=button-link href='")
|
||||
.append(versionsUrl(bucket, prefix, page.nextKey(), page.nextVersionId()))
|
||||
.append("'>Next page →</a></nav>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminOperationsPages {
|
||||
private AdminOperationsPages() { }
|
||||
|
||||
static String auditPage(Set<String> identities, RequestDiagnostics diagnostics, AdminAuditTrail audit, String csrf, AdminAccessCheck.Result result,
|
||||
Map<String, String> form) throws IOException {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Audit & access</h2>" +
|
||||
"<p>Recent admin changes and effective key access</p></div></div>");
|
||||
content.append("<section class=insight><h3>Check access</h3>" +
|
||||
"<p class=muted>Checks key scope, bucket policy, identity policy, and ACL for the current object. " +
|
||||
"It does not make a request or change data.</p><form class=settings-form method=post action='")
|
||||
.append(PATH).append("/action/access-check'><input type=hidden name=csrf value='")
|
||||
.append(csrf).append("'><div class=settings-grid><label>Access key<select name=principal required>");
|
||||
for (String identity : identities.stream().sorted().toList()) {
|
||||
content.append("<option value='").append(escape(identity)).append("'")
|
||||
.append(identity.equals(form.get("principal")) ? " selected" : "")
|
||||
.append(">").append(escape(identity)).append("</option>");
|
||||
}
|
||||
content.append("</select></label><label>Operation<select name=operation>");
|
||||
for (String operation : List.of("list", "read", "write", "delete")) {
|
||||
content.append("<option value='").append(operation).append("'")
|
||||
.append(operation.equals(form.get("operation")) ? " selected" : "")
|
||||
.append(">").append(operation).append("</option>");
|
||||
}
|
||||
content.append("</select></label><label>Bucket<input name=bucket required maxlength=63 value='")
|
||||
.append(escape(form.getOrDefault("bucket", "")))
|
||||
.append("'></label><label>Object key or list prefix<input name=key maxlength=1024 value='")
|
||||
.append(escape(form.getOrDefault("key", "")))
|
||||
.append("'></label></div><button type=submit>Check access</button></form>");
|
||||
if (result != null) content.append("<div class=detail-card role=status><strong>")
|
||||
.append(result.allowed() ? "Allowed" : "Denied").append("</strong><p>")
|
||||
.append(escape(result.stage())).append(": ").append(escape(result.explanation()))
|
||||
.append("</p></div>");
|
||||
content.append("</section><section class=insight><h3>Key activity since restart</h3>" +
|
||||
"<p class=muted>Counts include authenticated S3 requests on this gateway. No secrets or object keys are logged.</p>");
|
||||
RequestDiagnostics current = diagnostics;
|
||||
List<RequestDiagnostics.KeyActivity> keys = current == null ? List.of() : current.keyActivity();
|
||||
if (keys.isEmpty()) content.append("<p class=muted>No key activity yet.</p>");
|
||||
else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Access key</th><th>Requests</th>" +
|
||||
"<th>Errors</th><th>Last seen (UTC)</th></tr></thead><tbody>");
|
||||
for (var key : keys) content.append("<tr><td><code>").append(escape(key.principal()))
|
||||
.append("</code></td><td>").append(key.requests()).append("</td><td>")
|
||||
.append(key.failures()).append("</td><td>")
|
||||
.append(java.time.Instant.ofEpochMilli(key.lastSeenMillis())).append("</td></tr>");
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section><section class=insight><h3>Admin event trail</h3>" +
|
||||
"<p class=muted>Last 100 events from this gateway, stored on the admin data volume. " +
|
||||
"Older events rotate out.</p>");
|
||||
List<AdminAuditTrail.Entry> entries = audit.recent(100);
|
||||
if (entries.isEmpty()) content.append("<p class=muted>No events yet.</p>");
|
||||
else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Time (UTC)</th><th>Action</th>" +
|
||||
"<th>Target</th><th>Result</th><th>Peer</th></tr></thead><tbody>");
|
||||
for (var entry : entries) content.append("<tr><td>")
|
||||
.append(java.time.Instant.ofEpochMilli(entry.timeMillis())).append("</td><td>")
|
||||
.append(escape(entry.action())).append("</td><td><code>")
|
||||
.append(escape(entry.target())).append("</code></td><td>")
|
||||
.append(escape(entry.result())).append("</td><td>")
|
||||
.append(escape(entry.peer())).append("</td></tr>");
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
return page(content.append("</section>").toString(), true);
|
||||
}
|
||||
|
||||
static String jobsPage(AdminBulkJobs jobs, String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Bulk jobs</h2><p>Copy, delete, tag, or export an object inventory</p>" +
|
||||
"</div></div><p class=perf-note>One job at a time, up to " + AdminBulkJobs.MAX_ITEMS +
|
||||
" current objects per job. Jobs continue after leaving this page, but history and reports " +
|
||||
"reset when this gateway restarts. Cancellation takes effect between objects.</p>" +
|
||||
"<section class=insight><h3>Start a job</h3><form class=settings-form method=post action='" +
|
||||
PATH + "/action/bulk-start'><input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<div class=settings-grid><label>Operation<select name=operation>" +
|
||||
"<option value=inventory>Export inventory</option><option value=copy>Copy</option>" +
|
||||
"<option value=tag>Set tag</option><option value=delete>Delete</option></select></label>" +
|
||||
"<label>Source bucket<input name=bucket required maxlength=63></label>" +
|
||||
"<label>Key prefix<input name=prefix maxlength=1024 placeholder='Optional'></label>" +
|
||||
"<label data-bulk-only=copy>Destination bucket<input name=targetBucket maxlength=63></label>" +
|
||||
"<label data-bulk-only=copy>Destination prefix<input name=targetPrefix maxlength=1024></label>" +
|
||||
"<label data-bulk-only=tag>Tag key<input name=tag maxlength=128></label>" +
|
||||
"<label data-bulk-only=tag>Tag value<input name=value maxlength=256></label>" +
|
||||
"<label data-bulk-only=delete>Confirm source bucket<input name=confirm maxlength=63></label>" +
|
||||
"</div><p class=muted>Copy uses create-only writes and reports destination conflicts. " +
|
||||
"Delete follows bucket versioning and may create delete markers. " +
|
||||
"Inventory reports current objects only.</p><button type=submit>Start job</button>" +
|
||||
"</form></section><section class=insight><h3>Recent jobs</h3>");
|
||||
List<AdminBulkJobs.Snapshot> recent = jobs.list();
|
||||
if (recent.isEmpty()) content.append("<p class=muted>No jobs started on this gateway.</p>");
|
||||
for (AdminBulkJobs.Snapshot job : recent) {
|
||||
content.append("<div class=detail-card data-job-id='").append(job.id()).append("'>")
|
||||
.append("<div class=fact><span><strong>").append(escape(job.spec().operation()))
|
||||
.append("</strong> · <code>").append(escape(job.spec().bucket())).append("/")
|
||||
.append(escape(job.spec().prefix())).append("</code></span><biscuit-badgeview " +
|
||||
"data-job-state theme=deep-dark>").append(escape(job.state()))
|
||||
.append("</biscuit-badgeview></div><p data-job-counts>")
|
||||
.append(job.processed()).append(" processed · ").append(job.succeeded())
|
||||
.append(" succeeded · ").append(job.failed()).append(" failed")
|
||||
.append("</p><div class=form-row><a href='").append(PATH)
|
||||
.append("/jobs.csv?id=").append(job.id()).append("'>Download CSV report</a>");
|
||||
if (job.finished() == 0) content.append("<form method=post action='").append(PATH)
|
||||
.append("/action/bulk-cancel'><input type=hidden name=csrf value='")
|
||||
.append(csrf).append("'><input type=hidden name=id value='")
|
||||
.append(job.id()).append("'><button type=submit>Cancel</button></form>");
|
||||
content.append("</div>");
|
||||
if (job.capped()) content.append("<p class=rename-warning>Stopped at the job limit. " +
|
||||
"Run another job with a narrower prefix for remaining objects.</p>");
|
||||
if (job.reportTruncated()) content.append("<p class=rename-warning>The CSV report reached its " +
|
||||
"size limit; counters include all processed objects.</p>");
|
||||
content.append("</div>");
|
||||
}
|
||||
return page(content.append("</section>").toString(), true);
|
||||
}
|
||||
|
||||
static String jobJson(AdminBulkJobs.Snapshot job) {
|
||||
return "{\"state\":\"" + job.state() + "\",\"processed\":" + job.processed() +
|
||||
",\"succeeded\":" + job.succeeded() + ",\"failed\":" + job.failed() +
|
||||
",\"finished\":" + job.finished() + ",\"capped\":" + job.capped() +
|
||||
",\"reportTruncated\":" + job.reportTruncated() + "}";
|
||||
}
|
||||
|
||||
static String clusterPage(ObjectStorage store, String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Cluster</h2><p>Metadata and storage-node health</p></div></div>");
|
||||
if (!(store instanceof ClusterStore cluster)) {
|
||||
content.append("<section class=insight><p class=muted>This gateway runs in disk mode. " +
|
||||
"Cluster status appears here when cluster mode is enabled.</p></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
ClusterStore.ClusterStatus status = cluster.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();
|
||||
content.append("<p class=perf-note>Checked ")
|
||||
.append(java.time.Instant.ofEpochMilli(status.checkedAt()))
|
||||
.append(" UTC · Refresh for a new snapshot. Checks are cached for 15 seconds and probe at most " +
|
||||
"64 nodes. Node identity probes are bounded; this page does not scan object data.</p>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Metadata primary</small><strong>")
|
||||
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
|
||||
.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("<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>");
|
||||
for (ClusterStore.NodeStatus node : status.nodes()) {
|
||||
content.append("<div class=cluster-node data-state=")
|
||||
.append(node.reachable() ? "online" : "offline")
|
||||
.append("><strong>").append(node.reachable() ? "● Online" : "● Offline")
|
||||
.append("</strong><code>Node ").append(node.node().id())
|
||||
.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() ?
|
||||
"Not measured" :
|
||||
Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L)))
|
||||
.append("</small></div>");
|
||||
}
|
||||
content.append("</div></section>");
|
||||
content.append("<p class=muted>Host IDs show physical failure domains as configured by the operator. " +
|
||||
"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>");
|
||||
ClusterStore.RepairStatus repair = status.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>");
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminSettingsPages {
|
||||
private AdminSettingsPages() { }
|
||||
|
||||
static String credentialsPage(ManagedCredentials managedCredentials, ObjectStorage store, String csrf, ManagedCredentials.Key created) throws IOException {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf));
|
||||
content.append("<div class=intro><div><h2>Access keys</h2><p>Scoped S3 credentials for applications</p></div></div>");
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null) {
|
||||
content.append("<p class=muted>Managed keys are disabled. Configure a separate master key file to enable them.</p>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
if (created != null) {
|
||||
content.append("<section class=settings-form><h3>Save this secret now</h3>")
|
||||
.append("<p>The secret will not be displayed again.</p><div class=fact><span>Access key ID</span><strong><code>")
|
||||
.append(escape(created.id())).append("</code></strong></div>")
|
||||
.append("<div class=fact><span>Secret access key</span><strong><code>")
|
||||
.append(escape(created.secret())).append("</code></strong></div></section>");
|
||||
}
|
||||
content.append("<form class=settings-form method=post action='").append(PATH)
|
||||
.append("/action/create-key'><h3>Create scoped key</h3><p>Select one bucket and an optional key prefix.</p>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<label for=key-bucket>Bucket</label><select id=key-bucket name=bucket required>");
|
||||
for (ObjectStorage.Bucket bucket : store.buckets())
|
||||
content.append("<option value='").append(escape(bucket.name())).append("'>")
|
||||
.append(escape(bucket.name())).append("</option>");
|
||||
content.append("</select><label for=key-prefix>Key prefix</label>")
|
||||
.append("<input id=key-prefix name=prefix maxlength=256 placeholder='images/'>")
|
||||
.append("<div class=check-grid><label class=check><input type=checkbox name=read>Read</label>")
|
||||
.append("<label class=check><input type=checkbox name=write>Write</label>")
|
||||
.append("<label class=check><input type=checkbox name=list>List</label></div>")
|
||||
.append("<button type=submit>").append(icon("access-key"))
|
||||
.append("Create key</button></form>")
|
||||
.append("<section class=buckets><h2>Managed keys</h2><p>Disabling a key rejects new signed requests immediately.</p>");
|
||||
for (ManagedCredentials.Key key : managed.list()) {
|
||||
content.append("<div class=settings-form><h3><code>").append(escape(key.id()))
|
||||
.append("</code> <biscuit-badgeview theme=deep-dark variant=")
|
||||
.append(key.enabled() ? "success" : "warning").append(" size=small>")
|
||||
.append(key.enabled() ? "Active" : "Disabled")
|
||||
.append("</biscuit-badgeview></h3><p>")
|
||||
.append(escape(key.bucket())).append(" / ")
|
||||
.append(escape(key.prefix())).append(" · ")
|
||||
.append(escape(String.join(", ", key.actions().stream().sorted().toList())))
|
||||
.append("</p>")
|
||||
.append("<form method=post action='").append(PATH).append("/action/update-key'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<input type=hidden name=id value='").append(key.id()).append("'>")
|
||||
.append("<label>Bucket<input name=bucket required value='").append(escape(key.bucket()))
|
||||
.append("'></label><label>Prefix<input name=prefix maxlength=256 value='")
|
||||
.append(escape(key.prefix())).append("'></label><div class=check-grid>");
|
||||
for (String permission : List.of("read", "write", "list"))
|
||||
content.append("<label class=check><input type=checkbox name=").append(permission)
|
||||
.append(key.actions().contains(permission) ? " checked" : "")
|
||||
.append(">").append(permission).append("</label>");
|
||||
content.append("</div><label>Type the access key ID to confirm changes")
|
||||
.append("<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>Save scope</button></form>")
|
||||
.append("<form method=post action='").append(PATH).append("/action/")
|
||||
.append(key.enabled() ? "disable-key" : "enable-key").append("'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<input type=hidden name=id value='").append(key.id()).append("'>")
|
||||
.append("<label>Type the access key ID to confirm<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>").append(key.enabled() ? "Disable" : "Enable")
|
||||
.append("</button></form><form method=post action='").append(PATH)
|
||||
.append("/action/delete-key'><input type=hidden name=csrf value='").append(csrf)
|
||||
.append("'><input type=hidden name=id value='").append(key.id())
|
||||
.append("'><label>Type the access key ID to delete<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>Delete key</button></form></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String settingsPage(String csrf) {
|
||||
return consoleHeader(csrf) +
|
||||
"<nav class=crumbs aria-label=Breadcrumb><a href='" + PATH +
|
||||
"/overview'>Overview</a><span>/</span><span>Settings</span></nav>" +
|
||||
"<div class=intro><div><h2>Appearance</h2>" +
|
||||
"<p>Choose a theme for this browser or set the default for all admins.</p></div></div>" +
|
||||
"<section class=settings-grid><div class=settings-form>" +
|
||||
"<h3>Theme</h3><label for=admin-theme>This browser</label>" +
|
||||
"<select id=admin-theme><option value=default>Use server default</option>" +
|
||||
"<option value=dark>Dark</option>" +
|
||||
"<option value=auto>Follow system</option>" +
|
||||
"<option value=light>Light</option>" +
|
||||
"<option value=deep-dark>Deep dark</option></select>" +
|
||||
"<p class=muted>Your choice is saved only in this browser.</p>" +
|
||||
"<form method=post action='" + PATH + "/action/default-theme'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=admin-global-theme>Global default</label>" +
|
||||
"<select id=admin-global-theme name=defaultTheme>" +
|
||||
"<option value=deep-dark>Deep dark</option>" +
|
||||
"<option value=dark>Dark</option>" +
|
||||
"<option value=light>Light</option>" +
|
||||
"<option value=auto>Follow system</option></select>" +
|
||||
"<button type=submit>Save global default</button></form>" +
|
||||
"<p class=muted>Used by browsers without a personal theme choice.</p></div>" +
|
||||
"<div class=settings-form><h3>Branding</h3>" +
|
||||
"<form method=post action='" + PATH + "/action/branding-name'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=admin-brand-text>Display name</label>" +
|
||||
"<input id=admin-brand-text name=displayName maxlength=40 required placeholder='ObjectStore admin'>" +
|
||||
"<button type=submit>Save name</button></form>" +
|
||||
"<label for=admin-brand-icon>Icon image</label>" +
|
||||
"<input id=admin-brand-icon type=file data-csrf='" + csrf +
|
||||
"' accept='image/png,image/jpeg,image/webp'>" +
|
||||
"<div class=brand-preview><img id=admin-brand-preview src='" + PATH +
|
||||
"/logo.png' alt='Current admin icon' width=52 height=52>" +
|
||||
"<span id=admin-brand-preview-text>ObjectStore admin</span></div>" +
|
||||
"<p class=muted>PNG, JPEG, or WebP, up to 128 KiB. Changes appear on every device.</p>" +
|
||||
"<form method=post action='" + PATH + "/action/branding-reset'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<button id=admin-brand-reset type=submit>Reset branding</button></form>" +
|
||||
"<p id=admin-settings-status role=status></p></div></section>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.FileStore;
|
||||
import java.util.List;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminStatusPages {
|
||||
private AdminStatusPages() { }
|
||||
|
||||
static String overviewPage(String mode, String status, long maxObject, long maxTotal,
|
||||
List<ObjectStorage.Bucket> buckets, boolean bucketListAvailable,
|
||||
String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Overview</h2><p>Service status and configured limits</p></div>" +
|
||||
"<biscuit-badgeview theme=deep-dark variant='" + (status.equals("Ready") ? "success" : "danger") + "'>" +
|
||||
status + "</biscuit-badgeview></div>" +
|
||||
"<div class=grid><biscuit-cardview><small>Storage mode</small><strong>" + mode +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Buckets</small><strong>" +
|
||||
(bucketListAvailable ? buckets.size() : "Unavailable") +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Maximum object</small><strong>" +
|
||||
formatBytes(maxObject) + "</strong></biscuit-cardview><biscuit-cardview>" +
|
||||
"<small>Total storage limit</small><strong>" + formatBytes(maxTotal) +
|
||||
"</strong></biscuit-cardview></div><section class=buckets><h2>Buckets</h2>" +
|
||||
"<p>First 25 buckets. <a href='" + PATH +
|
||||
"/buckets'>Browse all buckets</a></p>");
|
||||
if (!bucketListAvailable || buckets.isEmpty()) {
|
||||
content.append("<div class='table-wrap empty'>")
|
||||
.append(bucketListAvailable ? "No buckets yet." : "Bucket list unavailable.")
|
||||
.append("</div>");
|
||||
} else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>" +
|
||||
"<th>Ownership</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : buckets.stream().limit(25).toList()) {
|
||||
String versioning = bucket.versioning() == ObjectStorage.VersioningState.NEVER ?
|
||||
"Off" : bucket.versioning().name().toLowerCase(java.util.Locale.ROOT);
|
||||
String ownership = switch (bucket.ownership()) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
content.append("<tr><td><a href='").append(AdminBrowser.bucketUrl(bucket.name(), "", null))
|
||||
.append("'>").append(escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioning).append("</td><td>").append(ownership).append("</td></tr>");
|
||||
}
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String performancePage(String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf));
|
||||
content.append("<div class=intro><div><h2>Performance</h2>")
|
||||
.append("<p>Live S3 traffic and process health</p></div>")
|
||||
.append("<biscuit-badgeview theme=deep-dark variant=accent>Live</biscuit-badgeview></div>")
|
||||
.append("<p class=perf-note>Live samples arrive about once a second while this tab is visible. ")
|
||||
.append("Traffic excludes admin pages and health checks. Charts keep only the last 60 samples ")
|
||||
.append("in this browser tab.</p><div class=perf-status-row>")
|
||||
.append("<biscuit-loadingindicator id=perf-loader theme=deep-dark size=small ")
|
||||
.append("label='Loading performance metrics' aria-hidden=true></biscuit-loadingindicator>")
|
||||
.append("<p id=perf-state class=perf-status data-state=loading role=status>Collecting samples…</p></div>")
|
||||
.append("<div class=perf-grid>")
|
||||
.append(perfCard("Requests / second", "perf-rps"))
|
||||
.append(perfCard("Average latency", "perf-latency"))
|
||||
.append(perfCard("Inbound / second", "perf-inbound"))
|
||||
.append(perfCard("Outbound / second", "perf-outbound"))
|
||||
.append(perfCard("Average CPU · recent", "perf-cpu"))
|
||||
.append(perfCard("Process RAM (RSS)", "perf-ram"))
|
||||
.append(perfCard("GC collections", "perf-gc"))
|
||||
.append(perfCard("In flight", "perf-inflight"))
|
||||
.append("</div><div class=perf-charts hidden>")
|
||||
.append("<biscuit-chartview id=perf-requests-chart theme=deep-dark type=line ")
|
||||
.append("name='Requests / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-transfer-chart theme=deep-dark type=line ")
|
||||
.append("name='Transfer / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-cpu-chart theme=deep-dark type=line ")
|
||||
.append("name='Process CPU' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-memory-chart theme=deep-dark type=line ")
|
||||
.append("name='Process memory' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("</div><p class=perf-note>Inbound and outbound measure HTTP body bytes, including ")
|
||||
.append("S3 metadata responses. CPU is the process share of available cores. ")
|
||||
.append("GC counts reset when the service restarts.</p>");
|
||||
return page(content.toString(), true, true);
|
||||
}
|
||||
|
||||
static String healthPage(DiskStore diskStore, ObjectStorage store, String csrf) {
|
||||
boolean ready = store.ready();
|
||||
String mode = diskStore == null ? "Cluster" : "Disk";
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Health & recovery</h2>" +
|
||||
"<p>Current service and storage state</p></div><biscuit-badgeview variant='" +
|
||||
(ready ? "success" : "danger") + "'>" + (ready ? "Ready" : "Unavailable") +
|
||||
"</biscuit-badgeview></div><div class=grid>" +
|
||||
"<biscuit-cardview><small>Storage mode</small><strong>" + mode +
|
||||
"</strong></biscuit-cardview>");
|
||||
if (diskStore != null) {
|
||||
long used = diskStore.usedBytes();
|
||||
long quota = store.limits().maxTotalBytes();
|
||||
content.append("<biscuit-cardview><small>Quota used</small><strong>")
|
||||
.append(formatBytes(used)).append(" / ").append(formatBytes(quota))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Current objects</small><strong>")
|
||||
.append(diskStore.objectCount()).append("</strong></biscuit-cardview>");
|
||||
try {
|
||||
FileStore volume = Files.getFileStore(diskStore.root());
|
||||
long free = volume.getUsableSpace();
|
||||
content.append("<biscuit-cardview><small>Filesystem available</small><strong>")
|
||||
.append(formatBytes(free)).append("</strong></biscuit-cardview>");
|
||||
if (free < Math.max(0, quota - used))
|
||||
content.append("<p class=rename-warning>Filesystem free space is below the remaining configured quota. " +
|
||||
"The volume can fill before the quota is reached.</p>");
|
||||
} catch (IOException unavailable) {
|
||||
content.append("<biscuit-cardview><small>Filesystem available</small><strong>Unavailable" +
|
||||
"</strong></biscuit-cardview>");
|
||||
}
|
||||
} else {
|
||||
content.append("<biscuit-cardview><small>Storage nodes</small><strong>Not measured here" +
|
||||
"</strong></biscuit-cardview>");
|
||||
}
|
||||
content.append("</div><section class=insight><div class=detail-card><h3>Recovery readiness</h3>" +
|
||||
"<div class=fact><span>Latest off-site backup</span><strong>Not reported</strong></div>" +
|
||||
"<div class=fact><span>Latest restore test</span><strong>Not reported</strong></div>" +
|
||||
"<p class=muted>ObjectStore cannot verify external backups or restores. Check your backup jobs " +
|
||||
"and perform a restore drill before relying on this service for important data.</p>" +
|
||||
"<a href='https://lunarsky.cloud/objectstore/v0.0.8/operations'>Recovery documentation</a>" +
|
||||
"</div></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String diagnosticsPage(RequestDiagnostics diagnostics, String csrf) {
|
||||
RequestDiagnostics current = diagnostics;
|
||||
RequestDiagnostics.Snapshot snapshot = current == null ? null : current.snapshot();
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Request diagnostics</h2>" +
|
||||
"<p>Recent S3 requests on this gateway</p></div></div>" +
|
||||
"<p class=perf-note>Five-minute rolling window. Latency percentiles are histogram upper bounds. " +
|
||||
"Admin requests and health checks are excluded. Refresh to update.</p>");
|
||||
if (snapshot == null) {
|
||||
content.append("<p class=error>Request diagnostics are unavailable.</p>");
|
||||
} else {
|
||||
content.append("<div class=grid><biscuit-cardview><small>Requests</small><strong>")
|
||||
.append(snapshot.requests()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>4xx / 5xx</small><strong>")
|
||||
.append(snapshot.clientErrors()).append(" / ").append(snapshot.serverErrors())
|
||||
.append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>p50 / p95</small><strong>")
|
||||
.append(latencyLabel(snapshot.p50Millis())).append(" / ")
|
||||
.append(latencyLabel(snapshot.p95Millis())).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>p99</small><strong>")
|
||||
.append(latencyLabel(snapshot.p99Millis())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<section class=insight><h3>Recent errors</h3><p class=muted>Most recent 64 errors; " +
|
||||
"bucket names and request IDs only. Object keys and credentials are not retained.</p>");
|
||||
if (snapshot.recentFailures().isEmpty()) {
|
||||
content.append("<div class='table-wrap empty'>No errors in this window.</div>");
|
||||
} else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Time (UTC)</th><th>Status</th>" +
|
||||
"<th>Operation</th><th>Bucket</th><th>Request ID</th></tr></thead><tbody>");
|
||||
for (RequestDiagnostics.Failure failure : snapshot.recentFailures()) {
|
||||
content.append("<tr><td>").append(java.time.Instant.ofEpochMilli(failure.timeMillis()))
|
||||
.append("</td><td>").append(failure.status()).append("</td><td>")
|
||||
.append(escape(failure.operation())).append("</td><td>")
|
||||
.append(escape(failure.bucket())).append("</td><td><code>")
|
||||
.append(escape(failure.requestId())).append("</code></td></tr>");
|
||||
}
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
}
|
||||
content.append("<section class=insight><div class=detail-card><h3>Connection probe</h3>" +
|
||||
"<p class=muted>Download 1 MiB from the admin listener to measure browser-to-gateway timing. " +
|
||||
"This does not measure object reads, disks, or storage nodes.</p>" +
|
||||
"<button id=diagnostic-probe type=button>Run probe</button> " +
|
||||
"<span id=diagnostic-probe-result role=status></span></div></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String latencyLabel(long upperMillis) {
|
||||
return upperMillis < 0 ? ">10 s" : upperMillis + " ms";
|
||||
}
|
||||
|
||||
static String perfCard(String label, String id) {
|
||||
return "<biscuit-cardview><small>" + label + "</small><strong id='" + id +
|
||||
"'><biscuit-skeletonview width=72px height=22px></biscuit-skeletonview>" +
|
||||
"</strong></biscuit-cardview>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminTextEditor {
|
||||
static final int MAX_BYTES = 32 * 1024;
|
||||
|
||||
private AdminTextEditor() { }
|
||||
|
||||
static boolean supports(ObjectStorage.Metadata metadata) {
|
||||
if (metadata.length() > MAX_BYTES) return false;
|
||||
String type = metadata.contentType() == null ? "" :
|
||||
metadata.contentType().split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
|
||||
if (type.startsWith("text/") || type.equals("application/json") ||
|
||||
type.equals("application/xml") || type.equals("application/javascript") ||
|
||||
type.equals("application/x-javascript") || type.equals("application/x-yaml")) return true;
|
||||
String key = metadata.key().toLowerCase(Locale.ROOT);
|
||||
return type.equals("application/octet-stream") &&
|
||||
(key.endsWith(".txt") || key.endsWith(".json") || key.endsWith(".xml") ||
|
||||
key.endsWith(".md") || key.endsWith(".html") || key.endsWith(".css") ||
|
||||
key.endsWith(".js") || key.endsWith(".java") || key.endsWith(".yaml") ||
|
||||
key.endsWith(".yml"));
|
||||
}
|
||||
|
||||
static String read(ObjectStorage.OpenObject opened) throws IOException {
|
||||
byte[] data = opened.stream().readNBytes(MAX_BYTES + 1);
|
||||
if (data.length > MAX_BYTES) throw new StoreException(413, "EntityTooLarge", "Text preview is too large");
|
||||
try {
|
||||
String text = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(data)).toString();
|
||||
if (text.indexOf('\0') >= 0)
|
||||
throw new StoreException(415, "InvalidObjectState", "This object contains binary data");
|
||||
return text;
|
||||
} catch (CharacterCodingException error) {
|
||||
throw new StoreException(415, "InvalidObjectState", "This object is not UTF-8 text");
|
||||
}
|
||||
}
|
||||
|
||||
static String language(ObjectStorage.Metadata metadata) {
|
||||
String key = metadata.key().toLowerCase(Locale.ROOT);
|
||||
String type = metadata.contentType() == null ? "" : metadata.contentType().toLowerCase(Locale.ROOT);
|
||||
if (key.endsWith(".json") || type.contains("json")) return "json";
|
||||
if (key.endsWith(".html") || type.contains("html")) return "html";
|
||||
if (key.endsWith(".css") || type.contains("css")) return "css";
|
||||
if (key.endsWith(".js") || type.contains("javascript")) return "javascript";
|
||||
if (key.endsWith(".java")) return "java";
|
||||
return "plain";
|
||||
}
|
||||
|
||||
static String save(ObjectStorage store, Map<String, String> form) throws IOException {
|
||||
String bucket = form.getOrDefault("bucket", "");
|
||||
String key = form.getOrDefault("key", "");
|
||||
if (bucket.isEmpty() || bucket.length() > 63 || key.isEmpty() || key.length() > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object path");
|
||||
if (store.bucket(bucket).versioning() != ObjectStorage.VersioningState.ENABLED)
|
||||
throw new StoreException(409, "InvalidBucketState", "Enable bucket versioning before editing objects");
|
||||
String value = form.getOrDefault("content", "");
|
||||
byte[] data = value.getBytes(StandardCharsets.UTF_8);
|
||||
if (data.length > MAX_BYTES)
|
||||
throw new StoreException(413, "EntityTooLarge", "Text files are limited to 32 KiB in the admin editor");
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key)) {
|
||||
metadata = opened.metadata();
|
||||
if (!supports(metadata))
|
||||
throw new StoreException(415, "InvalidObjectState", "Only small text objects can be edited");
|
||||
read(opened);
|
||||
}
|
||||
if (metadata.versionId() == null || !metadata.versionId().equals(form.get("originalVersion")) ||
|
||||
metadata.sha256() == null || !SigV4.hex(metadata.sha256()).equals(form.get("originalSha256")))
|
||||
throw new StoreException(409, "Conflict", "The object changed. Reload before saving your edit");
|
||||
try {
|
||||
store.replaceVersion(bucket, key, data, metadata);
|
||||
} catch (StoreException error) {
|
||||
if (error.status == 412)
|
||||
throw new StoreException(409, "Conflict", "The object changed. Reload before saving your edit");
|
||||
throw error;
|
||||
} finally {
|
||||
Arrays.fill(data, (byte) 0);
|
||||
}
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,8 @@ final class AwsChunkedInputStream extends FilterInputStream {
|
||||
throw invalid("Invalid signed chunk header");
|
||||
try { chunkLeft = Long.parseUnsignedLong(size, 16); }
|
||||
catch (NumberFormatException error) { throw invalid("Invalid signed chunk size"); }
|
||||
if (chunkLeft > decodedLength - decoded) throw invalid("Signed chunks exceed decoded length");
|
||||
if (chunkLeft < 0 || chunkLeft > decodedLength - decoded)
|
||||
throw invalid("Signed chunks exceed decoded length");
|
||||
chunkHash.reset();
|
||||
if (chunkLeft == 0) finishPayload();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
final class BucketActivity implements AutoCloseable {
|
||||
private static final int DAYS = 365;
|
||||
private final Path file;
|
||||
private final ConcurrentHashMap<Key, Counts> counts = new ConcurrentHashMap<>();
|
||||
private final AtomicBoolean dirty = new AtomicBoolean();
|
||||
private final ScheduledExecutorService writer = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
Thread thread = new Thread(task, "objectstore-bucket-activity");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
record Day(LocalDate date, long reads, long writes) {
|
||||
long total() { return reads + writes; }
|
||||
}
|
||||
|
||||
private record Key(String bucket, long epochDay) { }
|
||||
|
||||
private static final class Counts {
|
||||
final LongAdder reads = new LongAdder();
|
||||
final LongAdder writes = new LongAdder();
|
||||
}
|
||||
|
||||
BucketActivity(Path file) {
|
||||
this.file = file.toAbsolutePath().normalize();
|
||||
try { load(); }
|
||||
catch (IOException | IllegalArgumentException error) {
|
||||
counts.clear();
|
||||
System.err.println("Could not load bucket activity: " + error.getMessage());
|
||||
}
|
||||
writer.scheduleWithFixedDelay(this::flushSafely, 60, 60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
void record(String bucket, String method) {
|
||||
if (!validBucket(bucket)) return;
|
||||
if (!method.equals("GET") && !method.equals("HEAD") &&
|
||||
!method.equals("PUT") && !method.equals("POST") && !method.equals("DELETE")) return;
|
||||
long epochDay = Math.floorDiv(System.currentTimeMillis(), 86_400_000L);
|
||||
Counts day = counts.computeIfAbsent(new Key(bucket, epochDay),
|
||||
ignored -> new Counts());
|
||||
if (method.equals("GET") || method.equals("HEAD")) day.reads.increment();
|
||||
else day.writes.increment();
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
List<Day> days(String bucket) {
|
||||
LocalDate today = LocalDate.now(ZoneOffset.UTC);
|
||||
LocalDate start = today.minusDays(DAYS - 1);
|
||||
List<Day> result = new ArrayList<>(DAYS);
|
||||
for (int offset = 0; offset < DAYS; offset++) {
|
||||
LocalDate date = start.plusDays(offset);
|
||||
Counts value = counts.get(new Key(bucket, date.toEpochDay()));
|
||||
result.add(new Day(date, value == null ? 0 : value.reads.sum(),
|
||||
value == null ? 0 : value.writes.sum()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
synchronized void rename(String oldName, String newName) {
|
||||
if (oldName.equals(newName)) return;
|
||||
for (var entry : counts.entrySet()) {
|
||||
Key key = entry.getKey();
|
||||
if (!key.bucket.equals(oldName)) continue;
|
||||
Counts moved = counts.computeIfAbsent(new Key(newName, key.epochDay), ignored -> new Counts());
|
||||
moved.reads.add(entry.getValue().reads.sum());
|
||||
moved.writes.add(entry.getValue().writes.sum());
|
||||
counts.remove(key, entry.getValue());
|
||||
}
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
synchronized void remove(String bucket) {
|
||||
counts.keySet().removeIf(key -> key.bucket.equals(bucket));
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
private void load() throws IOException {
|
||||
if (!Files.exists(file)) return;
|
||||
if (Files.size(file) > 64L * 1024 * 1024)
|
||||
throw new IOException("Activity file is too large");
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
if (lines.isEmpty() || !lines.getFirst().equals("ObjectStoreActivity 1"))
|
||||
throw new IOException("Invalid activity file header");
|
||||
LocalDate earliest = LocalDate.now(ZoneOffset.UTC).minusDays(DAYS - 1);
|
||||
for (int index = 1; index < lines.size(); index++) {
|
||||
String[] fields = lines.get(index).split("\\t", -1);
|
||||
if (fields.length != 4 || !validBucket(fields[0]))
|
||||
throw new IOException("Invalid activity record");
|
||||
try {
|
||||
LocalDate date = LocalDate.parse(fields[1]);
|
||||
long reads = Long.parseLong(fields[2]);
|
||||
long writes = Long.parseLong(fields[3]);
|
||||
if (reads < 0 || writes < 0) throw new NumberFormatException();
|
||||
if (date.isBefore(earliest) || date.isAfter(LocalDate.now(ZoneOffset.UTC))) continue;
|
||||
Counts value = counts.computeIfAbsent(new Key(fields[0], date.toEpochDay()),
|
||||
ignored -> new Counts());
|
||||
value.reads.add(reads);
|
||||
value.writes.add(writes);
|
||||
} catch (RuntimeException error) {
|
||||
throw new IOException("Invalid activity record", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void flushSafely() {
|
||||
if (!dirty.getAndSet(false)) return;
|
||||
try { flush(); }
|
||||
catch (IOException error) {
|
||||
dirty.set(true);
|
||||
System.err.println("Could not save bucket activity: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void flush() throws IOException {
|
||||
LocalDate earliest = LocalDate.now(ZoneOffset.UTC).minusDays(DAYS - 1);
|
||||
counts.keySet().removeIf(key -> key.epochDay < earliest.toEpochDay());
|
||||
StringBuilder data = new StringBuilder("ObjectStoreActivity 1\n");
|
||||
counts.entrySet().stream().sorted((left, right) -> {
|
||||
int byBucket = left.getKey().bucket.compareTo(right.getKey().bucket);
|
||||
return byBucket == 0 ? Long.compare(left.getKey().epochDay, right.getKey().epochDay) : byBucket;
|
||||
}).forEach(entry -> data.append(entry.getKey().bucket).append('\t')
|
||||
.append(LocalDate.ofEpochDay(entry.getKey().epochDay)).append('\t')
|
||||
.append(entry.getValue().reads.sum())
|
||||
.append('\t').append(entry.getValue().writes.sum()).append('\n'));
|
||||
Path parent = file.getParent();
|
||||
Files.createDirectories(parent);
|
||||
Path temporary = Files.createTempFile(parent, "bucket-activity-", ".part");
|
||||
try {
|
||||
ByteBuffer bytes = StandardCharsets.UTF_8.encode(data.toString());
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
while (bytes.hasRemaining()) channel.write(bytes);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(parent, StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private static boolean validBucket(String bucket) {
|
||||
if (bucket == null || bucket.length() < 3 || bucket.length() > 63 ||
|
||||
bucket.charAt(0) == '-' || bucket.charAt(bucket.length() - 1) == '-') return false;
|
||||
for (int index = 0; index < bucket.length(); index++) {
|
||||
char character = bucket.charAt(index);
|
||||
if (character != '-' && (character < 'a' || character > 'z') &&
|
||||
(character < '0' || character > '9')) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
writer.shutdown();
|
||||
flushSafely();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
final class BucketNameCatalog {
|
||||
private final DiskStore store;
|
||||
private final Path catalog;
|
||||
private final Path deletion;
|
||||
|
||||
BucketNameCatalog(DiskStore store) {
|
||||
this.store = store;
|
||||
catalog = store.root().resolve("bucket-names.txt");
|
||||
deletion = store.root().resolve("bucket-name-deletion.txt");
|
||||
}
|
||||
|
||||
Map<String, String> load() throws IOException {
|
||||
Map<String, String> loaded = new HashMap<>();
|
||||
if (Files.exists(catalog)) {
|
||||
for (String line : Files.readAllLines(catalog, StandardCharsets.UTF_8)) {
|
||||
String[] names = parse(line);
|
||||
if (loaded.putIfAbsent(names[0], names[1]) != null)
|
||||
throw new IOException("Duplicate bucket alias");
|
||||
}
|
||||
}
|
||||
Set<String> physical = store.buckets().stream().map(ObjectStorage.Bucket::name)
|
||||
.collect(Collectors.toSet());
|
||||
if (Files.exists(deletion)) {
|
||||
String[] names = parse(Files.readString(deletion, StandardCharsets.UTF_8).strip());
|
||||
String target = loaded.get(names[0]);
|
||||
if (target != null && !target.equals(names[1]))
|
||||
throw new IOException("Bucket deletion conflicts with name catalog");
|
||||
if (!physical.contains(names[1])) {
|
||||
loaded.remove(names[0]);
|
||||
save(loaded);
|
||||
}
|
||||
finishDelete();
|
||||
}
|
||||
if (!physical.containsAll(loaded.values()) ||
|
||||
loaded.values().stream().distinct().count() != loaded.size() ||
|
||||
loaded.keySet().stream().anyMatch(physical::contains))
|
||||
throw new IOException("Bucket name catalog conflicts with stored buckets");
|
||||
return Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
private static String[] parse(String line) throws IOException {
|
||||
String[] names = line.split("\t", -1);
|
||||
if (names.length != 2 || !valid(names[0]) || !valid(names[1]) || names[0].equals(names[1]))
|
||||
throw new IOException("Invalid bucket name catalog");
|
||||
return names;
|
||||
}
|
||||
|
||||
private static boolean valid(String name) {
|
||||
return name.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]");
|
||||
}
|
||||
|
||||
void save(Map<String, String> next) throws IOException {
|
||||
StringBuilder text = new StringBuilder();
|
||||
next.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
text.append(entry.getKey()).append('\t').append(entry.getValue()).append('\n'));
|
||||
write(catalog, text.toString());
|
||||
}
|
||||
|
||||
void beginDelete(String visible, String physical) throws IOException {
|
||||
if (Files.exists(deletion))
|
||||
throw new IOException("An interrupted bucket deletion requires a restart before deleting another renamed bucket");
|
||||
write(deletion, visible + "\t" + physical + "\n");
|
||||
}
|
||||
|
||||
void finishDelete() throws IOException {
|
||||
Files.deleteIfExists(deletion);
|
||||
DiskStore.syncDirectory(store.root());
|
||||
}
|
||||
|
||||
private void write(Path destination, String text) throws IOException {
|
||||
Path pending = Files.createTempFile(store.root().resolve("pending"), "bucket-names-", ".part");
|
||||
try {
|
||||
Files.writeString(pending, text, StandardCharsets.UTF_8);
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) {
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
DiskStore.syncDirectory(store.root());
|
||||
} finally {
|
||||
Files.deleteIfExists(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,12 +115,23 @@ final class BucketPolicy {
|
||||
}
|
||||
|
||||
private static boolean glob(String pattern, String text) {
|
||||
int p = 0, t = 0, star = -1, retry = 0;
|
||||
int p = 0;
|
||||
int t = 0;
|
||||
int star = -1;
|
||||
int retry = 0;
|
||||
while (t < text.length()) {
|
||||
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) { p++; t++; }
|
||||
else if (p < pattern.length() && pattern.charAt(p) == '*') { star = p++; retry = t; }
|
||||
else if (star >= 0) { p = star + 1; t = ++retry; }
|
||||
else return false;
|
||||
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) {
|
||||
p++;
|
||||
t++;
|
||||
} else if (p < pattern.length() && pattern.charAt(p) == '*') {
|
||||
star = p++;
|
||||
retry = t;
|
||||
} else if (star >= 0) {
|
||||
p = star + 1;
|
||||
t = ++retry;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while (p < pattern.length() && pattern.charAt(p) == '*') p++;
|
||||
return p == pattern.length();
|
||||
@@ -190,7 +201,10 @@ final class BucketPolicy {
|
||||
char c = input.charAt(index++);
|
||||
if (c == '"') return result.toString();
|
||||
if (c < 0x20) throw invalid();
|
||||
if (c != '\\') { result.append(c); continue; }
|
||||
if (c != '\\') {
|
||||
result.append(c);
|
||||
continue;
|
||||
}
|
||||
if (index == input.length()) throw invalid();
|
||||
char escape = input.charAt(index++);
|
||||
switch (escape) {
|
||||
@@ -217,7 +231,10 @@ final class BucketPolicy {
|
||||
}
|
||||
|
||||
private boolean take(char expected) {
|
||||
if (index < input.length() && input.charAt(index) == expected) { index++; return true; }
|
||||
if (index < input.length() && input.charAt(index) == expected) {
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import static cloud.lunarsky.store.ClusterStore.*;
|
||||
|
||||
final class ClusterMonitor {
|
||||
@FunctionalInterface
|
||||
interface Connections { Connection open() throws SQLException; }
|
||||
private final Connections connections;
|
||||
private final NodeClient nodes;
|
||||
private volatile ClusterStatus cachedStatus;
|
||||
private volatile long statusUntil;
|
||||
|
||||
ClusterMonitor(Connections connections, NodeClient nodes) {
|
||||
this.connections = connections;
|
||||
this.nodes = nodes;
|
||||
}
|
||||
|
||||
synchronized ClusterStatus status() {
|
||||
long now = System.nanoTime();
|
||||
ClusterStatus cached = cachedStatus;
|
||||
if (cached != null && now < statusUntil) return cached;
|
||||
boolean writable = false;
|
||||
RepairStatus repair = null;
|
||||
Map<UUID, Long> verifiedReplicas = new java.util.HashMap<>();
|
||||
try (Connection connection = connections.open(); var statement = connection.createStatement()) {
|
||||
connection.setAutoCommit(false);
|
||||
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
try (ResultSet result = statement.executeQuery(
|
||||
"SELECT NOT pg_is_in_recovery() AND current_setting('transaction_read_only') = 'off'")) {
|
||||
writable = result.next() && result.getBoolean(1);
|
||||
}
|
||||
try (ResultSet result = statement.executeQuery("SELECT started_at, updated_at, finished_at, state, " +
|
||||
"scanned, restored, rebalanced, under_replicated, unrecoverable " +
|
||||
"FROM cluster_repair_status WHERE singleton=1")) {
|
||||
if (result.next()) repair = new RepairStatus(result.getLong(1), result.getLong(2),
|
||||
result.getLong(3), result.getString(4),
|
||||
new RepairReport(result.getInt(5), result.getInt(6), result.getInt(7),
|
||||
result.getInt(8), result.getInt(9)));
|
||||
}
|
||||
if (repair != null && repair.state().equals("completed")) {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT node_id, verified_replicas FROM cluster_repair_node_counts " +
|
||||
"WHERE finished_at >= ?")) {
|
||||
query.setLong(1, repair.startedAt());
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
while (result.next())
|
||||
verifiedReplicas.put((UUID) result.getObject(1), result.getLong(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
connection.commit();
|
||||
} catch (SQLException unavailable) { writable = false; }
|
||||
List<NodeClient.Node> configured = nodes.nodes();
|
||||
int visible = Math.min(64, configured.size());
|
||||
List<NodeStatus> live = new ArrayList<>();
|
||||
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
java.util.concurrent.Semaphore slots = new java.util.concurrent.Semaphore(16);
|
||||
List<java.util.concurrent.Future<NodeStatus>> checks = new ArrayList<>();
|
||||
for (int i = 0; i < visible; i++) {
|
||||
NodeClient.Node node = configured.get(i);
|
||||
checks.add(executor.submit(() -> {
|
||||
slots.acquireUninterruptibly();
|
||||
try { return new NodeStatus(node, nodes.reachable(node)); }
|
||||
finally { slots.release(); }
|
||||
}));
|
||||
}
|
||||
for (var check : checks) {
|
||||
try { live.add(check.get()); }
|
||||
catch (Exception error) { live.add(new NodeStatus(configured.get(live.size()), false)); }
|
||||
}
|
||||
}
|
||||
ClusterStatus snapshot = new ClusterStatus(writable, List.copyOf(live),
|
||||
configured.size() - visible, repair, Map.copyOf(verifiedReplicas),
|
||||
System.currentTimeMillis());
|
||||
cachedStatus = snapshot;
|
||||
statusUntil = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(15);
|
||||
return snapshot;
|
||||
}
|
||||
void completeRepair(long startedAt, RepairReport report, Map<UUID, Long> counts) {
|
||||
try (Connection connection = connections.open()) {
|
||||
connection.setAutoCommit(false);
|
||||
long now = System.currentTimeMillis();
|
||||
try (var clear = connection.createStatement()) {
|
||||
clear.executeUpdate("DELETE FROM cluster_repair_node_counts");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_repair_node_counts VALUES (?, ?, ?)")) {
|
||||
for (var entry : counts.entrySet()) {
|
||||
insert.setObject(1, entry.getKey());
|
||||
insert.setLong(2, entry.getValue());
|
||||
insert.setLong(3, now);
|
||||
insert.addBatch();
|
||||
}
|
||||
insert.executeBatch();
|
||||
}
|
||||
writeRepairStatus(connection, "completed", startedAt, now, report);
|
||||
connection.commit();
|
||||
cachedStatus = null;
|
||||
} catch (SQLException error) {
|
||||
System.err.println("Cluster repair summary could not be saved: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
void recordRepairStatus(String state, long startedAt, RepairReport report) {
|
||||
try (Connection connection = connections.open()) {
|
||||
writeRepairStatus(connection, state, startedAt, System.currentTimeMillis(), report);
|
||||
cachedStatus = null;
|
||||
} catch (SQLException error) {
|
||||
System.err.println("Cluster repair status could not be saved: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeRepairStatus(Connection connection, String state, long startedAt, long now,
|
||||
RepairReport report) throws SQLException {
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"INSERT INTO cluster_repair_status (singleton, started_at, updated_at, finished_at, state, " +
|
||||
"scanned, restored, rebalanced, under_replicated, unrecoverable) " +
|
||||
"VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (singleton) DO UPDATE SET " +
|
||||
"started_at=EXCLUDED.started_at, updated_at=EXCLUDED.updated_at, " +
|
||||
"finished_at=EXCLUDED.finished_at, state=EXCLUDED.state, " +
|
||||
"scanned=EXCLUDED.scanned, restored=EXCLUDED.restored, " +
|
||||
"rebalanced=EXCLUDED.rebalanced, under_replicated=EXCLUDED.under_replicated, " +
|
||||
"unrecoverable=EXCLUDED.unrecoverable")) {
|
||||
update.setLong(1, startedAt);
|
||||
update.setLong(2, now);
|
||||
update.setLong(3, state.equals("running") ? 0 : now);
|
||||
update.setString(4, state);
|
||||
update.setInt(5, report.scanned());
|
||||
update.setInt(6, report.restored());
|
||||
update.setInt(7, report.rebalanced());
|
||||
update.setInt(8, report.underReplicated());
|
||||
update.setInt(9, report.unrecoverable());
|
||||
update.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import static cloud.lunarsky.store.ClusterStore.RepairReport;
|
||||
|
||||
final class ClusterRepairPass {
|
||||
private record Target(UUID owner, int part, int ordinal, long version,
|
||||
UUID segment, int length, byte[] hash, List<UUID> replicas) {}
|
||||
private final ClusterMonitor.Connections connections;
|
||||
private final NodeClient nodes;
|
||||
private final boolean testNodeDomains;
|
||||
private final ClusterMonitor monitor;
|
||||
private final Map<UUID, Long> verifiedCounts = new HashMap<>();
|
||||
private int scanned;
|
||||
private int restored;
|
||||
private int rebalanced;
|
||||
private int underReplicated;
|
||||
private int unrecoverable;
|
||||
|
||||
ClusterRepairPass(ClusterMonitor.Connections connections, NodeClient nodes,
|
||||
boolean testNodeDomains, ClusterMonitor monitor) {
|
||||
this.connections = connections;
|
||||
this.nodes = nodes;
|
||||
this.testNodeDomains = testNodeDomains;
|
||||
this.monitor = monitor;
|
||||
}
|
||||
|
||||
RepairReport run() throws IOException {
|
||||
try (Connection reader = connections.open()) {
|
||||
reader.setAutoCommit(false);
|
||||
try (var lock = reader.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092782)");
|
||||
}
|
||||
long startedAt = System.currentTimeMillis();
|
||||
monitor.recordRepairStatus("running", startedAt, report());
|
||||
try {
|
||||
scan(reader, startedAt);
|
||||
monitor.completeRepair(startedAt, report(), verifiedCounts);
|
||||
reader.commit();
|
||||
return report();
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
monitor.recordRepairStatus("failed", startedAt, report());
|
||||
throw error;
|
||||
}
|
||||
} catch (SQLException error) {
|
||||
throw new IOException("Metadata database operation failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
private RepairReport report() {
|
||||
return new RepairReport(scanned, restored, rebalanced, underReplicated, unrecoverable);
|
||||
}
|
||||
|
||||
private void scan(Connection reader, long startedAt) throws SQLException, IOException {
|
||||
long lastProgressAt = startedAt;
|
||||
try (PreparedStatement query = reader.prepareStatement(
|
||||
"SELECT s.generation, 0, s.ordinal, s.segment_id, s.length, s.sha256, s.replica_ids, s.placement_version " +
|
||||
"FROM cluster_segments s JOIN cluster_object_versions o ON o.generation=s.generation " +
|
||||
"UNION ALL SELECT s.upload_id, s.part_number, s.ordinal, s.segment_id, s.length, s.sha256, " +
|
||||
"s.replica_ids, s.placement_version FROM cluster_upload_segments s ORDER BY 1, 2, 3")) {
|
||||
query.setFetchSize(128);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
scanned++;
|
||||
repair(target(rows));
|
||||
long now = System.currentTimeMillis();
|
||||
if (scanned % 256 == 0 || now - lastProgressAt >= 5000) {
|
||||
monitor.recordRepairStatus("running", startedAt, report());
|
||||
lastProgressAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Target target(ResultSet rows) throws SQLException, IOException {
|
||||
java.sql.Array value = rows.getArray(7);
|
||||
if (value == null) throw new IOException("Segment has no migrated replica identities");
|
||||
try {
|
||||
List<UUID> replicas = new ArrayList<>();
|
||||
for (Object id : (Object[]) value.getArray()) replicas.add((UUID) id);
|
||||
return new Target((UUID) rows.getObject(1), rows.getInt(2), rows.getInt(3),
|
||||
rows.getLong(8), (UUID) rows.getObject(4), rows.getInt(5), rows.getBytes(6),
|
||||
List.copyOf(replicas));
|
||||
} finally {
|
||||
value.free();
|
||||
}
|
||||
}
|
||||
|
||||
private void repair(Target target) throws SQLException {
|
||||
Set<UUID> healthy = new LinkedHashSet<>();
|
||||
Set<UUID> healthyHosts = new HashSet<>();
|
||||
byte[] copy = readReplicas(target, healthy, healthyHosts);
|
||||
if (copy == null) {
|
||||
unrecoverable++;
|
||||
return;
|
||||
}
|
||||
List<UUID> preferred = preferred(target.segment());
|
||||
for (UUID id : preferred) {
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id)) continue;
|
||||
if (repairReplica(node, target, copy)) {
|
||||
healthy.add(id);
|
||||
healthyHosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
restored++;
|
||||
}
|
||||
}
|
||||
if (healthyHosts.size() < 3) underReplicated++;
|
||||
List<UUID> listed = placement(target, preferred, healthy);
|
||||
boolean published = listed.equals(target.replicas()) || updatePlacement(target, listed);
|
||||
if (published && preferred.stream().anyMatch(id ->
|
||||
!target.replicas().contains(id) && listed.contains(id))) rebalanced++;
|
||||
for (UUID id : published ? listed : target.replicas()) {
|
||||
if (healthy.contains(id)) verifiedCounts.merge(id, 1L, Long::sum);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readReplicas(Target target, Set<UUID> healthy, Set<UUID> hosts) {
|
||||
byte[] copy = null;
|
||||
for (UUID id : target.replicas()) {
|
||||
int node = nodes.index(id);
|
||||
if (node < 0) continue;
|
||||
byte[] candidate = readableReplica(node, target);
|
||||
if (candidate == null) continue;
|
||||
if (copy == null) copy = candidate;
|
||||
healthy.add(id);
|
||||
hosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private byte[] readableReplica(int node, Target target) {
|
||||
try { return nodes.get(node, target.segment(), target.length(), target.hash()); }
|
||||
catch (IOException unavailable) { return null; }
|
||||
}
|
||||
|
||||
private boolean repairReplica(int node, Target target, byte[] copy) {
|
||||
try {
|
||||
nodes.repair(node, target.segment(), copy, target.hash());
|
||||
return true;
|
||||
} catch (IOException unavailable) { return false; }
|
||||
}
|
||||
|
||||
private List<UUID> preferred(UUID segment) {
|
||||
List<UUID> preferred = new ArrayList<>();
|
||||
Set<UUID> hosts = new HashSet<>();
|
||||
for (int node : PlacementPolicy.candidates(segment, nodes, testNodeDomains)) {
|
||||
if (!hosts.add(nodes.faultDomain(node, testNodeDomains))) continue;
|
||||
preferred.add(nodes.node(node).id());
|
||||
if (preferred.size() == 3) break;
|
||||
}
|
||||
return preferred;
|
||||
}
|
||||
|
||||
private List<UUID> placement(Target target, List<UUID> preferred, Set<UUID> healthy) {
|
||||
List<UUID> listed = new ArrayList<>();
|
||||
Set<UUID> hosts = new HashSet<>();
|
||||
for (UUID id : preferred) {
|
||||
if (healthy.contains(id)) {
|
||||
listed.add(id);
|
||||
hosts.add(nodes.faultDomain(nodes.index(id), testNodeDomains));
|
||||
}
|
||||
}
|
||||
for (UUID id : target.replicas()) {
|
||||
if (listed.size() == 3) break;
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id) && node >= 0 &&
|
||||
hosts.add(nodes.faultDomain(node, testNodeDomains))) listed.add(id);
|
||||
}
|
||||
if (listed.size() < 3) {
|
||||
for (UUID id : target.replicas()) {
|
||||
if (!listed.contains(id)) listed.add(id);
|
||||
}
|
||||
}
|
||||
return listed;
|
||||
}
|
||||
|
||||
private boolean updatePlacement(Target target, List<UUID> listed) throws SQLException {
|
||||
String table = target.part() == 0 ? "cluster_segments" : "cluster_upload_segments";
|
||||
String identity = target.part() == 0 ? "generation=? AND ordinal=?" :
|
||||
"upload_id=? AND part_number=? AND ordinal=?";
|
||||
try (Connection writer = connections.open(); PreparedStatement update = writer.prepareStatement(
|
||||
"UPDATE " + table + " SET replica_ids=?, placement_version=placement_version+1 WHERE " +
|
||||
identity + " AND placement_version=?")) {
|
||||
java.sql.Array ids = writer.createArrayOf("uuid", listed.toArray());
|
||||
try {
|
||||
update.setArray(1, ids);
|
||||
update.setObject(2, target.owner());
|
||||
int next = 3;
|
||||
if (target.part() != 0) update.setInt(next++, target.part());
|
||||
update.setInt(next++, target.ordinal());
|
||||
update.setLong(next, target.version());
|
||||
return update.executeUpdate() == 1;
|
||||
} finally {
|
||||
ids.free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -29,16 +28,22 @@ import java.util.UUID;
|
||||
|
||||
final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
private record Segment(UUID id, int length, byte[] hash, List<UUID> replicas) {}
|
||||
private record RepairTarget(UUID id, int part, int ordinal, long version, Segment segment) {}
|
||||
private record Upload(String contentType, Map<String, String> userMetadata,
|
||||
Map<String, String> tags, Map<String, String> acl) {}
|
||||
private record StoredPart(long length, String etag, List<Segment> segments) {}
|
||||
record RepairReport(int scanned, int restored, int rebalanced, int underReplicated, int unrecoverable) {}
|
||||
record RepairStatus(long startedAt, long updatedAt, long finishedAt, String state,
|
||||
RepairReport report) {}
|
||||
record NodeStatus(NodeClient.Node node, boolean reachable) {}
|
||||
record ClusterStatus(boolean metadataWritable, List<NodeStatus> nodes,
|
||||
int omittedNodes, RepairStatus repair,
|
||||
Map<UUID, Long> verifiedReplicas, long checkedAt) {}
|
||||
record GcReport(int scanned, int eligible, int deleted, int unavailableNodes) {}
|
||||
private final String jdbcUrl, user, password, configuredBucket;
|
||||
private final String jdbcUrl, user, password;
|
||||
private final NodeClient nodes;
|
||||
private final long maxObject, maxTotal;
|
||||
private final boolean testNodeDomains;
|
||||
private final ClusterMonitor monitor;
|
||||
|
||||
ClusterStore(String jdbcUrl, String user, String password, String bucket,
|
||||
List<URI> nodeUrls, String token, String repairToken, long maxObject, long maxTotal,
|
||||
@@ -50,7 +55,6 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
this.jdbcUrl = jdbcUrl;
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.configuredBucket = bucket;
|
||||
this.maxObject = maxObject;
|
||||
this.maxTotal = maxTotal;
|
||||
this.testNodeDomains = testNodeDomains;
|
||||
@@ -58,6 +62,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
int format = SchemaMigrator.prepare(connection, bucket);
|
||||
if (format != 2) throw new IOException("Legacy replica positions require objectstore cluster-migrate before this gateway can start");
|
||||
nodes = NodeRegistry.load(connection, nodeUrls, token, repairToken);
|
||||
monitor = new ClusterMonitor(this::connect, nodes);
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@@ -268,6 +273,60 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void renameBucket(String oldName, String newName) throws IOException {
|
||||
if (newName == null || !newName.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
|
||||
throw new StoreException(400, "InvalidBucketName", "Invalid bucket name");
|
||||
if (oldName.equals(newName))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a different name");
|
||||
try (Connection connection = connect()) {
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
try (var lock = connection.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092784)");
|
||||
lock.execute("LOCK TABLE cluster_usage, cluster_buckets, cluster_objects, " +
|
||||
"cluster_tombstones, cluster_object_versions, cluster_object_heads, " +
|
||||
"cluster_uploads IN ACCESS EXCLUSIVE MODE");
|
||||
}
|
||||
lockUsage(connection, oldName);
|
||||
try (PreparedStatement check = connection.prepareStatement(
|
||||
"SELECT EXISTS (SELECT 1 FROM cluster_buckets WHERE name=?)")) {
|
||||
check.setString(1, newName);
|
||||
try (ResultSet result = check.executeQuery()) {
|
||||
result.next();
|
||||
if (result.getBoolean(1))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET name=?, bucket_policy=" +
|
||||
"replace(replace(bucket_policy, ?, ?), ?, ?) WHERE name=?")) {
|
||||
update.setString(1, newName);
|
||||
update.setString(2, "arn:aws:s3:::" + oldName + "/");
|
||||
update.setString(3, "arn:aws:s3:::" + newName + "/");
|
||||
update.setString(4, "arn:aws:s3:::" + oldName + "\"");
|
||||
update.setString(5, "arn:aws:s3:::" + newName + "\"");
|
||||
update.setString(6, oldName);
|
||||
if (update.executeUpdate() != 1)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
}
|
||||
for (String table : List.of("cluster_usage", "cluster_objects", "cluster_tombstones",
|
||||
"cluster_object_versions", "cluster_object_heads", "cluster_uploads")) {
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE " + table + " SET bucket=? WHERE bucket=?")) {
|
||||
update.setString(1, newName);
|
||||
update.setString(2, oldName);
|
||||
update.executeUpdate();
|
||||
}
|
||||
}
|
||||
connection.commit();
|
||||
} catch (SQLException | RuntimeException error) {
|
||||
connection.rollback();
|
||||
if (error instanceof SQLException sql) throw databaseError(sql);
|
||||
throw error;
|
||||
}
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static void lockGc(Connection connection, boolean shared) throws SQLException {
|
||||
try (var statement = connection.createStatement()) {
|
||||
statement.execute("SELECT pg_advisory_lock" + (shared ? "_shared" : "") + "(6834071092783)");
|
||||
@@ -279,6 +338,24 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, checksums, acl, null);
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
if (expected == null || expected.versionId() == null)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object has no stable version to replace");
|
||||
return put(bucket, key, new ByteArrayInputStream(content), content.length, null, null, false,
|
||||
expected.contentType(), expected.userMetadata(), expected.tags(), Map::of, expected.acl(),
|
||||
expected);
|
||||
}
|
||||
|
||||
private Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl, Metadata expected) throws IOException {
|
||||
validatePut(bucket, length, contentType);
|
||||
MessageDigest md5 = digest("MD5");
|
||||
Crc64Nvme crc64 = new Crc64Nvme();
|
||||
@@ -295,7 +372,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Metadata metadata = new Metadata(length, Instant.now().toEpochMilli(),
|
||||
HexFormat.of().formatHex(md5.digest()), fullHash, bucket, key, contentType,
|
||||
Map.copyOf(userMetadata), Map.copyOf(tags), null, storedChecksums, Map.copyOf(acl));
|
||||
return persistObject(connection, metadata, segments, createOnly);
|
||||
return persistObject(connection, metadata, segments, createOnly, expected);
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
} finally { Files.deleteIfExists(staged); }
|
||||
}
|
||||
@@ -384,7 +461,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
}
|
||||
|
||||
private Metadata persistObject(Connection connection, Metadata metadata, List<Segment> segments,
|
||||
boolean createOnly) throws IOException {
|
||||
boolean createOnly, Metadata expected) throws IOException {
|
||||
String bucket = metadata.bucket(), key = metadata.key();
|
||||
long length = metadata.length();
|
||||
UUID generation = UUID.randomUUID();
|
||||
@@ -393,6 +470,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
try {
|
||||
long used = lockUsage(connection, bucket);
|
||||
VersioningState state = versioningState(connection, bucket);
|
||||
if (expected != null) requireCurrentVersion(connection, bucket, key, state, expected);
|
||||
long previous = currentLength(connection, bucket, key);
|
||||
if (createOnly && previous >= 0)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
@@ -416,7 +494,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Metadata stored = publishObject(connection, metadata, generation, used, replaced, state);
|
||||
connection.commit();
|
||||
return stored;
|
||||
} catch (SQLException | RuntimeException error) {
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
connection.rollback();
|
||||
if (error instanceof SQLException sql) throw databaseError(sql);
|
||||
throw error;
|
||||
@@ -424,6 +502,24 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static void requireCurrentVersion(Connection connection, String bucket, String key,
|
||||
VersioningState state, Metadata expected) throws SQLException, IOException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT h.version_id, v.sha256, v.tags, v.acl FROM cluster_object_heads h JOIN cluster_object_versions v " +
|
||||
"USING (bucket, object_key, version_id) WHERE h.bucket=? AND h.object_key=? AND NOT v.delete_marker")) {
|
||||
query.setString(1, bucket);
|
||||
query.setString(2, key);
|
||||
try (ResultSet row = query.executeQuery()) {
|
||||
if (state != VersioningState.ENABLED || !row.next() ||
|
||||
!expected.versionId().equals(row.getString(1)) ||
|
||||
!MessageDigest.isEqual(expected.sha256(), row.getBytes(2)) ||
|
||||
!expected.tags().equals(ObjectAttributes.decode(row.getBytes(3))) ||
|
||||
!expected.acl().equals(ObjectAttributes.decode(row.getBytes(4))))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long nullVersionLength(Connection connection, String bucket, String key) throws SQLException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT length FROM cluster_object_versions WHERE bucket=? AND object_key=? AND version_id='null'")) {
|
||||
@@ -763,8 +859,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
|
||||
@Override public int activeUploads() {
|
||||
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT count(*) FROM cluster_uploads WHERE bucket=?")) {
|
||||
query.setString(1, configuredBucket);
|
||||
"SELECT count(*) FROM cluster_uploads")) {
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
result.next();
|
||||
return result.getInt(1);
|
||||
@@ -773,8 +868,11 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
}
|
||||
|
||||
@Override public long stagedBytes() {
|
||||
try (Connection connection = connect()) { return stagedBytes(connection, configuredBucket); }
|
||||
catch (SQLException error) { throw new IllegalStateException("Could not count staged bytes", error); }
|
||||
try (Connection connection = connect(); var query = connection.createStatement();
|
||||
ResultSet result = query.executeQuery("SELECT COALESCE(sum(length), 0) FROM cluster_upload_parts")) {
|
||||
result.next();
|
||||
return result.getLong(1);
|
||||
} catch (SQLException error) { throw new IllegalStateException("Could not count staged bytes", error); }
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key) throws IOException {
|
||||
@@ -1400,104 +1498,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
return result.next() && result.getBoolean(1);
|
||||
} catch (SQLException error) { return false; }
|
||||
}
|
||||
ClusterStatus status() { return monitor.status(); }
|
||||
RepairReport repairOnce() throws IOException {
|
||||
int scanned = 0, restored = 0, rebalanced = 0, underReplicated = 0, unrecoverable = 0;
|
||||
try (Connection reader = connect()) {
|
||||
reader.setAutoCommit(false);
|
||||
try (var lock = reader.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092782)");
|
||||
}
|
||||
try (PreparedStatement query = reader.prepareStatement(
|
||||
"SELECT s.generation, 0, s.ordinal, s.segment_id, s.length, s.sha256, s.replica_ids, s.placement_version " +
|
||||
"FROM cluster_segments s JOIN cluster_object_versions o ON o.generation=s.generation " +
|
||||
"UNION ALL SELECT s.upload_id, s.part_number, s.ordinal, s.segment_id, s.length, s.sha256, " +
|
||||
"s.replica_ids, s.placement_version FROM cluster_upload_segments s " +
|
||||
"ORDER BY 1, 2, 3")) {
|
||||
query.setFetchSize(128);
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
while (result.next()) {
|
||||
scanned++;
|
||||
RepairTarget target = new RepairTarget((UUID) result.getObject(1), result.getInt(2),
|
||||
result.getInt(3), result.getLong(8), new Segment((UUID) result.getObject(4),
|
||||
result.getInt(5), result.getBytes(6), replicaIds(result, 7)));
|
||||
Segment segment = target.segment();
|
||||
byte[] copy = null;
|
||||
Set<UUID> healthy = new LinkedHashSet<>();
|
||||
Set<UUID> healthyHosts = new HashSet<>();
|
||||
for (UUID id : segment.replicas()) {
|
||||
int node = nodes.index(id);
|
||||
if (node < 0) continue;
|
||||
byte[] candidate = readableReplica(node, segment);
|
||||
if (candidate == null) continue;
|
||||
if (copy == null) copy = candidate;
|
||||
healthy.add(id);
|
||||
healthyHosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
}
|
||||
if (copy == null) {
|
||||
unrecoverable++;
|
||||
continue;
|
||||
}
|
||||
List<UUID> preferred = new ArrayList<>();
|
||||
Set<UUID> preferredHosts = new HashSet<>();
|
||||
for (int node : PlacementPolicy.candidates(segment.id(), nodes, testNodeDomains)) {
|
||||
UUID host = nodes.faultDomain(node, testNodeDomains);
|
||||
if (!preferredHosts.add(host)) continue;
|
||||
preferred.add(nodes.node(node).id());
|
||||
if (preferred.size() == 3) break;
|
||||
}
|
||||
for (UUID id : preferred) {
|
||||
int node = nodes.index(id);
|
||||
UUID host = nodes.faultDomain(node, testNodeDomains);
|
||||
if (healthy.contains(id)) continue;
|
||||
if (repairReplica(node, segment, copy)) {
|
||||
healthy.add(id);
|
||||
healthyHosts.add(host);
|
||||
restored++;
|
||||
}
|
||||
}
|
||||
if (healthyHosts.size() < 3) underReplicated++;
|
||||
List<UUID> listed = new ArrayList<>();
|
||||
Set<UUID> listedHosts = new HashSet<>();
|
||||
for (UUID id : preferred) {
|
||||
if (healthy.contains(id)) {
|
||||
listed.add(id);
|
||||
listedHosts.add(nodes.faultDomain(nodes.index(id), testNodeDomains));
|
||||
}
|
||||
}
|
||||
for (UUID id : segment.replicas()) {
|
||||
if (listed.size() == 3) break;
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id) && node >= 0 &&
|
||||
listedHosts.add(nodes.faultDomain(node, testNodeDomains))) listed.add(id);
|
||||
}
|
||||
if (listed.size() < 3) {
|
||||
for (UUID id : segment.replicas()) {
|
||||
if (!listed.contains(id)) listed.add(id);
|
||||
}
|
||||
}
|
||||
if (!listed.equals(segment.replicas())) {
|
||||
String table = target.part() == 0 ? "cluster_segments" : "cluster_upload_segments";
|
||||
String identity = target.part() == 0 ? "generation=? AND ordinal=?" :
|
||||
"upload_id=? AND part_number=? AND ordinal=?";
|
||||
try (Connection writer = connect(); PreparedStatement update = writer.prepareStatement(
|
||||
"UPDATE " + table + " SET replica_ids=?, placement_version=placement_version+1 WHERE " +
|
||||
identity + " AND placement_version=?")) {
|
||||
update.setArray(1, writer.createArrayOf("uuid", listed.toArray()));
|
||||
update.setObject(2, target.id());
|
||||
int next = 3;
|
||||
if (target.part() != 0) update.setInt(next++, target.part());
|
||||
update.setInt(next++, target.ordinal());
|
||||
update.setLong(next, target.version());
|
||||
if (update.executeUpdate() == 1 && preferred.stream().anyMatch(id ->
|
||||
!segment.replicas().contains(id) && listed.contains(id))) rebalanced++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
reader.commit();
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
return new RepairReport(scanned, restored, rebalanced, underReplicated, unrecoverable);
|
||||
return new ClusterRepairPass(this::connect, nodes, testNodeDomains, monitor).run();
|
||||
}
|
||||
|
||||
private byte[] readableReplica(int node, Segment segment) {
|
||||
@@ -1505,13 +1508,6 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
catch (IOException unavailable) { return null; }
|
||||
}
|
||||
|
||||
private boolean repairReplica(int node, Segment segment, byte[] copy) {
|
||||
try {
|
||||
nodes.repair(node, segment.id(), copy, segment.hash());
|
||||
return true;
|
||||
} catch (IOException unavailable) { return false; }
|
||||
}
|
||||
|
||||
GcReport collectGarbage(long minimumAgeMillis, boolean apply) throws IOException {
|
||||
if (minimumAgeMillis < 0 || (minimumAgeMillis == 0 && !testNodeDomains))
|
||||
throw new IllegalArgumentException("Invalid garbage collection age");
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
final class DiskBucketNames implements ObjectStorage, MultipartStorage {
|
||||
private final DiskStore store;
|
||||
private final MultipartStore uploads;
|
||||
private final BucketNameCatalog catalog;
|
||||
private volatile Map<String, String> aliases;
|
||||
|
||||
DiskBucketNames(DiskStore store, MultipartStore uploads) throws IOException {
|
||||
this.store = store;
|
||||
this.uploads = uploads;
|
||||
catalog = new BucketNameCatalog(store);
|
||||
aliases = catalog.load();
|
||||
}
|
||||
|
||||
private static boolean valid(String name) {
|
||||
return name != null && name.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]");
|
||||
}
|
||||
|
||||
private String physical(String name) {
|
||||
Map<String, String> current = aliases;
|
||||
String found = current.get(name);
|
||||
if (found != null) return found;
|
||||
if (current.containsValue(name))
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return name;
|
||||
}
|
||||
|
||||
private String visible(String physical) {
|
||||
for (var entry : aliases.entrySet())
|
||||
if (entry.getValue().equals(physical)) return entry.getKey();
|
||||
return physical;
|
||||
}
|
||||
|
||||
private static String policyName(String policy, String from, String to) {
|
||||
if (policy == null) return null;
|
||||
String arn = "arn:aws:s3:::";
|
||||
return policy.replace(arn + from + "/", arn + to + "/")
|
||||
.replace(arn + from + "\"", arn + to + "\"");
|
||||
}
|
||||
|
||||
private Bucket visible(Bucket bucket) {
|
||||
String name = visible(bucket.name());
|
||||
return new Bucket(name, bucket.created(), bucket.versioning(), bucket.acl(),
|
||||
bucket.ownership(), bucket.publicAccessBlock(),
|
||||
policyName(bucket.policy(), bucket.name(), name));
|
||||
}
|
||||
|
||||
private Metadata visible(Metadata metadata) {
|
||||
if (metadata == null) return null;
|
||||
return new Metadata(metadata.length(), metadata.modified(), metadata.etag(), metadata.sha256(),
|
||||
visible(metadata.bucket()), metadata.key(), metadata.contentType(), metadata.userMetadata(),
|
||||
metadata.tags(), metadata.versionId(), metadata.checksums(), metadata.acl());
|
||||
}
|
||||
|
||||
private void save(Map<String, String> next) throws IOException {
|
||||
catalog.save(next);
|
||||
aliases = Map.copyOf(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void renameBucket(String oldName, String newName) throws IOException {
|
||||
if (!valid(newName)) throw new StoreException(400, "InvalidBucketName", "Invalid bucket name");
|
||||
String underlying = physical(oldName);
|
||||
store.bucket(underlying);
|
||||
if (oldName.equals(newName)) throw new StoreException(400, "InvalidArgument", "Choose a different name");
|
||||
if (aliases.containsKey(newName) || store.buckets().stream().anyMatch(b -> b.name().equals(newName)))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
Map<String, String> next = new HashMap<>(aliases);
|
||||
next.remove(oldName);
|
||||
next.put(newName, underlying);
|
||||
save(next);
|
||||
}
|
||||
|
||||
@Override public Metadata put(String bucket, String key, InputStream input, long length,
|
||||
String expectedHash, String checksum, boolean createOnly,
|
||||
String contentType, Map<String, String> userMetadata,
|
||||
Map<String, String> tags, Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return visible(store.put(physical(bucket), key, input, length, expectedHash, checksum,
|
||||
createOnly, contentType, userMetadata, tags, checksums, acl));
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
return visible(store.replaceVersion(physical(bucket), key, content, expected));
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key) throws IOException {
|
||||
return open(bucket, key, null);
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
OpenObject opened = store.open(physical(bucket), key, versionId);
|
||||
return new OpenObject(visible(opened.metadata()), opened.stream());
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key) throws IOException {
|
||||
return store.tags(physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key, String versionId) throws IOException {
|
||||
return store.tags(physical(bucket), key, versionId);
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, Map<String, String> tags) throws IOException {
|
||||
store.setTags(physical(bucket), key, tags);
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, String versionId,
|
||||
Map<String, String> tags) throws IOException {
|
||||
store.setTags(physical(bucket), key, versionId, tags);
|
||||
}
|
||||
|
||||
@Override public void delete(String bucket, String key) throws IOException {
|
||||
store.delete(physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public DeleteResult delete(String bucket, String key, String versionId) throws IOException {
|
||||
return store.delete(physical(bucket), key, versionId);
|
||||
}
|
||||
|
||||
@Override public void setVersioning(String bucket, VersioningState state) throws IOException {
|
||||
store.setVersioning(physical(bucket), state);
|
||||
}
|
||||
|
||||
@Override public VersionPage listVersions(String bucket, String prefix, String keyMarker,
|
||||
String versionMarker, int maxKeys) throws IOException {
|
||||
VersionPage page = store.listVersions(physical(bucket), prefix, keyMarker, versionMarker, maxKeys);
|
||||
return new VersionPage(page.entries().stream().map(entry -> new VersionEntry(entry.key(),
|
||||
entry.versionId(), entry.modified(), entry.deleteMarker(), entry.latest(),
|
||||
visible(entry.metadata()))).toList(), page.nextKey(), page.nextVersionId(), page.truncated());
|
||||
}
|
||||
|
||||
@Override public ListPage list(String bucket, String prefix, String delimiter,
|
||||
int maxKeys, String after) throws IOException {
|
||||
ListPage page = store.list(physical(bucket), prefix, delimiter, maxKeys, after);
|
||||
return new ListPage(page.objects().stream().map(entry ->
|
||||
new ListedObject(entry.key(), visible(entry.metadata()))).toList(),
|
||||
page.prefixes(), page.nextKey(), page.truncated());
|
||||
}
|
||||
|
||||
@Override public synchronized void ensureBucket(String bucket) throws IOException {
|
||||
if (aliases.containsValue(bucket)) return;
|
||||
store.ensureBucket(physical(bucket));
|
||||
}
|
||||
|
||||
@Override public Bucket bucket(String bucket) throws IOException {
|
||||
return visible(store.bucket(physical(bucket)));
|
||||
}
|
||||
|
||||
@Override public List<Bucket> buckets() throws IOException {
|
||||
return store.buckets().stream().map(this::visible).toList();
|
||||
}
|
||||
|
||||
@Override public synchronized void createBucket(String bucket) throws IOException {
|
||||
if (aliases.containsKey(bucket) || aliases.containsValue(bucket))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
store.createBucket(bucket);
|
||||
}
|
||||
|
||||
@Override public synchronized void deleteBucket(String bucket) throws IOException {
|
||||
String name = physical(bucket);
|
||||
synchronized (uploads) {
|
||||
if (!uploads.listUploads(name, "").isEmpty())
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket contains multipart uploads");
|
||||
if (!aliases.containsKey(bucket)) {
|
||||
store.deleteBucket(name);
|
||||
return;
|
||||
}
|
||||
catalog.beginDelete(bucket, name);
|
||||
boolean deleted = false;
|
||||
try {
|
||||
store.deleteBucket(name);
|
||||
deleted = true;
|
||||
Map<String, String> next = new HashMap<>(aliases);
|
||||
next.remove(bucket);
|
||||
save(next);
|
||||
catalog.finishDelete();
|
||||
} catch (IOException | RuntimeException error) {
|
||||
try {
|
||||
if (deleted) aliases = catalog.load();
|
||||
else if (error instanceof StoreException) catalog.finishDelete();
|
||||
} catch (IOException recovery) { error.addSuppressed(recovery); }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void setBucketAcl(String bucket, Map<String, String> acl) throws IOException {
|
||||
store.setBucketAcl(physical(bucket), acl);
|
||||
}
|
||||
|
||||
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
|
||||
store.setBucketOwnership(physical(bucket), ownership);
|
||||
}
|
||||
|
||||
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
|
||||
store.setPublicAccessBlock(physical(bucket), block);
|
||||
}
|
||||
|
||||
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
|
||||
String name = physical(bucket);
|
||||
store.setBucketPolicy(name, policyName(policy, bucket, name));
|
||||
}
|
||||
|
||||
@Override public void setObjectAcl(String bucket, String key, String versionId,
|
||||
Map<String, String> acl) throws IOException {
|
||||
store.setObjectAcl(physical(bucket), key, versionId, acl);
|
||||
}
|
||||
|
||||
@Override public Limits limits() { return store.limits(); }
|
||||
@Override public boolean ready() { return store.ready(); }
|
||||
@Override public void close() throws IOException { store.close(); }
|
||||
|
||||
@Override public String create(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return uploads.create(physical(bucket), key, contentType, userMetadata, tags, acl);
|
||||
}
|
||||
|
||||
@Override public String putPart(String id, String bucket, String key, int number, InputStream input,
|
||||
long length, String expectedHash, String checksum) throws IOException {
|
||||
return uploads.putPart(id, physical(bucket), key, number, input, length, expectedHash, checksum);
|
||||
}
|
||||
|
||||
@Override public Metadata complete(String id, String bucket, String key, List<Part> parts)
|
||||
throws IOException {
|
||||
return visible(uploads.complete(id, physical(bucket), key, parts));
|
||||
}
|
||||
|
||||
@Override public void abort(String id, String bucket, String key) throws IOException {
|
||||
uploads.abort(id, physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public PartPage listParts(String id, String bucket, String key, int marker, int maxParts)
|
||||
throws IOException {
|
||||
return uploads.listParts(id, physical(bucket), key, marker, maxParts);
|
||||
}
|
||||
|
||||
@Override public List<UploadInfo> listUploads(String bucket, String prefix) throws IOException {
|
||||
return uploads.listUploads(physical(bucket), prefix);
|
||||
}
|
||||
|
||||
@Override public int activeUploads() { return uploads.activeUploads(); }
|
||||
@Override public long stagedBytes() { return uploads.stagedBytes(); }
|
||||
}
|
||||
@@ -475,6 +475,24 @@ final class DiskStore implements ObjectStorage {
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, checksums, acl, null);
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
if (expected == null || expected.versionId() == null)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object has no stable version to replace");
|
||||
return put(bucket, key, new ByteArrayInputStream(content), content.length, null, null, false,
|
||||
expected.contentType(), expected.userMetadata(), expected.tags(), Map::of, expected.acl(),
|
||||
expected);
|
||||
}
|
||||
|
||||
private Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl, Metadata expected) throws IOException {
|
||||
if (length < 0) throw new StoreException(411, "MissingContentLength", "Content-Length is required");
|
||||
if (length > maxObject) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
byte[] bucketBytes = bucket.getBytes(StandardCharsets.UTF_8);
|
||||
@@ -488,7 +506,7 @@ final class DiskStore implements ObjectStorage {
|
||||
Metadata metadata = stagePut(pending, input, length, expectedHash, checksum,
|
||||
bucket, key, contentType, bucketBytes, keyBytes, typeBytes,
|
||||
metadataBytes, tagBytes, userMetadata, tags, checksums, acl);
|
||||
return installPending(destination, pending, metadata, createOnly);
|
||||
return installPending(destination, pending, metadata, createOnly, expected);
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
}
|
||||
|
||||
@@ -554,10 +572,19 @@ final class DiskStore implements ObjectStorage {
|
||||
}
|
||||
|
||||
private Metadata installPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly) throws IOException {
|
||||
boolean createOnly, Metadata expected) throws IOException {
|
||||
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)
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
|
||||
@@ -22,12 +22,23 @@ public final class Main {
|
||||
private final ClientLimits clientLimits;
|
||||
private final Semaphore slots;
|
||||
private final Semaphore adminSlots = new Semaphore(8);
|
||||
private final Semaphore adminStreams = new Semaphore(4);
|
||||
private final String virtualHostSuffix;
|
||||
private final BrowserCors cors;
|
||||
private final KeyScopes keyScopes;
|
||||
private final RequestMetrics metrics;
|
||||
private final StoreOperations operations = new StoreOperations();
|
||||
private final RequestDiagnostics diagnostics = new RequestDiagnostics();
|
||||
private volatile BucketActivity bucketActivity;
|
||||
private final int maxInFlight;
|
||||
private volatile AdminConsole adminConsole;
|
||||
private volatile ManagedCredentials managedCredentials;
|
||||
|
||||
private static final class RequestContext {
|
||||
String principal;
|
||||
String bucket;
|
||||
String operation;
|
||||
}
|
||||
|
||||
Main(DiskStore store, SigV4 authentication, String bucket) throws IOException {
|
||||
this(store, new MultipartStore(store), authentication, bucket);
|
||||
@@ -103,7 +114,37 @@ public final class Main {
|
||||
|
||||
void setAdminConsole(AdminConsole adminConsole) {
|
||||
this.adminConsole = adminConsole;
|
||||
if (adminConsole != null) adminConsole.setMetrics(metrics);
|
||||
if (adminConsole != null) {
|
||||
adminConsole.setOperations(operations);
|
||||
adminConsole.setMetrics(metrics);
|
||||
adminConsole.setDiagnostics(diagnostics);
|
||||
adminConsole.setBucketActivity(bucketActivity);
|
||||
adminConsole.setIdentities(authentication.identities());
|
||||
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
|
||||
adminConsole.setAccessCheck((principal, operation, bucket, key) ->
|
||||
new AdminAccessCheck(store, access, keyScopes, authentication.identities(),
|
||||
managedCredentials).check(principal, operation, bucket, key));
|
||||
}
|
||||
}
|
||||
|
||||
void setBucketActivity(BucketActivity bucketActivity) {
|
||||
this.bucketActivity = bucketActivity;
|
||||
if (adminConsole != null) adminConsole.setBucketActivity(bucketActivity);
|
||||
}
|
||||
|
||||
void setManagedCredentials(ManagedCredentials managedCredentials) {
|
||||
this.managedCredentials = managedCredentials;
|
||||
refreshManagedCredentials();
|
||||
if (adminConsole != null)
|
||||
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
|
||||
}
|
||||
|
||||
private synchronized void refreshManagedCredentials() {
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null) return;
|
||||
access.setManagedPolicies(managed.policies());
|
||||
authentication.setManagedIdentities(managed.identities());
|
||||
if (adminConsole != null) adminConsole.setIdentities(authentication.identities());
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
@@ -113,6 +154,7 @@ public final class Main {
|
||||
TrafficMeter traffic = null;
|
||||
ClientLimits.Client client = null;
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
RequestContext context = new RequestContext();
|
||||
exchange.getResponseHeaders().set("x-amz-request-id", requestId);
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
try {
|
||||
@@ -132,8 +174,9 @@ public final class Main {
|
||||
admitted = slots.tryAcquire();
|
||||
if (!admitted) throw new StoreException(503, "SlowDown", "Too many concurrent requests");
|
||||
if (cors.preflight(exchange)) return;
|
||||
if (handleStatus(exchange)) return;
|
||||
dispatch(exchange);
|
||||
operations.read(() -> {
|
||||
if (!handleStatus(exchange)) dispatch(exchange, context);
|
||||
});
|
||||
} catch (StoreException error) {
|
||||
sendStoreError(exchange, error, requestId);
|
||||
} catch (Exception error) {
|
||||
@@ -146,15 +189,20 @@ public final class Main {
|
||||
clientLimits.leave(client);
|
||||
long elapsed = System.nanoTime() - started;
|
||||
metrics.record(exchange.getResponseCode(), elapsed);
|
||||
if (dataStarted)
|
||||
if (dataStarted) {
|
||||
metrics.dataFinished(exchange.getResponseCode(), elapsed,
|
||||
traffic.inbound(), traffic.outbound());
|
||||
if (adminConsole != null) diagnostics.record(requestId,
|
||||
context.operation, context.bucket, exchange.getResponseCode(), elapsed,
|
||||
context.principal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleAdmin(HttpExchange exchange) throws IOException {
|
||||
boolean admitted = false;
|
||||
boolean streaming = false;
|
||||
try {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (adminConsole == null ||
|
||||
@@ -162,29 +210,31 @@ public final class Main {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
admitted = adminSlots.tryAcquire();
|
||||
streaming = path.equals(AdminConsole.PATH + "/performance.events");
|
||||
admitted = (streaming ? adminStreams : adminSlots).tryAcquire();
|
||||
if (!admitted) {
|
||||
exchange.sendResponseHeaders(503, -1);
|
||||
return;
|
||||
}
|
||||
adminConsole.handle(exchange);
|
||||
} catch (StoreException error) {
|
||||
exchange.sendResponseHeaders(error.status, -1);
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(error.status, -1);
|
||||
} catch (Exception error) {
|
||||
System.err.println("ObjectStore admin request failed: " + error.getClass().getSimpleName());
|
||||
exchange.sendResponseHeaders(500, -1);
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(500, -1);
|
||||
} finally {
|
||||
exchange.close();
|
||||
if (admitted) adminSlots.release();
|
||||
if (admitted) (streaming ? adminStreams : adminSlots).release();
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatch(HttpExchange exchange) throws IOException {
|
||||
private void dispatch(HttpExchange exchange, RequestContext context) throws IOException {
|
||||
SigV4.Verified verified = anonymousRead(exchange)
|
||||
? new SigV4.Verified("UNSIGNED-PAYLOAD", exchange.getRequestURI().getRawQuery(),
|
||||
null, null, null, null, null)
|
||||
: authentication.verifyRequest(exchange.getRequestMethod(),
|
||||
exchange.getRequestURI(), exchange.getRequestHeaders());
|
||||
context.principal = verified.principal();
|
||||
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
|
||||
Map<String, String> query = S3Request.query(verified.applicationQuery());
|
||||
if (path.equals(CAPABILITIES_PATH)) {
|
||||
@@ -209,18 +259,40 @@ public final class Main {
|
||||
int slash = path.indexOf('/', 1);
|
||||
String requestedBucket = hostBucket == null ?
|
||||
(slash < 0 ? path.substring(1) : path.substring(1, slash)) : hostBucket;
|
||||
context.bucket = requestedBucket;
|
||||
context.operation = (hostBucket != null ? path.equals("/") : slash < 0 ||
|
||||
slash == path.length() - 1) ? "Bucket " + exchange.getRequestMethod() :
|
||||
"Object " + exchange.getRequestMethod();
|
||||
if (requestedBucket.isEmpty()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (hostBucket != null ? path.equals("/") : slash < 0 || slash == path.length() - 1) {
|
||||
keyScopes.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
else keyScopes.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
bucketHandler.handleBucket(exchange, query, verified.payload(), requestedBucket, verified.principal());
|
||||
} else {
|
||||
store.bucket(requestedBucket);
|
||||
String key = hostBucket == null ? path.substring(slash + 1) : path.substring(1);
|
||||
keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
else keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
objectHandler.handleObject(exchange, key,
|
||||
query, verified, requestedBucket);
|
||||
}
|
||||
BucketActivity activity = bucketActivity;
|
||||
if (activity != null && exchange.getResponseCode() > 0 && exchange.getResponseCode() < 400)
|
||||
activity.record(requestedBucket, exchange.getRequestMethod());
|
||||
}
|
||||
|
||||
private ManagedCredentials managedScope(String principal) {
|
||||
if (principal == null || authentication.configuredIdentity(principal)) return null;
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null || !managed.contains(principal))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
return managed;
|
||||
}
|
||||
|
||||
private static String validateVirtualHostSuffix(String value) {
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
final class ManagedCredentials {
|
||||
record Key(String id, String secret, String bucket, String prefix,
|
||||
Set<String> actions, boolean enabled) { }
|
||||
|
||||
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final Set<String> ACTIONS = Set.of("read", "write", "list");
|
||||
private final Path path;
|
||||
private final SecretKeySpec master;
|
||||
private final Set<String> reserved;
|
||||
private volatile Map<String, Key> keys;
|
||||
|
||||
private ManagedCredentials(Path path, byte[] master, Set<String> reserved) throws IOException {
|
||||
this.path = path;
|
||||
this.master = new SecretKeySpec(master, "AES");
|
||||
this.reserved = Set.copyOf(reserved);
|
||||
java.util.Arrays.fill(master, (byte) 0);
|
||||
this.keys = load();
|
||||
}
|
||||
|
||||
static ManagedCredentials fromEnvironment(Map<String, String> env, ObjectStorage store,
|
||||
Set<String> reserved) throws IOException {
|
||||
String configured = env.get("S3_MANAGED_KEYS_MASTER_FILE");
|
||||
if (configured == null || configured.isBlank()) return null;
|
||||
if (!(store instanceof DiskStore))
|
||||
throw new IllegalArgumentException("Managed credentials require disk mode");
|
||||
byte[] master;
|
||||
try {
|
||||
master = HexFormat.of().parseHex(Files.readString(Path.of(configured)).trim());
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid managed credentials master key", error);
|
||||
}
|
||||
if (master.length != 32)
|
||||
throw new IllegalArgumentException("Managed credentials master key must contain 32 bytes");
|
||||
return new ManagedCredentials(Path.of(env.getOrDefault("DATA_DIR", "/data"))
|
||||
.resolve("managed-credentials.bin"), master, reserved);
|
||||
}
|
||||
|
||||
List<Key> list() { return keys.values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
|
||||
boolean contains(String principal) { return principal != null && keys.containsKey(principal); }
|
||||
|
||||
Map<String, String> identities() {
|
||||
Map<String, String> active = new HashMap<>();
|
||||
keys.values().stream().filter(Key::enabled).forEach(key -> active.put(key.id(), key.secret()));
|
||||
return Map.copyOf(active);
|
||||
}
|
||||
|
||||
Map<String, BucketPolicy> policies() {
|
||||
Map<String, BucketPolicy> active = new HashMap<>();
|
||||
for (Key key : keys.values()) {
|
||||
if (!key.enabled()) continue;
|
||||
List<String> objectActions = new ArrayList<>();
|
||||
if (key.actions().contains("read")) {
|
||||
objectActions.add("s3:GetObject");
|
||||
objectActions.add("s3:GetObjectVersion");
|
||||
}
|
||||
if (key.actions().contains("write")) {
|
||||
objectActions.add("s3:PutObject");
|
||||
objectActions.add("s3:DeleteObject");
|
||||
objectActions.add("s3:DeleteObjectVersion");
|
||||
objectActions.add("s3:AbortMultipartUpload");
|
||||
}
|
||||
String bucketArn = "arn:aws:s3:::" + key.bucket();
|
||||
StringBuilder statements = new StringBuilder();
|
||||
if (key.actions().contains("list"))
|
||||
statements.append("{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"")
|
||||
.append(bucketArn).append("\"}");
|
||||
if (!objectActions.isEmpty()) {
|
||||
if (!statements.isEmpty()) statements.append(',');
|
||||
statements.append("{\"Effect\":\"Allow\",\"Action\":[");
|
||||
for (int i = 0; i < objectActions.size(); i++) {
|
||||
if (i > 0) statements.append(',');
|
||||
statements.append('"').append(objectActions.get(i)).append('"');
|
||||
}
|
||||
statements.append("],\"Resource\":\"").append(bucketArn).append('/')
|
||||
.append(key.prefix()).append("*\"}");
|
||||
}
|
||||
active.put(key.id(), BucketPolicy.parseIdentity(
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"));
|
||||
}
|
||||
return Map.copyOf(active);
|
||||
}
|
||||
|
||||
synchronized Key create(String bucket, String prefix, Set<String> actions) throws IOException {
|
||||
if (keys.size() >= 64) invalid("Too many managed access keys");
|
||||
validateScope(bucket, prefix, actions);
|
||||
byte[] random = new byte[24];
|
||||
String id;
|
||||
do {
|
||||
RANDOM.nextBytes(random);
|
||||
id = HexFormat.of().withUpperCase().formatHex(random, 0, 16);
|
||||
} while (reserved.contains(id) || keys.containsKey(id));
|
||||
RANDOM.nextBytes(random);
|
||||
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(random) +
|
||||
Base64.getUrlEncoder().withoutPadding().encodeToString(randomToken());
|
||||
Key key = new Key(id, secret, bucket, prefix, Set.copyOf(actions), true);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, key);
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
return key;
|
||||
}
|
||||
|
||||
synchronized void update(String id, String bucket, String prefix, Set<String> actions) throws IOException {
|
||||
Key old = key(id);
|
||||
validateScope(bucket, prefix, actions);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
private static void validateScope(String bucket, String prefix, Set<String> actions) {
|
||||
if (bucket == null || prefix == null || actions == null ||
|
||||
!bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
|
||||
prefix.length() > 256 || !prefix.matches("[A-Za-z0-9/_-]*") ||
|
||||
actions.isEmpty() || !ACTIONS.containsAll(actions))
|
||||
invalid("Invalid key scope");
|
||||
}
|
||||
|
||||
synchronized void setEnabled(String id, boolean enabled) throws IOException {
|
||||
Key old = key(id);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
synchronized void remove(String id) throws IOException {
|
||||
key(id);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.remove(id);
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
void checkBucket(String principal, String bucket, String method, Map<String, String> query) {
|
||||
Key key = key(principal);
|
||||
boolean head = method.equals("HEAD") &&
|
||||
(query.isEmpty() || query.size() == 1 && "HeadBucket".equals(query.get("x-id")));
|
||||
boolean list = method.equals("GET") && "2".equals(query.get("list-type")) &&
|
||||
query.getOrDefault("prefix", "").startsWith(key.prefix());
|
||||
if (!key.enabled() || !key.bucket().equals(bucket) || !key.actions().contains("list") ||
|
||||
!(head || list))
|
||||
denied();
|
||||
}
|
||||
|
||||
void checkObject(String principal, String bucket, String object, String method,
|
||||
Map<String, String> query, Headers headers) {
|
||||
Key key = key(principal);
|
||||
String action = method.equals("GET") || method.equals("HEAD") ? "read" : "write";
|
||||
if (!key.enabled() || !key.bucket().equals(bucket) || !object.startsWith(key.prefix()) ||
|
||||
!key.actions().contains(action) || query.containsKey("acl") ||
|
||||
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(name ->
|
||||
name.toLowerCase(java.util.Locale.ROOT).startsWith("x-amz-grant-"))) denied();
|
||||
String source = headers.getFirst("x-amz-copy-source");
|
||||
if (source != null) {
|
||||
if (source.startsWith("/")) source = source.substring(1);
|
||||
int question = source.indexOf('?');
|
||||
if (question >= 0) source = source.substring(0, question);
|
||||
int slash = source.indexOf('/');
|
||||
if (slash < 1 || !key.actions().contains("read") ||
|
||||
!key.bucket().equals(SigV4.decode(source.substring(0, slash))) ||
|
||||
!SigV4.decode(source.substring(slash + 1)).startsWith(key.prefix())) denied();
|
||||
}
|
||||
}
|
||||
|
||||
private Key key(String id) {
|
||||
Key key = keys.get(id);
|
||||
if (key == null) throw new StoreException(404, "NoSuchKey", "Access key not found");
|
||||
return key;
|
||||
}
|
||||
|
||||
private Map<String, Key> load() throws IOException {
|
||||
if (!Files.exists(path)) return Map.of();
|
||||
byte[] bytes = Files.readAllBytes(path);
|
||||
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > 65536 ||
|
||||
!java.util.Arrays.equals(MAGIC, java.util.Arrays.copyOf(bytes, MAGIC.length)))
|
||||
throw new IOException("Invalid managed credential store");
|
||||
byte[] nonce = java.util.Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
|
||||
byte[] plain;
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, master, new GCMParameterSpec(128, nonce));
|
||||
cipher.updateAAD(MAGIC);
|
||||
plain = cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Managed credential store could not be decrypted", error);
|
||||
}
|
||||
Map<String, Key> loaded = new HashMap<>();
|
||||
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split("\t", -1);
|
||||
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
|
||||
fields[1].length() < 32 || !fields[2].matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
|
||||
!fields[3].matches("[A-Za-z0-9/_-]*") || fields[3].length() > 256 ||
|
||||
!Set.of("true", "false").contains(fields[5]) || reserved.contains(fields[0]))
|
||||
throw new IOException("Invalid managed credential entry");
|
||||
Set<String> actions;
|
||||
try { actions = Set.of(fields[4].split(",")); }
|
||||
catch (IllegalArgumentException error) { throw new IOException("Invalid managed credential entry", error); }
|
||||
if (actions.isEmpty() || !ACTIONS.containsAll(actions) || loaded.size() >= 64 ||
|
||||
loaded.putIfAbsent(fields[0], new Key(fields[0], fields[1], fields[2], fields[3],
|
||||
actions, Boolean.parseBoolean(fields[5]))) != null)
|
||||
throw new IOException("Invalid managed credential entry");
|
||||
}
|
||||
java.util.Arrays.fill(plain, (byte) 0);
|
||||
return Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
private void persist(Map<String, Key> updated) throws IOException {
|
||||
StringBuilder contents = new StringBuilder();
|
||||
updated.values().stream().sorted(java.util.Comparator.comparing(Key::id)).forEach(key ->
|
||||
contents.append(key.id()).append('\t').append(key.secret()).append('\t')
|
||||
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
|
||||
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
|
||||
.append(key.enabled()).append('\n'));
|
||||
byte[] nonce = randomToken();
|
||||
byte[] encrypted;
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, master, new GCMParameterSpec(128, nonce));
|
||||
cipher.updateAAD(MAGIC);
|
||||
encrypted = cipher.doFinal(contents.toString().getBytes(StandardCharsets.UTF_8));
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Could not encrypt managed credentials", error);
|
||||
}
|
||||
Files.createDirectories(path.getParent());
|
||||
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
|
||||
try {
|
||||
Files.setPosixFilePermissions(temporary, java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
writeAll(channel, MAGIC);
|
||||
writeAll(channel, nonce);
|
||||
writeAll(channel, encrypted);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeAll(FileChannel channel, byte[] bytes) throws IOException {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
}
|
||||
|
||||
private static byte[] randomToken() {
|
||||
byte[] nonce = new byte[12];
|
||||
RANDOM.nextBytes(nonce);
|
||||
return nonce;
|
||||
}
|
||||
|
||||
private static void invalid(String message) { throw new StoreException(400, "InvalidArgument", message); }
|
||||
private static void denied() { throw new StoreException(403, "AccessDenied", "Access denied"); }
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
@@ -76,18 +75,11 @@ final class NodeClient {
|
||||
HttpRequest request = HttpRequest.newBuilder(url.resolve("/identity"))
|
||||
.timeout(Duration.ofSeconds(2)).header("X-Cluster-Token", token).GET().build();
|
||||
try {
|
||||
HttpResponse<InputStream> response = http.send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(128);
|
||||
if (bytes.length == 128) throw new IOException("Node identity response is too large");
|
||||
String[] parts = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).trim().split(" ", -1);
|
||||
if (parts.length != 2) throw new IOException("Invalid node identity response");
|
||||
return new NodeIdentity(UUID.fromString(parts[0]), UUID.fromString(parts[1]));
|
||||
}
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during node identity request", error);
|
||||
HttpResponse<byte[]> response = NodeHttp.bytes(http, request, 127);
|
||||
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
|
||||
String[] parts = new String(response.body(), java.nio.charset.StandardCharsets.US_ASCII).trim().split(" ", -1);
|
||||
if (parts.length != 2) throw new IOException("Invalid node identity response");
|
||||
return new NodeIdentity(UUID.fromString(parts[0]), UUID.fromString(parts[1]));
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node identity response", error);
|
||||
}
|
||||
@@ -98,6 +90,12 @@ final class NodeClient {
|
||||
catch (IOException offline) { return null; }
|
||||
}
|
||||
|
||||
boolean reachable(Node node) {
|
||||
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
|
||||
return actual != null && actual.nodeId().equals(node.id()) &&
|
||||
actual.hostId().equals(node.hostId());
|
||||
}
|
||||
|
||||
private static NodeIdentity probeIfAvailable(URI url, String token, HttpClient http) {
|
||||
try { return probe(url, token, http); }
|
||||
catch (IOException offline) { return null; }
|
||||
@@ -176,8 +174,8 @@ final class NodeClient {
|
||||
throw new IOException("Repair authority is not available to this process");
|
||||
builder.header("X-Cluster-Repair", "true").header("X-Cluster-Repair-Token", repairToken);
|
||||
}
|
||||
HttpResponse<Void> response = send(builder.PUT(HttpRequest.BodyPublishers.ofByteArray(data)).build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
HttpResponse<Void> response = NodeHttp.discard(http,
|
||||
builder.PUT(HttpRequest.BodyPublishers.ofByteArray(data)).build());
|
||||
if (response.statusCode() != 200) throw new IOException("Node " + node.id() + " rejected segment: " + response.statusCode());
|
||||
}
|
||||
|
||||
@@ -196,22 +194,15 @@ final class NodeClient {
|
||||
HttpRequest request = HttpRequest.newBuilder(node.url().resolve("/segments/" + id))
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString()).GET().build();
|
||||
HttpResponse<InputStream> response;
|
||||
try { response = send(request, HttpResponse.BodyHandlers.ofInputStream()); }
|
||||
HttpResponse<byte[]> response;
|
||||
try { response = NodeHttp.bytes(http, request, length + 1); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
response.body().close();
|
||||
if (response.statusCode() != 200)
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
}
|
||||
byte[] bytes;
|
||||
try (InputStream body = response.body()) { bytes = body.readNBytes(length + 1); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
byte[] bytes = response.body();
|
||||
if (bytes.length != length || !MessageDigest.isEqual(SigV4.hash(bytes), sha256))
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
unreadableUntil.remove(node.id());
|
||||
@@ -228,31 +219,28 @@ final class NodeClient {
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString())
|
||||
.header("X-Cluster-Repair-Token", repairToken).GET().build();
|
||||
HttpResponse<InputStream> response = send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) throw new IOException("Node inventory failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(70001);
|
||||
if (bytes.length > 70000) throw new IOException("Node inventory response is too large");
|
||||
List<StoredSegment> result = new ArrayList<>();
|
||||
String last = after == null ? "" : after.toString();
|
||||
for (String line : new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split(" ", -1);
|
||||
if (fields.length != 2) throw new IOException("Invalid node inventory response");
|
||||
try {
|
||||
UUID id = UUID.fromString(fields[0]);
|
||||
if (!id.toString().equals(fields[0]) || !fields[0].startsWith(shard) ||
|
||||
fields[0].compareTo(last) <= 0)
|
||||
throw new IOException("Invalid node inventory cursor");
|
||||
result.add(new StoredSegment(id, Long.parseLong(fields[1])));
|
||||
last = fields[0];
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node inventory response", error);
|
||||
}
|
||||
HttpResponse<byte[]> response = NodeHttp.bytes(http, request, 70000);
|
||||
if (response.statusCode() != 200) throw new IOException("Node inventory failed: " + response.statusCode());
|
||||
byte[] bytes = response.body();
|
||||
List<StoredSegment> result = new ArrayList<>();
|
||||
String last = after == null ? "" : after.toString();
|
||||
for (String line : new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split(" ", -1);
|
||||
if (fields.length != 2) throw new IOException("Invalid node inventory response");
|
||||
try {
|
||||
UUID id = UUID.fromString(fields[0]);
|
||||
if (!id.toString().equals(fields[0]) || !fields[0].startsWith(shard) ||
|
||||
fields[0].compareTo(last) <= 0)
|
||||
throw new IOException("Invalid node inventory cursor");
|
||||
result.add(new StoredSegment(id, Long.parseLong(fields[1])));
|
||||
last = fields[0];
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node inventory response", error);
|
||||
}
|
||||
if (result.size() > 1000) throw new IOException("Node inventory page is too large");
|
||||
return result;
|
||||
}
|
||||
if (result.size() > 1000) throw new IOException("Node inventory page is too large");
|
||||
return result;
|
||||
}
|
||||
|
||||
boolean deleteOrphan(int index, StoredSegment segment, long minimumAgeMillis) throws IOException {
|
||||
@@ -266,17 +254,10 @@ final class NodeClient {
|
||||
.header("X-Cluster-Expected-Mtime", Long.toString(segment.modified()))
|
||||
.header("X-Cluster-Gc-Min-Age-Millis", Long.toString(minimumAgeMillis))
|
||||
.DELETE().build();
|
||||
HttpResponse<Void> response = send(request, HttpResponse.BodyHandlers.discarding());
|
||||
HttpResponse<Void> response = NodeHttp.discard(http, request);
|
||||
if (response.statusCode() == 204) return true;
|
||||
if (response.statusCode() == 404 || response.statusCode() == 409) return false;
|
||||
throw new IOException("Node refused orphan deletion: " + response.statusCode());
|
||||
}
|
||||
|
||||
private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler) throws IOException {
|
||||
try { return http.send(request, handler); }
|
||||
catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during node request", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpTimeoutException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
final class NodeHttp {
|
||||
private NodeHttp() {}
|
||||
|
||||
static HttpResponse<byte[]> bytes(HttpClient client, HttpRequest request, int maximum) throws IOException {
|
||||
if (maximum < 0) throw new IllegalArgumentException("Invalid response size limit");
|
||||
return send(client, request, HttpResponse.BodySubscribers.ofByteArray(), maximum);
|
||||
}
|
||||
|
||||
static HttpResponse<Void> discard(HttpClient client, HttpRequest request) throws IOException {
|
||||
return send(client, request, HttpResponse.BodySubscribers.discarding(), Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
private static <T> HttpResponse<T> send(HttpClient client, HttpRequest request,
|
||||
HttpResponse.BodySubscriber<T> delegate, long maximum) throws IOException {
|
||||
long timeout = request.timeout().orElseThrow().toNanos();
|
||||
long started = System.nanoTime();
|
||||
ResponseBody<T> body = new ResponseBody<>(delegate, maximum);
|
||||
CompletableFuture<HttpResponse<T>> response = client.sendAsync(request, ignored -> body);
|
||||
boolean completed = false;
|
||||
try {
|
||||
HttpResponse<T> result = response.get(Math.max(1, timeout - (System.nanoTime() - started)),
|
||||
TimeUnit.NANOSECONDS);
|
||||
completed = true;
|
||||
return result;
|
||||
} catch (TimeoutException error) {
|
||||
throw new HttpTimeoutException("Storage node response timed out");
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during storage node request", error);
|
||||
} catch (ExecutionException error) {
|
||||
if (error.getCause() instanceof IOException failure) throw failure;
|
||||
throw new IOException("Storage node request failed", error.getCause());
|
||||
} finally {
|
||||
if (!completed) {
|
||||
body.abort(new IOException("Storage node request cancelled"));
|
||||
response.cancel(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ResponseBody<T> implements HttpResponse.BodySubscriber<T> {
|
||||
private final HttpResponse.BodySubscriber<T> delegate;
|
||||
private Flow.Subscription subscription;
|
||||
private long remaining;
|
||||
private boolean finished;
|
||||
|
||||
ResponseBody(HttpResponse.BodySubscriber<T> delegate, long maximum) {
|
||||
this.delegate = delegate;
|
||||
remaining = maximum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<T> getBody() {
|
||||
return delegate.getBody();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onSubscribe(Flow.Subscription incoming) {
|
||||
if (finished || subscription != null) {
|
||||
incoming.cancel();
|
||||
return;
|
||||
}
|
||||
subscription = incoming;
|
||||
delegate.onSubscribe(incoming);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onNext(List<ByteBuffer> buffers) {
|
||||
if (finished) return;
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
if (buffer.remaining() > remaining) {
|
||||
abort(new IOException("Storage node response is too large"));
|
||||
return;
|
||||
}
|
||||
remaining -= buffer.remaining();
|
||||
}
|
||||
delegate.onNext(buffers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onError(Throwable error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
delegate.onError(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onComplete() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
delegate.onComplete();
|
||||
}
|
||||
|
||||
synchronized void abort(IOException error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
if (subscription != null) subscription.cancel();
|
||||
delegate.onError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,10 @@ interface ObjectStorage extends AutoCloseable {
|
||||
String checksum, boolean createOnly, String contentType) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType, Map.of(), Map.of());
|
||||
}
|
||||
default Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Conditional object editing is unavailable");
|
||||
}
|
||||
OpenObject open(String bucket, String key) throws IOException;
|
||||
default OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
if (versionId == null) return open(bucket, key);
|
||||
@@ -126,6 +130,9 @@ interface ObjectStorage extends AutoCloseable {
|
||||
Bucket bucket(String bucket) throws IOException;
|
||||
List<Bucket> buckets() throws IOException;
|
||||
void createBucket(String bucket) throws IOException;
|
||||
default void renameBucket(String bucket, String newName) throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Bucket rename is unavailable");
|
||||
}
|
||||
void deleteBucket(String bucket) throws IOException;
|
||||
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
|
||||
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
|
||||
|
||||
@@ -28,6 +28,7 @@ final class ObjectStoreServer {
|
||||
String mode = env.getOrDefault("STORE_MODE", "disk");
|
||||
ObjectStorage store;
|
||||
MultipartStorage multipart;
|
||||
DiskStore disk = null;
|
||||
if (mode.equals("cluster")) {
|
||||
if (!"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Cluster mode is local development only; set CLUSTER_LOCAL_DEV=true");
|
||||
@@ -39,9 +40,10 @@ final class ObjectStoreServer {
|
||||
maxObject, maxTotal, "true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS")));
|
||||
multipart = (ClusterStore) store;
|
||||
} else if (mode.equals("disk")) {
|
||||
DiskStore disk = new DiskStore(Path.of(env.getOrDefault("DATA_DIR", "/data")), maxObject, maxTotal);
|
||||
store = disk;
|
||||
multipart = new MultipartStore(disk);
|
||||
disk = new DiskStore(Path.of(env.getOrDefault("DATA_DIR", "/data")), maxObject, maxTotal);
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
store = names;
|
||||
multipart = names;
|
||||
} else throw new IllegalArgumentException("Invalid STORE_MODE");
|
||||
Map<String, String> identities = identities(env, access, secret);
|
||||
var sessions = SessionCredentials.fromEnvironment(env, identities.keySet());
|
||||
@@ -55,7 +57,14 @@ final class ObjectStoreServer {
|
||||
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")),
|
||||
IdentityPolicies.fromEnvironment(env, access, allIdentities),
|
||||
publicEndpoint(env));
|
||||
BucketActivity bucketActivity = "true".equals(env.get("ADMIN_UI_ENABLED")) ?
|
||||
new BucketActivity(Path.of(env.getOrDefault("ADMIN_UI_STATE_DIR",
|
||||
env.getOrDefault("DATA_DIR", "/data")), "bucket-activity.tsv")) : null;
|
||||
if (bucketActivity != null) app.setBucketActivity(bucketActivity);
|
||||
app.setManagedCredentials(ManagedCredentials.fromEnvironment(env,
|
||||
disk == null ? store : disk, allIdentities));
|
||||
AdminConsole adminConsole = AdminConsole.fromEnvironment(env, store);
|
||||
if (adminConsole != null) adminConsole.setDiskStore(disk);
|
||||
app.setAdminConsole(adminConsole);
|
||||
int port = Integer.parseInt(env.getOrDefault("PORT", "9000"));
|
||||
int adminPort = adminConsole == null ? 0 : positiveInt(env, "ADMIN_UI_PORT", 9001, 65535);
|
||||
@@ -77,12 +86,13 @@ final class ObjectStoreServer {
|
||||
server.stop(5);
|
||||
if (adminServer != null) adminServer.stop(5);
|
||||
executor.close();
|
||||
if (bucketActivity != null) bucketActivity.close();
|
||||
try { store.close(); }
|
||||
catch (IOException error) { System.err.println("Could not release ObjectStore data lock: " + error.getMessage()); }
|
||||
}));
|
||||
server.start();
|
||||
if (adminServer != null) adminServer.start();
|
||||
if (store instanceof DiskStore disk) printStartup(disk, multipart, bucket, region, port);
|
||||
if (disk != null) printStartup(disk, multipart, bucket, region, port);
|
||||
else System.out.println("ObjectStore local cluster prototype v" + Version.VALUE + " listening on :" + port);
|
||||
if (adminServer != null) System.out.println("ObjectStore admin listening on :" + adminPort);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
final class RequestDiagnostics {
|
||||
private static final long MINUTE_MILLIS = 60_000;
|
||||
private static final long[] LATENCY_BOUNDS_MS = {1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000};
|
||||
private final AtomicReferenceArray<Window> windows = new AtomicReferenceArray<>(5);
|
||||
private final AtomicReferenceArray<Failure> failures = new AtomicReferenceArray<>(64);
|
||||
private final AtomicLong failureSequence = new AtomicLong();
|
||||
private final ConcurrentHashMap<String, KeyCounters> keys = new ConcurrentHashMap<>();
|
||||
|
||||
record Failure(long sequence, long timeMillis, String requestId, String operation, String bucket,
|
||||
int status) { }
|
||||
record Snapshot(long requests, long clientErrors, long serverErrors, long p50Millis,
|
||||
long p95Millis, long p99Millis, List<Failure> recentFailures) { }
|
||||
record KeyActivity(String principal, long requests, long failures, long lastSeenMillis) { }
|
||||
|
||||
private static final class KeyCounters {
|
||||
final LongAdder requests = new LongAdder();
|
||||
final LongAdder failures = new LongAdder();
|
||||
final AtomicLong lastSeen = new AtomicLong();
|
||||
}
|
||||
|
||||
private static final class Window {
|
||||
final long minute;
|
||||
final LongAdder requests = new LongAdder();
|
||||
final LongAdder clientErrors = new LongAdder();
|
||||
final LongAdder serverErrors = new LongAdder();
|
||||
final LongAdder[] latency = new LongAdder[LATENCY_BOUNDS_MS.length + 1];
|
||||
|
||||
Window(long minute) {
|
||||
this.minute = minute;
|
||||
for (int i = 0; i < latency.length; i++) latency[i] = new LongAdder();
|
||||
}
|
||||
}
|
||||
|
||||
void record(String requestId, String operation, String bucket, int status, long elapsedNanos) {
|
||||
record(requestId, operation, bucket, status, elapsedNanos, null);
|
||||
}
|
||||
|
||||
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;
|
||||
int slot = (int) Math.floorMod(minute, windows.length());
|
||||
Window window;
|
||||
do {
|
||||
window = windows.get(slot);
|
||||
if (window != null && window.minute == minute) break;
|
||||
Window fresh = new Window(minute);
|
||||
if (windows.compareAndSet(slot, window, fresh)) {
|
||||
window = fresh;
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
window.requests.increment();
|
||||
if (status >= 500) window.serverErrors.increment();
|
||||
else if (status >= 400) window.clientErrors.increment();
|
||||
long millis = Math.max(0, elapsedNanos / 1_000_000);
|
||||
int latencySlot = 0;
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
List<KeyActivity> keyActivity() {
|
||||
return keys.entrySet().stream().map(entry -> new KeyActivity(entry.getKey(),
|
||||
entry.getValue().requests.sum(), entry.getValue().failures.sum(),
|
||||
entry.getValue().lastSeen.get()))
|
||||
.sorted((a, b) -> Long.compare(b.lastSeenMillis(), a.lastSeenMillis()))
|
||||
.limit(100).toList();
|
||||
}
|
||||
|
||||
Snapshot snapshot() {
|
||||
long minute = System.currentTimeMillis() / MINUTE_MILLIS;
|
||||
long requests = 0, clientErrors = 0, serverErrors = 0;
|
||||
long[] histogram = new long[LATENCY_BOUNDS_MS.length + 1];
|
||||
for (int slot = 0; slot < windows.length(); slot++) {
|
||||
Window window = windows.get(slot);
|
||||
if (window == null || window.minute > minute || window.minute <= minute - windows.length()) continue;
|
||||
requests += window.requests.sum();
|
||||
clientErrors += window.clientErrors.sum();
|
||||
serverErrors += window.serverErrors.sum();
|
||||
for (int i = 0; i < histogram.length; i++) histogram[i] += window.latency[i].sum();
|
||||
}
|
||||
List<Failure> recent = new ArrayList<>();
|
||||
long newest = failureSequence.get();
|
||||
for (long sequence = newest - 1; sequence >= Math.max(0, newest - failures.length()); sequence--) {
|
||||
Failure failure = failures.get((int) (sequence % failures.length()));
|
||||
if (failure != null && failure.sequence() == sequence &&
|
||||
failure.timeMillis() >= (minute - windows.length() + 1) * MINUTE_MILLIS &&
|
||||
failure.timeMillis() <= System.currentTimeMillis()) recent.add(failure);
|
||||
}
|
||||
return new Snapshot(requests, clientErrors, serverErrors,
|
||||
percentile(histogram, requests, 50), percentile(histogram, requests, 95),
|
||||
percentile(histogram, requests, 99), List.copyOf(recent));
|
||||
}
|
||||
|
||||
private static long percentile(long[] histogram, long count, int percent) {
|
||||
if (count == 0) return 0;
|
||||
long target = (count * percent + 99) / 100;
|
||||
long seen = 0;
|
||||
for (int i = 0; i < histogram.length; i++) {
|
||||
seen += histogram[i];
|
||||
if (seen >= target) return i == LATENCY_BOUNDS_MS.length ? -1 : LATENCY_BOUNDS_MS[i];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import java.io.IOException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
final class S3Access {
|
||||
record Decision(boolean allowed, String reason) { }
|
||||
private final ObjectStorage store;
|
||||
private final String owner;
|
||||
private final java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final java.util.Map<String, BucketPolicy> configuredIdentityPolicies;
|
||||
private volatile java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
|
||||
private record CachedPolicy(String source, BucketPolicy parsed) { }
|
||||
|
||||
@@ -17,7 +19,16 @@ final class S3Access {
|
||||
S3Access(ObjectStorage store, String owner, java.util.Map<String, BucketPolicy> identityPolicies) {
|
||||
this.store = store;
|
||||
this.owner = owner;
|
||||
this.identityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
this.configuredIdentityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
this.identityPolicies = configuredIdentityPolicies;
|
||||
}
|
||||
|
||||
synchronized void setManagedPolicies(java.util.Map<String, BucketPolicy> managed) {
|
||||
var combined = new java.util.HashMap<>(configuredIdentityPolicies);
|
||||
for (var entry : managed.entrySet())
|
||||
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null)
|
||||
throw new IllegalArgumentException("Managed policy conflicts with a configured identity");
|
||||
identityPolicies = java.util.Map.copyOf(combined);
|
||||
}
|
||||
|
||||
String owner() {
|
||||
@@ -46,19 +57,43 @@ final class S3Access {
|
||||
require(store.bucket(bucket), metadata.acl(), principal, permission, action, key);
|
||||
}
|
||||
|
||||
Decision inspectBucket(String bucket, String principal) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
return decide(current, current.acl(), principal, Acl.READ, "s3:ListBucket", null);
|
||||
}
|
||||
|
||||
Decision inspectWrite(String bucket, String key, String principal, String action) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
return decide(current, current.acl(), principal, Acl.WRITE, action, key);
|
||||
}
|
||||
|
||||
Decision inspectObject(String bucket, String key, ObjectStorage.Metadata metadata,
|
||||
String principal) throws IOException {
|
||||
return decide(store.bucket(bucket), metadata.acl(), principal, Acl.READ, "s3:GetObject", key);
|
||||
}
|
||||
|
||||
private void require(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
if (!decide(bucket, acl, principal, permission, action, key).allowed())
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
}
|
||||
|
||||
private Decision decide(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
String resource = "arn:aws:s3:::" + bucket.name() + (key == null ? "" : "/" + key);
|
||||
BucketPolicy policy = policy(bucket);
|
||||
int decision = policy.decide(principal, action, resource);
|
||||
int identityDecision = principal == null ? 0 :
|
||||
identityPolicies.getOrDefault(principal, BucketPolicy.empty()).decide(principal, action, resource);
|
||||
if (decision < 0 || identityDecision < 0 ||
|
||||
!BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission) &&
|
||||
identityDecision <= 0 &&
|
||||
!(decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow())))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
if (decision < 0) return new Decision(false, "Explicit bucket policy deny");
|
||||
if (identityDecision < 0) return new Decision(false, "Explicit identity policy deny");
|
||||
if (BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission))
|
||||
return new Decision(true, "Owner or ACL grants this action");
|
||||
if (identityDecision > 0) return new Decision(true, "Identity policy allows this action");
|
||||
if (decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow()))
|
||||
return new Decision(true, "Bucket policy allows this action");
|
||||
return new Decision(false, "No ACL or policy grants this action");
|
||||
}
|
||||
|
||||
private BucketPolicy policy(ObjectStorage.Bucket bucket) {
|
||||
|
||||
@@ -21,7 +21,7 @@ final class SchemaMigrator {
|
||||
result.next();
|
||||
version = result.getInt(1);
|
||||
}
|
||||
if (version > 11) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version > 14) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version < 1) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
|
||||
@@ -109,11 +109,36 @@ final class SchemaMigrator {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
|
||||
}
|
||||
if (version < 12) {
|
||||
statement.execute("CREATE TABLE cluster_repair_status (singleton integer PRIMARY KEY " +
|
||||
"CHECK (singleton=1), finished_at bigint NOT NULL, scanned integer NOT NULL, " +
|
||||
"restored integer NOT NULL, rebalanced integer NOT NULL, under_replicated integer NOT NULL, " +
|
||||
"unrecoverable integer NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (12)");
|
||||
}
|
||||
if (version < 13) {
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN started_at bigint NOT NULL DEFAULT 0");
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN updated_at bigint NOT NULL DEFAULT 0");
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN state text NOT NULL DEFAULT 'completed' " +
|
||||
"CHECK (state IN ('running','completed','failed'))");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (13)");
|
||||
}
|
||||
if (version < 14) {
|
||||
statement.execute("CREATE TABLE cluster_repair_node_counts (node_id uuid PRIMARY KEY, " +
|
||||
"verified_replicas bigint NOT NULL CHECK (verified_replicas >= 0), " +
|
||||
"finished_at bigint NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (14)");
|
||||
}
|
||||
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.executeUpdate();
|
||||
try (PreparedStatement check = connection.prepareStatement(
|
||||
"SELECT count(*), count(*) FILTER (WHERE name=?) FROM cluster_buckets")) {
|
||||
check.setString(1, bucket);
|
||||
try (ResultSet result = check.executeQuery()) {
|
||||
result.next();
|
||||
if (result.getLong(1) > 0 && result.getLong(2) == 0)
|
||||
throw new IOException("Configured S3_BUCKET does not exist; update it or create the bucket explicitly");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
@@ -123,6 +148,10 @@ final class SchemaMigrator {
|
||||
insert.setLong(2, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
int format;
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT version FROM cluster_format WHERE singleton=1")) {
|
||||
|
||||
@@ -29,7 +29,8 @@ final class SigV4 {
|
||||
}
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
|
||||
private final Map<String, String> identities;
|
||||
private final Map<String, String> configuredIdentities;
|
||||
private volatile Map<String, String> identities;
|
||||
private final Map<String, SessionCredentials.Session> sessions;
|
||||
private final String root;
|
||||
private final String region;
|
||||
@@ -45,7 +46,8 @@ final class SigV4 {
|
||||
|
||||
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
|
||||
String root, String region, Clock clock) {
|
||||
this.identities = Map.copyOf(identities);
|
||||
this.configuredIdentities = Map.copyOf(identities);
|
||||
this.identities = configuredIdentities;
|
||||
this.sessions = Map.copyOf(sessions);
|
||||
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
|
||||
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
|
||||
@@ -56,6 +58,17 @@ final class SigV4 {
|
||||
}
|
||||
|
||||
String root() { return root; }
|
||||
boolean configuredIdentity(String principal) {
|
||||
return principal != null &&
|
||||
(configuredIdentities.containsKey(principal) || sessions.containsKey(principal));
|
||||
}
|
||||
synchronized void setManagedIdentities(Map<String, String> managed) {
|
||||
Map<String, String> combined = new java.util.HashMap<>(configuredIdentities);
|
||||
for (var entry : managed.entrySet())
|
||||
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null || sessions.containsKey(entry.getKey()))
|
||||
throw new IllegalArgumentException("Managed access key conflicts with a configured identity");
|
||||
identities = Map.copyOf(combined);
|
||||
}
|
||||
Set<String> identities() {
|
||||
var all = new java.util.HashSet<>(identities.keySet());
|
||||
all.addAll(sessions.keySet());
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
final class StoreOperations {
|
||||
@FunctionalInterface
|
||||
interface Action {
|
||||
void run() throws IOException;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface Query<T> {
|
||||
T get() throws IOException;
|
||||
}
|
||||
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
|
||||
|
||||
void read(Action action) throws IOException {
|
||||
run(lock.readLock(), action);
|
||||
}
|
||||
|
||||
void write(Action action) throws IOException {
|
||||
Lock writing = lock.writeLock();
|
||||
try {
|
||||
if (!writing.tryLock(1, TimeUnit.SECONDS))
|
||||
throw new StoreException(409, "OperationAborted",
|
||||
"Storage is busy; retry after transfers finish");
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new StoreException(503, "SlowDown", "Storage operation was interrupted");
|
||||
}
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
writing.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
<T> T readValue(Query<T> query) throws IOException {
|
||||
Lock reading = lock.readLock();
|
||||
reading.lock();
|
||||
try {
|
||||
return query.get();
|
||||
} finally {
|
||||
reading.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static void run(Lock lock, Action action) throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user