mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-26 06:07:13 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6cf5a5bd7 | ||
|
|
7df43ad9b5 | ||
|
|
a736ba1c21 | ||
|
|
14d247703a | ||
|
|
1391a85a20 | ||
|
|
0e9f702152 | ||
|
|
d47cc45b1f | ||
|
|
b13463880c | ||
|
|
b56d155b31 | ||
|
|
c1636ac41c | ||
|
|
e64c821139 | ||
|
|
3fd5018bd2 | ||
|
|
7e608c877a | ||
|
|
138220b961 | ||
|
|
c7781bfca2 | ||
|
|
ef5fee6c28 | ||
|
|
284796c7b6 | ||
|
|
561768a426 | ||
|
|
da243b9423 | ||
|
|
26754fca4d | ||
|
|
94357ac6a9 | ||
|
|
240f82d6d2 | ||
|
|
1e858d8af0 | ||
|
|
4fb3e22a01 | ||
|
|
339a597e7e | ||
|
|
c2591b4395 | ||
|
|
aabd44fbb5 | ||
|
|
f724828bcb | ||
|
|
3718301599 | ||
|
|
18cdb3819b | ||
|
|
871d7ddc02 | ||
|
|
5468707289 | ||
|
|
0345658ea8 | ||
|
|
34f9b91d69 | ||
|
|
b44cf51fe9 | ||
|
|
4f8af455bf | ||
|
|
37962e2445 | ||
|
|
42030381ae | ||
|
|
c3b06bf809 | ||
|
|
3eb550a3f1 | ||
|
|
582b7268f5 |
No files matched your search
@@ -37,6 +37,21 @@ jobs:
|
||||
# Fail only if there are actual vet errors (not counting the filtered lock warnings)
|
||||
if grep -q "vet:" vet-output.txt; then exit 1; fi
|
||||
|
||||
vet-32bit:
|
||||
name: Go Vet 32-bit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v6
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
- name: Go Vet linux/386 (type-checks code and tests for 32-bit int overflows)
|
||||
run: |
|
||||
GOOS=linux GOARCH=386 go vet ./... 2>&1 | grep -v "MessageState contains sync.Mutex" | grep -v "IdentityAccessManagement contains sync.RWMutex" | tee vet-32bit-output.txt
|
||||
if grep -q "vet:" vet-32bit-output.txt; then exit 1; fi
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
@@ -62,3 +77,19 @@ jobs:
|
||||
go-version-file: 'go.mod'
|
||||
- name: Test
|
||||
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
|
||||
|
||||
test-32bit:
|
||||
name: Test 32-bit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v6
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
# 386 test binaries run natively on the amd64 runner. This catches what vet
|
||||
# can't: unaligned 64-bit atomics and arithmetic that wraps at runtime.
|
||||
# -short skips the e2e suites already covered on amd64.
|
||||
- name: Test linux/386
|
||||
run: cd weed; GOOS=linux GOARCH=386 go test -short ./...
|
||||
@@ -68,6 +68,55 @@ jobs:
|
||||
grep -q "security-config" /tmp/security.yaml
|
||||
echo "Security configuration renders correctly"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing JWT expiration overrides ==="
|
||||
helm template test $CHART_DIR \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.expiresAfterSeconds.volumeWrite=11 \
|
||||
> /tmp/jwt-volume-write-expiration.yaml
|
||||
grep -q "security-config" /tmp/jwt-volume-write-expiration.yaml
|
||||
grep -q "expires_after_seconds = 11" /tmp/jwt-volume-write-expiration.yaml
|
||||
|
||||
helm template test $CHART_DIR \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.volumeRead=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.filerWrite=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.filerRead=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.expiresAfterSeconds.volumeWrite=11 \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.expiresAfterSeconds.volumeRead=22 \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.expiresAfterSeconds.filerWrite=33 \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.expiresAfterSeconds.filerRead=44 \
|
||||
> /tmp/jwt-expiration.yaml
|
||||
|
||||
assert_jwt_expiration() {
|
||||
local section="$1"
|
||||
local seconds="$2"
|
||||
awk -v section="[$section]" -v seconds="$seconds" '
|
||||
/^[[:space:]]*\[.*\][[:space:]]*$/ {
|
||||
in_section = index($0, section) > 0
|
||||
}
|
||||
in_section && $0 ~ "^[[:space:]]*expires_after_seconds = " seconds "$" {
|
||||
found = 1
|
||||
}
|
||||
END { exit !found }
|
||||
' /tmp/jwt-expiration.yaml
|
||||
}
|
||||
|
||||
assert_jwt_expiration jwt.signing 11
|
||||
assert_jwt_expiration jwt.signing.read 22
|
||||
assert_jwt_expiration jwt.filer_signing 33
|
||||
assert_jwt_expiration jwt.filer_signing.read 44
|
||||
|
||||
helm template test $CHART_DIR \
|
||||
--set global.seaweedfs.enableSecurity=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.volumeRead=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.filerWrite=true \
|
||||
--set global.seaweedfs.securityConfig.jwtSigning.filerRead=true \
|
||||
> /tmp/jwt-default-expiration.yaml
|
||||
if grep -q "expires_after_seconds =" /tmp/jwt-default-expiration.yaml; then
|
||||
echo "FAIL: zero JWT expiration values should preserve runtime defaults"
|
||||
exit 1
|
||||
fi
|
||||
echo "JWT expiration overrides render correctly"
|
||||
|
||||
echo ""
|
||||
echo "=== Testing IAM gRPC opt-in path ==="
|
||||
# Regression test: the filer registers the IAM gRPC service the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.33"
|
||||
appVersion: "4.34"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.33.0
|
||||
version: 4.34.0
|
||||
@@ -333,11 +333,13 @@ Create the name of the service account to use
|
||||
{{- end -}}
|
||||
|
||||
{{/* True when security.toml should be rendered and mounted. volumeWrite is
|
||||
excluded since it defaults to true. */}}
|
||||
excluded unless its non-default expiration is configured. */}}
|
||||
{{- define "seaweedfs.securityConfigEnabled" -}}
|
||||
{{- $sec := (.Values.global.seaweedfs).securityConfig | default dict -}}
|
||||
{{- $jwt := $sec.jwtSigning | default dict -}}
|
||||
{{- if or .Values.global.seaweedfs.enableSecurity $jwt.volumeRead $jwt.filerWrite $jwt.filerRead -}}
|
||||
{{- $expiresAfterSeconds := $jwt.expiresAfterSeconds | default dict -}}
|
||||
{{- $volumeWriteExpirationConfigured := and $jwt.volumeWrite (gt (int $expiresAfterSeconds.volumeWrite) 0) -}}
|
||||
{{- if or .Values.global.seaweedfs.enableSecurity $volumeWriteExpirationConfigured $jwt.volumeRead $jwt.filerWrite $jwt.filerRead -}}
|
||||
true
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
@@ -19,40 +19,56 @@ data:
|
||||
{{- $existing = lookup "v1" "ConfigMap" .Release.Namespace $legacyName }}
|
||||
{{- end }}
|
||||
{{- $securityConfig := fromToml (dig "data" "security.toml" "" $existing) }}
|
||||
{{- $securityConfigValues := .Values.global.seaweedfs.securityConfig | default dict }}
|
||||
{{- $jwtSigning := $securityConfigValues.jwtSigning | default dict }}
|
||||
{{- $expiresAfterSeconds := $jwtSigning.expiresAfterSeconds | default dict }}
|
||||
security.toml: |-
|
||||
# this file is read by master, volume server, and filer
|
||||
|
||||
{{- if .Values.global.seaweedfs.securityConfig.jwtSigning.volumeWrite }}
|
||||
{{- if $jwtSigning.volumeWrite }}
|
||||
# the jwt signing key is read by master and volume server
|
||||
# a jwt expires in 10 seconds
|
||||
# the jwt defaults to expire after 10 seconds
|
||||
[jwt.signing]
|
||||
key = "{{ dig "jwt" "signing" "key" (randAlphaNum 10 | b64enc) $securityConfig }}"
|
||||
{{- if gt (int $expiresAfterSeconds.volumeWrite) 0 }}
|
||||
expires_after_seconds = {{ int $expiresAfterSeconds.volumeWrite }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Values.global.seaweedfs.securityConfig.jwtSigning.volumeRead }}
|
||||
{{- if $jwtSigning.volumeRead }}
|
||||
# this jwt signing key is read by master and volume server, and it is used for read operations:
|
||||
# - the Master server generates the JWT, which can be used to read a certain file on a volume server
|
||||
# - the Volume server validates the JWT on reading
|
||||
# the jwt defaults to expire after 60 seconds
|
||||
[jwt.signing.read]
|
||||
key = "{{ dig "jwt" "signing" "read" "key" (randAlphaNum 10 | b64enc) $securityConfig }}"
|
||||
{{- if gt (int $expiresAfterSeconds.volumeRead) 0 }}
|
||||
expires_after_seconds = {{ int $expiresAfterSeconds.volumeRead }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Values.global.seaweedfs.securityConfig.jwtSigning.filerWrite }}
|
||||
{{- if $jwtSigning.filerWrite }}
|
||||
# If this JWT key is configured, Filer only accepts writes over HTTP if they are signed with this JWT:
|
||||
# - f.e. the S3 API Shim generates the JWT
|
||||
# - the Filer server validates the JWT on writing
|
||||
# the jwt defaults to expire after 10 seconds.
|
||||
# the jwt defaults to expire after 10 seconds
|
||||
[jwt.filer_signing]
|
||||
key = "{{ dig "jwt" "filer_signing" "key" (randAlphaNum 10 | b64enc) $securityConfig }}"
|
||||
{{- if gt (int $expiresAfterSeconds.filerWrite) 0 }}
|
||||
expires_after_seconds = {{ int $expiresAfterSeconds.filerWrite }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Values.global.seaweedfs.securityConfig.jwtSigning.filerRead }}
|
||||
{{- if $jwtSigning.filerRead }}
|
||||
# If this JWT key is configured, Filer only accepts reads over HTTP if they are signed with this JWT:
|
||||
# - f.e. the S3 API Shim generates the JWT
|
||||
# - the Filer server validates the JWT on reading
|
||||
# the jwt defaults to expire after 10 seconds.
|
||||
# the jwt defaults to expire after 60 seconds
|
||||
[jwt.filer_signing.read]
|
||||
key = "{{ dig "jwt" "filer_signing" "read" "key" (randAlphaNum 10 | b64enc) $securityConfig }}"
|
||||
{{- if gt (int $expiresAfterSeconds.filerRead) 0 }}
|
||||
expires_after_seconds = {{ int $expiresAfterSeconds.filerRead }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
|
||||
@@ -26,6 +26,13 @@ global:
|
||||
volumeRead: false
|
||||
filerWrite: false
|
||||
filerRead: false
|
||||
# Positive values override SeaweedFS token lifetime defaults.
|
||||
# Zero keeps the runtime defaults: 10s for writes and 60s for reads.
|
||||
expiresAfterSeconds:
|
||||
volumeWrite: 0
|
||||
volumeRead: 0
|
||||
filerWrite: 0
|
||||
filerRead: 0
|
||||
# we will use this serviceAccountName for all ClusterRoles/ClusterRoleBindings
|
||||
serviceAccountName: "seaweedfs"
|
||||
serviceAccountAnnotations: {}
|
||||
|
||||
@@ -78,6 +78,11 @@ service SeaweedFiler {
|
||||
rpc SubscribeLocalMetadata (SubscribeMetadataRequest) returns (stream SubscribeMetadataResponse) {
|
||||
}
|
||||
|
||||
// List the metadata subscribers currently connected to this filer
|
||||
// (FUSE mounts, S3, filer.sync, peer filers, ...).
|
||||
rpc ListMetadataSubscribers (ListMetadataSubscribersRequest) returns (ListMetadataSubscribersResponse) {
|
||||
}
|
||||
|
||||
rpc KvGet (KvGetRequest) returns (KvGetResponse) {
|
||||
}
|
||||
|
||||
@@ -388,7 +393,13 @@ message PosixLockRequest {
|
||||
bool is_moved = 2;
|
||||
PosixLockOp op = 3;
|
||||
PosixLockRange lock = 4;
|
||||
// locks carries the full set a mount holds on key for a KEEP_ALIVE
|
||||
// re-assertion, so the current owner filer can rebuild its in-memory state
|
||||
// after an ownership change or restart. lock.sid identifies the session.
|
||||
repeated PosixLockRange locks = 5;
|
||||
// cooling_probe marks a dual-read a new owner sends to the previous owner
|
||||
// during a ring change, so the previous owner answers from local state
|
||||
// without itself cooling-off (no recursion).
|
||||
bool cooling_probe = 6;
|
||||
}
|
||||
|
||||
@@ -615,6 +626,22 @@ message SubscribeMetadataResponse {
|
||||
repeated SubscribeMetadataResponse events = 4; // batch of additional events (backlog catch-up)
|
||||
repeated LogFileChunkRef log_file_refs = 5; // log file chunk refs for client direct-read
|
||||
}
|
||||
message ListMetadataSubscribersRequest {
|
||||
repeated string client_types = 1; // optional filter by client type, e.g. "mount"; empty = all
|
||||
}
|
||||
message ListMetadataSubscribersResponse {
|
||||
repeated MetadataSubscriber subscribers = 1;
|
||||
}
|
||||
message MetadataSubscriber {
|
||||
string client_name = 1; // "<type>@<address>"
|
||||
string client_type = 2; // e.g. "mount", "sw-vfs", "s3", "filer:<addr>"
|
||||
string address = 3; // client peer address
|
||||
string path_prefix = 4; // subscribed path prefix
|
||||
int32 client_id = 5;
|
||||
int32 client_epoch = 6;
|
||||
int64 connected_at_ns = 7;
|
||||
string filer_address = 8; // the filer this subscriber is connected to
|
||||
}
|
||||
// A persisted log file that the client can read directly from volume servers.
|
||||
// The file format is: [4-byte size | protobuf LogEntry] repeated.
|
||||
// Each LogEntry.Data contains a marshaled SubscribeMetadataResponse.
|
||||
|
||||
+9010
-3402
File diff suppressed because it is too large.
Load diff
@@ -147,7 +147,11 @@ message VolumeEcShardInformationMessage {
|
||||
repeated int64 shard_sizes = 7; // optimized: sizes for shards in order of set bits in ec_index_bits
|
||||
uint64 file_count = 8; // total needles in the .ecx index (live + tombstoned)
|
||||
uint64 delete_count = 9; // node-local tombstones in the .ecj deletion journal
|
||||
// fields 10-19 reserved for future upstream open-source additions.
|
||||
// encode-run identity (unix nanos) from the .vif EcShardConfig; lets the admin
|
||||
// group shards by encode generation. Numbered 14 (not 10) to skip the
|
||||
// enterprise fork's reserved 10-13.
|
||||
int64 encode_ts_ns = 14;
|
||||
// fields 15-19 reserved for future upstream open-source additions.
|
||||
// fields 20+ are owned by the enterprise fork (e.g. data_shards/parity_shards)
|
||||
// and must not be used here without coordination.
|
||||
}
|
||||
|
||||
@@ -451,6 +451,7 @@ message VolumeEcShardsDeleteRequest {
|
||||
string collection = 2;
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
@@ -468,6 +469,7 @@ message VolumeEcShardsMountResponse {
|
||||
message VolumeEcShardsUnmountRequest {
|
||||
uint32 volume_id = 1;
|
||||
repeated uint32 shard_ids = 3;
|
||||
int64 encode_ts_ns = 4; // generation fence: skip a disk whose mounted EC volume is this generation or newer (0 = unfenced, unmount all)
|
||||
}
|
||||
message VolumeEcShardsUnmountResponse {
|
||||
}
|
||||
|
||||
@@ -1080,21 +1080,15 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
// If volume already exists locally, delete it first
|
||||
{
|
||||
// A pre-existing local replica is NOT deleted up front. Deleting before
|
||||
// the source is confirmed reachable destroys a healthy copy on a
|
||||
// transient source outage (and, on retry, can lose the volume
|
||||
// entirely). The delete is deferred until read_volume_file_status below
|
||||
// proves the source holds the volume; readability alone is the gate.
|
||||
let had_existing_volume = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
if store.find_volume(vid).is_some() {
|
||||
drop(store);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
// keep remote data: the inbound copy carries a .vif that may
|
||||
// point at the same cloud-tier object the existing volume
|
||||
// references.
|
||||
store.delete_volume(vid, false, true).map_err(|e| {
|
||||
Status::internal(format!("failed to delete existing volume {}: {}", vid, e))
|
||||
})?;
|
||||
self.state.volume_state_notify.notify_one();
|
||||
}
|
||||
}
|
||||
store.find_volume(vid).is_some()
|
||||
};
|
||||
|
||||
// Parse source_data_node address: "ip:port.grpcPort" or "ip:port" (grpc = port + 10000)
|
||||
let source = &req.source_data_node;
|
||||
@@ -1135,6 +1129,19 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.map_err(|e| Status::internal(format!("read volume file status failed, {}", e)))?
|
||||
.into_inner();
|
||||
|
||||
// Source is reachable and holds the volume: only now is it safe to drop
|
||||
// an existing local replica before overwriting its files.
|
||||
if had_existing_volume {
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
// keep remote data: the inbound copy carries a .vif that may point
|
||||
// at the same cloud-tier object the existing volume references.
|
||||
store.delete_volume(vid, false, true).map_err(|e| {
|
||||
Status::internal(format!("failed to delete existing volume {}: {}", vid, e))
|
||||
})?;
|
||||
drop(store);
|
||||
self.state.volume_state_notify.notify_one();
|
||||
}
|
||||
|
||||
let requested_disk_type = if !req.disk_type.is_empty() {
|
||||
DiskType::from_string(&req.disk_type)
|
||||
} else {
|
||||
@@ -1166,9 +1173,12 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let idx_base_name =
|
||||
crate::storage::volume::volume_file_name(&idx_base, &vol_info.collection, vid);
|
||||
|
||||
// Write a .note file to indicate copy in progress
|
||||
// Write a .note file to indicate copy in progress. A leftover note
|
||||
// fails the volume load on restart, so a write failure must abort.
|
||||
let note_path = format!("{}.note", data_base_name);
|
||||
let _ = std::fs::write(¬e_path, format!("copying from {}", source));
|
||||
std::fs::write(¬e_path, format!("copying from {}", source)).map_err(|e| {
|
||||
Status::internal(format!("write .note for volume {}: {}", vid, e))
|
||||
})?;
|
||||
|
||||
let has_remote_dat = vol_info
|
||||
.volume_info
|
||||
@@ -1247,7 +1257,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.await
|
||||
.map_err(|e| Status::internal(e))?;
|
||||
if dat_modified_ts_ns > 0 {
|
||||
set_file_mtime(&dat_path, dat_modified_ts_ns);
|
||||
let _ = set_file_mtime(&dat_path, dat_modified_ts_ns);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1272,7 +1282,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.await
|
||||
.map_err(|e| Status::internal(e))?;
|
||||
if idx_modified_ts_ns > 0 {
|
||||
set_file_mtime(&idx_path, idx_modified_ts_ns);
|
||||
let _ = set_file_mtime(&idx_path, idx_modified_ts_ns);
|
||||
}
|
||||
|
||||
// Copy .vif file (ignore if not found on source)
|
||||
@@ -1296,11 +1306,19 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.await
|
||||
.map_err(|e| Status::internal(e))?;
|
||||
if vif_modified_ts_ns > 0 {
|
||||
set_file_mtime(&vif_path, vif_modified_ts_ns);
|
||||
let _ = set_file_mtime(&vif_path, vif_modified_ts_ns);
|
||||
}
|
||||
|
||||
// Remove the .note file
|
||||
let _ = std::fs::remove_file(¬e_path);
|
||||
// Remove the .note file. A leftover note fails the load on the
|
||||
// next restart, so a removal failure must fail the copy.
|
||||
if let Err(e) = std::fs::remove_file(¬e_path) {
|
||||
if e.kind() != std::io::ErrorKind::NotFound {
|
||||
return Err(Status::internal(format!(
|
||||
"remove .note for volume {}: {}",
|
||||
vid, e
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// Verify file sizes
|
||||
if !has_remote_dat {
|
||||
@@ -2644,15 +2662,54 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
if req.full_teardown {
|
||||
// Pre-encode cleanup: evict the volume and wipe every EC artifact for it
|
||||
// on every disk, not just the listed shards, so a remote node retains no
|
||||
// stale generation that a fresh gen-0 copy would collide with. Echo the
|
||||
// acknowledgement so the caller can tell a pre-upgrade server apart.
|
||||
{
|
||||
if req.encode_ts_ns == 0 {
|
||||
// Blanket teardown (shell pre-encode cleanup / pre-upgrade caller): evict
|
||||
// the volume and wipe every EC artifact for it on every disk, not just the
|
||||
// listed shards, so a remote node retains no stale generation a fresh copy
|
||||
// collides with. Echo the acknowledgement so the caller can tell a
|
||||
// pre-upgrade server apart.
|
||||
{
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
let _ = store.remove_ec_volume(vid);
|
||||
for loc in &store.locations {
|
||||
loc.remove_ec_volume_files_full_teardown(&req.collection, vid)
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"full teardown of ec volume {}: {}",
|
||||
req.volume_id, e
|
||||
))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Generation-fenced teardown (stale-worker pre-distribute cleanup): wipe
|
||||
// only a disk whose .vif generation is strictly OLDER than the request;
|
||||
// preserve same-or-newer, generation 0 (recovered/pre-upgrade live volume),
|
||||
// and an unreadable .vif, so a stale run never wipes a newer run's live
|
||||
// shards. Unload and remove only the strictly-older disks, never node-wide.
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
let _ = store.remove_ec_volume(vid);
|
||||
for loc in &store.locations {
|
||||
loc.remove_ec_volume_files_full_teardown(&req.collection, vid);
|
||||
for disk_id in 0..store.locations.len() {
|
||||
let disk_gen = store.locations[disk_id].ec_generation_ts_ns(&req.collection, vid);
|
||||
let older = matches!(disk_gen, Some(g) if g > 0 && g < req.encode_ts_ns);
|
||||
if !older {
|
||||
tracing::info!(
|
||||
volume_id = vid.0,
|
||||
disk_id,
|
||||
?disk_gen,
|
||||
req = req.encode_ts_ns,
|
||||
"ec full teardown preserved: generation not older than request"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
store.locations[disk_id].remove_ec_volume(vid);
|
||||
store.locations[disk_id]
|
||||
.remove_ec_volume_files_full_teardown(&req.collection, vid)
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"fenced teardown of ec volume {}: {}",
|
||||
req.volume_id, e
|
||||
))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
self.state.volume_state_notify.notify_one();
|
||||
@@ -2710,9 +2767,11 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Matches Go: for _, shardId := range req.ShardIds { err = vs.store.UnmountEcShards(...) }
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
for &shard_id in &req.shard_ids {
|
||||
store.unmount_ec_shard(vid, shard_id).map_err(|e| {
|
||||
Status::internal(format!("unmount {}.{}: {}", req.volume_id, shard_id, e))
|
||||
})?;
|
||||
store
|
||||
.unmount_ec_shard(vid, shard_id, req.encode_ts_ns)
|
||||
.map_err(|e| {
|
||||
Status::internal(format!("unmount {}.{}: {}", req.volume_id, shard_id, e))
|
||||
})?;
|
||||
}
|
||||
drop(store);
|
||||
self.state.volume_state_notify.notify_one();
|
||||
@@ -3087,6 +3146,15 @@ impl VolumeServer for VolumeGrpcService {
|
||||
dat_path
|
||||
};
|
||||
|
||||
// Store the source .dat mtime, not the upload time, so a reload computes
|
||||
// TTL from real data age (matches Go VolumeTierMoveDatToRemote).
|
||||
let dat_modified_secs = std::fs::metadata(&dat_path)
|
||||
.and_then(|m| m.modified())
|
||||
.map_err(|e| Status::internal(format!("stat data file {}: {}", dat_path, e)))?
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
// Look up the S3 tier backend
|
||||
let backend = {
|
||||
let registry = self.state.s3_tier_registry.read().unwrap();
|
||||
@@ -3139,18 +3207,13 @@ impl VolumeServer for VolumeGrpcService {
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
if let Some((_, vol)) = store.find_volume_mut(vid) {
|
||||
let now_unix = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
vol.volume_info.files.push(volume_server_pb::RemoteFile {
|
||||
backend_type: backend_type.clone(),
|
||||
backend_id: backend_id.clone(),
|
||||
key,
|
||||
offset: 0,
|
||||
file_size: size,
|
||||
modified_time: now_unix,
|
||||
modified_time: dat_modified_secs,
|
||||
extension: ".dat".to_string(),
|
||||
});
|
||||
vol.refresh_remote_write_mode();
|
||||
@@ -3201,7 +3264,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
// Validate volume and get remote storage info
|
||||
let (dat_path, storage_name, storage_key) = {
|
||||
let (dat_path, storage_name, storage_key, remote_modified_secs) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let (_, vol) = store
|
||||
.find_volume(vid)
|
||||
@@ -3231,7 +3294,14 @@ impl VolumeServer for VolumeGrpcService {
|
||||
)));
|
||||
}
|
||||
|
||||
(dat_path, storage_name, storage_key)
|
||||
let remote_modified_secs = vol
|
||||
.volume_info
|
||||
.files
|
||||
.first()
|
||||
.map(|f| f.modified_time)
|
||||
.unwrap_or(0);
|
||||
|
||||
(dat_path, storage_name, storage_key, remote_modified_secs)
|
||||
};
|
||||
|
||||
// Look up the S3 tier backend
|
||||
@@ -3279,6 +3349,15 @@ impl VolumeServer for VolumeGrpcService {
|
||||
))
|
||||
})?;
|
||||
|
||||
// Restore the .dat mtime so a reload computes TTL from real data age,
|
||||
// not download time (matches Go VolumeTierMoveDatFromRemote).
|
||||
if remote_modified_secs > 0 {
|
||||
let modified_ts_ns = (remote_modified_secs as i64).saturating_mul(1_000_000_000);
|
||||
if let Err(e) = set_file_mtime(&dat_path, modified_ts_ns) {
|
||||
tracing::warn!("volume {} restore data file {} modified time: {}", vid, dat_path, e);
|
||||
}
|
||||
}
|
||||
|
||||
if !keep_remote {
|
||||
// Delete remote file
|
||||
backend.delete_file(&storage_key).await.map_err(|e| {
|
||||
@@ -4150,17 +4229,16 @@ async fn ping_filer_target(
|
||||
use super::grpc_client::parse_grpc_address;
|
||||
|
||||
/// Set the modification time of a file from nanoseconds since Unix epoch.
|
||||
fn set_file_mtime(path: &str, modified_ts_ns: i64) {
|
||||
fn set_file_mtime(path: &str, modified_ts_ns: i64) -> std::io::Result<()> {
|
||||
use std::time::{Duration, SystemTime};
|
||||
let ts = if modified_ts_ns >= 0 {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_nanos(modified_ts_ns as u64)
|
||||
} else {
|
||||
SystemTime::UNIX_EPOCH
|
||||
};
|
||||
if let Ok(file) = std::fs::File::open(path) {
|
||||
let ft = std::fs::FileTimes::new().set_accessed(ts).set_modified(ts);
|
||||
let _ = file.set_times(ft);
|
||||
}
|
||||
let file = std::fs::File::open(path)?;
|
||||
let ft = std::fs::FileTimes::new().set_accessed(ts).set_modified(ts);
|
||||
file.set_times(ft)
|
||||
}
|
||||
|
||||
/// Copy a file from a remote volume server via CopyFile streaming RPC.
|
||||
|
||||
@@ -314,6 +314,7 @@ fn collect_ec_shard_delta_messages(
|
||||
disk_type: ec_vol.disk_type.to_string(),
|
||||
expire_at_sec: ec_vol.expire_at_sec,
|
||||
disk_id: disk_id as u32,
|
||||
encode_ts_ns: ec_vol.encode_ts_ns,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::io;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tracing::{info, warn};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::erasure_coding::ec_shard::{
|
||||
@@ -19,7 +19,7 @@ use crate::storage::erasure_coding::ec_shard::{
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_volume::EcVolume;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE};
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::{
|
||||
remove_volume_files, volume_file_name, VifVolumeInfo, Volume, VolumeError,
|
||||
@@ -106,6 +106,12 @@ impl DiskLocation {
|
||||
fs::create_dir_all(&self.idx_directory)?;
|
||||
}
|
||||
|
||||
// Recover any interrupted compaction commit before the volume scan. This
|
||||
// must run here, not inside the .dat loop: that loop is keyed on .dat
|
||||
// files and would miss the marker-only or already-renamed-.idx states a
|
||||
// mid-commit crash can leave behind.
|
||||
self.reconcile_compact_states();
|
||||
|
||||
// Scan for .dat files
|
||||
let entries = fs::read_dir(&self.directory)?;
|
||||
let mut dat_files: Vec<(String, VolumeId)> = Vec::new();
|
||||
@@ -125,16 +131,9 @@ impl DiskLocation {
|
||||
let volume_name = volume_file_name(&self.directory, &collection, vid);
|
||||
let idx_name = volume_file_name(&self.idx_directory, &collection, vid);
|
||||
|
||||
// Check for incomplete volume (.note file means a VolumeCopy was interrupted)
|
||||
let note_path = format!("{}.note", volume_name);
|
||||
if std::path::Path::new(¬e_path).exists() {
|
||||
let note = fs::read_to_string(¬e_path).unwrap_or_default();
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"volume was not completed: {}, removing files", note
|
||||
);
|
||||
remove_volume_files(&volume_name, false);
|
||||
remove_volume_files(&idx_name, false);
|
||||
// Sweep a leftover empty `.dat` stub (a phantom from the pre-fix
|
||||
// loader) before it loads as a phantom volume or blocks startup.
|
||||
if remove_empty_ec_dat_stub(&volume_name, &idx_name, vid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -158,21 +157,36 @@ impl DiskLocation {
|
||||
volume_id = vid.0,
|
||||
"EC volume validation failed, removing incomplete EC files"
|
||||
);
|
||||
self.remove_ec_volume_files(&collection, vid);
|
||||
let _ = self.remove_ec_volume_files(&collection, vid);
|
||||
// Fall through to load .dat file
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale compaction temp files
|
||||
let cpd_path = format!("{}.cpd", volume_name);
|
||||
let cpx_path = format!("{}.cpx", idx_name);
|
||||
if std::path::Path::new(&cpd_path).exists() {
|
||||
info!(volume_id = vid.0, "removing stale compaction file .cpd");
|
||||
let _ = fs::remove_file(&cpd_path);
|
||||
}
|
||||
if std::path::Path::new(&cpx_path).exists() {
|
||||
info!(volume_id = vid.0, "removing stale compaction file .cpx");
|
||||
let _ = fs::remove_file(&cpx_path);
|
||||
// Stale .cpd/.cpx temp files were already rolled forward or back by
|
||||
// the reconcile_compact_states pre-pass above.
|
||||
|
||||
// Check for an incomplete volume (.note means a VolumeCopy was
|
||||
// interrupted). This runs BELOW the empty-stub sweep and EC
|
||||
// validation: when an .ecx for this vid coexists on the disk, the
|
||||
// regular and EC volumes share <base>.vif, so removing the
|
||||
// incomplete regular copy must keep the .vif (keep_vif=true) or it
|
||||
// would strip the EC volume's info file.
|
||||
let note_path = format!("{}.note", volume_name);
|
||||
if std::path::Path::new(¬e_path).exists() {
|
||||
let note = fs::read_to_string(¬e_path).unwrap_or_default();
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"volume was not completed: {}, removing files", note
|
||||
);
|
||||
// Re-check .ecx now (not the pre-validation ecx_exists): the
|
||||
// invalid-EC cleanup above may have removed it, in which case
|
||||
// the .vif is no longer shared and must not be preserved.
|
||||
let keep_vif = std::path::Path::new(&ecx_path).exists()
|
||||
|| (self.idx_directory != self.directory
|
||||
&& std::path::Path::new(&format!("{}.ecx", volume_name)).exists());
|
||||
remove_volume_files(&volume_name, keep_vif);
|
||||
remove_volume_files(&idx_name, keep_vif);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if already loaded (e.g., from a previous call)
|
||||
@@ -186,8 +200,14 @@ impl DiskLocation {
|
||||
// the sibling-.dat prune deletes real shards against. Remote-tiered
|
||||
// volumes also have no local `.dat`, but their `.vif` points at
|
||||
// remote files and must still load via the remote path.
|
||||
// Plain existence check (not check_dat_file_exists): an empty
|
||||
// .dat here is a fresh, needle-less volume that must still load.
|
||||
// A stat error other than NotFound counts as present so a
|
||||
// transient error doesn't skip a real volume.
|
||||
let dat_path = format!("{}.dat", volume_name);
|
||||
if !check_dat_file_exists(&dat_path)
|
||||
let dat_missing = matches!(fs::metadata(&dat_path),
|
||||
Err(ref e) if e.kind() == io::ErrorKind::NotFound);
|
||||
if dat_missing
|
||||
&& !vif_references_remote_file(&format!("{}.vif", volume_name))
|
||||
&& !vif_references_remote_file(&format!("{}.vif", idx_name))
|
||||
{
|
||||
@@ -230,22 +250,78 @@ impl DiskLocation {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate EC volume shards: all shards must be same size, and if .dat exists,
|
||||
/// need at least DATA_SHARDS_COUNT shards with size matching expected.
|
||||
/// Directory pre-pass that recovers interrupted compaction commits. Collects
|
||||
/// every volume id that still has a .cpc commit marker or a leftover
|
||||
/// .cpd/.cpx temp file across the data and idx directories, then rolls the
|
||||
/// swap forward (marker present) or back (marker absent) per volume.
|
||||
fn reconcile_compact_states(&self) {
|
||||
let mut pending: HashSet<(String, VolumeId)> = HashSet::new();
|
||||
let mut collect = |dir: &str| {
|
||||
if let Ok(entries) = fs::read_dir(dir) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().into_string().unwrap_or_default();
|
||||
let stem = name
|
||||
.strip_suffix(".cpc")
|
||||
.or_else(|| name.strip_suffix(".cpd"))
|
||||
.or_else(|| name.strip_suffix(".cpx"));
|
||||
if let Some(stem) = stem {
|
||||
if let Some(key) = parse_collection_volume_id(stem) {
|
||||
pending.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
collect(&self.directory);
|
||||
if self.idx_directory != self.directory {
|
||||
collect(&self.idx_directory);
|
||||
}
|
||||
|
||||
for (collection, vid) in pending {
|
||||
// On a runtime reload (SIGHUP), an already-loaded volume may be
|
||||
// mid-vacuum: its .cpd/.cpx are live, not crash leftovers, and
|
||||
// rolling them back would clobber the in-flight compaction. Only
|
||||
// reconcile vids not currently loaded; genuine startup recovery
|
||||
// runs before any volume is loaded.
|
||||
if self.volumes.contains_key(&vid) {
|
||||
continue;
|
||||
}
|
||||
let v = Volume::new_unloaded(&self.directory, &self.idx_directory, &collection, vid);
|
||||
if let Err(e) = v.reconcile_compact_state() {
|
||||
warn!(volume_id = vid.0, error = %e, "reconcile interrupted compaction failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports whether the EC files for (collection, vid) on this disk may be
|
||||
/// deleted to reclaim the local .dat. Returns false (delete) only when that
|
||||
/// provably loses no data; every ambiguity returns true (keep), since the
|
||||
/// shards may be the only copy. Mirrors Go's validateEcVolume.
|
||||
fn validate_ec_volume(&self, collection: &str, vid: VolumeId) -> bool {
|
||||
let base = volume_file_name(&self.directory, collection, vid);
|
||||
let dat_path = format!("{}.dat", base);
|
||||
|
||||
let mut expected_shard_size: Option<i64> = None;
|
||||
let dat_exists = std::path::Path::new(&dat_path).exists();
|
||||
// Custom ratio comes from the volume's own .vif; the server holds no
|
||||
// cluster EC config in memory.
|
||||
let data_shards =
|
||||
ec_data_shards_from_vif(&self.directory, &self.idx_directory, collection, vid);
|
||||
|
||||
if dat_exists {
|
||||
if let Ok(meta) = fs::metadata(&dat_path) {
|
||||
expected_shard_size = Some(calculate_expected_shard_size(meta.len() as i64));
|
||||
} else {
|
||||
return false;
|
||||
// On-disk .dat: an empty <= superblock one is a stub; a transient stat
|
||||
// error keeps the shards rather than deleting.
|
||||
let mut expected_shard_size: Option<i64> = None;
|
||||
let dat_exists = match fs::metadata(&dat_path) {
|
||||
Ok(meta) if meta.len() > SUPER_BLOCK_SIZE as u64 => {
|
||||
expected_shard_size =
|
||||
Some(calculate_expected_shard_size(meta.len() as i64, data_shards));
|
||||
true
|
||||
}
|
||||
}
|
||||
Ok(_) => false,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
|
||||
Err(e) => {
|
||||
warn!(volume_id = vid.0, error = %e, "cannot stat .dat; keeping EC shards");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
let mut shard_count = 0usize;
|
||||
let mut actual_shard_size: Option<i64> = None;
|
||||
@@ -258,14 +334,10 @@ impl DiskLocation {
|
||||
let size = meta.len() as i64;
|
||||
if let Some(prev) = actual_shard_size {
|
||||
if size != prev {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
shard = i,
|
||||
size,
|
||||
expected = prev,
|
||||
"EC shard size mismatch"
|
||||
);
|
||||
return false;
|
||||
// Inconsistent sizes signal corruption or mixed
|
||||
// generations; not trusted for deletion -> keep.
|
||||
warn!(volume_id = vid.0, shard = i, size, expected = prev, "EC shard size mismatch; keeping shards");
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
actual_shard_size = Some(size);
|
||||
@@ -273,49 +345,30 @@ impl DiskLocation {
|
||||
shard_count += 1;
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
shard = i,
|
||||
error = %e,
|
||||
"failed to stat EC shard"
|
||||
);
|
||||
return false;
|
||||
warn!(volume_id = vid.0, shard = i, error = %e, "cannot stat EC shard; keeping shards");
|
||||
return true;
|
||||
}
|
||||
_ => {} // not found or zero size — skip
|
||||
}
|
||||
}
|
||||
|
||||
// If .dat exists, validate shard size matches expected
|
||||
if dat_exists {
|
||||
if let (Some(actual), Some(expected)) = (actual_shard_size, expected_shard_size) {
|
||||
if actual != expected {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
actual_shard_size = actual,
|
||||
expected_shard_size = expected,
|
||||
"EC shard size doesn't match .dat file"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Distributed EC (no .dat): any shard count is valid
|
||||
if !dat_exists {
|
||||
return true;
|
||||
return true; // distributed EC; any shard count is valid
|
||||
}
|
||||
|
||||
// With .dat: need at least DATA_SHARDS_COUNT shards
|
||||
if shard_count < DATA_SHARDS_COUNT {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
shard_count,
|
||||
required = DATA_SHARDS_COUNT,
|
||||
"EC volume has .dat but too few shards"
|
||||
);
|
||||
// Reclaim only when it loses no data. Shards smaller than this .dat's
|
||||
// full encode are an interrupted encode whose .dat is the complete
|
||||
// source -> reclaim. Shards >= expected (valid/distributing EC, or a
|
||||
// stale/partial .dat beside larger real shards) may be the only copy -> keep.
|
||||
if shard_count == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let (Some(actual), Some(expected)) = (actual_shard_size, expected_shard_size) {
|
||||
if actual < expected {
|
||||
warn!(volume_id = vid.0, actual, expected, "shards smaller than the .dat's full encode; reclaiming the complete .dat");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -324,24 +377,25 @@ impl DiskLocation {
|
||||
/// `store_ec_reconcile.rs` can call it to scrub partial EC artefacts
|
||||
/// when a healthy `.dat` for the same vid lives on a sibling disk
|
||||
/// (seaweedfs/seaweedfs#9478).
|
||||
pub(crate) fn remove_ec_volume_files(&self, collection: &str, vid: VolumeId) {
|
||||
pub(crate) fn remove_ec_volume_files(&self, collection: &str, vid: VolumeId) -> io::Result<()> {
|
||||
let base = volume_file_name(&self.directory, collection, vid);
|
||||
let idx_base = volume_file_name(&self.idx_directory, collection, vid);
|
||||
const MAX_SHARD_COUNT: usize = 32;
|
||||
|
||||
// Remove index files from idx directory (.ecx, .ecj)
|
||||
let _ = fs::remove_file(format!("{}.ecx", idx_base));
|
||||
let _ = fs::remove_file(format!("{}.ecj", idx_base));
|
||||
rm_if_present(format!("{}.ecx", idx_base))?;
|
||||
rm_if_present(format!("{}.ecj", idx_base))?;
|
||||
// Also try data directory in case .ecx/.ecj were created before -dir.idx was configured
|
||||
if self.idx_directory != self.directory {
|
||||
let _ = fs::remove_file(format!("{}.ecx", base));
|
||||
let _ = fs::remove_file(format!("{}.ecj", base));
|
||||
rm_if_present(format!("{}.ecx", base))?;
|
||||
rm_if_present(format!("{}.ecj", base))?;
|
||||
}
|
||||
|
||||
// Remove all EC shard files (.ec00 ~ .ec31)
|
||||
for i in 0..MAX_SHARD_COUNT {
|
||||
let _ = fs::remove_file(format!("{}.ec{:02}", base, i));
|
||||
rm_if_present(format!("{}.ec{:02}", base, i))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Full-teardown variant: everything remove_ec_volume_files clears, PLUS the
|
||||
@@ -352,8 +406,12 @@ impl DiskLocation {
|
||||
/// .vif. Reconcile/load-fallback call remove_ec_volume_files directly and
|
||||
/// intentionally preserve it, mirroring Go's removeEcVolumeFiles (reconcile) vs
|
||||
/// removeStaleEcArtifacts (teardown) split.
|
||||
pub(crate) fn remove_ec_volume_files_full_teardown(&self, collection: &str, vid: VolumeId) {
|
||||
self.remove_ec_volume_files(collection, vid);
|
||||
pub(crate) fn remove_ec_volume_files_full_teardown(
|
||||
&self,
|
||||
collection: &str,
|
||||
vid: VolumeId,
|
||||
) -> io::Result<()> {
|
||||
self.remove_ec_volume_files(collection, vid)?;
|
||||
let base = volume_file_name(&self.directory, collection, vid);
|
||||
let idx_base = volume_file_name(&self.idx_directory, collection, vid);
|
||||
// try_exists, not exists(): a stat error on a PRESENT .idx must not read as
|
||||
@@ -363,16 +421,36 @@ impl DiskLocation {
|
||||
std::path::Path::new(&format!("{}.idx", idx_base)).try_exists(),
|
||||
Ok(false)
|
||||
) {
|
||||
let _ = fs::remove_file(format!("{}.vif", idx_base));
|
||||
rm_if_present(format!("{}.vif", idx_base))?;
|
||||
if self.idx_directory != self.directory
|
||||
&& matches!(
|
||||
std::path::Path::new(&format!("{}.idx", base)).try_exists(),
|
||||
Ok(false)
|
||||
)
|
||||
{
|
||||
let _ = fs::remove_file(format!("{}.vif", base));
|
||||
rm_if_present(format!("{}.vif", base))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// EC encode generation recorded in this disk's .vif (data dir first, then idx
|
||||
/// dir for the split-disk layout). None if no .vif was readable, so the fenced
|
||||
/// teardown preserves it (fail-safe). A present .vif with no ec_shard_config
|
||||
/// yields Some(0) (a recovered or pre-upgrade live volume), also preserved.
|
||||
pub(crate) fn ec_generation_ts_ns(&self, collection: &str, vid: VolumeId) -> Option<i64> {
|
||||
for dir in [&self.directory, &self.idx_directory] {
|
||||
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
|
||||
if let Ok(s) = fs::read_to_string(&vif) {
|
||||
if let Ok(vi) = serde_json::from_str::<VifVolumeInfo>(&s) {
|
||||
return Some(vi.ec_shard_config.map(|c| c.encode_ts_ns).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
if self.directory == self.idx_directory {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Find a volume by ID.
|
||||
@@ -871,34 +949,23 @@ impl DiskLocation {
|
||||
volume_id = vid.0,
|
||||
"Incomplete or invalid EC volume: .dat exists but validation failed, cleaning up EC files",
|
||||
);
|
||||
self.remove_ec_volume_files(collection, vid);
|
||||
let _ = self.remove_ec_volume_files(collection, vid);
|
||||
return;
|
||||
}
|
||||
|
||||
let shard_ids: Vec<u32> = shards.iter().map(|(_, sid)| *sid).collect();
|
||||
if let Err(e) = self.mount_ec_shards(vid, collection, &shard_ids, "") {
|
||||
// mount_ec_shards adds shards one at a time and increments
|
||||
// the per-shard metric for each. If it fails halfway, plain
|
||||
// ec_volumes.remove(vid) would leak metric increments for
|
||||
// the shards that did mount. Drive cleanup through
|
||||
// unmount_ec_shards which mirror-decrements the metric, then
|
||||
// the empty EcVolume drops itself.
|
||||
if dat_exists {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"Failed to load EC shards and .dat exists ({}), cleaning up EC files to use .dat",
|
||||
e,
|
||||
);
|
||||
self.unmount_ec_shards(vid, &shard_ids);
|
||||
self.remove_ec_volume_files(collection, vid);
|
||||
} else {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"Failed to load EC shards: {} (this may be normal for distributed EC volumes)",
|
||||
e,
|
||||
);
|
||||
self.unmount_ec_shards(vid, &shard_ids);
|
||||
}
|
||||
// A mount failure (corrupt/locked .ecx, EMFILE, transient I/O) is
|
||||
// not proof the shards are disposable -- validate_ec_volume already
|
||||
// decided they may be the only copy. Release partially-mounted
|
||||
// shards (mirror-decrements the metric) but keep the files; never
|
||||
// delete on a load error.
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"Failed to load EC shards: {}; keeping files for retry",
|
||||
e,
|
||||
);
|
||||
self.unmount_ec_shards(vid, &shard_ids);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,7 +991,7 @@ impl DiskLocation {
|
||||
"Found {} EC shards without .ecx file (incomplete encoding interrupted before .ecx), cleaning up",
|
||||
shards.len(),
|
||||
);
|
||||
self.remove_ec_volume_files(collection, vid);
|
||||
let _ = self.remove_ec_volume_files(collection, vid);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
@@ -985,14 +1052,14 @@ pub fn get_disk_stats(path: &str) -> (u64, u64) {
|
||||
/// Calculate expected EC shard size from .dat file size.
|
||||
/// Matches Go's `calculateExpectedShardSize`: large blocks (1GB * data_shards) first,
|
||||
/// then small blocks (1MB * data_shards) for the remainder.
|
||||
fn calculate_expected_shard_size(dat_file_size: i64) -> i64 {
|
||||
let large_batch_size = ERASURE_CODING_LARGE_BLOCK_SIZE as i64 * DATA_SHARDS_COUNT as i64;
|
||||
fn calculate_expected_shard_size(dat_file_size: i64, data_shards: usize) -> i64 {
|
||||
let large_batch_size = ERASURE_CODING_LARGE_BLOCK_SIZE as i64 * data_shards as i64;
|
||||
let num_large_batches = dat_file_size / large_batch_size;
|
||||
let mut shard_size = num_large_batches * ERASURE_CODING_LARGE_BLOCK_SIZE as i64;
|
||||
let remaining = dat_file_size - (num_large_batches * large_batch_size);
|
||||
|
||||
if remaining > 0 {
|
||||
let small_batch_size = ERASURE_CODING_SMALL_BLOCK_SIZE as i64 * DATA_SHARDS_COUNT as i64;
|
||||
let small_batch_size = ERASURE_CODING_SMALL_BLOCK_SIZE as i64 * data_shards as i64;
|
||||
// Ceiling division
|
||||
let num_small_batches = (remaining + small_batch_size - 1) / small_batch_size;
|
||||
shard_size += num_small_batches * ERASURE_CODING_SMALL_BLOCK_SIZE as i64;
|
||||
@@ -1001,6 +1068,39 @@ fn calculate_expected_shard_size(dat_file_size: i64) -> i64 {
|
||||
shard_size
|
||||
}
|
||||
|
||||
/// Resolve the EC data-shard count from the volume's own `.vif` (the volume
|
||||
/// server never holds the cluster EC config in memory), checking the data dir
|
||||
/// then the idx dir. Falls back to the default ratio when no EC `.vif` is found.
|
||||
/// Remove a file, treating a missing file as success but propagating real errors
|
||||
/// (permissions, disk full). Mirrors Go's removeFileIfExists so a teardown failure
|
||||
/// surfaces instead of silently leaving stale artifacts.
|
||||
fn rm_if_present(path: String) -> io::Result<()> {
|
||||
match fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ec_data_shards_from_vif(directory: &str, idx_directory: &str, collection: &str, vid: VolumeId) -> usize {
|
||||
for dir in [directory, idx_directory] {
|
||||
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
|
||||
if let Some(ds) = fs::read_to_string(&vif)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
|
||||
.and_then(|vi| vi.ec_shard_config)
|
||||
.map(|c| c.data_shards as usize)
|
||||
{
|
||||
if ds > 0 {
|
||||
return ds;
|
||||
}
|
||||
}
|
||||
if directory == idx_directory {
|
||||
break;
|
||||
}
|
||||
}
|
||||
DATA_SHARDS_COUNT
|
||||
}
|
||||
|
||||
/// Parse a volume filename like "collection_42.dat" or "42.dat" into (collection, VolumeId).
|
||||
/// Parse a `<collection>_<vid>` or `<vid>` base name into its parts.
|
||||
/// Mirrors `parseCollectionVolumeId` in
|
||||
@@ -1054,12 +1154,14 @@ fn parse_ec_shard_extension(ext: &str) -> Option<u32> {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Robust `.dat` existence check: any unexpected stat error (permission,
|
||||
/// I/O) is treated as "exists" so we don't misclassify local EC as
|
||||
/// distributed EC. Mirrors `checkDatFileExists` in Go.
|
||||
/// Robust check that a `.dat` with actual data exists. An empty `.dat`
|
||||
/// (<= a superblock, zero needles) is a leftover stub, not an encode source,
|
||||
/// and counts as absent so it never justifies deleting shards. Any unexpected
|
||||
/// stat error (permission, I/O) is treated as "exists" so we don't misclassify
|
||||
/// local EC as distributed EC. Mirrors `checkDatFileExists` in Go.
|
||||
fn check_dat_file_exists(path: &str) -> bool {
|
||||
match fs::metadata(path) {
|
||||
Ok(_) => true,
|
||||
Ok(meta) => meta.len() > SUPER_BLOCK_SIZE as u64,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
|
||||
Err(_) => true,
|
||||
}
|
||||
@@ -1076,20 +1178,53 @@ fn vif_references_remote_file(vif_path: &str) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// True when a `.vif` records an EC shard config, i.e. the volume was
|
||||
/// erasure-coded. Such a volume keeps no local `.dat`, so an empty `.dat`
|
||||
/// alongside it is a leftover stub safe to remove.
|
||||
fn vif_is_ec_volume(vif_path: &str) -> bool {
|
||||
fs::read_to_string(vif_path)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
|
||||
.map(|vif| vif.ec_shard_config.is_some())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Remove a leftover empty EC `.dat` stub and return whether one was swept.
|
||||
///
|
||||
/// A stub is an empty `.dat` (<= a superblock, i.e. zero needles) whose `.vif`
|
||||
/// records an EC shard config. An EC volume keeps no local `.dat`, so the stub
|
||||
/// holds no data — its shards live on other servers. Such stubs (phantoms from
|
||||
/// the pre-fix loader) otherwise load as phantom empty volumes, and a same-vid
|
||||
/// stub on two disks blocks startup via the duplicate-vid check. The `.dat` and
|
||||
/// its empty `.idx` are removed; non-EC empty `.dat` files are left alone. The
|
||||
/// `.vif` is looked up in both the data and idx directories (which differ only
|
||||
/// when `-dir.idx` is configured), each read at most once.
|
||||
fn remove_empty_ec_dat_stub(volume_name: &str, idx_name: &str, vid: VolumeId) -> bool {
|
||||
let dat_path = format!("{}.dat", volume_name);
|
||||
match fs::metadata(&dat_path) {
|
||||
Ok(meta) if meta.len() <= SUPER_BLOCK_SIZE as u64 => {}
|
||||
_ => return false,
|
||||
}
|
||||
|
||||
let data_vif = format!("{}.vif", volume_name);
|
||||
let idx_vif = format!("{}.vif", idx_name);
|
||||
let is_ec = vif_is_ec_volume(&data_vif) || (idx_vif != data_vif && vif_is_ec_volume(&idx_vif));
|
||||
if !is_ec {
|
||||
return false;
|
||||
}
|
||||
|
||||
warn!(volume_id = vid.0, "removing leftover empty .dat stub for EC volume");
|
||||
let _ = fs::remove_file(&dat_path);
|
||||
let _ = fs::remove_file(format!("{}.idx", idx_name));
|
||||
true
|
||||
}
|
||||
|
||||
fn parse_volume_filename(filename: &str) -> Option<(String, VolumeId)> {
|
||||
let stem = filename
|
||||
.strip_suffix(".dat")
|
||||
.or_else(|| filename.strip_suffix(".vif"))
|
||||
.or_else(|| filename.strip_suffix(".idx"))?;
|
||||
if let Some(pos) = stem.rfind('_') {
|
||||
let collection = &stem[..pos];
|
||||
let id_str = &stem[pos + 1..];
|
||||
let id: u32 = id_str.parse().ok()?;
|
||||
Some((collection.to_string(), VolumeId(id)))
|
||||
} else {
|
||||
let id: u32 = stem.parse().ok()?;
|
||||
Some((String::new(), VolumeId(id)))
|
||||
}
|
||||
parse_collection_volume_id(stem)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -1101,6 +1236,138 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// When `-dir.idx` is configured the EC `.vif` may live in the idx
|
||||
/// directory; the sweep must look there too, not only the data dir.
|
||||
#[test]
|
||||
fn test_remove_empty_ec_dat_stub_finds_vif_in_idx_dir() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let data = tmp.path().join("data");
|
||||
let idx = tmp.path().join("idx");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::create_dir_all(&idx).unwrap();
|
||||
let vbase = format!("{}/warp-cal_42", data.to_str().unwrap());
|
||||
let ibase = format!("{}/warp-cal_42", idx.to_str().unwrap());
|
||||
std::fs::write(format!("{}.dat", vbase), vec![0u8; 8]).unwrap();
|
||||
|
||||
let vif = VifVolumeInfo {
|
||||
version: 3,
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(format!("{}.vif", ibase), serde_json::to_string(&vif).unwrap()).unwrap();
|
||||
|
||||
assert!(
|
||||
remove_empty_ec_dat_stub(&vbase, &ibase, VolumeId(42)),
|
||||
"EC .vif in the idx dir should be found and the stub removed",
|
||||
);
|
||||
assert!(!std::path::Path::new(&format!("{}.dat", vbase)).exists());
|
||||
}
|
||||
|
||||
// The headline geometry: a stale/partial .dat (e.g. an interrupted decode)
|
||||
// smaller than the volume's real source sits next to the full-size shards
|
||||
// that are the only copy. validate_ec_volume must keep the shards.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_partial_dat_next_to_full_shards_keeps() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = DiskLocation::new(dir, dir, 10, DiskType::HardDrive, MinFreeSpace::Percent(1.0), Vec::new()).unwrap();
|
||||
let base = volume_file_name(dir, "", VolumeId(70));
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let full = calculate_expected_shard_size(30 * 1024 * 1024, ds);
|
||||
for i in 0..ds {
|
||||
std::fs::File::create(format!("{}.ec{:02}", base, i)).unwrap().set_len(full as u64).unwrap();
|
||||
}
|
||||
// Partial .dat: bigger than a superblock so it is not swept as a stub,
|
||||
// but smaller than what these shards encode.
|
||||
std::fs::File::create(format!("{}.dat", base)).unwrap().set_len(5 * 1024 * 1024).unwrap();
|
||||
assert!(
|
||||
loc.validate_ec_volume("", VolumeId(70)),
|
||||
"full-size shards beside a smaller (stale/partial) .dat must be kept",
|
||||
);
|
||||
}
|
||||
|
||||
// The legitimate cleanup: a full source .dat next to shards SMALLER than it
|
||||
// would encode (an interrupted encode). The .dat is the complete source, so
|
||||
// reclaiming it loses no data.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_interrupted_encode_reclaims() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = DiskLocation::new(dir, dir, 10, DiskType::HardDrive, MinFreeSpace::Percent(1.0), Vec::new()).unwrap();
|
||||
let base = volume_file_name(dir, "", VolumeId(71));
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let dat_size = 30 * 1024 * 1024i64;
|
||||
std::fs::File::create(format!("{}.dat", base)).unwrap().set_len(dat_size as u64).unwrap();
|
||||
let partial = calculate_expected_shard_size(dat_size, ds) / 3;
|
||||
assert!(partial > 0);
|
||||
for i in 0..ds {
|
||||
std::fs::File::create(format!("{}.ec{:02}", base, i)).unwrap().set_len(partial as u64).unwrap();
|
||||
}
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", VolumeId(71)),
|
||||
"shards smaller than the full source .dat should be reclaimable",
|
||||
);
|
||||
}
|
||||
|
||||
// The per-disk generation reader behind the fenced EC teardown: a present .vif
|
||||
// yields its generation (or 0 with no EC config), a missing .vif is unreadable
|
||||
// (preserved, fail-safe), and the idx dir is a fallback for the split-disk layout.
|
||||
#[test]
|
||||
fn test_ec_generation_ts_ns_reads_and_fences() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let data = tmp.path().join("data");
|
||||
let idx = tmp.path().join("idx");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::create_dir_all(&idx).unwrap();
|
||||
let loc = DiskLocation::new(
|
||||
data.to_str().unwrap(),
|
||||
idx.to_str().unwrap(),
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let vid = VolumeId(88);
|
||||
let dbase = volume_file_name(data.to_str().unwrap(), "", vid);
|
||||
let ibase = volume_file_name(idx.to_str().unwrap(), "", vid);
|
||||
|
||||
// No .vif anywhere -> unreadable (the fenced teardown preserves on None).
|
||||
assert_eq!(loc.ec_generation_ts_ns("", vid), None);
|
||||
|
||||
// .vif in the data dir carries its generation.
|
||||
let with_gen = VifVolumeInfo {
|
||||
version: 3,
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
encode_ts_ns: 4242,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(format!("{}.vif", dbase), serde_json::to_string(&with_gen).unwrap()).unwrap();
|
||||
assert_eq!(loc.ec_generation_ts_ns("", vid), Some(4242));
|
||||
|
||||
// A .vif with no EC config reads as generation 0 (recovered/pre-upgrade live volume).
|
||||
std::fs::remove_file(format!("{}.vif", dbase)).unwrap();
|
||||
let no_cfg = VifVolumeInfo {
|
||||
version: 3,
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(format!("{}.vif", dbase), serde_json::to_string(&no_cfg).unwrap()).unwrap();
|
||||
assert_eq!(loc.ec_generation_ts_ns("", vid), Some(0));
|
||||
|
||||
// idx-dir fallback: only the idx dir holds the .vif.
|
||||
std::fs::remove_file(format!("{}.vif", dbase)).unwrap();
|
||||
std::fs::write(format!("{}.vif", ibase), serde_json::to_string(&with_gen).unwrap()).unwrap();
|
||||
assert_eq!(loc.ec_generation_ts_ns("", vid), Some(4242));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_volume_filename() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::storage::idx;
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::volume_file_name;
|
||||
use crate::storage::volume::{fsync_dir, volume_file_name};
|
||||
|
||||
/// Calculate .dat file size from the max offset entry in .ecx.
|
||||
/// Reads the volume version from the first EC shard (.ec00) superblock,
|
||||
@@ -123,60 +123,81 @@ pub fn write_dat_file_from_shards_with_dirs(
|
||||
}
|
||||
let base = volume_file_name(dat_dir, collection, volume_id);
|
||||
let dat_path = format!("{}.dat", base);
|
||||
// Write to a temp file and atomically rename into place, so a crash
|
||||
// mid-write never leaves a partial .dat at the final name beside the
|
||||
// source shards.
|
||||
let tmp_path = format!("{}.tmp", dat_path);
|
||||
|
||||
// Open data shards from their individual home dirs.
|
||||
let mut shards: Vec<EcVolumeShard> = (0..data_shards as u8)
|
||||
.map(|i| EcVolumeShard::new(&shard_dirs[i as usize], collection, volume_id, i))
|
||||
.collect();
|
||||
let write_result = (|| -> io::Result<()> {
|
||||
// Open data shards from their individual home dirs.
|
||||
let mut shards: Vec<EcVolumeShard> = (0..data_shards as u8)
|
||||
.map(|i| EcVolumeShard::new(&shard_dirs[i as usize], collection, volume_id, i))
|
||||
.collect();
|
||||
|
||||
for shard in &mut shards {
|
||||
shard.open()?;
|
||||
}
|
||||
|
||||
let mut dat_file = File::create(&dat_path)?;
|
||||
let mut remaining = dat_file_size;
|
||||
let large_block_size = ERASURE_CODING_LARGE_BLOCK_SIZE;
|
||||
let small_block_size = ERASURE_CODING_SMALL_BLOCK_SIZE;
|
||||
let large_row_size = (large_block_size * data_shards) as i64;
|
||||
|
||||
let mut shard_offset: u64 = 0;
|
||||
|
||||
// Read large blocks
|
||||
while remaining >= large_row_size {
|
||||
for i in 0..data_shards {
|
||||
let mut buf = vec![0u8; large_block_size];
|
||||
shards[i].read_at(&mut buf, shard_offset)?;
|
||||
let to_write = large_block_size.min(remaining as usize);
|
||||
dat_file.write_all(&buf[..to_write])?;
|
||||
remaining -= to_write as i64;
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
for shard in &mut shards {
|
||||
shard.open()?;
|
||||
}
|
||||
shard_offset += large_block_size as u64;
|
||||
}
|
||||
|
||||
// Read small blocks
|
||||
while remaining > 0 {
|
||||
for i in 0..data_shards {
|
||||
let mut buf = vec![0u8; small_block_size];
|
||||
shards[i].read_at(&mut buf, shard_offset)?;
|
||||
let to_write = small_block_size.min(remaining as usize);
|
||||
dat_file.write_all(&buf[..to_write])?;
|
||||
remaining -= to_write as i64;
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
let mut dat_file = File::create(&tmp_path)?;
|
||||
let mut remaining = dat_file_size;
|
||||
let large_block_size = ERASURE_CODING_LARGE_BLOCK_SIZE;
|
||||
let small_block_size = ERASURE_CODING_SMALL_BLOCK_SIZE;
|
||||
let large_row_size = (large_block_size * data_shards) as i64;
|
||||
|
||||
let mut shard_offset: u64 = 0;
|
||||
|
||||
// Read large blocks
|
||||
while remaining >= large_row_size {
|
||||
for i in 0..data_shards {
|
||||
let mut buf = vec![0u8; large_block_size];
|
||||
shards[i].read_at(&mut buf, shard_offset)?;
|
||||
let to_write = large_block_size.min(remaining as usize);
|
||||
dat_file.write_all(&buf[..to_write])?;
|
||||
remaining -= to_write as i64;
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
shard_offset += large_block_size as u64;
|
||||
}
|
||||
shard_offset += small_block_size as u64;
|
||||
}
|
||||
|
||||
for shard in &mut shards {
|
||||
shard.close();
|
||||
}
|
||||
// Read small blocks
|
||||
while remaining > 0 {
|
||||
for i in 0..data_shards {
|
||||
let mut buf = vec![0u8; small_block_size];
|
||||
shards[i].read_at(&mut buf, shard_offset)?;
|
||||
let to_write = small_block_size.min(remaining as usize);
|
||||
dat_file.write_all(&buf[..to_write])?;
|
||||
remaining -= to_write as i64;
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
shard_offset += small_block_size as u64;
|
||||
}
|
||||
|
||||
dat_file.sync_all()?;
|
||||
Ok(())
|
||||
for shard in &mut shards {
|
||||
shard.close();
|
||||
}
|
||||
|
||||
// fsync, rename, then fsync the dir so the decoded .dat is durable and
|
||||
// atomically published before the caller deletes the source shards.
|
||||
dat_file.sync_all()?;
|
||||
drop(dat_file);
|
||||
// Windows rename does not replace an existing file on every version;
|
||||
// remove the destination first, matching the compaction commit path.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::fs::remove_file(&dat_path);
|
||||
}
|
||||
std::fs::rename(&tmp_path, &dat_path)?;
|
||||
fsync_dir(&dat_path)?;
|
||||
Ok(())
|
||||
})();
|
||||
if write_result.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp_path);
|
||||
}
|
||||
write_result
|
||||
}
|
||||
|
||||
/// Write .idx file from .ecx index + .ecj deletion journal.
|
||||
@@ -192,34 +213,59 @@ pub fn write_idx_file_from_ec_index(
|
||||
let ecx_path = format!("{}.ecx", base);
|
||||
let ecj_path = format!("{}.ecj", base);
|
||||
let idx_path = format!("{}.idx", base);
|
||||
// Write to a temp file and atomically rename into place, so a crash
|
||||
// mid-write never leaves a partial .idx at the final name beside the
|
||||
// source shards.
|
||||
let tmp_path = format!("{}.tmp", idx_path);
|
||||
|
||||
// Copy .ecx to .idx
|
||||
std::fs::copy(&ecx_path, &idx_path)?;
|
||||
let write_result = (|| -> io::Result<()> {
|
||||
// Copy .ecx to the temp .idx
|
||||
std::fs::copy(&ecx_path, &tmp_path)?;
|
||||
|
||||
// Append deletions from .ecj as tombstones
|
||||
if std::path::Path::new(&ecj_path).exists() {
|
||||
let ecj_data = std::fs::read(&ecj_path)?;
|
||||
if !ecj_data.is_empty() {
|
||||
let mut idx_file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.open(&idx_path)?;
|
||||
|
||||
let count = ecj_data.len() / NEEDLE_ID_SIZE;
|
||||
for i in 0..count {
|
||||
let start = i * NEEDLE_ID_SIZE;
|
||||
let needle_id = NeedleId::from_bytes(&ecj_data[start..start + NEEDLE_ID_SIZE]);
|
||||
idx::write_index_entry(
|
||||
&mut idx_file,
|
||||
needle_id,
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)?;
|
||||
// Append deletions from .ecj as tombstones. Read the journal directly
|
||||
// and treat only NotFound as "no journal": Path::exists would also
|
||||
// swallow a permission/IO error and silently skip deletions, which
|
||||
// would resurrect deleted needles as live.
|
||||
let mut idx_file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.open(&tmp_path)?;
|
||||
match std::fs::read(&ecj_path) {
|
||||
Ok(ecj_data) => {
|
||||
let count = ecj_data.len() / NEEDLE_ID_SIZE;
|
||||
for i in 0..count {
|
||||
let start = i * NEEDLE_ID_SIZE;
|
||||
let needle_id = NeedleId::from_bytes(&ecj_data[start..start + NEEDLE_ID_SIZE]);
|
||||
idx::write_index_entry(
|
||||
&mut idx_file,
|
||||
needle_id,
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
// fsync, rename, then fsync the dir so the decoded .idx is durable and
|
||||
// atomically published before the caller deletes the source shards.
|
||||
idx_file.sync_all()?;
|
||||
drop(idx_file);
|
||||
// Windows rename does not replace an existing file on every version;
|
||||
// remove the destination first, matching the compaction commit path.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::fs::remove_file(&idx_path);
|
||||
}
|
||||
std::fs::rename(&tmp_path, &idx_path)?;
|
||||
fsync_dir(&idx_path)?;
|
||||
Ok(())
|
||||
})();
|
||||
if write_result.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp_path);
|
||||
}
|
||||
write_result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -288,6 +334,10 @@ mod tests {
|
||||
.unwrap();
|
||||
write_idx_file_from_ec_index(dir, "", VolumeId(1)).unwrap();
|
||||
|
||||
// Atomic publish must rename the temp files away, never leaving them behind.
|
||||
assert!(!std::path::Path::new(&format!("{}/1.dat.tmp", dir)).exists());
|
||||
assert!(!std::path::Path::new(&format!("{}/1.idx.tmp", dir)).exists());
|
||||
|
||||
// Verify reconstructed .dat matches original
|
||||
let reconstructed_dat = std::fs::read(format!("{}/1.dat", dir)).unwrap();
|
||||
assert_eq!(
|
||||
@@ -319,4 +369,16 @@ mod tests {
|
||||
assert_eq!(&n.data, expected_data, "needle {} data should match", id);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decode_missing_shard_leaves_no_dat() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
// No shard files exist, so de-striping must fail and publish nothing:
|
||||
// neither the final .dat nor a partial .dat.tmp may remain.
|
||||
let res = write_dat_file_from_shards(dir, "", VolumeId(7), 100, 10);
|
||||
assert!(res.is_err());
|
||||
assert!(!std::path::Path::new(&format!("{}/7.dat", dir)).exists());
|
||||
assert!(!std::path::Path::new(&format!("{}/7.dat.tmp", dir)).exists());
|
||||
}
|
||||
}
|
||||
@@ -136,11 +136,22 @@ pub fn rebuild_ec_files(
|
||||
// Allocate buffers for all shards. Option<Vec<u8>> is required by rs.reconstruct()
|
||||
let mut buffers: Vec<Option<Vec<u8>>> = vec![None; total_shards];
|
||||
|
||||
// Read available shards
|
||||
// Read available shards. A short read means a truncated/corrupt input
|
||||
// shard; treat it as an error rather than reconstructing over a
|
||||
// zero-padded tail and publishing the result as restored redundancy.
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if !missing_shard_ids.contains(&(i as u32)) {
|
||||
let mut buf = vec![0u8; to_process];
|
||||
shard.read_at(&mut buf, offset)?;
|
||||
let n = shard.read_at(&mut buf, offset)?;
|
||||
if n != to_process {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"ec rebuild short read shard {} at {}: got {} want {}",
|
||||
i, offset, n, to_process
|
||||
),
|
||||
));
|
||||
}
|
||||
buffers[i] = Some(buf);
|
||||
}
|
||||
}
|
||||
@@ -655,6 +666,81 @@ mod tests {
|
||||
assert!(std::path::Path::new(&ecx_path).exists());
|
||||
}
|
||||
|
||||
// encode_sample_volume writes a small volume and EC-encodes it, returning
|
||||
// the dir path so a test can drop/truncate shards and rebuild.
|
||||
fn encode_sample_volume(tmp: &TempDir) -> String {
|
||||
let dir = tmp.path().to_str().unwrap().to_string();
|
||||
let mut v = Volume::new(
|
||||
&dir,
|
||||
&dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=20 {
|
||||
let data = format!("test data for needle {} padded with bytes", i).repeat(64);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
write_ec_files(&dir, &dir, "", VolumeId(1), 10, 4).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
// A truncated/corrupt input shard must abort rebuild_ec_files with an error
|
||||
// rather than reconstructing over a zero-padded tail and publishing a
|
||||
// truncated shard as restored redundancy.
|
||||
#[test]
|
||||
fn test_rebuild_ec_files_short_read_input_errors() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = encode_sample_volume(&tmp);
|
||||
|
||||
// Truncate a present input shard to half its size.
|
||||
let victim = format!("{}/1.ec03", dir);
|
||||
let full = std::fs::metadata(&victim).unwrap().len();
|
||||
assert!(full > 0, "encoded shard should be non-empty");
|
||||
let f = std::fs::OpenOptions::new().write(true).open(&victim).unwrap();
|
||||
f.set_len(full / 2).unwrap();
|
||||
drop(f);
|
||||
|
||||
// Rebuild a different (genuinely missing) shard.
|
||||
std::fs::remove_file(format!("{}/1.ec07", dir)).unwrap();
|
||||
let res = rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4);
|
||||
assert!(res.is_err(), "truncated input shard must abort the rebuild");
|
||||
}
|
||||
|
||||
// Happy path: dropping a shard and rebuilding it from the rest must succeed
|
||||
// and recreate the shard file (the short-read guard must not false-positive).
|
||||
#[test]
|
||||
fn test_rebuild_ec_files_happy_path() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = encode_sample_volume(&tmp);
|
||||
|
||||
let dropped = format!("{}/1.ec07", dir);
|
||||
std::fs::remove_file(&dropped).unwrap();
|
||||
rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4).unwrap();
|
||||
assert!(
|
||||
std::path::Path::new(&dropped).exists(),
|
||||
"rebuilt shard .ec07 should exist"
|
||||
);
|
||||
assert!(
|
||||
std::fs::metadata(&dropped).unwrap().len() > 0,
|
||||
"rebuilt shard should be non-empty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reed_solomon_basic() {
|
||||
let data_shards = 10;
|
||||
|
||||
@@ -448,6 +448,7 @@ impl EcVolume {
|
||||
disk_id,
|
||||
file_count,
|
||||
delete_count,
|
||||
encode_ts_ns: self.encode_ts_ns,
|
||||
..Default::default()
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -369,6 +369,16 @@ impl Store {
|
||||
let vif_path = format!("{}.vif", base);
|
||||
if std::path::Path::new(&dat_path).exists() || std::path::Path::new(&vif_path).exists()
|
||||
{
|
||||
// A persisting .note means the copy that produced these files
|
||||
// never completed; mounting it would expose a truncated volume.
|
||||
// Fail the mount so the caller (VolumeCopy) treats it as an error.
|
||||
let note_path = format!("{}.note", base);
|
||||
if std::path::Path::new(¬e_path).exists() {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("volume {} copy incomplete: .note still present", vid),
|
||||
)));
|
||||
}
|
||||
return loc.create_volume(
|
||||
vid,
|
||||
collection,
|
||||
@@ -706,17 +716,37 @@ impl Store {
|
||||
|
||||
/// Unmount a single EC shard, searching all locations.
|
||||
/// Matches Go's Store.UnmountEcShards which unmounts one shard at a time.
|
||||
pub fn unmount_ec_shard(&mut self, vid: VolumeId, shard_id: u32) -> Result<(), VolumeError> {
|
||||
pub fn unmount_ec_shard(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
shard_id: u32,
|
||||
req_encode_ts_ns: i64,
|
||||
) -> Result<(), VolumeError> {
|
||||
// Walk all locations rather than stopping at the first with the
|
||||
// vid — split-disk reconciled volumes can have the same vid on
|
||||
// multiple disks, with the target shard on any of them.
|
||||
for disk_id in 0..self.locations.len() {
|
||||
let has_shard = self.locations[disk_id]
|
||||
.find_ec_volume(vid)
|
||||
.is_some_and(|ec_vol| ec_vol.has_shard(shard_id as u8));
|
||||
let ec_vol = self.locations[disk_id].find_ec_volume(vid);
|
||||
let has_shard = ec_vol.is_some_and(|ec_vol| ec_vol.has_shard(shard_id as u8));
|
||||
if !has_shard {
|
||||
continue;
|
||||
}
|
||||
// Generation fence: when the caller carries a generation (stale-worker
|
||||
// cleanup), only unmount a strictly-older generation; preserve a disk
|
||||
// whose generation is same-or-newer, 0, or unknown, so a stale run cannot
|
||||
// unmount a newer run's live shards. req 0 (legacy/shell) unmounts all.
|
||||
let disk_gen = ec_vol.map_or(0, |v| v.encode_ts_ns);
|
||||
if req_encode_ts_ns > 0 && !(disk_gen > 0 && disk_gen < req_encode_ts_ns) {
|
||||
tracing::info!(
|
||||
volume_id = vid.0,
|
||||
shard_id,
|
||||
disk_id,
|
||||
disk_gen,
|
||||
req = req_encode_ts_ns,
|
||||
"UnmountEcShards skipped: generation not older than request"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
tracing::info!(
|
||||
volume_id = vid.0,
|
||||
shard_id,
|
||||
|
||||
@@ -23,7 +23,6 @@ use tracing::{info, warn};
|
||||
use crate::storage::disk_location::{is_ec_shard_extension, parse_collection_volume_id_pub};
|
||||
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
use crate::storage::store::Store;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
use crate::storage::types::VolumeId;
|
||||
|
||||
pub(crate) fn ec_local_ecx_path(dir: &str, collection: &str, vid: VolumeId) -> String {
|
||||
@@ -237,8 +236,15 @@ impl Store {
|
||||
let mut victims: Vec<Victim> = Vec::new();
|
||||
for (loc_idx, loc) in self.locations.iter().enumerate() {
|
||||
for (vid, ev) in loc.ec_volumes() {
|
||||
// Use the volume's own ratio, not the OSS default, so a full
|
||||
// custom-ratio data set (e.g. 9 of a 9+3) is not mistaken for a leftover.
|
||||
let data_shards = if ev.data_shards > 0 {
|
||||
ev.data_shards as usize
|
||||
} else {
|
||||
DATA_SHARDS_COUNT
|
||||
};
|
||||
let shard_count = ev.shard_count();
|
||||
if shard_count >= DATA_SHARDS_COUNT {
|
||||
if shard_count >= data_shards {
|
||||
continue;
|
||||
}
|
||||
let key = EcKey {
|
||||
@@ -254,15 +260,10 @@ impl Store {
|
||||
// per-disk pass; don't second-guess it here.
|
||||
continue;
|
||||
}
|
||||
// Credible source size: prefer .vif's encode-time size; when
|
||||
// unknown (0) require more than a bare superblock so an empty
|
||||
// 8-byte stub (e.g. a phantom .dat) can't pass.
|
||||
let required = if ev.dat_file_size > 0 {
|
||||
ev.dat_file_size as u64
|
||||
} else {
|
||||
SUPER_BLOCK_SIZE as u64 + 1
|
||||
};
|
||||
if owner.size < required {
|
||||
// Delete only against a byte-exact committed source: the sibling
|
||||
// .dat must equal the size .vif recorded at encode time. An
|
||||
// unknown (0) or mismatched size cannot prove the .dat holds this data.
|
||||
if ev.dat_file_size <= 0 || owner.size != ev.dat_file_size as u64 {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
collection = %ev.collection,
|
||||
@@ -270,8 +271,30 @@ impl Store {
|
||||
shard_count,
|
||||
sibling_dir = %self.locations[owner.location].directory,
|
||||
sibling_dat_size = owner.size,
|
||||
required,
|
||||
"sibling .dat is smaller than the EC source size; leaving partial EC in place so distributed reconstruction is still possible (issue 9478)",
|
||||
recorded = ev.dat_file_size,
|
||||
"sibling .dat does not byte-exactly match the recorded EC source size; leaving partial EC in place",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// Never prune when the shards are recoverable node-wide (a set
|
||||
// split across sibling disks summing to >= data_shards); they
|
||||
// may be sole copies of a distributed volume.
|
||||
let mut node_wide_bits = ev.shard_bits().0;
|
||||
for other in &self.locations {
|
||||
if let Some(other_ev) = other.find_ec_volume(*vid) {
|
||||
if other_ev.collection == ev.collection {
|
||||
node_wide_bits |= other_ev.shard_bits().0;
|
||||
}
|
||||
}
|
||||
}
|
||||
let node_wide = node_wide_bits.count_ones() as usize;
|
||||
if node_wide >= data_shards {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
collection = %ev.collection,
|
||||
node_wide,
|
||||
data_shards,
|
||||
"shards present node-wide are independently recoverable; leaving EC in place despite a sibling .dat",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
@@ -309,7 +332,7 @@ impl Store {
|
||||
// Also sweep any unmounted shard files (.ec00 .. .ec31)
|
||||
// that the per-disk loader skipped — destroy() only walks
|
||||
// the in-memory shards, but the disk may still hold others.
|
||||
loc.remove_ec_volume_files(&v.collection, v.vid);
|
||||
let _ = loc.remove_ec_volume_files(&v.collection, v.vid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +489,105 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn write_ec_vif(dir: &str, collection: &str, vid: u32) {
|
||||
let vif = VifVolumeInfo {
|
||||
version: 3,
|
||||
ec_shard_config: Some(VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
std::fs::write(
|
||||
format!("{}/{}_{}.vif", dir, collection, vid),
|
||||
serde_json::to_string(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// An empty `.dat` (<= a superblock, i.e. zero needles) for an EC volume
|
||||
/// is a leftover stub from the pre-fix loader. It must be swept on startup,
|
||||
/// not loaded as a phantom empty volume. With the same vid's stub on two
|
||||
/// disks this also unblocks startup, which previously failed the
|
||||
/// duplicate-vid check (the volume6 incident).
|
||||
#[test]
|
||||
fn test_empty_ec_dat_stub_removed_and_unblocks_startup() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let d0 = tmp.path().join("data0");
|
||||
let d1 = tmp.path().join("data1");
|
||||
std::fs::create_dir_all(&d0).unwrap();
|
||||
std::fs::create_dir_all(&d1).unwrap();
|
||||
let coll = "warp-cal";
|
||||
let vid = 41u32;
|
||||
|
||||
// A real (loadable) but empty superblock: without the sweep both disks
|
||||
// load it as vid 41 and add_location fails the duplicate-vid check.
|
||||
let stub = crate::storage::super_block::SuperBlock {
|
||||
version: crate::storage::types::Version::current(),
|
||||
..Default::default()
|
||||
}
|
||||
.to_bytes();
|
||||
for d in [&d0, &d1] {
|
||||
let dir = d.to_str().unwrap();
|
||||
std::fs::write(format!("{}/{}_{}.dat", dir, coll, vid), &stub).unwrap();
|
||||
write_ec_vif(dir, coll, vid);
|
||||
}
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
for d in [&d0, &d1] {
|
||||
store
|
||||
.add_location(
|
||||
d.to_str().unwrap(),
|
||||
d.to_str().unwrap(),
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.expect("a same-vid empty stub on two disks must not block startup");
|
||||
}
|
||||
|
||||
let loaded: usize = store.locations.iter().map(|l| l.volume_ids().len()).sum();
|
||||
assert_eq!(loaded, 0, "empty EC stub was loaded as a phantom volume");
|
||||
for d in [&d0, &d1] {
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}/{}_{}.dat", d.to_str().unwrap(), coll, vid))
|
||||
.exists(),
|
||||
"empty .dat stub was not removed",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Safety: an empty `.dat` for a NON-EC volume (no EC `.vif`) is left
|
||||
/// alone — only EC stubs are swept, so freshly-allocated empty volumes
|
||||
/// survive.
|
||||
#[test]
|
||||
fn test_keeps_empty_dat_for_non_ec_volume() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().join("data0");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dat = format!("{}/7.dat", dir.to_str().unwrap());
|
||||
std::fs::write(&dat, vec![0u8; 8]).unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir.to_str().unwrap(),
|
||||
dir.to_str().unwrap(),
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
std::path::Path::new(&dat).exists(),
|
||||
"a non-EC empty .dat must not be swept",
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression: a lone `.vif` whose `.ecx` is on a sibling disk must not
|
||||
/// make the loader create a phantom `.dat`, nor the sibling-.dat prune
|
||||
/// delete the real shards on the sibling.
|
||||
@@ -514,6 +636,97 @@ mod tests {
|
||||
assert_eq!(total, 2, "real EC shards were deleted (total={})", total);
|
||||
}
|
||||
|
||||
/// A disk holding a few local shards of a healthy distributed EC volume
|
||||
/// plus a leftover empty `.dat` stub: the stub must be swept before EC
|
||||
/// validation can mistake the volume for an interrupted local encode
|
||||
/// (fewer than data_shards local shards) and delete the only copies of
|
||||
/// those shards.
|
||||
#[test]
|
||||
fn test_empty_dat_stub_next_to_ecx_does_not_delete_shards() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let d0 = tmp.path().join("data0");
|
||||
std::fs::create_dir_all(&d0).unwrap();
|
||||
let dir = d0.to_str().unwrap();
|
||||
let coll = "warp-rec";
|
||||
let vid = 87u32;
|
||||
|
||||
write_shard(dir, coll, vid, 0);
|
||||
write_shard(dir, coll, vid, 5);
|
||||
write_index_files(dir, coll, vid, 10, 4);
|
||||
// Zero-byte stub .dat: the phantom left by the pre-fix loader.
|
||||
std::fs::write(d0.join(format!("{}_{}.dat", coll, vid)), b"").unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
!d0.join(format!("{}_{}.dat", coll, vid)).exists(),
|
||||
"empty .dat stub was not swept"
|
||||
);
|
||||
assert_eq!(
|
||||
store.locations[0].ec_shard_count(),
|
||||
2,
|
||||
"EC shards were deleted on the stub's account"
|
||||
);
|
||||
assert_eq!(
|
||||
store.locations[0].volume_ids().len(),
|
||||
0,
|
||||
"stub was loaded as a phantom volume"
|
||||
);
|
||||
}
|
||||
|
||||
/// Same shard-holding disk but the stub has no `.vif` at all, so the
|
||||
/// sweep has no EC evidence and must leave it. The empty `.dat` still
|
||||
/// must not count as an encode source: the shards survive and load as
|
||||
/// a distributed EC volume.
|
||||
#[test]
|
||||
fn test_empty_dat_without_vif_does_not_delete_shards() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let d0 = tmp.path().join("data0");
|
||||
std::fs::create_dir_all(&d0).unwrap();
|
||||
let dir = d0.to_str().unwrap();
|
||||
let coll = "warp-rec";
|
||||
let vid = 88u32;
|
||||
|
||||
write_shard(dir, coll, vid, 1);
|
||||
write_shard(dir, coll, vid, 7);
|
||||
write_index_files(dir, coll, vid, 10, 4);
|
||||
std::fs::remove_file(d0.join(format!("{}_{}.vif", coll, vid))).unwrap();
|
||||
std::fs::write(d0.join(format!("{}_{}.dat", coll, vid)), b"").unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.locations[0].ec_shard_count(),
|
||||
2,
|
||||
"EC shards were deleted on the empty .dat's account"
|
||||
);
|
||||
assert_eq!(
|
||||
store.locations[0].volume_ids().len(),
|
||||
0,
|
||||
"empty .dat was loaded as a phantom volume"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression for the prune credibility gate: when the EC `.vif`
|
||||
/// records no source size (`dat_file_size == 0`), an empty 8-byte
|
||||
/// sibling `.dat` stub must NOT justify deleting partial EC shards.
|
||||
@@ -831,7 +1044,7 @@ mod tests {
|
||||
let (mut store, _tmp) = build_split_disk_store(7003);
|
||||
let vid = VolumeId(7003);
|
||||
|
||||
store.unmount_ec_shard(vid, 1).unwrap();
|
||||
store.unmount_ec_shard(vid, 1, 0).unwrap();
|
||||
assert_eq!(store.find_ec_shard_location(vid, 1), None);
|
||||
// Other shards untouched.
|
||||
assert_eq!(store.find_ec_shard_location(vid, 0), Some(0));
|
||||
@@ -1060,14 +1273,33 @@ mod tests {
|
||||
let collection = "pics";
|
||||
let vid = 122u32;
|
||||
|
||||
// Disk A (sdd): a .dat whose name must be present so index_dat_owners
|
||||
// records this disk as the .dat owner (content doesn't matter).
|
||||
// Disk A (sdd): a .dat whose size must byte-exactly match the EC
|
||||
// source size recorded in the sibling .vif for the prune to treat it
|
||||
// as the committed source.
|
||||
let dat_path = dat_dir.join(format!("{}_{}.dat", collection, vid));
|
||||
std::fs::write(&dat_path, vec![0u8; 1024]).unwrap();
|
||||
|
||||
// Disk B (sdf): partial EC — one shard, plus .ecx / .ecj / .vif.
|
||||
write_shard(ec_dir.to_str().unwrap(), collection, vid, 1);
|
||||
write_index_files(ec_dir.to_str().unwrap(), collection, vid, 10, 4);
|
||||
// Record the encode-time source size in the EC .vif so the prune's
|
||||
// byte-exact credibility gate recognizes the 1024-byte sibling .dat as
|
||||
// the source (a real encoded volume records this).
|
||||
std::fs::write(
|
||||
ec_dir.join(format!("{}_{}.vif", collection, vid)),
|
||||
serde_json::to_string(&VifVolumeInfo {
|
||||
version: 3,
|
||||
dat_file_size: 1024,
|
||||
ec_shard_config: Some(VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
|
||||
@@ -588,6 +588,36 @@ impl Volume {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Build a minimal, unloaded Volume holding only the identity/path fields
|
||||
/// reconcile_compact_state needs. Used by the disk-location load pre-pass to
|
||||
/// recover an interrupted commit before the volume itself is loaded.
|
||||
pub fn new_unloaded(dirname: &str, dir_idx: &str, collection: &str, id: VolumeId) -> Self {
|
||||
Volume {
|
||||
id,
|
||||
dir: dirname.to_string(),
|
||||
dir_idx: dir_idx.to_string(),
|
||||
collection: collection.to_string(),
|
||||
dat_file: None,
|
||||
remote_dat_file: None,
|
||||
nm: None,
|
||||
needle_map_kind: NeedleMapKind::InMemory,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
super_block: SuperBlock::default(),
|
||||
no_write_or_delete: false,
|
||||
no_write_can_delete: false,
|
||||
location_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
last_modified_ts_seconds: 0,
|
||||
last_append_at_ns: 0,
|
||||
last_compact_index_offset: 0,
|
||||
last_compact_revision: 0,
|
||||
is_compacting: false,
|
||||
compaction_byte_per_second: 0,
|
||||
last_io_error: Mutex::new(None),
|
||||
volume_info: PbVolumeInfo::default(),
|
||||
has_remote_file: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the volume is currently being compacted.
|
||||
pub fn is_compacting(&self) -> bool {
|
||||
self.is_compacting
|
||||
@@ -2897,28 +2927,14 @@ impl Volume {
|
||||
self.dat_file = None;
|
||||
self.remote_dat_file = None;
|
||||
|
||||
let cpd_path = self.file_name(".cpd");
|
||||
let cpx_path = self.file_name(".cpx");
|
||||
let dat_path = self.file_name(".dat");
|
||||
let idx_path = self.file_name(".idx");
|
||||
|
||||
// Check that compact files exist
|
||||
if !Path::new(&cpd_path).exists() || !Path::new(&cpx_path).exists() {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"compact files (.cpd/.cpx) not found",
|
||||
)));
|
||||
}
|
||||
|
||||
// Swap files: .cpd → .dat, .cpx → .idx
|
||||
fs::rename(&cpd_path, &dat_path)?;
|
||||
fs::rename(&cpx_path, &idx_path)?;
|
||||
|
||||
// Remove any leveldb/redb index files (rebuilt from .idx on reload)
|
||||
let ldb_path = self.file_name(".ldb");
|
||||
let _ = fs::remove_dir_all(&ldb_path);
|
||||
let rdb_path = self.file_name(".rdb");
|
||||
let _ = fs::remove_file(&rdb_path);
|
||||
// makeup_diff has fsynced the .cpd/.cpx contents. Persist a durable .cpc
|
||||
// commit marker BEFORE the renames so the two-rename swap is atomic
|
||||
// across a crash: a marker on disk means the swap is decided and
|
||||
// reconcile rolls forward; no marker means roll back. Without it, a
|
||||
// crash between the two renames leaves a stale .idx that a later vacuum
|
||||
// compacts to empty.
|
||||
self.write_compact_commit_marker()?;
|
||||
self.apply_compact_swap()?;
|
||||
|
||||
// Reload
|
||||
self.load(true, false, 0, self.version())?;
|
||||
@@ -2926,30 +2942,165 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write and fsync the .cpc marker, then fsync the directory so the marker
|
||||
/// survives a crash before apply_compact_swap.
|
||||
fn write_compact_commit_marker(&self) -> Result<(), VolumeError> {
|
||||
let marker_path = self.file_name(".cpc");
|
||||
let f = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&marker_path)?;
|
||||
f.sync_all()?;
|
||||
drop(f);
|
||||
fsync_dir(&marker_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Perform the durable two-rename compaction commit. Idempotent: run both at
|
||||
/// the tail of commit and by reconcile rolling forward after a crash. It
|
||||
/// requires BOTH .cpd/.cpx to be present, so a stale or duplicate commit
|
||||
/// returns an error without deleting the live .dat/.idx.
|
||||
fn apply_compact_swap(&self) -> Result<(), VolumeError> {
|
||||
// Normal commit: both temp files must be present, or a stale/duplicate
|
||||
// commit could clobber the live .dat/.idx.
|
||||
if !Path::new(&self.file_name(".cpd")).exists()
|
||||
|| !Path::new(&self.file_name(".cpx")).exists()
|
||||
{
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"compact files (.cpd/.cpx) not found",
|
||||
)));
|
||||
}
|
||||
self.finish_compact_swap()
|
||||
}
|
||||
|
||||
/// Renames whichever compaction temp file is still present (.cpd->.dat,
|
||||
/// .cpx->.idx), fsyncs, drops the stale .ldb/.rdb, then clears the .cpc
|
||||
/// marker. Tolerates a partial state: a crash after the .dat rename but
|
||||
/// before the .idx rename leaves only .cpx, which must still be applied --
|
||||
/// not abandoned, which would pair a fresh .dat with a stale .idx. Existence
|
||||
/// is checked robustly so a transient error never silently skips the swap.
|
||||
fn finish_compact_swap(&self) -> Result<(), VolumeError> {
|
||||
let exists = |p: String| match fs::metadata(&p) {
|
||||
Ok(_) => true,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => false,
|
||||
Err(_) => true,
|
||||
};
|
||||
let dat_path = self.file_name(".dat");
|
||||
let idx_path = self.file_name(".idx");
|
||||
let cpd_exists = exists(self.file_name(".cpd"));
|
||||
let cpx_exists = exists(self.file_name(".cpx"));
|
||||
|
||||
if cpd_exists {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = fs::remove_file(&dat_path);
|
||||
}
|
||||
fs::rename(self.file_name(".cpd"), &dat_path)?;
|
||||
}
|
||||
if cpx_exists {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = fs::remove_file(&idx_path);
|
||||
}
|
||||
fs::rename(self.file_name(".cpx"), &idx_path)?;
|
||||
}
|
||||
if cpd_exists || cpx_exists {
|
||||
fsync_dir(&dat_path)?;
|
||||
if self.dir != self.dir_idx {
|
||||
fsync_dir(&idx_path)?;
|
||||
}
|
||||
let _ = fs::remove_dir_all(self.file_name(".ldb"));
|
||||
let _ = fs::remove_file(self.file_name(".rdb"));
|
||||
}
|
||||
|
||||
// Clear the marker last and fsync the dir so a restart does not re-run a
|
||||
// completed swap.
|
||||
let marker_path = self.file_name(".cpc");
|
||||
match fs::remove_file(&marker_path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
fsync_dir(&marker_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recover an interrupted compaction commit on load. When the .cpc marker is
|
||||
/// present the swap was decided, so roll FORWARD by finishing the renames;
|
||||
/// when it is absent any leftover .cpd/.cpx are an abandoned generation, so
|
||||
/// roll BACK by deleting them (and any stale .ldb beside a healthy .idx).
|
||||
pub fn reconcile_compact_state(&self) -> Result<(), VolumeError> {
|
||||
let cpc_path = self.file_name(".cpc");
|
||||
if Path::new(&cpc_path).exists() {
|
||||
// Marker present: the swap was decided. Finish whichever rename is
|
||||
// still pending -- a crash may have completed only the .dat rename,
|
||||
// so the lone remaining .cpx must still be applied, not abandoned.
|
||||
// If neither temp file remains, finish_compact_swap clears the marker.
|
||||
tracing::info!(
|
||||
volume_id = self.id.0,
|
||||
"rolling forward interrupted compaction commit"
|
||||
);
|
||||
return self.finish_compact_swap();
|
||||
}
|
||||
|
||||
// No marker: roll back any orphan compaction temp files.
|
||||
let mut rolled_back = false;
|
||||
for ext in &[".cpd", ".cpx"] {
|
||||
let p = self.file_name(ext);
|
||||
if Path::new(&p).exists() {
|
||||
tracing::info!(
|
||||
volume_id = self.id.0,
|
||||
"rolling back orphan compaction file {}",
|
||||
ext
|
||||
);
|
||||
match fs::remove_file(&p) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
rolled_back = true;
|
||||
}
|
||||
}
|
||||
if rolled_back {
|
||||
let _ = fs::remove_dir_all(self.file_name(".ldb"));
|
||||
let _ = fs::remove_file(self.file_name(".rdb"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clean up leftover compaction files (.cpd, .cpx).
|
||||
pub fn cleanup_compact(&self) -> Result<(), VolumeError> {
|
||||
// Refuse to unlink .cpd/.cpx while a .cpc marker exists: those temp files
|
||||
// are the only inputs reconcile can roll forward to, so removing them
|
||||
// mid-commit would strand a decided swap.
|
||||
if Path::new(&self.file_name(".cpc")).exists() {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!(
|
||||
"volume {}: refusing cleanup while commit marker present",
|
||||
self.id
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
let cpd_path = self.file_name(".cpd");
|
||||
let cpx_path = self.file_name(".cpx");
|
||||
let cpldb_path = self.file_name(".cpldb");
|
||||
let cpc_path = self.file_name(".cpc");
|
||||
|
||||
let e1 = fs::remove_file(&cpd_path);
|
||||
let e2 = fs::remove_file(&cpx_path);
|
||||
let e3 = fs::remove_dir_all(&cpldb_path);
|
||||
let e4 = fs::remove_file(&cpc_path);
|
||||
|
||||
// Ignore NotFound errors
|
||||
if let Err(e) = e1 {
|
||||
if e.kind() != io::ErrorKind::NotFound {
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
if let Err(e) = e2 {
|
||||
if e.kind() != io::ErrorKind::NotFound {
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
if let Err(e) = e3 {
|
||||
if e.kind() != io::ErrorKind::NotFound {
|
||||
return Err(e.into());
|
||||
for e in [e1, e2, e3, e4] {
|
||||
if let Err(e) = e {
|
||||
if e.kind() != io::ErrorKind::NotFound {
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3263,9 +3414,31 @@ fn get_append_at_ns(last: u64) -> u64 {
|
||||
|
||||
/// Remove all files associated with a volume.
|
||||
/// .dat/.idx removals log at info level so destructive calls are traceable.
|
||||
/// fsync the parent directory of `path` so a rename/create/unlink inside it is
|
||||
/// durable, propagating a sync failure so the commit path can abort rather than
|
||||
/// proceed with an undurable rename or marker. A path with no openable parent is
|
||||
/// tolerated; directory fsync is unsupported on Windows, so it is a no-op there
|
||||
/// (matching the Go fsyncDir helper, which ignores that error).
|
||||
pub(crate) fn fsync_dir(path: &str) -> io::Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
if let Some(parent) = Path::new(path).parent() {
|
||||
if let Ok(d) = File::open(parent) {
|
||||
return d.sync_all();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remove_volume_files(base: &str, keep_vif: bool) {
|
||||
for ext in &[
|
||||
".dat", ".idx", ".vif", ".sdx", ".cpd", ".cpx", ".note", ".rdb",
|
||||
".dat", ".idx", ".vif", ".sdx", ".cpd", ".cpx", ".cpc", ".note", ".rdb",
|
||||
] {
|
||||
if *ext == ".vif" && keep_vif {
|
||||
continue;
|
||||
@@ -4814,4 +4987,145 @@ mod tests {
|
||||
".ecx is an EC sidecar, never touched here"
|
||||
);
|
||||
}
|
||||
|
||||
/// A crash after the .idx/.dat were consumed but before the .cpx->.idx
|
||||
/// rename committed leaves only .cpd + .cpx + .cpc. reconcile_compact_state
|
||||
/// must roll the swap FORWARD and produce a loadable, writable volume
|
||||
/// holding the compacted needle count.
|
||||
#[test]
|
||||
fn test_reconcile_roll_forward_marker_only() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=6u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: format!("data-{}", i).into_bytes(),
|
||||
data_size: format!("data-{}", i).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
for id in [2u64, 5u64] {
|
||||
let mut del = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
..Needle::default()
|
||||
};
|
||||
v.delete_needle(&mut del).unwrap();
|
||||
}
|
||||
let expected_live = v.file_count() - v.deleted_count();
|
||||
|
||||
v.compact_by_index(0, 0, |_| true).unwrap();
|
||||
v.close();
|
||||
|
||||
let cpd = v.file_name(".cpd");
|
||||
let cpx = v.file_name(".cpx");
|
||||
let cpc = v.file_name(".cpc");
|
||||
let dat = v.file_name(".dat");
|
||||
let idx = v.file_name(".idx");
|
||||
assert!(Path::new(&cpd).exists());
|
||||
assert!(Path::new(&cpx).exists());
|
||||
|
||||
// Simulate the mid-commit crash: original .dat/.idx are gone and only
|
||||
// the compacted temp files plus the commit marker survive.
|
||||
fs::remove_file(&dat).unwrap();
|
||||
fs::remove_file(&idx).unwrap();
|
||||
let _ = fs::remove_dir_all(v.file_name(".ldb"));
|
||||
fs::write(&cpc, b"").unwrap();
|
||||
|
||||
v.reconcile_compact_state().unwrap();
|
||||
|
||||
assert!(!Path::new(&cpd).exists(), ".cpd consumed by roll-forward");
|
||||
assert!(!Path::new(&cpx).exists(), ".cpx consumed by roll-forward");
|
||||
assert!(!Path::new(&cpc).exists(), ".cpc cleared after swap");
|
||||
assert!(Path::new(&dat).exists(), ".dat restored by roll-forward");
|
||||
assert!(Path::new(&idx).exists(), ".idx restored by roll-forward");
|
||||
|
||||
// The rolled-forward files must load as a writable volume with the
|
||||
// compacted needle count.
|
||||
let reloaded = make_test_volume(dir);
|
||||
assert!(!reloaded.is_read_only(), "rolled-forward volume read-only");
|
||||
assert_eq!(
|
||||
reloaded.file_count(),
|
||||
expected_live,
|
||||
"rolled-forward volume needle count"
|
||||
);
|
||||
}
|
||||
|
||||
/// With no .cpc marker, leftover .cpd/.cpx are an abandoned generation;
|
||||
/// reconcile must roll BACK by deleting them and leave the live .dat/.idx.
|
||||
#[test]
|
||||
fn test_reconcile_roll_back_no_marker() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=4u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: format!("data-{}", i).into_bytes(),
|
||||
data_size: format!("data-{}", i).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.compact_by_index(0, 0, |_| true).unwrap();
|
||||
|
||||
let cpd = v.file_name(".cpd");
|
||||
let cpx = v.file_name(".cpx");
|
||||
let dat = v.file_name(".dat");
|
||||
let idx = v.file_name(".idx");
|
||||
assert!(Path::new(&cpd).exists());
|
||||
assert!(Path::new(&cpx).exists());
|
||||
// No .cpc marker exists.
|
||||
|
||||
v.reconcile_compact_state().unwrap();
|
||||
|
||||
assert!(!Path::new(&cpd).exists(), ".cpd rolled back");
|
||||
assert!(!Path::new(&cpx).exists(), ".cpx rolled back");
|
||||
assert!(Path::new(&dat).exists(), "live .dat kept");
|
||||
assert!(Path::new(&idx).exists(), "live .idx kept");
|
||||
}
|
||||
|
||||
/// apply_compact_swap must abort without touching the live .dat/.idx when
|
||||
/// the .cpd/.cpx temp files are missing (a stale or duplicate commit).
|
||||
#[test]
|
||||
fn test_apply_compact_swap_missing_temp_files_preserves_live() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=3u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: format!("data-{}", i).into_bytes(),
|
||||
data_size: format!("data-{}", i).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let dat = v.file_name(".dat");
|
||||
let idx = v.file_name(".idx");
|
||||
let dat_len_before = fs::metadata(&dat).unwrap().len();
|
||||
|
||||
// No .cpd/.cpx present: the swap must refuse.
|
||||
assert!(
|
||||
v.apply_compact_swap().is_err(),
|
||||
"swap should error when .cpd/.cpx are missing"
|
||||
);
|
||||
assert!(Path::new(&dat).exists(), "live .dat preserved");
|
||||
assert!(Path::new(&idx).exists(), "live .idx preserved");
|
||||
assert_eq!(
|
||||
fs::metadata(&dat).unwrap().len(),
|
||||
dat_len_before,
|
||||
"live .dat unchanged"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
# S3 Checksum Integration Tests
|
||||
# Covers flexible-checksum behavior on presigned URL uploads (issue #9075).
|
||||
# Covers flexible-checksum behavior on presigned uploads and multipart copy.
|
||||
|
||||
.PHONY: help build-weed check-deps start-server stop-server test test-with-server logs clean health-check
|
||||
|
||||
@@ -8,7 +8,7 @@ S3_PORT := 8333
|
||||
ACCESS_KEY ?= some_access_key1
|
||||
SECRET_KEY ?= some_secret_key1
|
||||
TEST_TIMEOUT := 10m
|
||||
TEST_PATTERN ?= TestPresignedPut
|
||||
TEST_PATTERN ?= .
|
||||
SERVER_DIR := ./test-volume-data/server-data
|
||||
|
||||
help:
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package checksum_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMultipartCopyPreservesChecksum(t *testing.T) {
|
||||
// aws-sdk-go-v2 sends flexible checksums as unsigned streaming trailers, which
|
||||
// it refuses over plain HTTP, so front the HTTP endpoint with a TLS proxy.
|
||||
target, err := url.Parse(defaultConfig.Endpoint)
|
||||
require.NoError(t, err)
|
||||
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
server := httptest.NewTLSServer(proxy)
|
||||
defer server.Close()
|
||||
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion(defaultConfig.Region),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
||||
defaultConfig.AccessKey, defaultConfig.SecretKey, "")),
|
||||
config.WithHTTPClient(server.Client()),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(server.URL)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
|
||||
bucket := uniqueBucket()
|
||||
createBucket(t, client, bucket)
|
||||
defer cleanupBucket(t, client, bucket)
|
||||
|
||||
cases := []struct {
|
||||
algorithm types.ChecksumAlgorithm
|
||||
srcSum func(*s3.PutObjectOutput) *string
|
||||
partSum func(*types.CopyPartResult) *string
|
||||
setPart func(*types.CompletedPart, *string)
|
||||
}{
|
||||
{
|
||||
algorithm: types.ChecksumAlgorithmCrc32,
|
||||
srcSum: func(o *s3.PutObjectOutput) *string { return o.ChecksumCRC32 },
|
||||
partSum: func(r *types.CopyPartResult) *string { return r.ChecksumCRC32 },
|
||||
setPart: func(p *types.CompletedPart, v *string) { p.ChecksumCRC32 = v },
|
||||
},
|
||||
{
|
||||
algorithm: types.ChecksumAlgorithmCrc32c,
|
||||
srcSum: func(o *s3.PutObjectOutput) *string { return o.ChecksumCRC32C },
|
||||
partSum: func(r *types.CopyPartResult) *string { return r.ChecksumCRC32C },
|
||||
setPart: func(p *types.CompletedPart, v *string) { p.ChecksumCRC32C = v },
|
||||
},
|
||||
{
|
||||
algorithm: types.ChecksumAlgorithmCrc64nvme,
|
||||
srcSum: func(o *s3.PutObjectOutput) *string { return o.ChecksumCRC64NVME },
|
||||
partSum: func(r *types.CopyPartResult) *string { return r.ChecksumCRC64NVME },
|
||||
setPart: func(p *types.CompletedPart, v *string) { p.ChecksumCRC64NVME = v },
|
||||
},
|
||||
{
|
||||
algorithm: types.ChecksumAlgorithmSha1,
|
||||
srcSum: func(o *s3.PutObjectOutput) *string { return o.ChecksumSHA1 },
|
||||
partSum: func(r *types.CopyPartResult) *string { return r.ChecksumSHA1 },
|
||||
setPart: func(p *types.CompletedPart, v *string) { p.ChecksumSHA1 = v },
|
||||
},
|
||||
{
|
||||
algorithm: types.ChecksumAlgorithmSha256,
|
||||
srcSum: func(o *s3.PutObjectOutput) *string { return o.ChecksumSHA256 },
|
||||
partSum: func(r *types.CopyPartResult) *string { return r.ChecksumSHA256 },
|
||||
setPart: func(p *types.CompletedPart, v *string) { p.ChecksumSHA256 = v },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(string(tc.algorithm), func(t *testing.T) {
|
||||
sourceKey := "source-" + string(tc.algorithm)
|
||||
source, err := client.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(sourceKey),
|
||||
Body: bytes.NewBufferString("trailing checksum"),
|
||||
ChecksumAlgorithm: tc.algorithm,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
key := "multipart-copy-" + string(tc.algorithm)
|
||||
create, err := client.CreateMultipartUpload(context.Background(), &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
ChecksumAlgorithm: tc.algorithm,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
part, err := client.UploadPartCopy(context.Background(), &s3.UploadPartCopyInput{
|
||||
Bucket: aws.String(bucket),
|
||||
CopySource: aws.String(fmt.Sprintf("%s/%s", bucket, sourceKey)),
|
||||
Key: aws.String(key),
|
||||
UploadId: create.UploadId,
|
||||
PartNumber: aws.Int32(1),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, aws.ToString(tc.srcSum(source)), aws.ToString(tc.partSum(part.CopyPartResult)))
|
||||
|
||||
completed := types.CompletedPart{ETag: part.CopyPartResult.ETag, PartNumber: aws.Int32(1)}
|
||||
tc.setPart(&completed, tc.partSum(part.CopyPartResult))
|
||||
_, err = client.CompleteMultipartUpload(context.Background(), &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: create.UploadId,
|
||||
MultipartUpload: &types.CompletedMultipartUpload{Parts: []types.CompletedPart{completed}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ func main() {
|
||||
Name: "newbucket",
|
||||
Versioning: false,
|
||||
},
|
||||
MaxBackoffDelay: aws.Int(int(time.Second * 5)),
|
||||
MaxBackoffDelay: aws.Int(int((5 * time.Second).Milliseconds())),
|
||||
MaxRetryAttempts: aws.Int(1),
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func MyAwsConfig(cfg MyConfig) (*aws.Config, error) {
|
||||
config.WithEndpointResolverWithOptions(customResolver),
|
||||
config.WithRetryer(func() aws.Retryer {
|
||||
r := retry.AddWithMaxAttempts(retry.NewStandard(), *cfg.MaxRetryAttempts)
|
||||
return retry.AddWithMaxBackoffDelay(r, time.Duration(*cfg.MaxBackoffDelay*1000*1000))
|
||||
return retry.AddWithMaxBackoffDelay(r, time.Duration(*cfg.MaxBackoffDelay)*time.Millisecond)
|
||||
}))
|
||||
return &awsCfg, err
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// TestEcLifecycleAcrossMultipleDisks drives encode, mount, read, drop-dat,
|
||||
@@ -482,7 +484,6 @@ func plantPartialEc(t testing.TB, dir, collection string, volumeID uint32, shard
|
||||
}{
|
||||
{".ecx", []byte("dummy ecx")},
|
||||
{".ecj", nil},
|
||||
{".vif", nil},
|
||||
} {
|
||||
p := filepath.Join(dir, sideFileName(collection, volumeID, side.ext))
|
||||
f, err := os.Create(p)
|
||||
@@ -497,6 +498,19 @@ func plantPartialEc(t testing.TB, dir, collection string, volumeID uint32, shard
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
// Record the encode-time source size so the prune's byte-exact gate
|
||||
// recognizes the sibling .dat as the source, as a real encoded volume does.
|
||||
vifPath := filepath.Join(dir, sideFileName(collection, volumeID, ".vif"))
|
||||
if err := volume_info.SaveVolumeInfo(vifPath, &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(needle.Version3),
|
||||
DatFileSize: datFileSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(erasure_coding.DataShardsCount),
|
||||
ParityShards: uint32(erasure_coding.ParityShardsCount),
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("save planted .vif: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// mirrors calculateExpectedShardSize in weed/storage/disk_location_ec.go
|
||||
|
||||
@@ -159,15 +159,22 @@ func TestVolumeEcShardsInfoReturnsAllShardsAcrossDisks(t *testing.T) {
|
||||
// End-to-end assertion via the same helper the worker uses to gate
|
||||
// source-volume deletion (weed/worker/tasks/erasure_coding/ec_task.go
|
||||
// verifyEcShardsBeforeDelete). The union across destinations is what
|
||||
// RequireFullShardSet measures; with one destination that holds every
|
||||
// shard, the union must cover dataShards + parityShards.
|
||||
// RequireRecoverableShardSet measures; with one destination that holds
|
||||
// every shard, the union must cover dataShards + parityShards without
|
||||
// being reported as degraded.
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
servers := []string{clusterHarness.VolumeServerAddress()}
|
||||
union, perServer := erasure_coding.VerifyShardsAcrossServers(ctx, volumeID, servers, dialOption)
|
||||
if err := erasure_coding.RequireFullShardSet(volumeID, union, erasure_coding.TotalShardsCount); err != nil {
|
||||
degraded, err := erasure_coding.RequireRecoverableShardSet(
|
||||
volumeID, union, erasure_coding.DataShardsCount, erasure_coding.TotalShardsCount)
|
||||
if err != nil {
|
||||
t.Fatalf("verifyEcShardsBeforeDelete-equivalent gate failed: %v\nper-server inventory: %s\nper-disk layout: %v",
|
||||
err, erasure_coding.SummarizeShardInventory(perServer), postReconcileLayout)
|
||||
}
|
||||
if degraded {
|
||||
t.Fatalf("verifyEcShardsBeforeDelete-equivalent gate reported a degraded shard set\nper-server inventory: %s\nper-disk layout: %v",
|
||||
erasure_coding.SummarizeShardInventory(perServer), postReconcileLayout)
|
||||
}
|
||||
if got, want := union.Count(), erasure_coding.TotalShardsCount; got != want {
|
||||
t.Fatalf("VerifyShardsAcrossServers union covered %d/%d shards (per-server=%s, layout=%v)",
|
||||
got, want, erasure_coding.SummarizeShardInventory(perServer), postReconcileLayout)
|
||||
|
||||
@@ -37,6 +37,13 @@ type AdminData struct {
|
||||
// EC shard totals for dashboard
|
||||
TotalEcVolumes int `json:"total_ec_volumes"` // Total number of EC volumes across all servers
|
||||
TotalEcShards int `json:"total_ec_shards"` // Total number of EC shards across all servers
|
||||
|
||||
// TotalMountClients is the number of connected FUSE/VFS mount clients across filers.
|
||||
TotalMountClients int `json:"total_mount_clients"`
|
||||
|
||||
// Trends holds at-a-glance sparklines built from the admin's own recent
|
||||
// cluster snapshots (no Prometheus required).
|
||||
Trends DashboardTrends `json:"trends"`
|
||||
}
|
||||
|
||||
// Object Store Users management structures
|
||||
@@ -182,6 +189,12 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
}
|
||||
totalEcVolumes = len(ecVolumeSet)
|
||||
|
||||
// Count connected FUSE/VFS mount clients (best-effort; don't fail the dashboard)
|
||||
totalMountClients := 0
|
||||
if mountData, mountErr := s.GetMountClients(); mountErr == nil {
|
||||
totalMountClients = mountData.TotalMountClients
|
||||
}
|
||||
|
||||
// Prepare admin data
|
||||
adminData := AdminData{
|
||||
Username: username,
|
||||
@@ -198,6 +211,8 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
LastUpdated: topology.UpdatedAt,
|
||||
TotalEcVolumes: totalEcVolumes,
|
||||
TotalEcShards: totalEcShards,
|
||||
TotalMountClients: totalMountClients,
|
||||
Trends: s.GetDashboardTrends(),
|
||||
}
|
||||
|
||||
return adminData, nil
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
|
||||
@@ -89,6 +90,12 @@ type AdminServer struct {
|
||||
lastCacheUpdate time.Time
|
||||
cachedTopology *ClusterTopology
|
||||
|
||||
// dashSamples is a bounded in-memory ring of recent cluster snapshots that
|
||||
// powers the dashboard's at-a-glance sparklines (see dashboard_metrics.go),
|
||||
// filled on the maintenance-metrics ticker. No Prometheus dependency.
|
||||
dashSamples []dashSample
|
||||
dashSamplesMu sync.Mutex
|
||||
|
||||
// Filer discovery and caching
|
||||
cachedFilers []string
|
||||
lastFilerUpdate time.Time
|
||||
@@ -375,12 +382,16 @@ func (s *AdminServer) publishMaintenanceMetrics(ctx context.Context) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Seed one sample so the dashboard has something to draw before the first tick.
|
||||
s.recordDashboardSample()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.collectMaintenanceMetrics()
|
||||
s.recordDashboardSample()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -706,7 +706,7 @@ func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
|
||||
MinVolumeAgeHours: int32(vacuumConfig.MinVolumeAgeSeconds / 3600), // Convert seconds to hours
|
||||
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/base"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
)
|
||||
|
||||
// TomlConfig is the subset of viper used to read admin.toml values.
|
||||
type TomlConfig interface {
|
||||
IsSet(key string) bool
|
||||
GetBool(key string) bool
|
||||
GetInt(key string) int
|
||||
GetFloat64(key string) float64
|
||||
GetString(key string) string
|
||||
GetStringSlice(key string) []string
|
||||
}
|
||||
|
||||
// ApplyMaintenanceConfigFromToml writes maintenance task settings declared in
|
||||
// admin.toml through to the persisted task configs, so they survive data
|
||||
// directory loss and override admin UI edits on restart. Absent keys keep
|
||||
// their persisted values.
|
||||
func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error {
|
||||
vacuumConf := vacuum.LoadConfigFromPersistence(cp)
|
||||
vacuumChanged := applyBaseConfigFromToml(v, "maintenance.vacuum.", &vacuumConf.BaseConfig)
|
||||
if k := "maintenance.vacuum.garbage_threshold"; v.IsSet(k) {
|
||||
vacuumConf.GarbageThreshold = v.GetFloat64(k)
|
||||
vacuumChanged = true
|
||||
}
|
||||
if k := "maintenance.vacuum.min_volume_age_seconds"; v.IsSet(k) {
|
||||
vacuumConf.MinVolumeAgeSeconds = v.GetInt(k)
|
||||
vacuumChanged = true
|
||||
}
|
||||
|
||||
balanceConf := balance.LoadConfigFromPersistence(cp)
|
||||
balanceChanged := applyBaseConfigFromToml(v, "maintenance.balance.", &balanceConf.BaseConfig)
|
||||
if k := "maintenance.balance.imbalance_threshold"; v.IsSet(k) {
|
||||
balanceConf.ImbalanceThreshold = v.GetFloat64(k)
|
||||
balanceChanged = true
|
||||
}
|
||||
if k := "maintenance.balance.min_server_count"; v.IsSet(k) {
|
||||
balanceConf.MinServerCount = v.GetInt(k)
|
||||
balanceChanged = true
|
||||
}
|
||||
|
||||
ecConf := erasure_coding.LoadConfigFromPersistence(cp)
|
||||
ecChanged := applyBaseConfigFromToml(v, "maintenance.erasure_coding.", &ecConf.BaseConfig)
|
||||
if k := "maintenance.erasure_coding.fullness_ratio"; v.IsSet(k) {
|
||||
ecConf.FullnessRatio = v.GetFloat64(k)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.quiet_for_seconds"; v.IsSet(k) {
|
||||
ecConf.QuietForSeconds = v.GetInt(k)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.min_size_mb"; v.IsSet(k) {
|
||||
ecConf.MinSizeMB = v.GetInt(k)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.collection_filter"; v.IsSet(k) {
|
||||
ecConf.CollectionFilter = v.GetString(k)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.preferred_tags"; v.IsSet(k) {
|
||||
// viper does not split comma-separated values from env vars
|
||||
var tags []string
|
||||
for _, tag := range v.GetStringSlice(k) {
|
||||
tags = append(tags, strings.Split(tag, ",")...)
|
||||
}
|
||||
ecConf.PreferredTags = util.NormalizeTagList(tags)
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.replica_placement"; v.IsSet(k) {
|
||||
ecConf.ReplicaPlacement = v.GetString(k)
|
||||
ecChanged = true
|
||||
}
|
||||
|
||||
if !vacuumChanged && !balanceChanged && !ecChanged {
|
||||
return nil
|
||||
}
|
||||
if !cp.IsConfigured() {
|
||||
return fmt.Errorf("admin.toml maintenance settings require -dataDir to persist")
|
||||
}
|
||||
|
||||
if vacuumChanged {
|
||||
if err := cp.SaveVacuumTaskPolicy(vacuumConf.ToTaskPolicy()); err != nil {
|
||||
return fmt.Errorf("save vacuum task config: %w", err)
|
||||
}
|
||||
glog.V(0).Infof("Applied [maintenance.vacuum] settings from admin.toml")
|
||||
}
|
||||
if balanceChanged {
|
||||
if err := cp.SaveBalanceTaskPolicy(balanceConf.ToTaskPolicy()); err != nil {
|
||||
return fmt.Errorf("save balance task config: %w", err)
|
||||
}
|
||||
glog.V(0).Infof("Applied [maintenance.balance] settings from admin.toml")
|
||||
}
|
||||
if ecChanged {
|
||||
if err := cp.SaveErasureCodingTaskPolicy(ecConf.ToTaskPolicy()); err != nil {
|
||||
return fmt.Errorf("save erasure coding task config: %w", err)
|
||||
}
|
||||
glog.V(0).Infof("Applied [maintenance.erasure_coding] settings from admin.toml")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyBaseConfigFromToml(v TomlConfig, prefix string, c *base.BaseConfig) bool {
|
||||
changed := false
|
||||
if k := prefix + "enabled"; v.IsSet(k) {
|
||||
c.Enabled = v.GetBool(k)
|
||||
changed = true
|
||||
}
|
||||
if k := prefix + "scan_interval_seconds"; v.IsSet(k) {
|
||||
c.ScanIntervalSeconds = v.GetInt(k)
|
||||
changed = true
|
||||
}
|
||||
if k := prefix + "max_concurrent"; v.IsSet(k) {
|
||||
c.MaxConcurrent = v.GetInt(k)
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func tomlConfig(t *testing.T, content string) *viper.Viper {
|
||||
t.Helper()
|
||||
v := viper.New()
|
||||
v.SetConfigType("toml")
|
||||
if err := v.ReadConfig(strings.NewReader(content)); err != nil {
|
||||
t.Fatalf("read toml: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestApplyMaintenanceConfigFromToml(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
// simulate an earlier UI edit
|
||||
saved := vacuum.NewDefaultConfig()
|
||||
saved.MaxConcurrent = 5
|
||||
saved.GarbageThreshold = 0.5
|
||||
if err := cp.SaveVacuumTaskPolicy(saved.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save vacuum policy: %v", err)
|
||||
}
|
||||
|
||||
balanceBefore := balance.LoadConfigFromPersistence(cp)
|
||||
|
||||
v := tomlConfig(t, `
|
||||
[maintenance.vacuum]
|
||||
garbage_threshold = 0.03
|
||||
min_volume_age_seconds = 1800
|
||||
|
||||
[maintenance.erasure_coding]
|
||||
enabled = false
|
||||
fullness_ratio = 0.8
|
||||
preferred_tags = "Fast, ssd"
|
||||
`)
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(v); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
|
||||
vacuumConf := vacuum.LoadConfigFromPersistence(cp)
|
||||
if vacuumConf.GarbageThreshold != 0.03 {
|
||||
t.Errorf("garbage threshold = %v, want 0.03", vacuumConf.GarbageThreshold)
|
||||
}
|
||||
// sub-hour values round up to a whole hour instead of truncating to 0
|
||||
if vacuumConf.MinVolumeAgeSeconds != 3600 {
|
||||
t.Errorf("min volume age = %v, want 3600", vacuumConf.MinVolumeAgeSeconds)
|
||||
}
|
||||
if vacuumConf.MaxConcurrent != 5 {
|
||||
t.Errorf("max concurrent = %v, want UI-saved 5 preserved", vacuumConf.MaxConcurrent)
|
||||
}
|
||||
|
||||
ecConf := erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ecConf.Enabled {
|
||||
t.Errorf("ec enabled = true, want false")
|
||||
}
|
||||
if ecConf.FullnessRatio != 0.8 {
|
||||
t.Errorf("fullness ratio = %v, want 0.8", ecConf.FullnessRatio)
|
||||
}
|
||||
if !reflect.DeepEqual(ecConf.PreferredTags, []string{"fast", "ssd"}) {
|
||||
t.Errorf("preferred tags = %v, want [fast ssd]", ecConf.PreferredTags)
|
||||
}
|
||||
if ecConf.QuietForSeconds != 3600 {
|
||||
t.Errorf("quiet for = %v, want default 3600 preserved", ecConf.QuietForSeconds)
|
||||
}
|
||||
|
||||
// balance section absent: nothing written
|
||||
if _, err := os.Stat(filepath.Join(dir, ConfigSubdir, BalanceTaskConfigFile)); !os.IsNotExist(err) {
|
||||
t.Errorf("balance config written without [maintenance.balance] section")
|
||||
}
|
||||
if got := balance.LoadConfigFromPersistence(cp); !reflect.DeepEqual(got, balanceBefore) {
|
||||
t.Errorf("balance config changed without [maintenance.balance] section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMaintenanceConfigFromTomlNoKeys(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(viper.New()); err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ConfigSubdir)); !os.IsNotExist(err) {
|
||||
t.Errorf("conf dir created without any maintenance keys set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMaintenanceConfigFromTomlRequiresDataDir(t *testing.T) {
|
||||
cp := NewConfigPersistence("")
|
||||
v := tomlConfig(t, `
|
||||
[maintenance.vacuum]
|
||||
garbage_threshold = 0.03
|
||||
`)
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(v); err == nil {
|
||||
t.Errorf("expected error when maintenance keys are set without a data dir")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// dashMaxSamples bounds the in-memory trend ring buffer. At the 15s sample
|
||||
// cadence (piggy-backed on publishMaintenanceMetrics) this is ~15 minutes.
|
||||
const dashMaxSamples = 60
|
||||
|
||||
// dashSample is one point-in-time snapshot of a few headline cluster numbers,
|
||||
// derived from data the admin already holds (cluster topology + the in-process
|
||||
// maintenance queue) — no Prometheus scrape required.
|
||||
type dashSample struct {
|
||||
t time.Time
|
||||
volumes float64
|
||||
ecShards float64
|
||||
diskUsed float64
|
||||
files float64
|
||||
tasks float64 // pending/assigned/in-progress maintenance tasks
|
||||
workers float64
|
||||
}
|
||||
|
||||
// DashboardTrends carries inline-SVG sparklines of recent cluster history,
|
||||
// keyed to the dashboard's existing summary cards so each card shows a value
|
||||
// plus its trend (rather than a separate, duplicate row). Maintenance metrics
|
||||
// that have no existing card carry their current value too, and fill the
|
||||
// previously-empty columns of the EC row.
|
||||
type DashboardTrends struct {
|
||||
Samples int `json:"samples"`
|
||||
|
||||
// Sparklines (raw <svg>) for the existing summary cards.
|
||||
Volumes string `json:"-"`
|
||||
Files string `json:"-"`
|
||||
DiskUsed string `json:"-"`
|
||||
EcShards string `json:"-"`
|
||||
|
||||
// Maintenance cards: value + sparkline.
|
||||
Tasks string `json:"-"`
|
||||
TasksValue string `json:"tasks"`
|
||||
Workers string `json:"-"`
|
||||
WorkersValue string `json:"workers"`
|
||||
}
|
||||
|
||||
// recordDashboardSample snapshots headline cluster numbers into the ring
|
||||
// buffer. Cheap: topology is already cached, and the maintenance stats are
|
||||
// in-memory. Called on the existing maintenance-metrics ticker.
|
||||
func (s *AdminServer) recordDashboardSample() {
|
||||
topology, err := s.GetClusterTopology()
|
||||
if err != nil || topology == nil {
|
||||
return
|
||||
}
|
||||
ecShards := 0
|
||||
for _, vs := range topology.VolumeServers {
|
||||
ecShards += vs.EcShards
|
||||
}
|
||||
sample := dashSample{
|
||||
t: time.Now(),
|
||||
volumes: float64(topology.TotalVolumes),
|
||||
ecShards: float64(ecShards),
|
||||
diskUsed: float64(topology.TotalSize),
|
||||
files: float64(topology.TotalFiles),
|
||||
}
|
||||
if s.maintenanceManager != nil {
|
||||
if stats := s.maintenanceManager.GetStats(); stats != nil {
|
||||
active := 0
|
||||
for status, n := range stats.TasksByStatus {
|
||||
switch string(status) {
|
||||
case "pending", "assigned", "in_progress":
|
||||
active += n
|
||||
}
|
||||
}
|
||||
sample.tasks = float64(active)
|
||||
sample.workers = float64(stats.ActiveWorkers)
|
||||
}
|
||||
}
|
||||
|
||||
s.dashSamplesMu.Lock()
|
||||
s.dashSamples = append(s.dashSamples, sample)
|
||||
if len(s.dashSamples) > dashMaxSamples {
|
||||
s.dashSamples = s.dashSamples[len(s.dashSamples)-dashMaxSamples:]
|
||||
}
|
||||
s.dashSamplesMu.Unlock()
|
||||
}
|
||||
|
||||
// GetDashboardTrends builds the trend cards from the current ring buffer.
|
||||
func (s *AdminServer) GetDashboardTrends() DashboardTrends {
|
||||
s.dashSamplesMu.Lock()
|
||||
samples := make([]dashSample, len(s.dashSamples))
|
||||
copy(samples, s.dashSamples)
|
||||
s.dashSamplesMu.Unlock()
|
||||
|
||||
series := func(pick func(dashSample) float64) []float64 {
|
||||
out := make([]float64, len(samples))
|
||||
for i, smp := range samples {
|
||||
out[i] = pick(smp)
|
||||
}
|
||||
return out
|
||||
}
|
||||
tasks := series(func(s dashSample) float64 { return s.tasks })
|
||||
workers := series(func(s dashSample) float64 { return s.workers })
|
||||
|
||||
// Sparkline colors match the existing cards' border colors.
|
||||
return DashboardTrends{
|
||||
Samples: len(samples),
|
||||
Volumes: sparklineSVG(series(func(s dashSample) float64 { return s.volumes }), "#1cc88a"), // success
|
||||
Files: sparklineSVG(series(func(s dashSample) float64 { return s.files }), "#36b9cc"), // info
|
||||
DiskUsed: sparklineSVG(series(func(s dashSample) float64 { return s.diskUsed }), "#f6c23e"), // warning
|
||||
EcShards: sparklineSVG(series(func(s dashSample) float64 { return s.ecShards }), "#5a5c69"), // dark
|
||||
Tasks: sparklineSVG(tasks, "#36b9cc"),
|
||||
TasksValue: trendCount(last(tasks)),
|
||||
Workers: sparklineSVG(workers, "#4e73df"),
|
||||
WorkersValue: trendCount(last(workers)),
|
||||
}
|
||||
}
|
||||
|
||||
func last(v []float64) float64 {
|
||||
if len(v) == 0 {
|
||||
return 0
|
||||
}
|
||||
return v[len(v)-1]
|
||||
}
|
||||
|
||||
// sparklineSVG renders a fixed-viewBox, width-responsive inline SVG line of the
|
||||
// given points. Self-contained (no JS/chart lib); safe to inline in the page.
|
||||
func sparklineSVG(pts []float64, color string) string {
|
||||
const w, h = 240.0, 48.0
|
||||
if len(pts) < 2 {
|
||||
// Not enough history yet — draw a flat baseline so the card isn't empty.
|
||||
return fmt.Sprintf(`<svg viewBox="0 0 %g %g" preserveAspectRatio="none" style="width:100%%;height:48px"><line x1="0" y1="%g" x2="%g" y2="%g" stroke="%s" stroke-width="2" opacity="0.4"/></svg>`, w, h, h/2, w, h/2, color)
|
||||
}
|
||||
minV, maxV := pts[0], pts[0]
|
||||
for _, v := range pts {
|
||||
if v < minV {
|
||||
minV = v
|
||||
}
|
||||
if v > maxV {
|
||||
maxV = v
|
||||
}
|
||||
}
|
||||
span := maxV - minV
|
||||
if span == 0 {
|
||||
span = 1
|
||||
}
|
||||
dx := w / float64(len(pts)-1)
|
||||
var line strings.Builder
|
||||
for i, v := range pts {
|
||||
x := float64(i) * dx
|
||||
y := h - 3 - (v-minV)/span*(h-6) // 3px padding top/bottom; SVG y grows down
|
||||
if i == 0 {
|
||||
fmt.Fprintf(&line, "M%.1f %.1f", x, y)
|
||||
} else {
|
||||
fmt.Fprintf(&line, " L%.1f %.1f", x, y)
|
||||
}
|
||||
}
|
||||
// Area path closes back along the baseline for a subtle fill.
|
||||
area := fmt.Sprintf("%s L%.1f %.1f L0 %.1f Z", line.String(), w, h, h)
|
||||
return fmt.Sprintf(`<svg viewBox="0 0 %g %g" preserveAspectRatio="none" style="width:100%%;height:48px"><path d="%s" fill="%s" opacity="0.12"/><path d="%s" fill="none" stroke="%s" stroke-width="2"/></svg>`,
|
||||
w, h, area, color, line.String(), color)
|
||||
}
|
||||
|
||||
// trendCount formats a count with thousands separators.
|
||||
func trendCount(v float64) string {
|
||||
n := int64(v)
|
||||
s := fmt.Sprintf("%d", n)
|
||||
if n < 0 {
|
||||
return s
|
||||
}
|
||||
var out []byte
|
||||
for i, c := range []byte(s) {
|
||||
if i > 0 && (len(s)-i)%3 == 0 {
|
||||
out = append(out, ',')
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// mountClientTypes are the metadata-subscriber client types that represent a
|
||||
// FUSE/VFS mount: the Go `weed mount` ("mount") and the Rust VFS ("sw-vfs").
|
||||
var mountClientTypes = []string{"mount", "sw-vfs"}
|
||||
|
||||
// mountClientsFilerTimeout bounds each per-filer ListMetadataSubscribers call so
|
||||
// a slow or unreachable filer can't stall the admin dashboard.
|
||||
const mountClientsFilerTimeout = 5 * time.Second
|
||||
|
||||
// GetMountClients queries every filer for its connected mount subscribers and
|
||||
// aggregates them. Each filer only knows the clients connected to itself, so a
|
||||
// cluster-wide view requires fanning out. The filers are queried concurrently,
|
||||
// each under a short timeout, and an unreachable filer is skipped.
|
||||
func (s *AdminServer) GetMountClients() (*MountClientsData, error) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
clients []MountClient
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
|
||||
for _, filerAddr := range s.GetAllFilers() {
|
||||
wg.Add(1)
|
||||
go func(filerAddr string) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), mountClientsFilerTimeout)
|
||||
defer cancel()
|
||||
err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.ListMetadataSubscribers(ctx, &filer_pb.ListMetadataSubscribersRequest{
|
||||
ClientTypes: mountClientTypes,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mu.Lock()
|
||||
for _, sub := range resp.Subscribers {
|
||||
clients = append(clients, MountClient{
|
||||
ClientName: sub.ClientName,
|
||||
ClientType: sub.ClientType,
|
||||
Address: sub.Address,
|
||||
PathPrefix: sub.PathPrefix,
|
||||
ClientId: sub.ClientId,
|
||||
ConnectedAt: time.Unix(0, sub.ConnectedAtNs),
|
||||
FilerAddress: sub.FilerAddress,
|
||||
})
|
||||
}
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.Warningf("list mount clients from filer %s: %v", filerAddr, err)
|
||||
}
|
||||
}(filerAddr)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
sort.Slice(clients, func(i, j int) bool {
|
||||
if clients[i].Address != clients[j].Address {
|
||||
return clients[i].Address < clients[j].Address
|
||||
}
|
||||
return clients[i].PathPrefix < clients[j].PathPrefix
|
||||
})
|
||||
|
||||
return &MountClientsData{
|
||||
MountClients: clients,
|
||||
TotalMountClients: len(clients),
|
||||
LastUpdated: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
@@ -295,6 +295,25 @@ type ClusterFilersData struct {
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
// MountClient is one connected FUSE/VFS mount as reported by a filer's
|
||||
// metadata-subscriber registry.
|
||||
type MountClient struct {
|
||||
ClientName string `json:"client_name"`
|
||||
ClientType string `json:"client_type"` // "mount" (Go) or "sw-vfs" (Rust VFS)
|
||||
Address string `json:"address"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
ClientId int32 `json:"client_id"`
|
||||
ConnectedAt time.Time `json:"connected_at"`
|
||||
FilerAddress string `json:"filer_address"`
|
||||
}
|
||||
|
||||
type MountClientsData struct {
|
||||
Username string `json:"username"`
|
||||
MountClients []MountClient `json:"mount_clients"`
|
||||
TotalMountClients int `json:"total_mount_clients"`
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
type MessageBrokerInfo struct {
|
||||
Address string `json:"address"`
|
||||
DataCenter string `json:"datacenter"`
|
||||
|
||||
@@ -127,6 +127,7 @@ func (h *AdminHandlers) registerUIRoutes(r *mux.Router) {
|
||||
r.HandleFunc("/cluster/filers", h.clusterHandlers.ShowClusterFilers).Methods(http.MethodGet)
|
||||
r.HandleFunc("/cluster/s3", h.clusterHandlers.ShowClusterS3Servers).Methods(http.MethodGet)
|
||||
r.HandleFunc("/cluster/volume-servers", h.clusterHandlers.ShowClusterVolumeServers).Methods(http.MethodGet)
|
||||
r.HandleFunc("/cluster/mount-clients", h.clusterHandlers.ShowMountClients).Methods(http.MethodGet)
|
||||
|
||||
// Storage management routes
|
||||
r.HandleFunc("/storage/volumes", h.clusterHandlers.ShowClusterVolumes).Methods(http.MethodGet)
|
||||
|
||||
@@ -51,6 +51,28 @@ func (h *ClusterHandlers) ShowClusterVolumeServers(w http.ResponseWriter, r *htt
|
||||
}
|
||||
}
|
||||
|
||||
// ShowMountClients renders the connected FUSE/VFS mount clients page
|
||||
func (h *ClusterHandlers) ShowMountClients(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := h.adminServer.GetMountClients()
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get mount clients: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
username := usernameOrDefault(r)
|
||||
data.Username = username
|
||||
|
||||
// Render HTML template
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
mountClientsComponent := app.MountClients(*data)
|
||||
viewCtx := layout.NewViewContext(r, username, dash.CSRFTokenFromContext(r.Context()))
|
||||
layoutComponent := layout.Layout(viewCtx, mountClientsComponent)
|
||||
if err := layoutComponent.Render(r.Context(), w); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to render template: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// ShowClusterVolumes renders the cluster volumes page
|
||||
func (h *ClusterHandlers) ShowClusterVolumes(w http.ResponseWriter, r *http.Request) {
|
||||
// Get pagination and sorting parameters from query string
|
||||
|
||||
@@ -33,7 +33,7 @@ func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
|
||||
MinVolumeAgeHours: int32(vacuumConfig.MinVolumeAgeSeconds / 3600), // Convert seconds to hours
|
||||
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -21,7 +21,8 @@ templ Admin(data dash.AdminData) {
|
||||
</div>
|
||||
|
||||
<div id="dashboard-content">
|
||||
<!-- Summary Cards -->
|
||||
<!-- Summary Cards — each carries an inline sparkline of recent history
|
||||
from the admin's own snapshots (no Prometheus required). -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-xl-3 col-md-6 mb-4">
|
||||
<div class="card border-left-success shadow h-100 py-2">
|
||||
@@ -39,6 +40,7 @@ templ Admin(data dash.AdminData) {
|
||||
<i class="fas fa-database fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.Volumes)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,6 +61,7 @@ templ Admin(data dash.AdminData) {
|
||||
<i class="fas fa-file fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.Files)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -79,6 +82,7 @@ templ Admin(data dash.AdminData) {
|
||||
<i class="fas fa-hdd fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.DiskUsed)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -142,15 +146,82 @@ templ Admin(data dash.AdminData) {
|
||||
<i class="fas fa-puzzle-piece fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.EcShards)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Empty columns to balance the row -->
|
||||
<div class="col-xl-3 col-md-6 mb-4"></div>
|
||||
<div class="col-xl-3 col-md-6 mb-4"></div>
|
||||
<div class="col-xl-3 col-md-6 mb-4">
|
||||
<div class="card border-left-info shadow h-100 py-2">
|
||||
<div class="card-body">
|
||||
<div class="row no-gutters align-items-center">
|
||||
<div class="col mr-2">
|
||||
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">
|
||||
Active Tasks
|
||||
</div>
|
||||
<div class="h5 mb-0 font-weight-bold text-gray-800">
|
||||
{ data.Trends.TasksValue }
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<i class="fas fa-tasks fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.Tasks)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6 mb-4">
|
||||
<div class="card border-left-primary shadow h-100 py-2">
|
||||
<div class="card-body">
|
||||
<div class="row no-gutters align-items-center">
|
||||
<div class="col mr-2">
|
||||
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
|
||||
Workers
|
||||
</div>
|
||||
<div class="h5 mb-0 font-weight-bold text-gray-800">
|
||||
{ data.Trends.WorkersValue }
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<i class="fas fa-users-cog fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
@templ.Raw(data.Trends.Workers)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mount Clients -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<div class="card shadow mb-4">
|
||||
<div class="card-header py-3 d-flex justify-content-between align-items-center">
|
||||
<h6 class="m-0 font-weight-bold text-primary">
|
||||
<i class="fas fa-plug me-2"></i>Mount Clients
|
||||
</h6>
|
||||
<a id="mountClientsDetailsLink" href="/cluster/mount-clients" class="btn btn-sm btn-outline-primary">
|
||||
View Details <i class="fas fa-arrow-right ms-1"></i>
|
||||
</a>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="fas fa-plug fa-2x text-gray-300 me-3"></i>
|
||||
<div>
|
||||
<div class="h4 mb-0 font-weight-bold text-gray-800">{fmt.Sprintf("%d", data.TotalMountClients)}</div>
|
||||
<div class="text-xs text-muted text-uppercase">Connected FUSE/VFS mount clients</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function(){var l=document.getElementById('mountClientsDetailsLink'); if(l){l.href=(window.__BASE_PATH__||'')+'/cluster/mount-clients';}})();
|
||||
</script>
|
||||
|
||||
<!-- Master Nodes Status -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-lg-4">
|
||||
|
||||
+408
-321
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,139 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
)
|
||||
|
||||
templ MountClients(data dash.MountClientsData) {
|
||||
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
||||
<h1 class="h2">
|
||||
<i class="fas fa-plug me-2"></i>Mount Clients
|
||||
</h1>
|
||||
<div class="btn-toolbar mb-2 mb-md-0">
|
||||
<div class="btn-group me-2">
|
||||
<button type="button" class="btn btn-sm btn-outline-primary" onclick="exportMountClients()">
|
||||
<i class="fas fa-download me-1"></i>Export
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="mount-clients-content">
|
||||
<!-- Summary Cards -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-xl-12 col-md-12 mb-4">
|
||||
<div class="card border-left-info shadow h-100 py-2">
|
||||
<div class="card-body">
|
||||
<div class="row no-gutters align-items-center">
|
||||
<div class="col mr-2">
|
||||
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">
|
||||
Connected Mount Clients
|
||||
</div>
|
||||
<div class="h5 mb-0 font-weight-bold text-gray-800">
|
||||
{ fmt.Sprintf("%d", data.TotalMountClients) }
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<i class="fas fa-plug fa-2x text-gray-300"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Mount Clients Table -->
|
||||
<div class="card shadow mb-4">
|
||||
<div class="card-header py-3">
|
||||
<h6 class="m-0 font-weight-bold text-primary">
|
||||
<i class="fas fa-plug me-2"></i>Mount Clients
|
||||
</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
if len(data.MountClients) > 0 {
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover" id="mountClientsTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Address</th>
|
||||
<th>Type</th>
|
||||
<th>Path Prefix</th>
|
||||
<th>Client ID</th>
|
||||
<th>Connected Since</th>
|
||||
<th>Filer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
for _, c := range data.MountClients {
|
||||
<tr>
|
||||
<td><code>{ c.Address }</code></td>
|
||||
<td>
|
||||
<span class="badge bg-info text-dark">{ c.ClientType }</span>
|
||||
</td>
|
||||
<td><code>{ c.PathPrefix }</code></td>
|
||||
<td>{ fmt.Sprintf("%d", c.ClientId) }</td>
|
||||
<td>
|
||||
if !c.ConnectedAt.IsZero() {
|
||||
{ c.ConnectedAt.Format("2006-01-02 15:04:05") }
|
||||
} else {
|
||||
<span class="text-muted">N/A</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-light text-dark">{ c.FilerAddress }</span>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} else {
|
||||
<div class="text-center py-5">
|
||||
<i class="fas fa-plug fa-3x text-muted mb-3"></i>
|
||||
<h5 class="text-muted">No Mount Clients Found</h5>
|
||||
<p class="text-muted">No FUSE or VFS mounts are currently connected to the cluster's filers.</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Last Updated -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<small class="text-muted">
|
||||
<i class="fas fa-clock me-1"></i>
|
||||
Last updated: { data.LastUpdated.Format("2006-01-02 15:04:05") }
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function exportMountClients() {
|
||||
const rows = Array.from(document.querySelectorAll('#mountClientsTable tbody tr')).map(row => {
|
||||
const cells = row.querySelectorAll('td');
|
||||
if (cells.length > 1) {
|
||||
return Array.from(cells).slice(0, 6).map(c => c.textContent.trim());
|
||||
}
|
||||
return null;
|
||||
}).filter(row => row !== null);
|
||||
|
||||
// Quote every field and escape embedded quotes so special characters in
|
||||
// paths (#, ?, %, commas) survive. Build a Blob rather than a data: URI.
|
||||
const esc = v => '"' + String(v).replace(/"/g, '""') + '"';
|
||||
const csv = "Address,Type,Path Prefix,Client ID,Connected Since,Filer\n" +
|
||||
rows.map(r => r.map(esc).join(",")).join("\n");
|
||||
|
||||
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "mount-clients.csv";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
</script>
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
)
|
||||
|
||||
func MountClients(data dash.MountClientsData) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
|
||||
if templ_7745c5c3_Var1 == nil {
|
||||
templ_7745c5c3_Var1 = templ.NopComponent
|
||||
}
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div class=\"d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom\"><h1 class=\"h2\"><i class=\"fas fa-plug me-2\"></i>Mount Clients</h1><div class=\"btn-toolbar mb-2 mb-md-0\"><div class=\"btn-group me-2\"><button type=\"button\" class=\"btn btn-sm btn-outline-primary\" onclick=\"exportMountClients()\"><i class=\"fas fa-download me-1\"></i>Export</button></div></div></div><div id=\"mount-clients-content\"><!-- Summary Cards --><div class=\"row mb-4\"><div class=\"col-xl-12 col-md-12 mb-4\"><div class=\"card border-left-info shadow h-100 py-2\"><div class=\"card-body\"><div class=\"row no-gutters align-items-center\"><div class=\"col mr-2\"><div class=\"text-xs font-weight-bold text-info text-uppercase mb-1\">Connected Mount Clients</div><div class=\"h5 mb-0 font-weight-bold text-gray-800\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalMountClients))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 34, Col: 52}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</div></div><div class=\"col-auto\"><i class=\"fas fa-plug fa-2x text-gray-300\"></i></div></div></div></div></div></div><!-- Mount Clients Table --><div class=\"card shadow mb-4\"><div class=\"card-header py-3\"><h6 class=\"m-0 font-weight-bold text-primary\"><i class=\"fas fa-plug me-2\"></i>Mount Clients</h6></div><div class=\"card-body\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if len(data.MountClients) > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<div class=\"table-responsive\"><table class=\"table table-hover\" id=\"mountClientsTable\"><thead><tr><th>Address</th><th>Type</th><th>Path Prefix</th><th>Client ID</th><th>Connected Since</th><th>Filer</th></tr></thead> <tbody>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, c := range data.MountClients {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "<tr><td><code>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(c.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 70, Col: 31}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</code></td><td><span class=\"badge bg-info text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(c.ClientType)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 72, Col: 63}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</span></td><td><code>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(c.PathPrefix)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 74, Col: 34}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</code></td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", c.ClientId))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 75, Col: 45}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if !c.ConnectedAt.IsZero() {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(c.ConnectedAt.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 78, Col: 57}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<span class=\"text-muted\">N/A</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</td><td><span class=\"badge bg-light text-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(c.FilerAddress)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 84, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</span></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</tbody></table></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<div class=\"text-center py-5\"><i class=\"fas fa-plug fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Mount Clients Found</h5><p class=\"text-muted\">No FUSE or VFS mounts are currently connected to the cluster's filers.</p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/mount_clients.templ`, Line: 106, Col: 67}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</small></div></div></div><script>\n\tfunction exportMountClients() {\n\t\tconst rows = Array.from(document.querySelectorAll('#mountClientsTable tbody tr')).map(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length > 1) {\n\t\t\t\treturn Array.from(cells).slice(0, 6).map(c => c.textContent.trim());\n\t\t\t}\n\t\t\treturn null;\n\t\t}).filter(row => row !== null);\n\n\t\t// Quote every field and escape embedded quotes so special characters in\n\t\t// paths (#, ?, %, commas) survive. Build a Blob rather than a data: URI.\n\t\tconst esc = v => '\"' + String(v).replace(/\"/g, '\"\"') + '\"';\n\t\tconst csv = \"Address,Type,Path Prefix,Client ID,Connected Since,Filer\\n\" +\n\t\t\trows.map(r => r.map(esc).join(\",\")).join(\"\\n\");\n\n\t\tconst blob = new Blob([csv], { type: \"text/csv;charset=utf-8;\" });\n\t\tconst url = URL.createObjectURL(blob);\n\t\tconst link = document.createElement(\"a\");\n\t\tlink.href = url;\n\t\tlink.download = \"mount-clients.csv\";\n\t\tdocument.body.appendChild(link);\n\t\tlink.click();\n\t\tdocument.body.removeChild(link);\n\t\tURL.revokeObjectURL(url);\n\t}\n\t</script>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -32,7 +32,7 @@ templ Layout(view ViewContext, content templ.Component) {
|
||||
isStoragePage := strings.HasPrefix(currentPath, "/storage/volumes") || strings.HasPrefix(currentPath, "/storage/ec-shards") || strings.HasPrefix(currentPath, "/storage/collections")
|
||||
|
||||
// Detect if we're on a cluster page (but not storage page) to keep submenu expanded
|
||||
isClusterPage := (strings.HasPrefix(currentPath, "/cluster/masters") || strings.HasPrefix(currentPath, "/cluster/volume-servers") || strings.HasPrefix(currentPath, "/cluster/filers") || strings.HasPrefix(currentPath, "/cluster/s3"))
|
||||
isClusterPage := (strings.HasPrefix(currentPath, "/cluster/masters") || strings.HasPrefix(currentPath, "/cluster/volume-servers") || strings.HasPrefix(currentPath, "/cluster/filers") || strings.HasPrefix(currentPath, "/cluster/s3") || strings.HasPrefix(currentPath, "/cluster/mount-clients"))
|
||||
|
||||
isDefaultWorkerPage := currentPath == "/plugin" ||
|
||||
strings.HasPrefix(currentPath, "/plugin/configuration") ||
|
||||
@@ -139,6 +139,11 @@ templ Layout(view ViewContext, content templ.Component) {
|
||||
<i class="fas fa-cloud me-2"></i>S3 Servers
|
||||
</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link py-2" href={ view.P("/cluster/mount-clients") }>
|
||||
<i class="fas fa-plug me-2"></i>Mount Clients
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+19
-1
@@ -171,8 +171,17 @@ var cmdAdmin = &Command{
|
||||
- Metrics are disabled when -metricsPort is 0 (the default)
|
||||
- Example: weed admin -metricsPort=9327 -master="localhost:9333"
|
||||
|
||||
Maintenance Configuration:
|
||||
- An optional admin.toml declares maintenance task settings
|
||||
([maintenance.vacuum], [maintenance.balance], [maintenance.erasure_coding])
|
||||
- Settings in admin.toml are applied at every startup, overriding values
|
||||
saved from the admin UI, so they can be managed declaratively
|
||||
- Requires -dataDir; values can also be set via WEED_* environment
|
||||
variables, e.g. WEED_MAINTENANCE_VACUUM_GARBAGE_THRESHOLD=0.3
|
||||
- Generate example admin.toml: weed scaffold -config=admin
|
||||
|
||||
Configuration File:
|
||||
- The security.toml file is read from ".", "$HOME/.seaweedfs/",
|
||||
- The security.toml and admin.toml files are read from ".", "$HOME/.seaweedfs/",
|
||||
"/usr/local/etc/seaweedfs/", or "/etc/seaweedfs/", in that order
|
||||
- Generate example security.toml: weed scaffold -config=security
|
||||
|
||||
@@ -191,6 +200,9 @@ func runAdmin(cmd *Command, args []string) bool {
|
||||
// Load security configuration
|
||||
util.LoadSecurityConfiguration()
|
||||
|
||||
// Optional admin.toml with maintenance task settings
|
||||
util.LoadConfiguration("admin", false)
|
||||
|
||||
// Apply security.toml / env var fallbacks for credential flags.
|
||||
// CLI flags take precedence over security.toml / WEED_* env vars.
|
||||
applyViperFallback(cmd, a.adminUser, "adminUser", "admin.user")
|
||||
@@ -337,6 +349,12 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,
|
||||
glog.Infof("Data directory created/verified: %s", dataDir)
|
||||
}
|
||||
|
||||
// Write maintenance task settings from admin.toml into the persisted
|
||||
// task configs before the server loads them
|
||||
if err := dash.NewConfigPersistence(dataDir).ApplyMaintenanceConfigFromToml(util.GetViper()); err != nil {
|
||||
return fmt.Errorf("apply admin.toml: %w", err)
|
||||
}
|
||||
|
||||
// Detect TLS configuration to set Secure cookie flag
|
||||
cookieSecure := viper.GetString("https.admin.key") != ""
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ func init() {
|
||||
}
|
||||
|
||||
var cmdScaffold = &Command{
|
||||
UsageLine: "scaffold -config=[filer|notification|replication|security|master|volume|shell|credential]",
|
||||
UsageLine: "scaffold -config=[filer|notification|replication|security|master|volume|shell|credential|admin]",
|
||||
Short: "generate basic configuration files",
|
||||
Long: `Generate configuration files with all possible configurations for you to customize.
|
||||
|
||||
@@ -31,7 +31,7 @@ var cmdScaffold = &Command{
|
||||
|
||||
var (
|
||||
outputPath = cmdScaffold.Flag.String("output", "", "if not empty, save the configuration file to this directory")
|
||||
config = cmdScaffold.Flag.String("config", "filer", "[filer|notification|replication|security|master|volume|shell|credential] the configuration file to generate")
|
||||
config = cmdScaffold.Flag.String("config", "filer", "[filer|notification|replication|security|master|volume|shell|credential|admin] the configuration file to generate")
|
||||
)
|
||||
|
||||
func runScaffold(cmd *Command, args []string) bool {
|
||||
@@ -54,6 +54,8 @@ func runScaffold(cmd *Command, args []string) bool {
|
||||
content = scaffold.Shell
|
||||
case "credential":
|
||||
content = scaffold.Credential
|
||||
case "admin":
|
||||
content = scaffold.Admin
|
||||
}
|
||||
if content == "" {
|
||||
println("need a valid -config option")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Put this file in one of the locations, with descending priority
|
||||
# ./admin.toml
|
||||
# $HOME/.seaweedfs/admin.toml
|
||||
# /etc/seaweedfs/admin.toml
|
||||
# this file is read by "weed admin"
|
||||
|
||||
# Maintenance task settings declared here are applied every time the admin
|
||||
# server starts, overriding values saved from the admin UI under
|
||||
# <dataDir>/conf. Commented-out keys keep their saved or default values.
|
||||
# Requires -dataDir.
|
||||
# Each value can also be set via environment variable, e.g.
|
||||
# export WEED_MAINTENANCE_VACUUM_GARBAGE_THRESHOLD=0.3
|
||||
|
||||
[maintenance.vacuum]
|
||||
# enabled = true
|
||||
# vacuum volumes with more deleted content than this ratio
|
||||
# garbage_threshold = 0.3
|
||||
# how often to scan for volumes needing vacuum
|
||||
# scan_interval_seconds = 7200
|
||||
# max_concurrent = 2
|
||||
# only vacuum volumes older than this (rounded up to whole hours)
|
||||
# min_volume_age_seconds = 86400
|
||||
|
||||
[maintenance.balance]
|
||||
# enabled = true
|
||||
# trigger balancing when volume distribution exceeds this ratio
|
||||
# imbalance_threshold = 0.2
|
||||
# scan_interval_seconds = 1800
|
||||
# max_concurrent = 1
|
||||
# minimum number of volume servers before balancing
|
||||
# min_server_count = 2
|
||||
|
||||
[maintenance.erasure_coding]
|
||||
# enabled = true
|
||||
# only erasure code volumes this full
|
||||
# fullness_ratio = 0.95
|
||||
# only erasure code volumes not modified for this long
|
||||
# quiet_for_seconds = 3600
|
||||
# scan_interval_seconds = 3600
|
||||
# max_concurrent = 1
|
||||
# min_size_mb = 30
|
||||
# only process volumes from this collection ("" = all collections)
|
||||
# collection_filter = ""
|
||||
# disk tags preferred for shard placement
|
||||
# preferred_tags = ["fast", "ssd"]
|
||||
# EC shard placement constraint, e.g. "020"; empty uses the master default replication
|
||||
# replica_placement = ""
|
||||
@@ -35,3 +35,6 @@ var Shell string
|
||||
|
||||
//go:embed credential.toml
|
||||
var Credential string
|
||||
|
||||
//go:embed admin.toml
|
||||
var Admin string
|
||||
@@ -33,6 +33,7 @@ type UploadOption struct {
|
||||
Filename string
|
||||
Cipher bool
|
||||
IsInputCompressed bool
|
||||
IsReplication bool // preserve the source needle's compression state
|
||||
MimeType string
|
||||
PairMap map[string]string
|
||||
Jwt security.EncodedJwt
|
||||
@@ -276,7 +277,7 @@ func (uploader *Uploader) retriedUploadData(ctx context.Context, data []byte, op
|
||||
func (uploader *Uploader) doUploadData(ctx context.Context, data []byte, option *UploadOption) (uploadResult *UploadResult, err error) {
|
||||
contentIsGzipped := option.IsInputCompressed
|
||||
shouldGzipNow := false
|
||||
if !option.IsInputCompressed {
|
||||
if !option.IsInputCompressed && !option.IsReplication {
|
||||
if option.MimeType == "" {
|
||||
option.MimeType = http.DetectContentType(data)
|
||||
// println("detect1 mimetype to", MimeType)
|
||||
@@ -311,8 +312,8 @@ func (uploader *Uploader) doUploadData(ctx context.Context, data []byte, option
|
||||
contentIsGzipped = true
|
||||
}
|
||||
}
|
||||
} else if option.IsInputCompressed {
|
||||
// just to get the clear data length
|
||||
} else if option.IsInputCompressed && !option.IsReplication {
|
||||
// decompress only to report the clear data length; replication discards the result, so skip it
|
||||
clearData, err = util.DecompressData(data)
|
||||
if err == nil {
|
||||
clearDataLen = len(clearData)
|
||||
|
||||
@@ -7,12 +7,14 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
type scriptedHTTPResponse struct {
|
||||
@@ -200,6 +202,60 @@ func TestUploadRewindsBodyOnConnectionReset(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicationUploadPreservesUncompressedNeedle(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
payload []byte
|
||||
}{
|
||||
{
|
||||
name: "unknown binary sampling",
|
||||
payload: bytes.Repeat([]byte{0}, 32*1024),
|
||||
},
|
||||
{
|
||||
name: "receiver MIME detection",
|
||||
payload: bytes.Repeat([]byte("plain text content\n"), 2048),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var replicatedNeedle *needle.Needle
|
||||
var parseErr error
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
replicatedNeedle, _, _, parseErr = needle.CreateNeedleFromRequest(r, false, 1024*1024, &bytes.Buffer{})
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = io.WriteString(w, `{"name":"payload.custom","size":32768}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
uploader := newUploader(server.Client())
|
||||
_, err := uploader.UploadData(context.Background(), tc.payload, &UploadOption{
|
||||
UploadUrl: server.URL + "/3,01637037d6?type=replicate",
|
||||
Filename: "payload.custom",
|
||||
IsReplication: true,
|
||||
MaxAttempts: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replication upload failed: %v", err)
|
||||
}
|
||||
if parseErr != nil {
|
||||
t.Fatalf("parse replicated upload: %v", parseErr)
|
||||
}
|
||||
if replicatedNeedle == nil {
|
||||
t.Fatal("replica did not receive a needle")
|
||||
}
|
||||
if replicatedNeedle.IsCompressed() {
|
||||
t.Fatal("replication changed an uncompressed needle to compressed")
|
||||
}
|
||||
if !bytes.Equal(replicatedNeedle.Data, tc.payload) {
|
||||
t.Fatalf("replicated data differs: got %d bytes, want %d", len(replicatedNeedle.Data), len(tc.payload))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// deadReplicaClient simulates an unreachable replica: every request blocks for
|
||||
// dialDelay (standing in for the TCP dial timeout) and then fails, unless the
|
||||
// request context is cancelled first.
|
||||
|
||||
@@ -78,6 +78,11 @@ service SeaweedFiler {
|
||||
rpc SubscribeLocalMetadata (SubscribeMetadataRequest) returns (stream SubscribeMetadataResponse) {
|
||||
}
|
||||
|
||||
// List the metadata subscribers currently connected to this filer
|
||||
// (FUSE mounts, S3, filer.sync, peer filers, ...).
|
||||
rpc ListMetadataSubscribers (ListMetadataSubscribersRequest) returns (ListMetadataSubscribersResponse) {
|
||||
}
|
||||
|
||||
rpc KvGet (KvGetRequest) returns (KvGetResponse) {
|
||||
}
|
||||
|
||||
@@ -621,6 +626,22 @@ message SubscribeMetadataResponse {
|
||||
repeated SubscribeMetadataResponse events = 4; // batch of additional events (backlog catch-up)
|
||||
repeated LogFileChunkRef log_file_refs = 5; // log file chunk refs for client direct-read
|
||||
}
|
||||
message ListMetadataSubscribersRequest {
|
||||
repeated string client_types = 1; // optional filter by client type, e.g. "mount"; empty = all
|
||||
}
|
||||
message ListMetadataSubscribersResponse {
|
||||
repeated MetadataSubscriber subscribers = 1;
|
||||
}
|
||||
message MetadataSubscriber {
|
||||
string client_name = 1; // "<type>@<address>"
|
||||
string client_type = 2; // e.g. "mount", "sw-vfs", "s3", "filer:<addr>"
|
||||
string address = 3; // client peer address
|
||||
string path_prefix = 4; // subscribed path prefix
|
||||
int32 client_id = 5;
|
||||
int32 client_epoch = 6;
|
||||
int64 connected_at_ns = 7;
|
||||
string filer_address = 8; // the filer this subscriber is connected to
|
||||
}
|
||||
// A persisted log file that the client can read directly from volume servers.
|
||||
// The file format is: [4-byte size | protobuf LogEntry] repeated.
|
||||
// Each LogEntry.Data contains a marshaled SubscribeMetadataResponse.
|
||||
|
||||
+462
-251
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,7 @@ const (
|
||||
SeaweedFiler_TraverseBfsMetadata_FullMethodName = "/filer_pb.SeaweedFiler/TraverseBfsMetadata"
|
||||
SeaweedFiler_SubscribeMetadata_FullMethodName = "/filer_pb.SeaweedFiler/SubscribeMetadata"
|
||||
SeaweedFiler_SubscribeLocalMetadata_FullMethodName = "/filer_pb.SeaweedFiler/SubscribeLocalMetadata"
|
||||
SeaweedFiler_ListMetadataSubscribers_FullMethodName = "/filer_pb.SeaweedFiler/ListMetadataSubscribers"
|
||||
SeaweedFiler_KvGet_FullMethodName = "/filer_pb.SeaweedFiler/KvGet"
|
||||
SeaweedFiler_KvPut_FullMethodName = "/filer_pb.SeaweedFiler/KvPut"
|
||||
SeaweedFiler_CacheRemoteObjectToLocalCluster_FullMethodName = "/filer_pb.SeaweedFiler/CacheRemoteObjectToLocalCluster"
|
||||
@@ -81,6 +82,9 @@ type SeaweedFilerClient interface {
|
||||
TraverseBfsMetadata(ctx context.Context, in *TraverseBfsMetadataRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[TraverseBfsMetadataResponse], error)
|
||||
SubscribeMetadata(ctx context.Context, in *SubscribeMetadataRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[SubscribeMetadataResponse], error)
|
||||
SubscribeLocalMetadata(ctx context.Context, in *SubscribeMetadataRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[SubscribeMetadataResponse], error)
|
||||
// List the metadata subscribers currently connected to this filer
|
||||
// (FUSE mounts, S3, filer.sync, peer filers, ...).
|
||||
ListMetadataSubscribers(ctx context.Context, in *ListMetadataSubscribersRequest, opts ...grpc.CallOption) (*ListMetadataSubscribersResponse, error)
|
||||
KvGet(ctx context.Context, in *KvGetRequest, opts ...grpc.CallOption) (*KvGetResponse, error)
|
||||
KvPut(ctx context.Context, in *KvPutRequest, opts ...grpc.CallOption) (*KvPutResponse, error)
|
||||
CacheRemoteObjectToLocalCluster(ctx context.Context, in *CacheRemoteObjectToLocalClusterRequest, opts ...grpc.CallOption) (*CacheRemoteObjectToLocalClusterResponse, error)
|
||||
@@ -382,6 +386,16 @@ func (c *seaweedFilerClient) SubscribeLocalMetadata(ctx context.Context, in *Sub
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type SeaweedFiler_SubscribeLocalMetadataClient = grpc.ServerStreamingClient[SubscribeMetadataResponse]
|
||||
|
||||
func (c *seaweedFilerClient) ListMetadataSubscribers(ctx context.Context, in *ListMetadataSubscribersRequest, opts ...grpc.CallOption) (*ListMetadataSubscribersResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListMetadataSubscribersResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_ListMetadataSubscribers_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) KvGet(ctx context.Context, in *KvGetRequest, opts ...grpc.CallOption) (*KvGetResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(KvGetResponse)
|
||||
@@ -509,6 +523,9 @@ type SeaweedFilerServer interface {
|
||||
TraverseBfsMetadata(*TraverseBfsMetadataRequest, grpc.ServerStreamingServer[TraverseBfsMetadataResponse]) error
|
||||
SubscribeMetadata(*SubscribeMetadataRequest, grpc.ServerStreamingServer[SubscribeMetadataResponse]) error
|
||||
SubscribeLocalMetadata(*SubscribeMetadataRequest, grpc.ServerStreamingServer[SubscribeMetadataResponse]) error
|
||||
// List the metadata subscribers currently connected to this filer
|
||||
// (FUSE mounts, S3, filer.sync, peer filers, ...).
|
||||
ListMetadataSubscribers(context.Context, *ListMetadataSubscribersRequest) (*ListMetadataSubscribersResponse, error)
|
||||
KvGet(context.Context, *KvGetRequest) (*KvGetResponse, error)
|
||||
KvPut(context.Context, *KvPutRequest) (*KvPutResponse, error)
|
||||
CacheRemoteObjectToLocalCluster(context.Context, *CacheRemoteObjectToLocalClusterRequest) (*CacheRemoteObjectToLocalClusterResponse, error)
|
||||
@@ -601,6 +618,9 @@ func (UnimplementedSeaweedFilerServer) SubscribeMetadata(*SubscribeMetadataReque
|
||||
func (UnimplementedSeaweedFilerServer) SubscribeLocalMetadata(*SubscribeMetadataRequest, grpc.ServerStreamingServer[SubscribeMetadataResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method SubscribeLocalMetadata not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) ListMetadataSubscribers(context.Context, *ListMetadataSubscribersRequest) (*ListMetadataSubscribersResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListMetadataSubscribers not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) KvGet(context.Context, *KvGetRequest) (*KvGetResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method KvGet not implemented")
|
||||
}
|
||||
@@ -1020,6 +1040,24 @@ func _SeaweedFiler_SubscribeLocalMetadata_Handler(srv interface{}, stream grpc.S
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type SeaweedFiler_SubscribeLocalMetadataServer = grpc.ServerStreamingServer[SubscribeMetadataResponse]
|
||||
|
||||
func _SeaweedFiler_ListMetadataSubscribers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListMetadataSubscribersRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).ListMetadataSubscribers(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_ListMetadataSubscribers_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).ListMetadataSubscribers(ctx, req.(*ListMetadataSubscribersRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_KvGet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(KvGetRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1275,6 +1313,10 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "GetFilerConfiguration",
|
||||
Handler: _SeaweedFiler_GetFilerConfiguration_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListMetadataSubscribers",
|
||||
Handler: _SeaweedFiler_ListMetadataSubscribers_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "KvGet",
|
||||
Handler: _SeaweedFiler_KvGet_Handler,
|
||||
|
||||
@@ -147,7 +147,11 @@ message VolumeEcShardInformationMessage {
|
||||
repeated int64 shard_sizes = 7; // optimized: sizes for shards in order of set bits in ec_index_bits
|
||||
uint64 file_count = 8; // total needles in the .ecx index (live + tombstoned)
|
||||
uint64 delete_count = 9; // node-local tombstones in the .ecj deletion journal
|
||||
// fields 10-19 reserved for future upstream open-source additions.
|
||||
// encode-run identity (unix nanos) from the .vif EcShardConfig; lets the admin
|
||||
// group shards by encode generation. Numbered 14 (not 10) to skip the
|
||||
// enterprise fork's reserved 10-13.
|
||||
int64 encode_ts_ns = 14;
|
||||
// fields 15-19 reserved for future upstream open-source additions.
|
||||
// fields 20+ are owned by the enterprise fork (e.g. data_shards/parity_shards)
|
||||
// and must not be used here without coordination.
|
||||
}
|
||||
|
||||
@@ -631,16 +631,20 @@ func (x *VolumeShortInformationMessage) GetDiskId() uint32 {
|
||||
}
|
||||
|
||||
type VolumeEcShardInformationMessage struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
EcIndexBits uint32 `protobuf:"varint,3,opt,name=ec_index_bits,json=ecIndexBits,proto3" json:"ec_index_bits,omitempty"`
|
||||
DiskType string `protobuf:"bytes,4,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"`
|
||||
ExpireAtSec uint64 `protobuf:"varint,5,opt,name=expire_at_sec,json=expireAtSec,proto3" json:"expire_at_sec,omitempty"` // used to record the destruction time of ec volume
|
||||
DiskId uint32 `protobuf:"varint,6,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
ShardSizes []int64 `protobuf:"varint,7,rep,packed,name=shard_sizes,json=shardSizes,proto3" json:"shard_sizes,omitempty"` // optimized: sizes for shards in order of set bits in ec_index_bits
|
||||
FileCount uint64 `protobuf:"varint,8,opt,name=file_count,json=fileCount,proto3" json:"file_count,omitempty"` // total needles in the .ecx index (live + tombstoned)
|
||||
DeleteCount uint64 `protobuf:"varint,9,opt,name=delete_count,json=deleteCount,proto3" json:"delete_count,omitempty"` // node-local tombstones in the .ecj deletion journal
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
EcIndexBits uint32 `protobuf:"varint,3,opt,name=ec_index_bits,json=ecIndexBits,proto3" json:"ec_index_bits,omitempty"`
|
||||
DiskType string `protobuf:"bytes,4,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"`
|
||||
ExpireAtSec uint64 `protobuf:"varint,5,opt,name=expire_at_sec,json=expireAtSec,proto3" json:"expire_at_sec,omitempty"` // used to record the destruction time of ec volume
|
||||
DiskId uint32 `protobuf:"varint,6,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"`
|
||||
ShardSizes []int64 `protobuf:"varint,7,rep,packed,name=shard_sizes,json=shardSizes,proto3" json:"shard_sizes,omitempty"` // optimized: sizes for shards in order of set bits in ec_index_bits
|
||||
FileCount uint64 `protobuf:"varint,8,opt,name=file_count,json=fileCount,proto3" json:"file_count,omitempty"` // total needles in the .ecx index (live + tombstoned)
|
||||
DeleteCount uint64 `protobuf:"varint,9,opt,name=delete_count,json=deleteCount,proto3" json:"delete_count,omitempty"` // node-local tombstones in the .ecj deletion journal
|
||||
// encode-run identity (unix nanos) from the .vif EcShardConfig; lets the admin
|
||||
// group shards by encode generation. Numbered 14 (not 10) to skip the
|
||||
// enterprise fork's reserved 10-13.
|
||||
EncodeTsNs int64 `protobuf:"varint,14,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -738,6 +742,13 @@ func (x *VolumeEcShardInformationMessage) GetDeleteCount() uint64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardInformationMessage) GetEncodeTsNs() int64 {
|
||||
if x != nil {
|
||||
return x.EncodeTsNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type StorageBackend struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||
@@ -4439,7 +4450,7 @@ const file_master_proto_rawDesc = "" +
|
||||
"\x03ttl\x18\n" +
|
||||
" \x01(\rR\x03ttl\x12\x1b\n" +
|
||||
"\tdisk_type\x18\x0f \x01(\tR\bdiskType\x12\x17\n" +
|
||||
"\adisk_id\x18\x10 \x01(\rR\x06diskId\"\xb2\x02\n" +
|
||||
"\adisk_id\x18\x10 \x01(\rR\x06diskId\"\xd4\x02\n" +
|
||||
"\x1fVolumeEcShardInformationMessage\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\rR\x02id\x12\x1e\n" +
|
||||
"\n" +
|
||||
@@ -4453,7 +4464,9 @@ const file_master_proto_rawDesc = "" +
|
||||
"shardSizes\x12\x1d\n" +
|
||||
"\n" +
|
||||
"file_count\x18\b \x01(\x04R\tfileCount\x12!\n" +
|
||||
"\fdelete_count\x18\t \x01(\x04R\vdeleteCount\"\xbe\x01\n" +
|
||||
"\fdelete_count\x18\t \x01(\x04R\vdeleteCount\x12 \n" +
|
||||
"\fencode_ts_ns\x18\x0e \x01(\x03R\n" +
|
||||
"encodeTsNs\"\xbe\x01\n" +
|
||||
"\x0eStorageBackend\x12\x12\n" +
|
||||
"\x04type\x18\x01 \x01(\tR\x04type\x12\x0e\n" +
|
||||
"\x02id\x18\x02 \x01(\tR\x02id\x12I\n" +
|
||||
|
||||
@@ -453,6 +453,7 @@ message VolumeEcShardsDeleteRequest {
|
||||
string collection = 2;
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
@@ -470,6 +471,7 @@ message VolumeEcShardsMountResponse {
|
||||
message VolumeEcShardsUnmountRequest {
|
||||
uint32 volume_id = 1;
|
||||
repeated uint32 shard_ids = 3;
|
||||
int64 encode_ts_ns = 4; // generation fence: skip a disk whose mounted EC volume is this generation or newer (0 = unfenced, unmount all)
|
||||
}
|
||||
message VolumeEcShardsUnmountResponse {
|
||||
}
|
||||
|
||||
@@ -3606,6 +3606,7 @@ type VolumeEcShardsDeleteRequest struct {
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3668,6 +3669,13 @@ func (x *VolumeEcShardsDeleteRequest) GetFullTeardown() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsDeleteRequest) GetEncodeTsNs() int64 {
|
||||
if x != nil {
|
||||
return x.EncodeTsNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type VolumeEcShardsDeleteResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
FullTeardownDone bool `protobuf:"varint,1,opt,name=full_teardown_done,json=fullTeardownDone,proto3" json:"full_teardown_done,omitempty"` // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
@@ -3820,6 +3828,7 @@ type VolumeEcShardsUnmountRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
EncodeTsNs int64 `protobuf:"varint,4,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // generation fence: skip a disk whose mounted EC volume is this generation or newer (0 = unfenced, unmount all)
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3868,6 +3877,13 @@ func (x *VolumeEcShardsUnmountRequest) GetShardIds() []uint32 {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsUnmountRequest) GetEncodeTsNs() int64 {
|
||||
if x != nil {
|
||||
return x.EncodeTsNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type VolumeEcShardsUnmountResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -7268,14 +7284,16 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\rcopy_vif_file\x18\a \x01(\bR\vcopyVifFile\x12\x17\n" +
|
||||
"\adisk_id\x18\b \x01(\rR\x06diskId\x12&\n" +
|
||||
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\"\x1c\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\x9c\x01\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\xbe\x01\n" +
|
||||
"\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
|
||||
"\n" +
|
||||
"collection\x18\x02 \x01(\tR\n" +
|
||||
"collection\x12\x1b\n" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12#\n" +
|
||||
"\rfull_teardown\x18\x04 \x01(\bR\ffullTeardown\"L\n" +
|
||||
"\rfull_teardown\x18\x04 \x01(\bR\ffullTeardown\x12 \n" +
|
||||
"\fencode_ts_ns\x18\x05 \x01(\x03R\n" +
|
||||
"encodeTsNs\"L\n" +
|
||||
"\x1cVolumeEcShardsDeleteResponse\x12,\n" +
|
||||
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xa0\x01\n" +
|
||||
"\x1aVolumeEcShardsMountRequest\x12\x1b\n" +
|
||||
@@ -7285,10 +7303,12 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"collection\x12\x1b\n" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12(\n" +
|
||||
"\x10source_disk_type\x18\x04 \x01(\tR\x0esourceDiskType\"\x1d\n" +
|
||||
"\x1bVolumeEcShardsMountResponse\"X\n" +
|
||||
"\x1bVolumeEcShardsMountResponse\"z\n" +
|
||||
"\x1cVolumeEcShardsUnmountRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1b\n" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\"\x1f\n" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12 \n" +
|
||||
"\fencode_ts_ns\x18\x04 \x01(\x03R\n" +
|
||||
"encodeTsNs\"\x1f\n" +
|
||||
"\x1dVolumeEcShardsUnmountResponse\"\xc1\x01\n" +
|
||||
"\x18VolumeEcShardReadRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x19\n" +
|
||||
|
||||
@@ -178,6 +178,7 @@ message ErasureCodingTaskParams {
|
||||
string master_client = 5; // Master server address
|
||||
bool cleanup_source = 6; // Whether to cleanup source volume after EC
|
||||
string source_disk_type = 8; // Source volume's disk type, passed to VolumeEcShardsMount so shards report under it (#9423)
|
||||
int64 encode_ts_ns = 9; // admin-issued encode generation (unix nanos); fences a stale worker's shard cleanup against a newer run. 0 => unfenced (legacy/shell), falls back to a blanket teardown.
|
||||
}
|
||||
|
||||
// TaskSource represents a unified source location for any task type
|
||||
|
||||
@@ -1323,6 +1323,7 @@ type ErasureCodingTaskParams struct {
|
||||
MasterClient string `protobuf:"bytes,5,opt,name=master_client,json=masterClient,proto3" json:"master_client,omitempty"` // Master server address
|
||||
CleanupSource bool `protobuf:"varint,6,opt,name=cleanup_source,json=cleanupSource,proto3" json:"cleanup_source,omitempty"` // Whether to cleanup source volume after EC
|
||||
SourceDiskType string `protobuf:"bytes,8,opt,name=source_disk_type,json=sourceDiskType,proto3" json:"source_disk_type,omitempty"` // Source volume's disk type, passed to VolumeEcShardsMount so shards report under it (#9423)
|
||||
EncodeTsNs int64 `protobuf:"varint,9,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // admin-issued encode generation (unix nanos); fences a stale worker's shard cleanup against a newer run. 0 => unfenced (legacy/shell), falls back to a blanket teardown.
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -1406,6 +1407,13 @@ func (x *ErasureCodingTaskParams) GetSourceDiskType() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ErasureCodingTaskParams) GetEncodeTsNs() int64 {
|
||||
if x != nil {
|
||||
return x.EncodeTsNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// TaskSource represents a unified source location for any task type
|
||||
type TaskSource struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4056,7 +4064,7 @@ const file_worker_proto_rawDesc = "" +
|
||||
"batch_size\x18\x03 \x01(\x05R\tbatchSize\x12\x1f\n" +
|
||||
"\vworking_dir\x18\x04 \x01(\tR\n" +
|
||||
"workingDir\x12'\n" +
|
||||
"\x0fverify_checksum\x18\x05 \x01(\bR\x0everifyChecksum\"\xae\x02\n" +
|
||||
"\x0fverify_checksum\x18\x05 \x01(\bR\x0everifyChecksum\"\xd0\x02\n" +
|
||||
"\x17ErasureCodingTaskParams\x120\n" +
|
||||
"\x14estimated_shard_size\x18\x01 \x01(\x04R\x12estimatedShardSize\x12\x1f\n" +
|
||||
"\vdata_shards\x18\x02 \x01(\x05R\n" +
|
||||
@@ -4066,7 +4074,9 @@ const file_worker_proto_rawDesc = "" +
|
||||
"workingDir\x12#\n" +
|
||||
"\rmaster_client\x18\x05 \x01(\tR\fmasterClient\x12%\n" +
|
||||
"\x0ecleanup_source\x18\x06 \x01(\bR\rcleanupSource\x12(\n" +
|
||||
"\x10source_disk_type\x18\b \x01(\tR\x0esourceDiskTypeJ\x04\b\a\x10\b\"\xcf\x01\n" +
|
||||
"\x10source_disk_type\x18\b \x01(\tR\x0esourceDiskType\x12 \n" +
|
||||
"\fencode_ts_ns\x18\t \x01(\x03R\n" +
|
||||
"encodeTsNsJ\x04\b\a\x10\b\"\xcf\x01\n" +
|
||||
"\n" +
|
||||
"TaskSource\x12\x12\n" +
|
||||
"\x04node\x18\x01 \x01(\tR\x04node\x12\x17\n" +
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAccountForUnscopedIdentity(t *testing.T) {
|
||||
assert.Equal(t, "alice", accountForUnscopedIdentity("alice").Id, "a named identity gets its own account id")
|
||||
assert.NotEqual(t, AccountAdmin.Id, accountForUnscopedIdentity("alice").Id, "a named identity must not inherit the admin account")
|
||||
assert.Same(t, &AccountAdmin, accountForUnscopedIdentity(AccountAdmin.Id), "the conventional admin keeps the admin account")
|
||||
assert.Same(t, &AccountAdmin, accountForUnscopedIdentity(""), "an empty name falls back to the admin account")
|
||||
}
|
||||
|
||||
func TestUnscopedIdentitiesGetDistinctAccounts(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
|
||||
config := `{
|
||||
"identities": [
|
||||
{"name": "alice", "credentials": [{"accessKey": "alice_ak", "secretKey": "alice_sk"}], "actions": ["Read"]},
|
||||
{"name": "admin", "credentials": [{"accessKey": "admin_ak", "secretKey": "admin_sk"}], "actions": ["Admin"]}
|
||||
]
|
||||
}`
|
||||
tmp, err := os.CreateTemp("", "s3-config-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tmp.Name())
|
||||
_, err = tmp.WriteString(config)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, tmp.Close())
|
||||
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmp.Name()}, nil, "memory")
|
||||
|
||||
alice, _, found := iam.LookupByAccessKey("alice_ak")
|
||||
require.True(t, found)
|
||||
require.NotNil(t, alice.Account)
|
||||
assert.Equal(t, "alice", alice.Account.Id, "a non-admin account-less identity owns resources as itself, not as admin")
|
||||
|
||||
admin, _, found := iam.LookupByAccessKey("admin_ak")
|
||||
require.True(t, found)
|
||||
require.NotNil(t, admin.Account)
|
||||
assert.Equal(t, AccountAdmin.Id, admin.Account.Id, "the admin identity keeps the admin account")
|
||||
}
|
||||
|
||||
// A distinct non-owner is denied an admin-owned bucket (iam nil => isUserAdmin
|
||||
// false, so only real ownership grants access).
|
||||
func TestCheckAccessByOwnershipDeniesNonOwner(t *testing.T) {
|
||||
adminOwner := AccountAdmin.Id
|
||||
s3a := &S3ApiServer{
|
||||
bucketRegistry: &BucketRegistry{
|
||||
metadataCache: map[string]*BucketMetaData{
|
||||
"b": {Name: "b", Owner: &s3.Owner{ID: &adminOwner}},
|
||||
},
|
||||
notFound: map[string]struct{}{},
|
||||
},
|
||||
}
|
||||
|
||||
nonOwner := httptest.NewRequest(http.MethodGet, "/b?ownershipControls=", nil)
|
||||
nonOwner.Header.Set(s3_constants.AmzAccountId, "alice")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, s3a.checkAccessByOwnership(nonOwner, "b"), "a distinct non-owner is denied the admin-owned bucket")
|
||||
|
||||
owner := httptest.NewRequest(http.MethodGet, "/b?ownershipControls=", nil)
|
||||
owner.Header.Set(s3_constants.AmzAccountId, AccountAdmin.Id)
|
||||
assert.Equal(t, s3err.ErrNone, s3a.checkAccessByOwnership(owner, "b"), "the actual owner is still allowed")
|
||||
}
|
||||
|
||||
// An account-less identity's synthesized account must be registered in the
|
||||
// account lookup so its id resolves to a display name. Otherwise ACL grantee
|
||||
// validation and owner display report the id as "not exists" — the regression
|
||||
// where a canned PutObjectAcl granting to the caller's own account returned
|
||||
// 400 InvalidRequest.
|
||||
func TestUnscopedIdentityAccountResolvesByName(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
|
||||
config := `{
|
||||
"identities": [
|
||||
{"name": "alice", "credentials": [{"accessKey": "alice_ak", "secretKey": "alice_sk"}], "actions": ["Read", "Write"]}
|
||||
]
|
||||
}`
|
||||
tmp, err := os.CreateTemp("", "s3-config-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tmp.Name())
|
||||
_, err = tmp.WriteString(config)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, tmp.Close())
|
||||
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmp.Name()}, nil, "memory")
|
||||
|
||||
assert.Equal(t, "alice", iam.GetAccountNameById("alice"),
|
||||
"account-less identity id must resolve to a display name for ACL/owner validation")
|
||||
}
|
||||
|
||||
// When an account is explicitly configured with the same id an account-less
|
||||
// identity would synthesize, the identity must reuse that configured account so
|
||||
// its custom display name/email are preserved.
|
||||
func TestUnscopedIdentityReusesConfiguredAccount(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
|
||||
config := `{
|
||||
"accounts": [
|
||||
{"id": "alice", "displayName": "Alice Smith", "emailAddress": "alice@example.com"}
|
||||
],
|
||||
"identities": [
|
||||
{"name": "alice", "credentials": [{"accessKey": "alice_ak", "secretKey": "alice_sk"}], "actions": ["Read"]}
|
||||
]
|
||||
}`
|
||||
tmp, err := os.CreateTemp("", "s3-config-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tmp.Name())
|
||||
_, err = tmp.WriteString(config)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, tmp.Close())
|
||||
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmp.Name()}, nil, "memory")
|
||||
|
||||
assert.Equal(t, "Alice Smith", iam.GetAccountNameById("alice"),
|
||||
"explicitly configured account display name must be preserved")
|
||||
|
||||
alice, _, found := iam.LookupByAccessKey("alice_ak")
|
||||
require.True(t, found)
|
||||
require.NotNil(t, alice.Account)
|
||||
assert.Equal(t, "Alice Smith", alice.Account.DisplayName,
|
||||
"identity must reuse the configured account, not the synthesized one")
|
||||
}
|
||||
@@ -137,6 +137,19 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// accountForUnscopedIdentity gives an identity with no configured account a
|
||||
// distinct account id from its name, so account-less identities are not all
|
||||
// collapsed into the shared admin account for ownership/ACL checks.
|
||||
func accountForUnscopedIdentity(name string) *Account {
|
||||
if name == "" || name == AccountAdmin.Id {
|
||||
return &AccountAdmin
|
||||
}
|
||||
return &Account{
|
||||
Id: name,
|
||||
DisplayName: name,
|
||||
}
|
||||
}
|
||||
|
||||
type Credential struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
@@ -614,7 +627,18 @@ func (iam *IdentityAccessManagement) ReplaceS3ApiConfiguration(config *iam_pb.S3
|
||||
t.Account = &AccountAnonymous
|
||||
identityAnonymous = t
|
||||
case ident.Account == nil:
|
||||
t.Account = &AccountAdmin
|
||||
// Account-less identities own resources under a distinct id derived
|
||||
// from their name. Reuse an explicitly-configured account with that
|
||||
// id if one exists (preserving its display name/email); otherwise
|
||||
// synthesize one and register it so the id resolves via
|
||||
// GetAccountNameById (ACL grantee validation, owner display).
|
||||
synthesized := accountForUnscopedIdentity(t.Name)
|
||||
if existing, ok := accounts[synthesized.Id]; ok {
|
||||
t.Account = existing
|
||||
} else {
|
||||
t.Account = synthesized
|
||||
accounts[synthesized.Id] = synthesized
|
||||
}
|
||||
default:
|
||||
if account, ok := accounts[ident.Account.Id]; ok {
|
||||
t.Account = account
|
||||
@@ -833,7 +857,18 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap
|
||||
t.Account = &AccountAnonymous
|
||||
identityAnonymous = t
|
||||
case ident.Account == nil:
|
||||
t.Account = &AccountAdmin
|
||||
// Account-less identities own resources under a distinct id derived
|
||||
// from their name. Reuse an explicitly-configured account with that
|
||||
// id if one exists (preserving its display name/email); otherwise
|
||||
// synthesize one and register it so the id resolves via
|
||||
// GetAccountNameById (ACL grantee validation, owner display).
|
||||
synthesized := accountForUnscopedIdentity(t.Name)
|
||||
if existing, ok := accounts[synthesized.Id]; ok {
|
||||
t.Account = existing
|
||||
} else {
|
||||
t.Account = synthesized
|
||||
accounts[synthesized.Id] = synthesized
|
||||
}
|
||||
default:
|
||||
if account, ok := accounts[ident.Account.Id]; ok {
|
||||
t.Account = account
|
||||
|
||||
@@ -433,22 +433,22 @@ func (iam *IdentityAccessManagement) validateSTSSessionToken(r *http.Request, se
|
||||
claims[k] = v
|
||||
}
|
||||
|
||||
// Create an identity for the STS session
|
||||
// The identity represents the assumed role user
|
||||
// Key the principal on the OIDC subject so a session resolves to the same
|
||||
// identity on the SigV4 and JWT paths (see s3_iam_middleware.go); fall back to
|
||||
// the assumed-role user when absent. Distinct per principal, not shared admin.
|
||||
principal := sessionInfo.Subject
|
||||
if principal == "" {
|
||||
principal = sessionInfo.AssumedRoleUser
|
||||
}
|
||||
identity := &Identity{
|
||||
Name: sessionInfo.AssumedRoleUser, // Use the assumed role user as the identity name
|
||||
Account: &AccountAdmin, // STS sessions use admin account
|
||||
Name: principal,
|
||||
Account: &Account{Id: principal, DisplayName: sessionInfo.SessionName, EmailAddress: principal + "@seaweedfs.local"},
|
||||
Credentials: []*Credential{cred},
|
||||
PrincipalArn: sessionInfo.Principal,
|
||||
PolicyNames: sessionInfo.Policies, // Populate PolicyNames for IAM authorization
|
||||
Claims: claims, // Populate Claims for policy variable substitution
|
||||
}
|
||||
|
||||
// Restore admin privileges if the session was created by an admin
|
||||
// if isAdmin, ok := claims["is_admin"].(bool); ok && isAdmin {
|
||||
// identity.Actions = append(identity.Actions, s3_constants.ACTION_ADMIN)
|
||||
// }
|
||||
|
||||
glog.V(2).Infof("Successfully validated STS session token for principal: %s, assumed role user: %s",
|
||||
sessionInfo.Principal, sessionInfo.AssumedRoleUser)
|
||||
return identity, cred, s3err.ErrNone
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -14,11 +15,59 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// An STS session owns resources as its own principal (OIDC subject, or the
|
||||
// assumed-role user when absent), not the shared admin account.
|
||||
func TestValidateSTSSessionTokenAssignsDistinctAccount(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
subject string
|
||||
assumedRoleUser string
|
||||
wantPrincipal string
|
||||
}{
|
||||
{"prefers the subject", "alice", "ReadOnlyRole/alice", "alice"},
|
||||
{"falls back to the assumed-role user", "", "ReadOnlyRole/bob", "ReadOnlyRole/bob"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{
|
||||
iamIntegration: &MockIAMIntegration{
|
||||
validateSessionFunc: func(ctx context.Context, token string) (*sts.SessionInfo, error) {
|
||||
return &sts.SessionInfo{
|
||||
AssumedRoleUser: tc.assumedRoleUser,
|
||||
Principal: "arn:aws:sts:::assumed-role/" + tc.assumedRoleUser,
|
||||
Subject: tc.subject,
|
||||
SessionName: "sess",
|
||||
Credentials: &sts.Credentials{
|
||||
AccessKeyId: "AKIATEST",
|
||||
SecretAccessKey: "secret",
|
||||
},
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
Policies: []string{"ReadOnly"},
|
||||
}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://s3/test", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
identity, _, errCode := iam.validateSTSSessionToken(req, "session-token", "AKIATEST")
|
||||
require.Equal(t, s3err.ErrNone, errCode)
|
||||
require.NotNil(t, identity.Account)
|
||||
assert.Equal(t, tc.wantPrincipal, identity.Account.Id, "STS session owns resources as its principal")
|
||||
assert.Equal(t, tc.wantPrincipal, identity.Name)
|
||||
assert.NotEqual(t, AccountAdmin.Id, identity.Account.Id, "STS session must not share the admin account")
|
||||
assert.False(t, identity.isAdmin(), "an STS session has no admin action")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// MockIAMIntegration is a mock implementation of IAM integration for testing
|
||||
type MockIAMIntegration struct {
|
||||
authenticateJWTFunc func(ctx context.Context, r *http.Request) (*IAMIdentity, s3err.ErrorCode)
|
||||
authorizeFunc func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode
|
||||
validateTrustPolicyFunc func(ctx context.Context, roleArn, principalArn string) error
|
||||
validateSessionFunc func(ctx context.Context, token string) (*sts.SessionInfo, error)
|
||||
authCalled bool
|
||||
}
|
||||
|
||||
@@ -38,6 +87,9 @@ func (m *MockIAMIntegration) AuthenticateJWT(ctx context.Context, r *http.Reques
|
||||
}
|
||||
|
||||
func (m *MockIAMIntegration) ValidateSessionToken(ctx context.Context, token string) (*sts.SessionInfo, error) {
|
||||
if m.validateSessionFunc != nil {
|
||||
return m.validateSessionFunc(ctx, token)
|
||||
}
|
||||
return nil, nil // Not needed for these tests
|
||||
}
|
||||
|
||||
|
||||
@@ -138,6 +138,7 @@ func (s3a *S3ApiServer) enforceBucketQuotas(ctx context.Context, buckets []*file
|
||||
}
|
||||
locPrefix := s3a.option.BucketsPath + "/" + bucket.Name + "/"
|
||||
readOnly, flipped := fc.ApplyBucketQuotaReadOnly(locPrefix, size, float64(bucket.Quota))
|
||||
stats.UpdateBucketQuotaMetrics(bucket.Name, float64(bucket.Quota), readOnly)
|
||||
if flipped {
|
||||
changed = true
|
||||
glog.V(0).Infof("bucket %s quota enforcement: readOnly=%v (size=%.0f quota=%d)", bucket.Name, readOnly, size, bucket.Quota)
|
||||
|
||||
@@ -137,6 +137,48 @@ func TestCopySourceDecodingPlusSign(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCopySourceRejectsTraversal verifies `.`/`..` segments in a copy source
|
||||
// are rejected so the source stays within the parsed bucket.
|
||||
func TestCopySourceRejectsTraversal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
rawCopySource string
|
||||
wantErr bool
|
||||
}{
|
||||
{"clean source passes", "bucket-a/dir/key", false},
|
||||
{"leading slash source passes", "/bucket-a/dir/key", false},
|
||||
{"source with versionId passes", "bucket-a/dir/key?versionId=v1", false},
|
||||
|
||||
{"dotdot escapes bucket", "bucket-a/../bucket-secret/flag", true},
|
||||
{"leading slash dotdot escapes bucket", "/bucket-a/../bucket-secret/flag", true},
|
||||
{"percent-encoded dotdot escapes bucket", "bucket-a/%2e%2e/bucket-secret/flag", true},
|
||||
{"encoded slash dotdot escapes bucket", "bucket-a/..%2fbucket-secret/flag", true},
|
||||
{"backslash dotdot escapes bucket", "bucket-a/..\\bucket-secret/flag", true},
|
||||
{"nested dotdot escapes bucket", "bucket-a/dir/../../bucket-secret/flag", true},
|
||||
{"bare dot segment rejected", "bucket-a/./key", true},
|
||||
{"dotdot bucket rejected", "../bucket-secret/flag", true},
|
||||
{"dotdot with versionId escapes bucket", "bucket-a/../bucket-secret/flag?versionId=v1", true},
|
||||
{"versionId encoded slash rejected", "bucket-a/dir/key?versionId=v1%2F..%2Fsecret", true},
|
||||
{"versionId backslash rejected", "bucket-a/dir/key?versionId=v1%5C..%5Csecret", true},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cpSrcPath, err := url.PathUnescape(tc.rawCopySource)
|
||||
if err != nil {
|
||||
cpSrcPath = tc.rawCopySource
|
||||
}
|
||||
srcBucket, srcObject, srcVersionId := pathToBucketObjectAndVersion(tc.rawCopySource, cpSrcPath)
|
||||
|
||||
gotErr := validateCopySource(cpSrcPath, srcBucket, srcObject, srcVersionId) != nil
|
||||
if gotErr != tc.wantErr {
|
||||
t.Errorf("ValidateCopySource(%q) error = %v, want %v (parsed bucket=%q object=%q)",
|
||||
tc.rawCopySource, gotErr, tc.wantErr, srcBucket, srcObject)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCopySourceRoutingWithSpecialChars tests that mux variable extraction
|
||||
// correctly handles special characters like ! (%21) in both the URL path
|
||||
// and the X-Amz-Copy-Source header.
|
||||
|
||||
@@ -1313,6 +1313,15 @@ func checksumAlgorithmFromHeaderName(headerName string) ChecksumAlgorithm {
|
||||
return ChecksumAlgorithmNone
|
||||
}
|
||||
|
||||
func checksumAlgorithmNameFromHeaderName(headerName string) string {
|
||||
for name, entry := range checksumAlgorithmMapping {
|
||||
if entry.name == headerName {
|
||||
return name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getEtagFromEntry(entry *filer_pb.Entry) string {
|
||||
if entry.Extended != nil {
|
||||
if etagBytes, ok := entry.Extended[s3_constants.ExtETagKey]; ok {
|
||||
|
||||
@@ -175,6 +175,18 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// location/name are client-supplied; confine the metadata write to the
|
||||
// authorized catalog bucket and reject traversal segments so path.Join in
|
||||
// saveMetadataFile cannot escape into another bucket.
|
||||
if metadataBucket != bucketName {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "table location must be within bucket "+bucketName)
|
||||
return
|
||||
}
|
||||
if !isValidTablePath(metadataPath) {
|
||||
writeError(w, http.StatusBadRequest, "BadRequestException", "invalid table location path")
|
||||
return
|
||||
}
|
||||
|
||||
// Authoritative existence check: ask the catalog whether a table is registered
|
||||
// at this name. If it is, short-circuit with the existing table (idempotent
|
||||
// CreateTable). Any leftover objects at the target path from a previous
|
||||
|
||||
@@ -56,6 +56,21 @@ func validateRequestPath(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// isValidTablePath reports whether a "/"-separated table path (the part below
|
||||
// the bucket) is free of segments that path.Join would collapse to escape the
|
||||
// bucket directory. Empty segments (from leading/duplicate slashes) are ignored.
|
||||
func isValidTablePath(tablePath string) bool {
|
||||
for _, segment := range strings.Split(tablePath, "/") {
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
if !isValidNameSegment(segment) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isValidNameSegment rejects a single path-segment value (bucket prefix slot,
|
||||
// table name, or one namespace part) that would be unsafe to embed in a filer
|
||||
// path: `.`, `..`, embedded slash/backslash, or NUL.
|
||||
|
||||
@@ -8,6 +8,27 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func TestIsValidTablePath(t *testing.T) {
|
||||
tests := []struct {
|
||||
tablePath string
|
||||
want bool
|
||||
}{
|
||||
{"sales.orders", true},
|
||||
{"ns/table", true},
|
||||
{"ns//table", true},
|
||||
{"", true},
|
||||
{"../other", false},
|
||||
{"ns/../../etc", false},
|
||||
{"ns/./x", false},
|
||||
{`ns\..\x`, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := isValidTablePath(tt.tablePath); got != tt.want {
|
||||
t.Errorf("isValidTablePath(%q) = %v, want %v", tt.tablePath, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequestPath_RejectsTraversal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -46,6 +46,13 @@ type Server struct {
|
||||
// NewServer creates a new Iceberg REST Catalog server.
|
||||
func NewServer(filerClient FilerClient, authenticator S3Authenticator) *Server {
|
||||
manager := s3tables.NewManager()
|
||||
// Mirror the S3 port: fall open by default only when the gateway itself is
|
||||
// open. With auth configured, an authenticated catalog caller must pass the
|
||||
// normal permission check instead of being allowed because no policy denied
|
||||
// it — even if the full identity struct ever fails to reach the handler.
|
||||
if authenticator != nil {
|
||||
manager.SetDefaultAllow(authenticator.DefaultAllow())
|
||||
}
|
||||
return &Server{
|
||||
filerClient: filerClient,
|
||||
tablesManager: manager,
|
||||
|
||||
@@ -212,6 +212,16 @@ func IsValidBucketName(bucket string) bool {
|
||||
return !strings.ContainsAny(bucket, "/\\\x00")
|
||||
}
|
||||
|
||||
// IsValidPathSegment reports whether value is safe to use as one filer path
|
||||
// component. It intentionally does not enforce any application-specific
|
||||
// format; callers can layer stricter checks on top.
|
||||
func IsValidPathSegment(value string) bool {
|
||||
if value == "" || value == "." || value == ".." {
|
||||
return false
|
||||
}
|
||||
return !strings.ContainsAny(value, "/\\\x00")
|
||||
}
|
||||
|
||||
// NormalizeObjectKey normalizes object keys by removing duplicate slashes and converting backslashes.
|
||||
// This normalizes keys from various sources (URL path, form values, etc.) to a consistent format.
|
||||
// It also converts Windows-style backslashes to forward slashes for cross-platform compatibility.
|
||||
|
||||
@@ -148,6 +148,29 @@ func TestIsValidBucketName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidPathSegment(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{"opaque-id_123", true},
|
||||
{"..hidden", true},
|
||||
{"", false},
|
||||
{".", false},
|
||||
{"..", false},
|
||||
{"dir/value", false},
|
||||
{"dir\\value", false},
|
||||
{"nul\x00value", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
if got := IsValidPathSegment(tt.input); got != tt.want {
|
||||
t.Errorf("IsValidPathSegment(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveDuplicateSlashes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -21,8 +21,12 @@ func (s3a *S3ApiServer) checkAccessByOwnership(r *http.Request, bucket string) s
|
||||
if errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
// Admin by capability, not account id: account-less identities share the "admin" id.
|
||||
if s3a.isUserAdmin(r) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
accountId := getAccountId(r)
|
||||
if accountId == AccountAdmin.Id || accountId == *metadata.Owner.ID {
|
||||
if metadata.Owner != nil && metadata.Owner.ID != nil && accountId == *metadata.Owner.ID {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return s3err.ErrAccessDenied
|
||||
|
||||
@@ -672,6 +672,16 @@ func (s3a *S3ApiServer) hasAccess(r *http.Request, entry *filer_pb.Entry) bool {
|
||||
// isUserAdmin securely checks if the authenticated user is an admin
|
||||
// This validates admin status through proper IAM authentication, not spoofable headers
|
||||
func (s3a *S3ApiServer) isUserAdmin(r *http.Request) bool {
|
||||
// Reuse the identity the Auth middleware stored; re-authenticating here would
|
||||
// fail once the request body has been read.
|
||||
if identityObj := s3_constants.GetIdentityFromContext(r); identityObj != nil {
|
||||
if identity, ok := identityObj.(*Identity); ok {
|
||||
return identity != nil && identity.isAdmin()
|
||||
}
|
||||
}
|
||||
if s3a.iam == nil {
|
||||
return false
|
||||
}
|
||||
// Use a minimal admin action to authenticate and check admin status
|
||||
adminAction := Action("Admin")
|
||||
identity, errCode := s3a.iam.authRequest(r, adminAction)
|
||||
|
||||
@@ -242,8 +242,12 @@ func validateEncryptionContext(contextHeader string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCopySource validates the copy source path and permissions
|
||||
// ValidateCopySource validates the copy source path.
|
||||
func ValidateCopySource(copySource string, srcBucket, srcObject string) error {
|
||||
return validateCopySource(copySource, srcBucket, srcObject, "")
|
||||
}
|
||||
|
||||
func validateCopySource(copySource string, srcBucket, srcObject, srcVersionId string) error {
|
||||
if copySource == "" {
|
||||
return &CopyValidationError{
|
||||
Code: s3err.ErrInvalidCopySource,
|
||||
@@ -265,6 +269,21 @@ func ValidateCopySource(copySource string, srcBucket, srcObject string) error {
|
||||
}
|
||||
}
|
||||
|
||||
// `.`/`..` segments are collapsed by the filer's path join; reject them as
|
||||
// IsValidObjectKey does for the request URL so the source stays in-bucket.
|
||||
if !s3_constants.IsValidBucketName(srcBucket) || !s3_constants.IsValidObjectKey(srcObject) {
|
||||
return &CopyValidationError{
|
||||
Code: s3err.ErrInvalidCopySource,
|
||||
Message: "Copy source contains invalid path segments",
|
||||
}
|
||||
}
|
||||
if !isValidVersionID(srcVersionId) {
|
||||
return &CopyValidationError{
|
||||
Code: s3err.ErrInvalidCopySource,
|
||||
Message: "Copy source contains an invalid version ID",
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCheckUploadIDRequiresGeneratedFormat(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
const object = "dir/object"
|
||||
hash := s3a.generateUploadID(object)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
uploadID string
|
||||
wantErr bool
|
||||
}{
|
||||
{"legacy hash", hash, false},
|
||||
{"current format", hash + "_" + strings.Repeat("a", 32), false},
|
||||
{"wrong object hash", strings.Repeat("0", 40) + "_" + strings.Repeat("a", 32), true},
|
||||
{"arbitrary suffix", hash + "_suffix", true},
|
||||
{"uppercase suffix", hash + "_" + strings.Repeat("A", 32), true},
|
||||
{"short suffix", hash + "_" + strings.Repeat("a", 31), true},
|
||||
{"long suffix", hash + "_" + strings.Repeat("a", 33), true},
|
||||
{"slash traversal", hash + "/../../../victim-bucket", true},
|
||||
{"suffix traversal", hash + "_" + strings.Repeat("a", 32) + "/../../../victim-bucket", true},
|
||||
{"backslash traversal", hash + `\..\..\victim-bucket`, true},
|
||||
{"nul suffix", hash + "_abc\x00def", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotErr := s3a.checkUploadId(object, tt.uploadID) != nil
|
||||
if gotErr != tt.wantErr {
|
||||
t.Errorf("checkUploadId(%q) error = %v, want %v", tt.uploadID, gotErr, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
|
||||
// Validate copy source and destination
|
||||
if err := ValidateCopySource(cpSrcPath, srcBucket, srcObject); err != nil {
|
||||
if err := validateCopySource(cpSrcPath, srcBucket, srcObject, srcVersionId); err != nil {
|
||||
glog.V(2).Infof("CopyObjectHandler validation error: %v", err)
|
||||
errCode := MapCopyValidationError(err)
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -713,8 +713,33 @@ func pathToBucketObjectAndVersion(rawPath, decodedPath string) (bucket, object,
|
||||
}
|
||||
|
||||
type CopyPartResult struct {
|
||||
LastModified time.Time `xml:"LastModified"`
|
||||
ETag string `xml:"ETag"`
|
||||
LastModified time.Time `xml:"LastModified"`
|
||||
ETag string `xml:"ETag"`
|
||||
ChecksumCRC32 string `xml:"ChecksumCRC32,omitempty"`
|
||||
ChecksumCRC32C string `xml:"ChecksumCRC32C,omitempty"`
|
||||
ChecksumCRC64NVME string `xml:"ChecksumCRC64NVME,omitempty"`
|
||||
ChecksumSHA1 string `xml:"ChecksumSHA1,omitempty"`
|
||||
ChecksumSHA256 string `xml:"ChecksumSHA256,omitempty"`
|
||||
}
|
||||
|
||||
func buildCopyPartResult(etag string, lastModified time.Time, metadata SSEResponseMetadata) CopyPartResult {
|
||||
result := CopyPartResult{
|
||||
ETag: etag,
|
||||
LastModified: lastModified,
|
||||
}
|
||||
switch metadata.ChecksumHeaderName {
|
||||
case s3_constants.AmzChecksumCRC32:
|
||||
result.ChecksumCRC32 = metadata.ChecksumValue
|
||||
case s3_constants.AmzChecksumCRC32C:
|
||||
result.ChecksumCRC32C = metadata.ChecksumValue
|
||||
case s3_constants.AmzChecksumCRC64NVME:
|
||||
result.ChecksumCRC64NVME = metadata.ChecksumValue
|
||||
case s3_constants.AmzChecksumSHA1:
|
||||
result.ChecksumSHA1 = metadata.ChecksumValue
|
||||
case s3_constants.AmzChecksumSHA256:
|
||||
result.ChecksumSHA256 = metadata.ChecksumValue
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// copyPartLocation returns the destination directory and filename for a
|
||||
@@ -764,12 +789,10 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
}
|
||||
|
||||
// If source object is empty or bucket is empty, reply back invalid copy source.
|
||||
// Note: srcObject can be "/" for root-level objects, but empty string means parsing failed
|
||||
if srcObject == "" || srcBucket == "" {
|
||||
glog.Errorf("CopyObjectPart: Invalid copy source - srcBucket=%q, srcObject=%q (original header: %q)",
|
||||
srcBucket, srcObject, r.Header.Get("X-Amz-Copy-Source"))
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
|
||||
// Validate the copy source as CopyObject does.
|
||||
if err := validateCopySource(cpSrcPath, srcBucket, srcObject, srcVersionId); err != nil {
|
||||
glog.V(2).Infof("CopyObjectPartHandler validation error: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, MapCopyValidationError(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -908,7 +931,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
|
||||
if uploadEntryHasSSE(uploadEntry) || sourceEntryHasSSE(entry) {
|
||||
if uploadEntryHasSSE(uploadEntry) || sourceEntryHasSSE(entry) || uploadEntryHasChecksum(uploadEntry) {
|
||||
etag, sseMetadata, errCode := s3a.copyObjectPartViaReencryption(r, entry, startOffset, endOffset, dstBucket, uploadID, partID, uploadEntry)
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
@@ -919,10 +942,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
// x-amz-server-side-encryption-aws-kms-key-id headers on the response
|
||||
// so clients can see the destination's encryption state.
|
||||
s3a.setSSEResponseHeaders(w, r, sseMetadata)
|
||||
writeSuccessResponseXML(w, r, CopyPartResult{
|
||||
ETag: etag,
|
||||
LastModified: t,
|
||||
})
|
||||
writeSuccessResponseXML(w, r, buildCopyPartResult(etag, t, sseMetadata))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -992,12 +1012,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
etag := copyEntryETag(dstEntry)
|
||||
setEtag(w, etag)
|
||||
|
||||
response := CopyPartResult{
|
||||
ETag: etag,
|
||||
LastModified: t,
|
||||
}
|
||||
|
||||
writeSuccessResponseXML(w, r, response)
|
||||
writeSuccessResponseXML(w, r, buildCopyPartResult(etag, t, SSEResponseMetadata{}))
|
||||
}
|
||||
|
||||
func replaceDirective(reqHeader http.Header) (replaceMeta, replaceTagging bool) {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func TestApplyDestChecksumHeaderToCopyRequest(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte(s3_constants.AmzChecksumCRC64NVME),
|
||||
}}
|
||||
request := httptest.NewRequest(http.MethodPut, "http://example.com/bucket/object", nil)
|
||||
|
||||
applyDestChecksumHeaderToCopyRequest(request, entry)
|
||||
|
||||
algorithm, headerName, errCode := detectRequestedChecksumAlgorithm(request)
|
||||
if errCode != s3err.ErrNone {
|
||||
t.Fatalf("detect checksum returned %v", errCode)
|
||||
}
|
||||
if algorithm != ChecksumAlgorithmCRC64NVMe {
|
||||
t.Fatalf("algorithm = %v, want %v", algorithm, ChecksumAlgorithmCRC64NVMe)
|
||||
}
|
||||
if headerName != s3_constants.AmzChecksumCRC64NVME {
|
||||
t.Fatalf("header = %q, want %q", headerName, s3_constants.AmzChecksumCRC64NVME)
|
||||
}
|
||||
|
||||
for _, noChecksum := range []*filer_pb.Entry{
|
||||
nil,
|
||||
{},
|
||||
{Extended: map[string][]byte{s3_constants.ExtChecksumAlgorithm: []byte("unknown")}},
|
||||
} {
|
||||
req := httptest.NewRequest(http.MethodPut, "http://example.com/bucket/object", nil)
|
||||
applyDestChecksumHeaderToCopyRequest(req, noChecksum)
|
||||
if got := req.Header.Get(s3_constants.AmzChecksumAlgorithm); got != "" {
|
||||
t.Fatalf("expected no checksum header, got %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadEntryHasChecksum(t *testing.T) {
|
||||
entry := &filer_pb.Entry{Extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte(s3_constants.AmzChecksumCRC64NVME),
|
||||
}}
|
||||
if !uploadEntryHasChecksum(entry) {
|
||||
t.Fatal("checksum-enabled upload was not detected")
|
||||
}
|
||||
|
||||
entry.Extended[s3_constants.ExtChecksumAlgorithm] = []byte("unknown")
|
||||
if uploadEntryHasChecksum(entry) {
|
||||
t.Fatal("unknown checksum algorithm was accepted")
|
||||
}
|
||||
|
||||
if uploadEntryHasChecksum(nil) || uploadEntryHasChecksum(&filer_pb.Entry{}) {
|
||||
t.Fatal("nil entry or nil Extended map reported a checksum")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildCopyPartResult(t *testing.T) {
|
||||
modified := time.Unix(123, 0).UTC()
|
||||
tests := []struct {
|
||||
name string
|
||||
header string
|
||||
element string
|
||||
expected CopyPartResult
|
||||
}{
|
||||
{
|
||||
name: "CRC32",
|
||||
header: s3_constants.AmzChecksumCRC32,
|
||||
element: "<ChecksumCRC32>value</ChecksumCRC32>",
|
||||
expected: CopyPartResult{
|
||||
ETag: "etag", LastModified: modified, ChecksumCRC32: "value",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "CRC32C",
|
||||
header: s3_constants.AmzChecksumCRC32C,
|
||||
element: "<ChecksumCRC32C>value</ChecksumCRC32C>",
|
||||
expected: CopyPartResult{
|
||||
ETag: "etag", LastModified: modified, ChecksumCRC32C: "value",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "CRC64NVME",
|
||||
header: s3_constants.AmzChecksumCRC64NVME,
|
||||
element: "<ChecksumCRC64NVME>value</ChecksumCRC64NVME>",
|
||||
expected: CopyPartResult{
|
||||
ETag: "etag", LastModified: modified, ChecksumCRC64NVME: "value",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "SHA1",
|
||||
header: s3_constants.AmzChecksumSHA1,
|
||||
element: "<ChecksumSHA1>value</ChecksumSHA1>",
|
||||
expected: CopyPartResult{
|
||||
ETag: "etag", LastModified: modified, ChecksumSHA1: "value",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "SHA256",
|
||||
header: s3_constants.AmzChecksumSHA256,
|
||||
element: "<ChecksumSHA256>value</ChecksumSHA256>",
|
||||
expected: CopyPartResult{
|
||||
ETag: "etag", LastModified: modified, ChecksumSHA256: "value",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Unknown",
|
||||
header: "x-amz-checksum-unknown",
|
||||
element: "",
|
||||
expected: CopyPartResult{ETag: "etag", LastModified: modified},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
result := buildCopyPartResult("etag", modified, SSEResponseMetadata{
|
||||
ChecksumHeaderName: test.header,
|
||||
ChecksumValue: "value",
|
||||
})
|
||||
if result != test.expected {
|
||||
t.Fatalf("result = %#v, want %#v", result, test.expected)
|
||||
}
|
||||
if encoded := string(s3err.EncodeXMLResponse(result)); test.element != "" && !strings.Contains(encoded, test.element) {
|
||||
t.Fatalf("response %q does not contain %q", encoded, test.element)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,14 @@ func uploadEntryHasSSE(uploadEntry *filer_pb.Entry) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func uploadEntryHasChecksum(uploadEntry *filer_pb.Entry) bool {
|
||||
if uploadEntry == nil || uploadEntry.Extended == nil {
|
||||
return false
|
||||
}
|
||||
headerName := string(uploadEntry.Extended[s3_constants.ExtChecksumAlgorithm])
|
||||
return checksumAlgorithmFromHeaderName(headerName) != ChecksumAlgorithmNone
|
||||
}
|
||||
|
||||
// sourceEntryHasSSE reports whether the source object's chunks are SSE
|
||||
// ciphertext on disk and therefore cannot be raw-copied — they must be
|
||||
// decrypted on read.
|
||||
@@ -315,10 +323,18 @@ func (s3a *S3ApiServer) applyDestSSEHeadersToCopyRequest(
|
||||
return s3a.handleSSES3MultipartHeaders(r, uploadEntry, uploadID)
|
||||
}
|
||||
|
||||
// fakeContentRequest builds a minimal request representing "PUT this body" for
|
||||
// the multipart-part write path used by UploadPartCopy. It clones the original
|
||||
// request's headers (so things like AmzAccountId carry over) and clears the
|
||||
// copy-only headers; SSE setup is added later by applyDestSSEHeadersToCopyRequest.
|
||||
func applyDestChecksumHeaderToCopyRequest(r *http.Request, uploadEntry *filer_pb.Entry) {
|
||||
if uploadEntry == nil || uploadEntry.Extended == nil {
|
||||
return
|
||||
}
|
||||
headerName := string(uploadEntry.Extended[s3_constants.ExtChecksumAlgorithm])
|
||||
if algorithm := checksumAlgorithmNameFromHeaderName(headerName); algorithm != "" {
|
||||
// Drop any inherited sdk-checksum selector; it outranks the header we set.
|
||||
r.Header.Del(s3_constants.AmzSdkChecksumAlgorithm)
|
||||
r.Header.Set(s3_constants.AmzChecksumAlgorithm, algorithm)
|
||||
}
|
||||
}
|
||||
|
||||
func fakeContentRequest(orig *http.Request, body io.ReadCloser, contentLength int64) *http.Request {
|
||||
cloned := orig.Clone(orig.Context())
|
||||
cloned.Body = body
|
||||
@@ -339,22 +355,11 @@ func fakeContentRequest(orig *http.Request, body io.ReadCloser, contentLength in
|
||||
return cloned
|
||||
}
|
||||
|
||||
// copyObjectPartViaReencryption implements the slow path of UploadPartCopy when
|
||||
// either the source object is SSE-encrypted or the destination multipart upload
|
||||
// is configured for SSE encryption. It:
|
||||
//
|
||||
// 1. Opens a plaintext reader of the source range (decrypting if needed).
|
||||
// 2. Stages the destination's SSE-S3 / SSE-KMS multipart headers on a cloned
|
||||
// request so handleAllSSEEncryption (called from putToFiler) routes the
|
||||
// body through the matching multipart-encryption helper.
|
||||
// 3. Calls putToFiler with the plaintext reader, which encrypts using the
|
||||
// destination upload session's key+baseIV (consistent with PutObjectPart),
|
||||
// auto-chunks, and writes the part entry with proper per-chunk SSE metadata.
|
||||
//
|
||||
// Without this path, copyChunksForRange's raw byte copy leaves destination
|
||||
// chunks SseType=NONE; completedMultipartChunk then "backfills" SSE-S3 metadata
|
||||
// with destination-baseIV-derived IVs, but the bytes on disk were encrypted
|
||||
// with the source's key — yielding deterministic byte corruption on GET (#8908).
|
||||
// copyObjectPartViaReencryption is the UploadPartCopy slow path: it re-streams the
|
||||
// source range through putToFiler so the destination's SSE re-encryption and/or
|
||||
// requested checksum are produced on write. A raw chunk copy can't: it would leave
|
||||
// dest chunks under the source key (corrupt GET) and parts with no checksum
|
||||
// (completion fails).
|
||||
func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
r *http.Request,
|
||||
srcEntry *filer_pb.Entry,
|
||||
@@ -363,11 +368,14 @@ func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
partID int,
|
||||
uploadEntry *filer_pb.Entry,
|
||||
) (etag string, sseMetadata SSEResponseMetadata, errCode s3err.ErrorCode) {
|
||||
if endOffset < startOffset {
|
||||
if endOffset < startOffset && !uploadEntryHasChecksum(uploadEntry) {
|
||||
tag, code := s3a.writeEmptyCopyPart(dstBucket, uploadID, partID)
|
||||
return tag, SSEResponseMetadata{}, code
|
||||
}
|
||||
sliceLen := endOffset - startOffset + 1
|
||||
sliceLen := int64(0)
|
||||
if endOffset >= startOffset {
|
||||
sliceLen = endOffset - startOffset + 1
|
||||
}
|
||||
|
||||
srcReader, err := s3a.openSourcePlaintextReader(r.Context(), srcEntry, startOffset, endOffset)
|
||||
if err != nil {
|
||||
@@ -388,15 +396,9 @@ func (s3a *S3ApiServer) copyObjectPartViaReencryption(
|
||||
glog.Errorf("UploadPartCopy: apply destination SSE headers: %v", err)
|
||||
return "", SSEResponseMetadata{}, s3err.ErrInternalError
|
||||
}
|
||||
applyDestChecksumHeaderToCopyRequest(cloned, uploadEntry)
|
||||
|
||||
// Surface putToFiler's SSE response metadata to the caller so the handler
|
||||
// can mirror PutObjectPart's behavior of writing
|
||||
// x-amz-server-side-encryption / x-amz-server-side-encryption-aws-kms-key-id
|
||||
// on the UploadPartCopy response. Without this, clients have no way to
|
||||
// see that the destination was encrypted.
|
||||
filePath := s3a.genPartUploadPath(dstBucket, uploadID, partID)
|
||||
// Copy-part is an MPU part write under .uploads/<id>/<n>; lifecycle
|
||||
// TTL only applies to the eventual completed object. Pass 0.
|
||||
tag, code, putSSE := s3a.putToFiler(cloned, filePath, srcReader, dstBucket, "", partID, 0, nil, false)
|
||||
if code != s3err.ErrNone {
|
||||
return "", SSEResponseMetadata{}, code
|
||||
|
||||
@@ -34,6 +34,13 @@ func deleteErrorFromCode(code s3err.ErrorCode, key, versionId string) DeleteErro
|
||||
}
|
||||
}
|
||||
|
||||
func validateDeleteObjectIdentifier(object ObjectIdentifier) s3err.ErrorCode {
|
||||
if !s3_constants.IsValidObjectKey(object.Key) || !isValidVersionID(object.VersionId) {
|
||||
return s3err.ErrInvalidRequest
|
||||
}
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
// isMissingDeleteConditionTarget normalizes missing-target detection for conditional deletes.
|
||||
// Prefer errors.Is(err, filer_pb.ErrNotFound) and errors.Is(err, ErrDeleteMarker); keep the
|
||||
// string-based fallback only as a defensive bridge for filer paths that still return plain text.
|
||||
@@ -50,6 +57,9 @@ func isMissingDeleteConditionTarget(err error) bool {
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) resolveDeleteConditionalEntry(bucket, object, versionId, versioningState string) (*filer_pb.Entry, error) {
|
||||
if !isValidVersionID(versionId) {
|
||||
return nil, errInvalidVersionID
|
||||
}
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
|
||||
@@ -173,6 +183,9 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
// when the entry's Attributes.TtlSec > 0 so the volume is guaranteed to
|
||||
// drop the chunks on its own.
|
||||
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string, metadataOnly bool) error {
|
||||
if !s3_constants.IsValidBucketName(bucket) || !s3_constants.IsValidObjectKey(object) {
|
||||
return errors.New("invalid bucket or object path")
|
||||
}
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object)
|
||||
dir, name := target.DirAndName()
|
||||
return deleteObjectEntry(client, dir, name, !metadataOnly, false)
|
||||
@@ -423,6 +436,10 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
if object.Key == "" {
|
||||
continue
|
||||
}
|
||||
if validationCode := validateDeleteObjectIdentifier(object); validationCode != s3err.ErrNone {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(validationCode, object.Key, object.VersionId))
|
||||
continue
|
||||
}
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object.Key); err != nil {
|
||||
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrAccessDenied, object.Key, object.VersionId))
|
||||
continue
|
||||
|
||||
@@ -1,13 +1,45 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateDeleteObjectIdentifier(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
identifier ObjectIdentifier
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"clean key", ObjectIdentifier{Key: "dir/key"}, s3err.ErrNone},
|
||||
{"clean version", ObjectIdentifier{Key: "dir/key", VersionId: "opaque-version"}, s3err.ErrNone},
|
||||
{"key traversal", ObjectIdentifier{Key: "../victim/key"}, s3err.ErrInvalidRequest},
|
||||
{"encoded traversal already decoded", ObjectIdentifier{Key: "dir/../../victim/key"}, s3err.ErrInvalidRequest},
|
||||
{"backslash traversal", ObjectIdentifier{Key: `..\victim\key`}, s3err.ErrInvalidRequest},
|
||||
{"version traversal", ObjectIdentifier{Key: "key", VersionId: "v1/../../../victim"}, s3err.ErrInvalidRequest},
|
||||
{"version backslash", ObjectIdentifier{Key: "key", VersionId: `v1\..\victim`}, s3err.ErrInvalidRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, validateDeleteObjectIdentifier(tt.identifier))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSpecificObjectVersionRejectsUnsafeVersionID(t *testing.T) {
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
|
||||
_, err := s3a.getSpecificObjectVersion("bucket", "key", "v1/../../../victim")
|
||||
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, errInvalidVersionID))
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_MetadataOnlySkipsChunkDelete(t *testing.T) {
|
||||
// metadataOnly=true must reach the filer as IsDeleteData=false so the
|
||||
// volume server reclaims chunks via TTL instead of the filer enqueueing
|
||||
@@ -50,6 +82,16 @@ func TestDeleteUnversionedObjectWithClient_FullPathFromBucketsRoot(t *testing.T)
|
||||
assert.Equal(t, "c.txt", client.deleteReq.Name)
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClientRejectsTraversal(t *testing.T) {
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
client := &deleteObjectEntryTestClient{}
|
||||
|
||||
err := s3a.deleteUnversionedObjectWithClient(client, "source-bucket", "../victim-bucket/secret", false)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, client.deleteReq, "invalid path must be rejected before a filer delete RPC")
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_PropagatesEntryAttributesIrrelevant(t *testing.T) {
|
||||
// The metadataOnly decision is the caller's responsibility (the
|
||||
// lifecycle handler). This function is dumb plumbing — it must not
|
||||
|
||||
@@ -521,13 +521,32 @@ func (s3a *S3ApiServer) checkUploadId(object string, id string) error {
|
||||
|
||||
hash := s3a.generateUploadID(object)
|
||||
|
||||
if !strings.HasPrefix(id, hash) {
|
||||
// uploadID becomes a filer directory name. Accept the historical hash-only
|
||||
// form and the exact current hash_UUID form, not arbitrary hash-prefixed paths.
|
||||
valid := id == hash // legacy upload IDs generated before the UUID suffix was added
|
||||
if len(id) == len(hash)+1+32 && strings.HasPrefix(id, hash+"_") {
|
||||
valid = isLowerHex(id[len(hash)+1:])
|
||||
}
|
||||
if !valid {
|
||||
glog.Errorf("object %s and uploadID %s are not matched", object, id)
|
||||
return fmt.Errorf("object %s and uploadID %s are not matched", object, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isLowerHex(value string) bool {
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Parse bucket url queries for ?uploads
|
||||
func getBucketMultipartResources(values url.Values) (prefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int, encodingType string) {
|
||||
prefix = values.Get("prefix")
|
||||
|
||||
@@ -56,7 +56,12 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
|
||||
if fileName != "" && strings.Contains(formValues.Get("Key"), "${filename}") {
|
||||
formValues.Set("Key", strings.Replace(formValues.Get("Key"), "${filename}", fileName, -1))
|
||||
}
|
||||
object := s3_constants.NormalizeObjectKey(formValues.Get("Key"))
|
||||
rawObject := formValues.Get("Key")
|
||||
if rawObject == "" || !s3_constants.IsValidObjectKey(rawObject) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
object := s3_constants.NormalizeObjectKey(rawObject)
|
||||
if err := s3a.validateTableBucketObjectPath(bucket, object); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
|
||||
return
|
||||
|
||||
@@ -555,6 +555,32 @@ func TestPostPolicyBucketHandlerKeyExtraction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostPolicyBucketHandlerRejectsTraversalKey(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
assert.NoError(t, writer.WriteField("key", "uploads/../../victim-bucket/secret"))
|
||||
assert.NoError(t, writer.WriteField("Policy", ""))
|
||||
part, err := writer.CreateFormFile("file", "payload.txt")
|
||||
assert.NoError(t, err)
|
||||
_, err = part.Write([]byte("secret"))
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, writer.Close())
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/source-bucket", &buf)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "source-bucket"})
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{BucketsPath: "/buckets"},
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
s3a.PostPolicyBucketHandler(rec, req)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
assert.Contains(t, rec.Body.String(), "InvalidRequest")
|
||||
}
|
||||
|
||||
// TestPostPolicyBucketHandler_PolicyViolationReturns403 drives the handler
|
||||
// end-to-end with a signed multipart POST whose policy conditions cannot be
|
||||
// satisfied by the form fields. It verifies the handler responds 403
|
||||
|
||||
@@ -371,6 +371,9 @@ type putFinalize struct {
|
||||
// targets and a part write would otherwise bind a TTL clock starting
|
||||
// before CompleteMultipartUpload.
|
||||
func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader io.Reader, bucket string, object string, partNumber int, lifecycleTTLSec int32, finalize *putFinalize, uniqueWritePath bool) (etag string, code s3err.ErrorCode, sseMetadata SSEResponseMetadata) {
|
||||
if !s3_constants.IsValidBucketName(bucket) || (object != "" && !s3_constants.IsValidObjectKey(object)) {
|
||||
return "", s3err.ErrInvalidRequest, SSEResponseMetadata{}
|
||||
}
|
||||
// NEW OPTIMIZATION: Write directly to volume servers, bypassing filer proxy
|
||||
// This eliminates the filer proxy overhead for PUT operations
|
||||
// Note: filePath is now passed directly instead of URL (no parsing needed)
|
||||
|
||||
@@ -112,6 +112,9 @@ func wormDeleteCondition(worm, bypass bool) *filer_pb.WriteCondition {
|
||||
// object (serializing the pointer recompute); for object-lock buckets the
|
||||
// condition gates the delete on the version's WORM guards evaluated on the owner.
|
||||
func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, bucket, object, versionId string, worm, bypass bool) s3err.ErrorCode {
|
||||
if !isValidVersionID(versionId) {
|
||||
return s3err.ErrInvalidRequest
|
||||
}
|
||||
versionFileName := s3a.getVersionFileName(versionId)
|
||||
versionsPath := s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder)
|
||||
cond := wormDeleteCondition(worm, bypass)
|
||||
|
||||
@@ -1033,6 +1033,9 @@ func (s3a *S3ApiServer) calculateETagFromChunks(chunks []*filer_pb.FileChunk) st
|
||||
|
||||
// getSpecificObjectVersion retrieves a specific version of an object
|
||||
func (s3a *S3ApiServer) getSpecificObjectVersion(bucket, object, versionId string) (*filer_pb.Entry, error) {
|
||||
if !isValidVersionID(versionId) {
|
||||
return nil, errInvalidVersionID
|
||||
}
|
||||
// Normalize object path to ensure consistency with toFilerPath behavior
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
|
||||
@@ -1068,6 +1071,9 @@ func (s3a *S3ApiServer) getSpecificObjectVersion(bucket, object, versionId strin
|
||||
// pass true when the live entry's Attributes.TtlSec > 0 so the volume
|
||||
// reclaims chunks on its own.
|
||||
func (s3a *S3ApiServer) deleteSpecificObjectVersion(ctx context.Context, bucket, object, versionId string, metadataOnly bool) error {
|
||||
if !isValidVersionID(versionId) {
|
||||
return errInvalidVersionID
|
||||
}
|
||||
// Normalize object path to ensure consistency with toFilerPath behavior
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
|
||||
|
||||
@@ -2,12 +2,52 @@ package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func hasPathSegmentQuery(rawQuery string) bool {
|
||||
if strings.Contains(rawQuery, "versionId") || strings.Contains(rawQuery, "uploadId") {
|
||||
return true
|
||||
}
|
||||
if !strings.Contains(rawQuery, "%") {
|
||||
return false
|
||||
}
|
||||
|
||||
for rawQuery != "" {
|
||||
field := rawQuery
|
||||
if i := strings.IndexByte(rawQuery, '&'); i >= 0 {
|
||||
field, rawQuery = rawQuery[:i], rawQuery[i+1:]
|
||||
} else {
|
||||
rawQuery = ""
|
||||
}
|
||||
if i := strings.IndexByte(field, '='); i >= 0 {
|
||||
field = field[:i]
|
||||
}
|
||||
if !strings.Contains(field, "%") {
|
||||
continue
|
||||
}
|
||||
key, err := url.QueryUnescape(field)
|
||||
if err == nil && (key == "versionId" || key == "uploadId") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hasInvalidPathSegment(values []string) bool {
|
||||
for _, value := range values {
|
||||
if value != "" && !s3_constants.IsValidPathSegment(value) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// validateRequestPath rejects requests whose captured {bucket}/{object} mux
|
||||
// vars would normalize to a parent-directory traversal once joined into a
|
||||
// filer path. The router runs with mux.NewRouter().SkipClean(true), so
|
||||
@@ -33,6 +73,15 @@ func validateRequestPath(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
}
|
||||
// versionId and uploadId are later used as filer entry names. Avoid
|
||||
// parsing every request's query while still recognizing encoded names.
|
||||
if hasPathSegmentQuery(r.URL.RawQuery) {
|
||||
query := r.URL.Query()
|
||||
if hasInvalidPathSegment(query["versionId"]) || hasInvalidPathSegment(query["uploadId"]) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -85,3 +85,57 @@ func TestValidateRequestPath_RejectsEmptyCapturedVars(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRequestPath_RejectsUnsafePathQueryValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
rawQuery string
|
||||
wantCode int
|
||||
}{
|
||||
{"clean version ID", "versionId=opaque-version", http.StatusOK},
|
||||
{"clean upload ID", "uploadId=opaque_upload", http.StatusOK},
|
||||
{"empty values", "versionId=&uploadId=", http.StatusOK},
|
||||
{"version ID encoded slash", "versionId=v1%2F..%2Fsecret", http.StatusBadRequest},
|
||||
{"version ID backslash", "versionId=v1%5C..%5Csecret", http.StatusBadRequest},
|
||||
{"upload ID traversal", "uploadId=hash%2F..%2F..%2Fvictim", http.StatusBadRequest},
|
||||
{"unsafe repeated value", "versionId=clean&versionId=bad%2Fvalue", http.StatusBadRequest},
|
||||
{"encoded version ID name", "version%49d=v1%2F..%2Fsecret", http.StatusBadRequest},
|
||||
{"encoded upload ID name", "upload%49d=hash%2F..%2Fvictim", http.StatusBadRequest},
|
||||
{"unrelated query", "prefix=folder&delimiter=%2F", http.StatusOK},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
called := false
|
||||
h := validateRequestPath(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
req := mux.SetURLVars(
|
||||
httptest.NewRequest(http.MethodGet, "/bucket-a/key?"+tt.rawQuery, nil),
|
||||
map[string]string{"bucket": "bucket-a", "object": "key"},
|
||||
)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
h.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != tt.wantCode {
|
||||
t.Fatalf("query %q: got status %d, want %d", tt.rawQuery, rr.Code, tt.wantCode)
|
||||
}
|
||||
if tt.wantCode != http.StatusOK && called {
|
||||
t.Fatalf("query %q: inner handler reached despite rejection", tt.rawQuery)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasPathSegmentQuery_CommonPathDoesNotAllocate(t *testing.T) {
|
||||
allocations := testing.AllocsPerRun(1000, func() {
|
||||
if hasPathSegmentQuery("prefix=folder&delimiter=%2F") {
|
||||
t.Fatal("unrelated query recognized as a path segment query")
|
||||
}
|
||||
})
|
||||
if allocations != 0 {
|
||||
t.Fatalf("common query path allocated %v times per run, want 0", allocations)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package s3api
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
@@ -24,6 +25,13 @@ const (
|
||||
versionIdFormatThreshold = 0x4000000000000000
|
||||
)
|
||||
|
||||
var errInvalidVersionID = errors.New("invalid version ID")
|
||||
|
||||
// Version IDs are opaque to clients but become filenames under .versions.
|
||||
func isValidVersionID(versionId string) bool {
|
||||
return versionId == "" || s3_constants.IsValidPathSegment(versionId)
|
||||
}
|
||||
|
||||
// generateVersionId creates a unique version ID
|
||||
// If useInvertedFormat is true, uses inverted timestamps so newer versions sort first
|
||||
// If false, uses raw timestamps (old format) for backward compatibility
|
||||
|
||||
@@ -63,6 +63,27 @@ func TestVersionIdFormatDetection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidVersionID(t *testing.T) {
|
||||
tests := []struct {
|
||||
versionID string
|
||||
want bool
|
||||
}{
|
||||
{"", true},
|
||||
{"null", true},
|
||||
{"opaque-version_123", true},
|
||||
{"v1/../../../victim", false},
|
||||
{`v1\..\victim`, false},
|
||||
{"bad\x00version", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.versionID, func(t *testing.T) {
|
||||
if got := isValidVersionID(tt.versionID); got != tt.want {
|
||||
t.Errorf("isValidVersionID(%q) = %v, want %v", tt.versionID, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenerateVersionIdFormats tests that generateVersionId produces correct format based on parameter
|
||||
func TestGenerateVersionIdFormats(t *testing.T) {
|
||||
// Generate old format version ID
|
||||
|
||||
@@ -48,6 +48,7 @@ type S3TablesHandler struct {
|
||||
region string
|
||||
accountID string
|
||||
defaultAllow bool // Whether to allow access by default (for zero-config IAM)
|
||||
trusted bool // Trusted local tooling (shell/admin) bypasses authorization
|
||||
iamAuthorizer IAMAuthorizer
|
||||
}
|
||||
|
||||
@@ -79,6 +80,12 @@ func (h *S3TablesHandler) SetDefaultAllow(allow bool) {
|
||||
h.defaultAllow = allow
|
||||
}
|
||||
|
||||
// SetTrusted lets local tooling that talks to the filer directly (shell, admin
|
||||
// console) bypass authorization. HTTP-facing callers must not set it.
|
||||
func (h *S3TablesHandler) SetTrusted(trusted bool) {
|
||||
h.trusted = trusted
|
||||
}
|
||||
|
||||
// FilerClient interface for filer operations
|
||||
type FilerClient interface {
|
||||
WithFilerClient(streamingMode bool, fn func(client filer_pb.SeaweedFilerClient) error) error
|
||||
@@ -212,7 +219,11 @@ func (h *S3TablesHandler) getAccountID(r *http.Request) string {
|
||||
idField := accountVal.FieldByName("Id")
|
||||
if idField.IsValid() && idField.Kind() == reflect.String {
|
||||
if principal := normalizePrincipalID(idField.String()); principal != "" {
|
||||
return principal
|
||||
// Account-less identities default to the admin account; only
|
||||
// keep it for real admins, else use the unique identity name.
|
||||
if principal != s3_constants.AccountAdminId || hasAdminAction(getIdentityActions(r)) {
|
||||
return principal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
|
||||
}
|
||||
if !CheckPermissionWithContext("CreateTableBucket", principal, owner, "", "", &PolicyContext{
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create table buckets")
|
||||
return NewAuthError("CreateTableBucket", principal, "not authorized to create table buckets")
|
||||
|
||||
@@ -72,7 +72,7 @@ func (h *S3TablesHandler) handleGetTableBucket(w http.ResponseWriter, r *http.Re
|
||||
if !CheckPermissionWithContext("GetTableBucket", principal, metadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to get table bucket details")
|
||||
return ErrAccessDenied
|
||||
@@ -97,16 +97,9 @@ func (h *S3TablesHandler) handleListTableBuckets(w http.ResponseWriter, r *http.
|
||||
return err
|
||||
}
|
||||
|
||||
principal := h.getAccountID(r)
|
||||
// No account-level gate: visibility is enforced per bucket below, so an
|
||||
// owner can always list its own buckets and others are filtered out.
|
||||
accountID := h.getAccountID(r)
|
||||
identityActions := getIdentityActions(r)
|
||||
if !CheckPermissionWithContext("ListTableBuckets", principal, accountID, "", "", &PolicyContext{
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to list table buckets")
|
||||
return NewAuthError("ListTableBuckets", principal, "not authorized to list table buckets")
|
||||
}
|
||||
|
||||
maxBuckets := req.MaxBuckets
|
||||
if maxBuckets <= 0 {
|
||||
@@ -200,7 +193,7 @@ func (h *S3TablesHandler) handleListTableBuckets(w http.ResponseWriter, r *http.
|
||||
if !CheckPermissionWithContext("GetTableBucket", accountID, metadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: entry.Entry.Name,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
continue
|
||||
}
|
||||
@@ -303,7 +296,7 @@ func (h *S3TablesHandler) handleDeleteTableBucket(w http.ResponseWriter, r *http
|
||||
if !CheckPermissionWithContext("DeleteTableBucket", principal, metadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
return NewAuthError("DeleteTableBucket", principal, fmt.Sprintf("not authorized to delete bucket %s", bucketName))
|
||||
}
|
||||
|
||||
@@ -16,7 +16,9 @@ type testIdentityAccount struct {
|
||||
}
|
||||
|
||||
type testIdentity struct {
|
||||
Name string
|
||||
Account *testIdentityAccount
|
||||
Actions []string
|
||||
Claims map[string]interface{}
|
||||
}
|
||||
|
||||
@@ -112,6 +114,53 @@ func TestGetAccountIDFallsBackToAccountID(t *testing.T) {
|
||||
assert.Equal(t, "my-account-id", h.getAccountID(req), "expected Account.Id to be returned when claims are missing")
|
||||
}
|
||||
|
||||
func TestGetAccountIDNonAdminDoesNotInheritAdminAccount(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
id := &testIdentity{
|
||||
Account: &testIdentityAccount{Id: s3_constants.AccountAdminId},
|
||||
Actions: []string{"Read", "List"},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), id))
|
||||
req = req.WithContext(s3_constants.SetIdentityNameInContext(req.Context(), "readonly"))
|
||||
|
||||
assert.Equal(t, "readonly", h.getAccountID(req), "a non-admin identity must not inherit the shared admin account")
|
||||
}
|
||||
|
||||
func TestGetAccountIDAdminActionKeepsAdminAccount(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
id := &testIdentity{
|
||||
Account: &testIdentityAccount{Id: s3_constants.AccountAdminId},
|
||||
Actions: []string{s3_constants.ACTION_ADMIN},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req = req.WithContext(s3_constants.SetIdentityInContext(req.Context(), id))
|
||||
req = req.WithContext(s3_constants.SetIdentityNameInContext(req.Context(), "root"))
|
||||
|
||||
assert.Equal(t, s3_constants.AccountAdminId, h.getAccountID(req), "an admin identity keeps the admin account as principal")
|
||||
}
|
||||
|
||||
func TestDefaultAllowForOnlyAppliesToUnauthenticatedOrAnonymous(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
h.SetDefaultAllow(true)
|
||||
|
||||
noIdentity := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
assert.True(t, h.defaultAllowFor(noIdentity), "zero-config requests with no identity keep the open default")
|
||||
|
||||
anon := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
anon = anon.WithContext(s3_constants.SetIdentityInContext(anon.Context(),
|
||||
&testIdentity{Name: s3_constants.AccountAnonymousId}))
|
||||
assert.True(t, h.defaultAllowFor(anon), "anonymous requests keep the open default")
|
||||
|
||||
authed := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
authed = authed.WithContext(s3_constants.SetIdentityInContext(authed.Context(),
|
||||
&testIdentity{Name: "readonly", Account: &testIdentityAccount{Id: s3_constants.AccountAdminId}, Actions: []string{"Read"}}))
|
||||
assert.False(t, h.defaultAllowFor(authed), "an authenticated identity must not benefit from the open default")
|
||||
|
||||
h.SetDefaultAllow(false)
|
||||
assert.False(t, h.defaultAllowFor(noIdentity), "default-allow disabled is never open")
|
||||
}
|
||||
|
||||
func TestGetAccountIDNormalizesAccountIDARN(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
id := &testIdentity{
|
||||
|
||||
@@ -118,7 +118,7 @@ func (h *S3TablesHandler) handleCreateNamespace(w http.ResponseWriter, r *http.R
|
||||
Namespace: namespaceName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
glog.Infof("S3Tables: Permission denied for CreateNamespace - principal=%s, owner=%s", principal, bucketMetadata.OwnerAccountID)
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create namespace in this bucket")
|
||||
@@ -259,7 +259,7 @@ func (h *S3TablesHandler) handleGetNamespace(w http.ResponseWriter, r *http.Requ
|
||||
Namespace: namespaceName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchNamespace, "namespace not found")
|
||||
return ErrAccessDenied
|
||||
@@ -346,7 +346,7 @@ func (h *S3TablesHandler) handleListNamespaces(w http.ResponseWriter, r *http.Re
|
||||
TableBucketName: bucketName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
|
||||
return ErrAccessDenied
|
||||
@@ -531,7 +531,7 @@ func (h *S3TablesHandler) handleDeleteNamespace(w http.ResponseWriter, r *http.R
|
||||
Namespace: namespaceName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusNotFound, ErrCodeNoSuchNamespace, "namespace not found")
|
||||
return ErrAccessDenied
|
||||
|
||||
@@ -94,7 +94,7 @@ func (h *S3TablesHandler) handlePutTableBucketPolicy(w http.ResponseWriter, r *h
|
||||
if !CheckPermissionWithContext("PutTableBucketPolicy", principal, bucketMetadata.OwnerAccountID, "", bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to put table bucket policy")
|
||||
return NewAuthError("PutTableBucketPolicy", principal, "not authorized to put table bucket policy")
|
||||
@@ -172,7 +172,7 @@ func (h *S3TablesHandler) handleGetTableBucketPolicy(w http.ResponseWriter, r *h
|
||||
if !CheckPermissionWithContext("GetTableBucketPolicy", principal, bucketMetadata.OwnerAccountID, string(policy), bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to get table bucket policy")
|
||||
return NewAuthError("GetTableBucketPolicy", principal, "not authorized to get table bucket policy")
|
||||
@@ -248,7 +248,7 @@ func (h *S3TablesHandler) handleDeleteTableBucketPolicy(w http.ResponseWriter, r
|
||||
if !CheckPermissionWithContext("DeleteTableBucketPolicy", principal, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to delete table bucket policy")
|
||||
return NewAuthError("DeleteTableBucketPolicy", principal, "not authorized to delete table bucket policy")
|
||||
@@ -349,7 +349,7 @@ func (h *S3TablesHandler) handlePutTablePolicy(w http.ResponseWriter, r *http.Re
|
||||
Namespace: namespaceName,
|
||||
TableName: tableName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to put table policy")
|
||||
return NewAuthError("PutTablePolicy", principal, "not authorized to put table policy")
|
||||
@@ -457,7 +457,7 @@ func (h *S3TablesHandler) handleGetTablePolicy(w http.ResponseWriter, r *http.Re
|
||||
Namespace: namespaceName,
|
||||
TableName: tableName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to get table policy")
|
||||
return NewAuthError("GetTablePolicy", principal, "not authorized to get table policy")
|
||||
@@ -547,7 +547,7 @@ func (h *S3TablesHandler) handleDeleteTablePolicy(w http.ResponseWriter, r *http
|
||||
Namespace: namespaceName,
|
||||
TableName: tableName,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to delete table policy")
|
||||
return NewAuthError("DeleteTablePolicy", principal, "not authorized to delete table policy")
|
||||
@@ -646,7 +646,7 @@ func (h *S3TablesHandler) handleTagResource(w http.ResponseWriter, r *http.Reque
|
||||
TagKeys: requestTagKeys,
|
||||
ResourceTags: existingTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
return NewAuthError("TagResource", principal, "not authorized to tag resource")
|
||||
}
|
||||
@@ -764,7 +764,7 @@ func (h *S3TablesHandler) handleListTagsForResource(w http.ResponseWriter, r *ht
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
return NewAuthError("ListTagsForResource", principal, "not authorized to list tags for resource")
|
||||
}
|
||||
@@ -872,7 +872,7 @@ func (h *S3TablesHandler) handleUntagResource(w http.ResponseWriter, r *http.Req
|
||||
TagKeys: req.TagKeys,
|
||||
ResourceTags: tags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
return NewAuthError("UntagResource", principal, "not authorized to untag resource")
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ func (h *S3TablesHandler) handleCreateTable(w http.ResponseWriter, r *http.Reque
|
||||
TagKeys: mapKeys(req.Tags),
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
bucketAllowed := CheckPermissionWithContext("CreateTable", accountID, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
@@ -153,7 +153,7 @@ func (h *S3TablesHandler) handleCreateTable(w http.ResponseWriter, r *http.Reque
|
||||
TagKeys: mapKeys(req.Tags),
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
|
||||
if !nsAllowed && !bucketAllowed {
|
||||
@@ -386,7 +386,7 @@ func (h *S3TablesHandler) handleGetTable(w http.ResponseWriter, r *http.Request,
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
bucketAllowed := CheckPermissionWithContext("GetTable", accountID, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
@@ -395,7 +395,7 @@ func (h *S3TablesHandler) handleGetTable(w http.ResponseWriter, r *http.Request,
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
|
||||
if !tableAllowed && !bucketAllowed {
|
||||
@@ -525,14 +525,14 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
Namespace: namespaceName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
bucketAllowed := CheckPermissionWithContext("ListTables", accountID, bucketMeta.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
Namespace: namespaceName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
if !nsAllowed && !bucketAllowed {
|
||||
return ErrAccessDenied
|
||||
@@ -577,7 +577,7 @@ func (h *S3TablesHandler) handleListTables(w http.ResponseWriter, r *http.Reques
|
||||
TableBucketName: bucketName,
|
||||
TableBucketTags: bucketTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
}) {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
@@ -916,7 +916,7 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
bucketAllowed := CheckPermissionWithContext("DeleteTable", principal, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
@@ -925,7 +925,7 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
if !tableAllowed && !bucketAllowed {
|
||||
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to delete table")
|
||||
@@ -1058,7 +1058,7 @@ func (h *S3TablesHandler) handleUpdateTable(w http.ResponseWriter, r *http.Reque
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
bucketAllowed := CheckPermissionWithContext("UpdateTable", principal, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
|
||||
TableBucketName: bucketName,
|
||||
@@ -1067,7 +1067,7 @@ func (h *S3TablesHandler) handleUpdateTable(w http.ResponseWriter, r *http.Reque
|
||||
TableBucketTags: bucketTags,
|
||||
ResourceTags: tableTags,
|
||||
IdentityActions: identityActions,
|
||||
DefaultAllow: h.defaultAllow,
|
||||
DefaultAllow: h.defaultAllowFor(r),
|
||||
})
|
||||
|
||||
if !tableAllowed && !bucketAllowed {
|
||||
|
||||
@@ -48,6 +48,24 @@ func (h *S3TablesHandler) shouldUseIAM(r *http.Request, identityActions, identit
|
||||
return len(identityPolicyNames) > 0
|
||||
}
|
||||
|
||||
// defaultAllowFor reports whether the open-by-default fallback applies: only for
|
||||
// trusted tooling or unauthenticated/anonymous access. An authenticated principal
|
||||
// must pass an explicit check.
|
||||
func (h *S3TablesHandler) defaultAllowFor(r *http.Request) bool {
|
||||
if h.trusted {
|
||||
return true
|
||||
}
|
||||
if !h.defaultAllow {
|
||||
return false
|
||||
}
|
||||
// The Manager path forwards only the identity name, so a name alone (no
|
||||
// identity object) still counts as an authenticated principal.
|
||||
if s3_constants.GetIdentityFromContext(r) == nil && s3_constants.GetIdentityNameFromContext(r) == "" {
|
||||
return true
|
||||
}
|
||||
return isAnonymousIdentity(r)
|
||||
}
|
||||
|
||||
func isAnonymousIdentity(r *http.Request) bool {
|
||||
val, ok := getIdentityStructValue(r)
|
||||
if !ok {
|
||||
|
||||
@@ -41,6 +41,11 @@ func (m *Manager) SetDefaultAllow(allow bool) {
|
||||
m.handler.SetDefaultAllow(allow)
|
||||
}
|
||||
|
||||
// SetTrusted lets trusted local tooling (shell, admin console) bypass authorization.
|
||||
func (m *Manager) SetTrusted(trusted bool) {
|
||||
m.handler.SetTrusted(trusted)
|
||||
}
|
||||
|
||||
// Execute runs an S3 Tables operation and decodes the response into resp (if provided).
|
||||
func (m *Manager) Execute(ctx context.Context, filerClient FilerClient, operation string, req interface{}, resp interface{}, identity string) error {
|
||||
body, err := json.Marshal(req)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var errFilerReached = errors.New("filer reached")
|
||||
|
||||
// recordingFilerClient reports whether the handler reached the filer. The
|
||||
// CreateTableBucket handler authorizes before touching the filer, so "filer
|
||||
// reached" is a proxy for "authorization passed".
|
||||
type recordingFilerClient struct {
|
||||
called bool
|
||||
}
|
||||
|
||||
func (c *recordingFilerClient) WithFilerClient(streamingMode bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
|
||||
c.called = true
|
||||
return errFilerReached
|
||||
}
|
||||
|
||||
// The Manager path (used by the Iceberg catalog) enforces authorization for
|
||||
// authenticated callers and only falls open for trusted/zero-config access.
|
||||
func TestManagerCreateTableBucketAuthorization(t *testing.T) {
|
||||
lowPriv := &testIdentity{
|
||||
Name: "alice",
|
||||
Account: &testIdentityAccount{Id: s3_constants.AccountAdminId},
|
||||
Actions: []string{"Read"},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
defaultAllow bool
|
||||
trusted bool
|
||||
ctx context.Context
|
||||
identity string
|
||||
wantFiler bool // true => authorization passed (filer reached)
|
||||
}{
|
||||
{
|
||||
name: "authenticated identity struct is enforced",
|
||||
defaultAllow: true,
|
||||
ctx: s3_constants.SetIdentityInContext(context.Background(), lowPriv),
|
||||
identity: "alice",
|
||||
wantFiler: false,
|
||||
},
|
||||
{
|
||||
name: "secured manager denies a name without struct",
|
||||
defaultAllow: false,
|
||||
ctx: context.Background(),
|
||||
identity: "alice",
|
||||
wantFiler: false,
|
||||
},
|
||||
{
|
||||
name: "untrusted name without struct is enforced",
|
||||
defaultAllow: true,
|
||||
ctx: context.Background(),
|
||||
identity: "alice",
|
||||
wantFiler: false,
|
||||
},
|
||||
{
|
||||
name: "trusted manager allows a name without struct",
|
||||
defaultAllow: true,
|
||||
trusted: true,
|
||||
ctx: context.Background(),
|
||||
identity: "alice",
|
||||
wantFiler: true,
|
||||
},
|
||||
{
|
||||
name: "admin principal is allowed",
|
||||
defaultAllow: false,
|
||||
ctx: context.Background(),
|
||||
identity: s3_constants.AccountAdminId,
|
||||
wantFiler: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
m := NewManager()
|
||||
m.SetDefaultAllow(tc.defaultAllow)
|
||||
m.SetTrusted(tc.trusted)
|
||||
fc := &recordingFilerClient{}
|
||||
err := m.Execute(tc.ctx, fc, "CreateTableBucket", &CreateTableBucketRequest{Name: "testbucket"}, nil, tc.identity)
|
||||
require.Error(t, err) // denied (403) or the filer sentinel (reached); never nil here
|
||||
assert.Equal(t, tc.wantFiler, fc.called, "filer reached should equal authorization passed")
|
||||
if !tc.wantFiler {
|
||||
var s3Err *S3TablesError
|
||||
require.ErrorAs(t, err, &s3Err)
|
||||
assert.Equal(t, ErrCodeAccessDenied, s3Err.Type)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -193,16 +193,14 @@ func hasIdentityPermission(operation string, ctx *PolicyContext) bool {
|
||||
if !strings.Contains(operation, ":") {
|
||||
fullAction = "s3tables:" + operation
|
||||
}
|
||||
if hasAdminAction(ctx.IdentityActions) {
|
||||
return true
|
||||
}
|
||||
candidates := []string{operation, fullAction}
|
||||
if ctx.TableBucketName != "" {
|
||||
candidates = append(candidates, operation+":"+ctx.TableBucketName, fullAction+":"+ctx.TableBucketName)
|
||||
}
|
||||
for _, action := range ctx.IdentityActions {
|
||||
// Legacy static identities may still use broad admin markers or s3 wildcards.
|
||||
// s3:* is treated as s3tables:* so shared admin policies still permit table access.
|
||||
if action == "*" || action == string(s3_constants.ACTION_ADMIN) || action == "s3:*" || action == "s3tables:*" {
|
||||
return true
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if action == candidate {
|
||||
return true
|
||||
@@ -215,6 +213,18 @@ func hasIdentityPermission(operation string, ctx *PolicyContext) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// hasAdminAction reports whether the action list grants blanket admin access.
|
||||
// Legacy static identities may use broad markers or s3 wildcards; s3:* is treated
|
||||
// as s3tables:* so shared admin policies still permit table access.
|
||||
func hasAdminAction(actions []string) bool {
|
||||
for _, action := range actions {
|
||||
if action == "*" || action == s3_constants.ACTION_ADMIN || action == "s3:*" || action == "s3tables:*" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// matchesPrincipal checks if the principal matches the statement's principal
|
||||
func matchesPrincipal(principalSpec interface{}, principal string) bool {
|
||||
if principalSpec == nil {
|
||||
|
||||
@@ -165,7 +165,7 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
|
||||
ctx := stream.Context()
|
||||
peerAddress := findClientAddress(ctx, 0)
|
||||
|
||||
isReplacing, alreadyKnown, clientName := fs.addClient("", req.ClientName, peerAddress, req.ClientId, req.ClientEpoch)
|
||||
isReplacing, alreadyKnown, clientName := fs.addClient("", req.ClientName, peerAddress, req.PathPrefix, req.ClientId, req.ClientEpoch)
|
||||
if isReplacing {
|
||||
fs.filer.MetaAggregator.ListenersCond.Broadcast() // nudges the subscribers that are waiting
|
||||
} else if alreadyKnown {
|
||||
@@ -314,7 +314,7 @@ func (fs *FilerServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataReq
|
||||
// use negative client id to differentiate from addClient()/deleteClient() used in SubscribeMetadata()
|
||||
req.ClientId = -req.ClientId
|
||||
|
||||
isReplacing, alreadyKnown, clientName := fs.addClient("local", req.ClientName, peerAddress, req.ClientId, req.ClientEpoch)
|
||||
isReplacing, alreadyKnown, clientName := fs.addClient("local", req.ClientName, peerAddress, req.PathPrefix, req.ClientId, req.ClientEpoch)
|
||||
if isReplacing {
|
||||
fs.listenersCond.Broadcast() // nudges the subscribers that are waiting
|
||||
} else if alreadyKnown {
|
||||
@@ -564,6 +564,14 @@ func (fs *FilerServer) maybeSendIdleHeartbeat(req *filer_pb.SubscribeMetadataReq
|
||||
glog.V(0).Infof("=> idle heartbeat to %s: %v", req.ClientName, err)
|
||||
return lastHeartbeatNs
|
||||
}
|
||||
// A heartbeat is a send too: advance the freshness gauge so an idle but
|
||||
// healthy subscriber doesn't look stale. The gauge otherwise only moves on
|
||||
// real matching events, which never arrive on a quiet path.
|
||||
var sourceFiler string
|
||||
if fs.option != nil {
|
||||
sourceFiler = fs.option.Host.String()
|
||||
}
|
||||
stats.FilerServerLastSendTsOfSubscribeGauge.WithLabelValues(sourceFiler, req.ClientName, req.PathPrefix).Set(float64(now))
|
||||
return now
|
||||
}
|
||||
|
||||
@@ -661,9 +669,9 @@ func (fs *FilerServer) eachEventNotificationFn(req *filer_pb.SubscribeMetadataRe
|
||||
}
|
||||
}
|
||||
|
||||
func (fs *FilerServer) addClient(prefix string, clientType string, clientAddress string, clientId int32, clientEpoch int32) (isReplacing, alreadyKnown bool, clientName string) {
|
||||
func (fs *FilerServer) addClient(scope string, clientType string, clientAddress string, pathPrefix string, clientId int32, clientEpoch int32) (isReplacing, alreadyKnown bool, clientName string) {
|
||||
clientName = clientType + "@" + clientAddress
|
||||
glog.V(0).Infof("+ %v listener %v clientId %v clientEpoch %v", prefix, clientName, clientId, clientEpoch)
|
||||
glog.V(0).Infof("+ %v listener %v clientId %v clientEpoch %v", scope, clientName, clientId, clientEpoch)
|
||||
if clientId != 0 {
|
||||
fs.knownListenersLock.Lock()
|
||||
defer fs.knownListenersLock.Unlock()
|
||||
@@ -671,6 +679,18 @@ func (fs *FilerServer) addClient(prefix string, clientType string, clientAddress
|
||||
if !found || epoch < clientEpoch {
|
||||
fs.knownListeners[clientId] = clientEpoch
|
||||
isReplacing = true
|
||||
if fs.subscribers == nil {
|
||||
fs.subscribers = make(map[int32]*metadataSubscriber)
|
||||
}
|
||||
fs.subscribers[clientId] = &metadataSubscriber{
|
||||
clientName: clientName,
|
||||
clientType: clientType,
|
||||
address: clientAddress,
|
||||
pathPrefix: pathPrefix,
|
||||
clientId: clientId,
|
||||
clientEpoch: clientEpoch,
|
||||
connectedAtNs: time.Now().UnixNano(),
|
||||
}
|
||||
} else {
|
||||
alreadyKnown = true
|
||||
}
|
||||
@@ -678,14 +698,15 @@ func (fs *FilerServer) addClient(prefix string, clientType string, clientAddress
|
||||
return
|
||||
}
|
||||
|
||||
func (fs *FilerServer) deleteClient(prefix string, clientName string, clientId int32, clientEpoch int32) {
|
||||
glog.V(0).Infof("- %v listener %v clientId %v clientEpoch %v", prefix, clientName, clientId, clientEpoch)
|
||||
func (fs *FilerServer) deleteClient(scope string, clientName string, clientId int32, clientEpoch int32) {
|
||||
glog.V(0).Infof("- %v listener %v clientId %v clientEpoch %v", scope, clientName, clientId, clientEpoch)
|
||||
if clientId != 0 {
|
||||
fs.knownListenersLock.Lock()
|
||||
defer fs.knownListenersLock.Unlock()
|
||||
epoch, found := fs.knownListeners[clientId]
|
||||
if found && epoch <= clientEpoch {
|
||||
delete(fs.knownListeners, clientId)
|
||||
delete(fs.subscribers, clientId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user