mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 21:57:05 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb93976166 | ||
|
|
7688e69146 | ||
|
|
56d7904dc5 | ||
|
|
e2a17a76fc | ||
|
|
ee8742f393 | ||
|
|
395d2c80af | ||
|
|
53342c9ba6 | ||
|
|
df1a25fd3e | ||
|
|
20e4614fc6 | ||
|
|
bc257fe72e | ||
|
|
3ccd4ed85c | ||
|
|
18868e5204 | ||
|
|
60ecdd7a2f | ||
|
|
638f6ff433 | ||
|
|
0a45c4d097 | ||
|
|
b763a5f6bf | ||
|
|
6dac0d30ef | ||
|
|
40615e3d9d | ||
|
|
443b5b1184 | ||
|
|
0c343e76eb | ||
|
|
b5ecfcd28c | ||
|
|
e411ff491d | ||
|
|
65484cb4bb | ||
|
|
8701299baf | ||
|
|
aad24f239c | ||
|
|
d6da0e0e13 | ||
|
|
7c32e651f7 | ||
|
|
0a70332adf | ||
|
|
bc827704d5 | ||
|
|
1826a5d222 | ||
|
|
b888cec106 | ||
|
|
93f91c96ca | ||
|
|
5e8152b81c | ||
|
|
b58e9ac3c4 | ||
|
|
33df4fe2c4 | ||
|
|
9c10d64ae9 | ||
|
|
8d388acc0e | ||
|
|
7e13340dcb | ||
|
|
76783f3d71 | ||
|
|
9266aaa88e | ||
|
|
3bf3d29058 | ||
|
|
3f7105df52 | ||
|
|
d28cd94601 | ||
|
|
d793efd13a | ||
|
|
3888e6f58a | ||
|
|
303b23f96a | ||
|
|
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
@@ -3,6 +3,11 @@ name: "go: build dev binaries"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/binaries_dev.yml'
|
||||
|
||||
concurrency:
|
||||
group: binaries-dev-${{ github.ref }}
|
||||
|
||||
@@ -2,6 +2,11 @@ name: "Code Scanning - Action"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/codeql.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/codeql
|
||||
|
||||
@@ -3,6 +3,12 @@ name: "docker: build dev containers"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'docker/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/container_dev.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "End to End"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'docker/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/e2e.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'docker/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/e2e.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/e2e
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "EC Integration Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/erasure_coding/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/ec-integration-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/erasure_coding/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/ec-integration-tests.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -3,8 +3,18 @@ name: "go: build binary"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/go.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/go.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/go
|
||||
@@ -37,6 +47,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 +87,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
|
||||
|
||||
@@ -3,8 +3,24 @@ name: "Kafka Quick Test (Load Test with Schema Registry)"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/mq/**'
|
||||
- 'weed/pb/mq_pb/**'
|
||||
- 'weed/pb/schema_pb/**'
|
||||
- 'test/kafka/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/kafka-quicktest.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/mq/**'
|
||||
- 'weed/pb/mq_pb/**'
|
||||
- 'weed/pb/schema_pb/**'
|
||||
- 'test/kafka/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/kafka-quicktest.yml'
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
|
||||
concurrency:
|
||||
|
||||
@@ -3,8 +3,24 @@ name: "Kafka Gateway Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/mq/**'
|
||||
- 'weed/pb/mq_pb/**'
|
||||
- 'weed/pb/schema_pb/**'
|
||||
- 'test/kafka/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/kafka-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/mq/**'
|
||||
- 'weed/pb/mq_pb/**'
|
||||
- 'weed/pb/schema_pb/**'
|
||||
- 'test/kafka/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/kafka-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/kafka-tests
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "Plugin Worker Integration Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/plugin_workers/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/plugin-workers.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/plugin_workers/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/plugin-workers.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -3,8 +3,24 @@ name: "PostgreSQL Gateway Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/server/postgres/**'
|
||||
- 'weed/query/**'
|
||||
- 'weed/mq/**'
|
||||
- 'test/postgres/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/postgres-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/server/postgres/**'
|
||||
- 'weed/query/**'
|
||||
- 'weed/mq/**'
|
||||
- 'test/postgres/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/postgres-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/postgres-tests
|
||||
|
||||
@@ -2,7 +2,16 @@ name: "S3 Authenticated Integration Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/iam/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/normal/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-example-integration-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/s3-integration-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
@@ -2,7 +2,15 @@ name: "S3 Filer Group Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/filer_group/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-filer-group-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/s3-filer-group-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
@@ -2,7 +2,15 @@ name: "S3 Go Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-go-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/s3-go-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
@@ -3,8 +3,22 @@ name: "S3 Proxy Signature Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/proxy_signature/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-proxy-signature-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3/proxy_signature/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-proxy-signature-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref || github.ref }}/s3-proxy-signature-tests
|
||||
|
||||
@@ -2,6 +2,14 @@ name: "S3 Tables Integration Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'test/s3tables/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3-tables-tests.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -3,8 +3,26 @@ name: "Ceph S3 tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'weed/iam/**'
|
||||
- 'test/s3/compatibility/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'weed/iam/**'
|
||||
- 'test/s3/compatibility/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/s3tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref }}/s3tests
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "test s3 over https using aws-cli"
|
||||
on:
|
||||
push:
|
||||
branches: [master, test-https-s3-awscli]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/server/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/test-s3-over-https-using-awscli.yml'
|
||||
pull_request:
|
||||
branches: [master, test-https-s3-awscli]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/server/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/test-s3-over-https-using-awscli.yml'
|
||||
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: some_access_key1
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "TLS Rotation Integration Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/tls_rotation/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/tls-rotation-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/tls_rotation/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/tls-rotation-tests.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -2,6 +2,13 @@ name: "TUS Protocol Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/server/**'
|
||||
- 'weed/filer/**'
|
||||
- 'test/tus/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/tus-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref || github.ref }}/tus-tests
|
||||
|
||||
@@ -3,8 +3,20 @@ name: "Vacuum Integration Tests"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/vacuum/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/vacuum-integration-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/vacuum/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/vacuum-integration-tests.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -426,7 +426,7 @@ If the hot/warm data is split as 20/80, with 20 servers, you can achieve storage
|
||||
|
||||
## SeaweedFS Filer ##
|
||||
|
||||
Built on top of the blob store, SeaweedFS Filer adds directory structure to create a file system. The directory sturcture is an interface that is implemented in many key-value stores or databases.
|
||||
Built on top of the blob store, SeaweedFS Filer adds directory structure to create a file system. The directory structure is an interface that is implemented in many key-value stores or databases.
|
||||
|
||||
The content of a file is mapped to one or many blobs, distributed to multiple volumes on multiple volume servers.
|
||||
|
||||
|
||||
+69
-15
@@ -1,24 +1,78 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
## Supported versions
|
||||
|
||||
If you find a security issue in SeaweedFS, please report it privately:
|
||||
Security fixes land in the latest release. Please reproduce against a recent
|
||||
release or `master` before reporting; issues that only reproduce on old,
|
||||
unsupported versions are not eligible for a fix or an advisory.
|
||||
|
||||
- Email: support@seaweedfs.com
|
||||
- Do not open a public GitHub issue
|
||||
## Reporting a vulnerability
|
||||
|
||||
Please include:
|
||||
- A clear description of the issue
|
||||
- Steps to reproduce (if possible)
|
||||
- Affected versions
|
||||
Report privately through GitHub private vulnerability reporting (the "Report a
|
||||
vulnerability" button under the repository's Security tab). This keeps the
|
||||
report, the fix, and any CVE in one place. Do not open a public issue.
|
||||
|
||||
## Response
|
||||
### What a report must include
|
||||
|
||||
- We will respond as soon as possible (usually within 1 business day)
|
||||
- We will investigate and work on a fix
|
||||
- We may coordinate disclosure with you
|
||||
We can only act on reports that show real impact. Please include:
|
||||
|
||||
## Notes
|
||||
- Affected version (a release tag or `master` commit you reproduced on)
|
||||
- The exact deployment and configuration: which components are running
|
||||
(master, volume, filer, S3, admin), which ports are reachable by the
|
||||
attacker, and what authentication is enabled
|
||||
- The attacker's starting position: unauthenticated, a valid S3 user, an admin,
|
||||
or someone with access to the internal cluster network
|
||||
- The trust boundary that is crossed (e.g. an unauthenticated client reading
|
||||
another tenant's data, an S3 user escalating to admin)
|
||||
- A minimal, working reproduction or proof of concept
|
||||
- Expected vs. actual behavior
|
||||
|
||||
- Please allow time for a fix before public disclosure
|
||||
- If you’re unsure whether something is a security issue, feel free to reach out
|
||||
A report without a working reproduction and a clear trust boundary is a
|
||||
hardening suggestion, not a vulnerability. We are glad to receive those, but
|
||||
they are handled on the normal issue tracker, not as security advisories.
|
||||
|
||||
### Automated and AI-assisted reports
|
||||
|
||||
Output from static analysis, dependency scanners, fuzzers, or LLMs is welcome
|
||||
only when you have manually validated it and can supply a working reproduction
|
||||
against a supported version, per the requirements above. Raw tool output,
|
||||
speculative findings, or generated reports without a demonstrated exploit will
|
||||
be closed as hardening suggestions.
|
||||
|
||||
## Trust model
|
||||
|
||||
SeaweedFS is built to run with its cluster components (master, volume servers,
|
||||
and the raw filer API) on a trusted network. Those internal APIs are not an
|
||||
authentication boundary unless you explicitly enable a control (for example
|
||||
volume JWT or filer authentication) and that control is bypassed. Exposing an
|
||||
internal port directly to untrusted clients is a deployment mistake, not a
|
||||
vulnerability in SeaweedFS.
|
||||
|
||||
Reports are in scope when they cross a boundary SeaweedFS is meant to enforce,
|
||||
for example:
|
||||
|
||||
- Unauthenticated access to data or operations that require authentication
|
||||
- One S3 identity reading, writing, or deleting another identity's data
|
||||
- Privilege escalation from a normal S3 user to administrative capability
|
||||
- Bypass of Object Lock / retention where it is configured
|
||||
- Remotely triggered data corruption or loss
|
||||
|
||||
Reports are generally out of scope when they require:
|
||||
|
||||
- Direct access to an internal cluster port that is meant to be private
|
||||
- Full master, filer, or volume server access (already a full compromise)
|
||||
- An insecure example configuration rather than a documented secure setup
|
||||
- Local-only impact on a host the attacker already controls
|
||||
|
||||
## CVE assignment
|
||||
|
||||
When a report is confirmed, we publish an advisory and request the CVE through
|
||||
GitHub. CVEs assigned by third parties without coordinating with us, or for
|
||||
issues that do not cross a boundary described above, may be disputed.
|
||||
|
||||
## Response and disclosure
|
||||
|
||||
- We aim to acknowledge a valid report within a few business days.
|
||||
- We will investigate, work on a fix, and coordinate a disclosure timeline
|
||||
with you.
|
||||
- Please allow time for a fix before any public disclosure.
|
||||
@@ -5,7 +5,7 @@ go 1.25.0
|
||||
require (
|
||||
cloud.google.com/go v0.123.0 // indirect
|
||||
cloud.google.com/go/pubsub v1.50.2
|
||||
cloud.google.com/go/storage v1.62.1
|
||||
cloud.google.com/go/storage v1.62.3
|
||||
github.com/Shopify/sarama v1.38.1
|
||||
github.com/aws/aws-sdk-go v1.55.8
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
@@ -85,7 +85,7 @@ require (
|
||||
github.com/xdg-go/scram v1.2.0
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
go.etcd.io/etcd/client/v3 v3.6.10
|
||||
go.etcd.io/etcd/client/v3 v3.6.12
|
||||
go.mongodb.org/mongo-driver v1.17.9
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
gocloud.dev v0.46.0
|
||||
@@ -93,8 +93,8 @@ require (
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.46.0
|
||||
golang.org/x/crypto v0.52.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.39.0
|
||||
golang.org/x/net v0.54.0
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/net v0.55.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.45.0
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
@@ -114,17 +114,18 @@ require (
|
||||
require (
|
||||
cloud.google.com/go/kms v1.31.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
github.com/ThreeDotsLabs/watermill v1.5.1
|
||||
github.com/a-h/templ v0.3.1001
|
||||
github.com/a-h/templ v0.3.1020
|
||||
github.com/apache/cassandra-gocql-driver/v2 v2.1.1
|
||||
github.com/apache/iceberg-go v0.5.0
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.12
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.21
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.20
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
|
||||
github.com/cognusion/imaging v1.0.3
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
@@ -142,7 +143,7 @@ require (
|
||||
github.com/parquet-go/parquet-go v0.30.1
|
||||
github.com/pkg/sftp v1.13.10
|
||||
github.com/rabbitmq/amqp091-go v1.11.0
|
||||
github.com/rclone/rclone v1.74.1
|
||||
github.com/rclone/rclone v1.74.3
|
||||
github.com/rdleal/intervalst v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.20.0
|
||||
github.com/schollz/progressbar/v3 v3.19.0
|
||||
@@ -179,7 +180,7 @@ require (
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apache/arrow-go/v18 v18.5.2-0.20260220015023-a886a5722b87 // indirect
|
||||
github.com/apache/thrift v0.23.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/bazelbuild/rules_go v0.46.0 // indirect
|
||||
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
|
||||
@@ -321,21 +322,21 @@ require (
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0
|
||||
github.com/aws/smithy-go v1.27.1
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3
|
||||
github.com/aws/smithy-go v1.27.2
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
@@ -482,7 +483,7 @@ require (
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
github.com/zeebo/errs v1.4.0 // indirect
|
||||
go.etcd.io/bbolt v1.4.3 // indirect
|
||||
go.etcd.io/etcd/api/v3 v3.6.10 // indirect
|
||||
go.etcd.io/etcd/api/v3 v3.6.12 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect
|
||||
|
||||
@@ -485,8 +485,8 @@ cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq
|
||||
cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc=
|
||||
cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s=
|
||||
cloud.google.com/go/storage v1.28.1/go.mod h1:Qnisd4CqDdo6BGs2AD5LLnEsmSQ80wQ5ogcBBKhU86Y=
|
||||
cloud.google.com/go/storage v1.62.1 h1:Os0G3XbUbjZumkpDUf2Y0rLoXJTCF1kU2kWUujKYXD8=
|
||||
cloud.google.com/go/storage v1.62.1/go.mod h1:cpYz/kRVZ+UQAF1uHeea10/9ewcRbxGoGNKsS9daSXA=
|
||||
cloud.google.com/go/storage v1.62.3 h1:SZq1t23NCI+e96dH77Dg3PEfsNNEjqO8zE5AnD8gVD0=
|
||||
cloud.google.com/go/storage v1.62.3/go.mod h1:cpYz/kRVZ+UQAF1uHeea10/9ewcRbxGoGNKsS9daSXA=
|
||||
cloud.google.com/go/storagetransfer v1.5.0/go.mod h1:dxNzUopWy7RQevYFHewchb29POFv3/AaBgnhqzqiK0w=
|
||||
cloud.google.com/go/storagetransfer v1.6.0/go.mod h1:y77xm4CQV/ZhFZH75PLEXY0ROiS7Gh6pSKrM8dJyg6I=
|
||||
cloud.google.com/go/storagetransfer v1.7.0/go.mod h1:8Giuj1QNb1kfLAiWM1bN6dHzfdlDAVC9rv9abHot2W4=
|
||||
@@ -648,8 +648,8 @@ github.com/ThreeDotsLabs/watermill v1.5.1 h1:t5xMivyf9tpmU3iozPqyrCZXHvoV1XQDfih
|
||||
github.com/ThreeDotsLabs/watermill v1.5.1/go.mod h1:Uop10dA3VeJWsSvis9qO3vbVY892LARrKAdki6WtXS4=
|
||||
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb h1:wumPkzt4zaxO4rHPBrjDK8iZMR41C1qs7njNqlacwQg=
|
||||
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb/go.mod h1:QiYsIBRQEO+Z4Rz7GoI+dsHVneZNONvhczuA+llOZNM=
|
||||
github.com/a-h/templ v0.3.1001 h1:yHDTgexACdJttyiyamcTHXr2QkIeVF1MukLy44EAhMY=
|
||||
github.com/a-h/templ v0.3.1001/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
|
||||
github.com/a-h/templ v0.3.1020 h1:ypAT/L5ySWEnZ6Zft/5yfoWXYYkhFNvEFOeeqecg4tw=
|
||||
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
|
||||
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 h1:iLDOF0rdGTrol/q8OfPIIs5kLD8XvA2q75o6Uq/tgak=
|
||||
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0/go.mod h1:DrEWcQJjz7t5iF2duaiyhg4jyoF0kxOD6LtECNGkZ/Q=
|
||||
github.com/aalpar/deheap v1.1.2 h1:MABHLcnjqsffb8GLkUFDigqpBBxOMz0DoKM9QfELeTw=
|
||||
@@ -711,50 +711,50 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
|
||||
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.12 h1:DIKX2c31ekm9RA2D9FBj1EWXx++9AdAqRw+e78Tq2Ck=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.12/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.21 h1:1i1v5jWn6iNPl7zkH4VwIXQOb+OMqMRFNjdHQeZbFVo=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.21/go.mod h1:7NXDJjk0e4QOMv3Y3ppwALx3ifdSQHzCACFtRX5J1hI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.20 h1:nIGz0+cQKwijxSsWNpggvPxjxFMtrAHNj16RYzGbu2Q=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.20/go.mod h1:/UQHYia3DSeilGdchXJDEVzJws15XuZSdnTlwbTBg0Q=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 h1:a1VPHz7eG7mVNHWHXUcCyC8rQDBEr4k+o4HJYbSoYZ0=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26/go.mod h1:9G8LPblMwaodeQdS+IfDBgPqABDctJLpyZ/M6jflE6s=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25 h1:ACCejvStYoilgwrfegSt5ZntCbPrk52qfwyNcnl3omM=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25/go.mod h1:LJyU8sDRbXUxFn8xMJIGP+v9QYYwveNLI8a/giAOiAs=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24 h1:2hQqYCV9yqyePQ9o6dCrZc/zO8U3TwPr9mIKlZnPu/I=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24/go.mod h1:IDwpACtwqHLISdzfwUUNq4P9DsB/h5BLg4FwJPNfqFY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 h1:r6qZHbT+wxgWO/e9vYNUEtg7lv5+UN3pRqKhLXvnArg=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29/go.mod h1:QRnaRcTVGKPGRy8w78HMQtKUGRYcnMZAANATkeVA6Mo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 h1:uMC4oL6G3MNhodo358QEqSDjrgvzV3TUQ58nyQSGq2E=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13/go.mod h1:Cer86AE2686DvVUe57LPve3jUBmbujuaonSX8pNzGgw=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 h1:dx1qc6V0exl5SK5/kwSc2IdOKCxLHoNbl/zXuYRwopw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26/go.mod h1:iDMGb+drKqPTqRjv1kWc5meMYzT6HsvPXxJV/Axq1t0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 h1:ZjsIjuahUd/OxnxgfeK6OZqrReRNru1BcPfFD95IoN0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26/go.mod h1:57VbRA0K0Xxx5XUUTUrVxZ/gm4u8Bk3LBflfufwHtKQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 h1:i49S7g2smFWmlconi97Nn8dxb7jSQ0TeOFD20NX3M+o=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27/go.mod h1:qiLes3uVQAK+cpb837HUEhypYKGBz2ZCDcDl5BYQtpM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 h1:f3vKqSo13fhTYb+JEcXwXefZQE26I1FB5eTSniU67ko=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29/go.mod h1:MzoLFUArKGpGD+ukmPiTPG1X5x4o6M2kq4v2dr1FiEc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 h1:RdwIf/CuUsvJX3RgJagbOyotl/cxoLY4xviKuE7p2GY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29/go.mod h1:71wt8W2EgswdZy9Mf9KNnzxZ3TiZlv4caKghPktDOkA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 h1:VTGy885W5DKBxWRUJbym9hytNaYzsyaPkCHGRRMAOhU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30/go.mod h1:AS0HycUvJRFvTt613AYDOgO2jzw+00cVSMny8XB3yMY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 h1:ZD2+BSw9vFsNlKYIasSNt3uDbjqqXIBcM13UJv/Lx2k=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12/go.mod h1:Ms4zlcVBbXbiP7EVLhl+lgjvA/a7YphqQ3Ih3174EmI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 h1:oIRaBVJ2CxT7T61l3JkBCW/rnyh2TFZIRL71MvJTKRI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26/go.mod h1:1gCTZPMlqAUSFoFbkl35hKtTpE96WFl7ORvDXmSLpRc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 h1:DRebniUGZ2MqiiIVmQJ04vIXr918hubdHMnarSLEWyU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29/go.mod h1:LfRkPCD8YHDM2E5eTkos2UpwYeZnBcVarTa8L59bJHA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 h1:qwU4CNor4G2gRW3Na24FWOCZSEvr967IAV3D+MXxdE0=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2/go.mod h1:vwIj2P3URYf7ZtOQkO2iVbAaR8qFhqMv05w3aPPA5XA=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 h1:3nXpRcFwRCW8n7HgO2QGy0Dc20eQNfBuUemGQhpF8m8=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0/go.mod h1:LxYujSTLPRlp2vTtcUO/+1ilrew8ytt6SvQyOgejzFQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 h1:p8WdWDh5AwSZdp19Haa3XMyPCICi9Z375a/Nu3IIEZY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14/go.mod h1:NKVY7DER6VXHkt2I/ycmHakALNboi3Rqwt4eEf/1Cnk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 h1:JP2wjWGmUp8lTCZb13Dv0Eciyc1jbO8pd0HZVMHFlrc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24/go.mod h1:Ql9ziDutk8ERAN9HMaYANCW3lop451ppebkxEJMLCTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 h1:cMDUWhi7vlmGFj6rldHofjnAQhLLBWwRvNRbtEoyZo4=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0/go.mod h1:VfGCm6HLUGwcouY6zjQJd81PoFsb8sfSmKd5QCg9XXc=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 h1:/pKy3mNES+ppFHf3g/XmI95+f3vdeXnkWYObByoYGAg=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3/go.mod h1:0z2rhlVAjsYeBzV8fdT4jR23Nq+fYhoJNSJN+4SBlqM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0 h1:HN43uYvF8D2NtaPTeE4L3HMvXgd+RtqEqrea4uUztkM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0/go.mod h1:qzhDlfw1BRYyoNofevemNzrlRpUXa0BJamWx7klrR8w=
|
||||
github.com/aws/smithy-go v1.27.1 h1:4T340VFndXtADGF52gYa1POyL7s9E4Z1OeZ1hCscIw8=
|
||||
github.com/aws/smithy-go v1.27.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 h1:ey1XLTYXb9PcLt4535632o5kCGXNXEhNb620Dqwuylo=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3/go.mod h1:Lk7PlmoTYryQmyBG0EXqj5BcUbj3whXdU2s3yGI3EAc=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 h1:yLr03zQE/5Eu5l3QU0Si+xMbLMbSDF2YXsigqXngs6g=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6/go.mod h1:Q5N6icH+KJZDLh+ESNwzdv6cZ6vLFF/egy3IOxWhmz4=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3 h1:VrIhKRCSK1umelSgB9RghvA9RTUYeQffyAS5ApXehNI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3/go.mod h1:r8wkDOuLaaMFqFiYAb8dGY2A3gJCOujMc6CFOVC4Zhc=
|
||||
github.com/aws/smithy-go v1.27.2 h1:y9NPmSE6am6LjEFPfqHqG/jJk7AauQvhCJONKh7kpzk=
|
||||
github.com/aws/smithy-go v1.27.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
|
||||
@@ -1468,6 +1468,7 @@ github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRt
|
||||
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
|
||||
github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4=
|
||||
github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE=
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
@@ -1783,8 +1784,8 @@ github.com/rclone/Proton-API-Bridge v1.0.3 h1:Bs7RC4xCFSN0BPIYVda/BNxp0qo3NV0gB2
|
||||
github.com/rclone/Proton-API-Bridge v1.0.3/go.mod h1:26RAest751Ofk+F/d8xtl4UyWXrZvMQwn39U8rm/WKM=
|
||||
github.com/rclone/go-proton-api v1.0.2 h1:cJtJUab0MGJ3C6q5kiEJs3pbyhSLnOKMyYOQehA0PBc=
|
||||
github.com/rclone/go-proton-api v1.0.2/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/rclone v1.74.1 h1:QQI//tl4O5uooTowdKwNKcv5qCQvJ3LIBG00+TKeXw0=
|
||||
github.com/rclone/rclone v1.74.1/go.mod h1:44epaKf5w/1ZQounefr76wx4+y9NZmgfMKle9T3pzj0=
|
||||
github.com/rclone/rclone v1.74.3 h1:a2wln7pvEa0tS1WIZJKulEkVjxgC1DkCoyxYydkdiSY=
|
||||
github.com/rclone/rclone v1.74.3/go.mod h1:t5Mh86PO49DD7xlPt0trnK/aNf2Z3M0uip4l1Jqwiv8=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
@@ -2099,12 +2100,12 @@ go.einride.tech/aip v0.83.0 h1:TI21IdeOnLTwZEJ3BxtImIZk6bsN2Q+sd0x99SLiQ+M=
|
||||
go.einride.tech/aip v0.83.0/go.mod h1:E8+wdTApA70odnpFzJgsGogHozC2JCIhFJBKPr8bVig=
|
||||
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
|
||||
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
|
||||
go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY=
|
||||
go.etcd.io/etcd/api/v3 v3.6.10/go.mod h1:pdV4VeFmvhdNjB4LWRkC8ReLyRBAxUOze3GarMhE2sk=
|
||||
go.etcd.io/etcd/api/v3 v3.6.12 h1:OLOZUKEuAA36TR48F0cIaa8FdzrWygjyfrJxXg4iDgs=
|
||||
go.etcd.io/etcd/api/v3 v3.6.12/go.mod h1:p14EIQXHbuOQbVvL/WEes5uqKnxP9AgKJgpjbMVvzvE=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.12 h1:36zzB+pQOdHbhN+kH2iJz/K8bJn0ZLtLfPPO7jozTDo=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.12/go.mod h1:hh2+ZXtfLzs3o6mn92ntgNPBrTJJOvXqICM5g3L3DMY=
|
||||
go.etcd.io/etcd/client/v3 v3.6.10 h1:J598zJ+C/ZPvImypmq5waj84+bovePrlZERHklf34y0=
|
||||
go.etcd.io/etcd/client/v3 v3.6.10/go.mod h1:iHhUDUcEwaKs1YFq3MgmI9U4zhTVasp/vgdVbFf1RS8=
|
||||
go.etcd.io/etcd/client/v3 v3.6.12 h1:kMSP6JcPZMqSJiX+TXdUIBU/4eXEZWBAaui4VihMbIc=
|
||||
go.etcd.io/etcd/client/v3 v3.6.12/go.mod h1:CMs6fJWYiZQk4ytFjd4lE1diOvvRMmtbbn/alZXd3dQ=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||
@@ -2238,8 +2239,8 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap
|
||||
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=
|
||||
golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -2342,8 +2343,8 @@ golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
|
||||
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
# Usage:
|
||||
# curl -fsSL https://raw.githubusercontent.com/seaweedfs/seaweedfs/master/install.sh | bash
|
||||
# curl -fsSL ... | bash -s -- --component volume-rust --large-disk
|
||||
# curl -fsSL ... | bash -s -- --version v3.93 --dir /usr/local/bin
|
||||
# curl -fsSL ... | bash -s -- --version 4.34 --dir /usr/local/bin
|
||||
#
|
||||
# Options:
|
||||
# --component COMP Which binary to install: weed, volume-rust, all (default: weed)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.33"
|
||||
appVersion: "4.35"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.33.0
|
||||
version: 4.35.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 }}
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
{{- $volumeName := trimSuffix "-" (printf "volume-%s" $vname) }}
|
||||
{{- $volume := mergeOverwrite (deepCopy $.Values.volume) (dict "enabled" true) $volume }}
|
||||
|
||||
{{- if and $volume.idx (eq ($volume.idx.type | toString) "emptyDir") }}
|
||||
{{- fail (printf "%s: idx.type \"emptyDir\" is not supported. An ephemeral index is wiped on every pod restart while the data persists, forcing a full index rebuild from the .dat on each start (a fatal crash on older versions). Use the default (idx: {}, kept next to the data) or a persistentVolumeClaim/hostPath/existingClaim for a separate persistent index." $volumeName) }}
|
||||
{{- end }}
|
||||
|
||||
{{- if $volume.enabled }}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
@@ -79,7 +83,23 @@ spec:
|
||||
image: {{ template "seaweedfs.volume.image" $ }}
|
||||
imagePullPolicy: {{ $.Values.global.seaweedfs.imagePullPolicy | default "IfNotPresent" }}
|
||||
command: [ '/bin/sh', '-c' ]
|
||||
args: [ '{{range $dir := $volume.dataDirs }}if ls /{{$dir.name}}/*.idx >/dev/null 2>&1; then mv /{{$dir.name}}/*.idx /idx/ ; fi; {{end}}' ]
|
||||
args:
|
||||
- |
|
||||
for dir in {{ range $index, $dir := $volume.dataDirs }}{{ if ne $index 0 }} {{ end }}/{{ $dir.name }}{{ end }}; do
|
||||
# Rebuild a .idx missing from both dirs (e.g. an index volume that lost files) from the .dat, else the server fatally exits on its idx check.
|
||||
for dat in "$dir"/*.dat; do
|
||||
[ -e "$dat" ] || continue
|
||||
base=${dat##*/}; base=${base%.dat}
|
||||
if [ ! -e "$dir/$base.idx" ] && [ ! -e "/idx/$base.idx" ]; then
|
||||
echo "rebuilding missing idx in $dir (trigger: volume $base)"
|
||||
weed fix "$dir"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if ls "$dir"/*.idx >/dev/null 2>&1; then
|
||||
mv "$dir"/*.idx /idx/
|
||||
fi
|
||||
done
|
||||
volumeMounts:
|
||||
- name: idx
|
||||
mountPath: /idx
|
||||
|
||||
@@ -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: {}
|
||||
@@ -378,7 +385,7 @@ volume:
|
||||
enabled: true
|
||||
image: alpine/k8s:1.28.4
|
||||
|
||||
# idx can be defined by:
|
||||
# idx (the volume index) may use a separate PERSISTENT volume:
|
||||
#
|
||||
# idx:
|
||||
# type: "hostPath"
|
||||
@@ -397,13 +404,14 @@ volume:
|
||||
# type: "existingClaim"
|
||||
# claimName: "myClaim"
|
||||
#
|
||||
# or
|
||||
# "emptyDir" is rejected for idx (the chart fails to render): an ephemeral
|
||||
# index is wiped on every restart while the data persists, forcing a full
|
||||
# rebuild each start (a fatal crash on older versions). "logs" may still use
|
||||
# any of the above or emptyDir.
|
||||
#
|
||||
# idx:
|
||||
# type: "emptyDir"
|
||||
|
||||
# same applies to "logs"
|
||||
|
||||
# Default {} keeps the index next to the data, so it persists with the data and
|
||||
# needs no separate volume. Recommended unless you must split the index onto
|
||||
# its own persistent storage.
|
||||
idx: {}
|
||||
|
||||
# Resource requests, limits, etc. for the vol-move-idx initContainer. This
|
||||
|
||||
@@ -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.
|
||||
|
||||
+9586
-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 {
|
||||
}
|
||||
|
||||
@@ -188,6 +188,12 @@ pub struct Cli {
|
||||
#[arg(long = "securityFile", default_value = "")]
|
||||
pub security_file: String,
|
||||
|
||||
/// If true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints
|
||||
/// including loopback / link-local hosts. Default rejects internal /
|
||||
/// metadata endpoints.
|
||||
#[arg(long = "volume.allowUntrustedRemoteEndpoints", default_value_t = false)]
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
|
||||
/// A file of command line options, each line in optionName=optionValue format.
|
||||
#[arg(long = "options", default_value = "")]
|
||||
pub options: String,
|
||||
@@ -258,6 +264,9 @@ pub struct VolumeServerConfig {
|
||||
pub enable_write_queue: bool,
|
||||
/// Path to security.toml — stored for SIGHUP reload.
|
||||
pub security_file: String,
|
||||
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
|
||||
/// (allows loopback / link-local / metadata hosts).
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
}
|
||||
|
||||
pub use crate::storage::needle_map::NeedleMapKind;
|
||||
@@ -804,6 +813,7 @@ fn resolve_config(cli: Cli) -> VolumeServerConfig {
|
||||
.map(|v| v == "1" || v == "true")
|
||||
.unwrap_or(false),
|
||||
security_file: cli.security_file,
|
||||
allow_untrusted_remote_endpoints: cli.allow_untrusted_remote_endpoints,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -327,6 +327,7 @@ async fn run(
|
||||
seaweed_volume::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: config.read_mode,
|
||||
allow_untrusted_remote_endpoints: config.allow_untrusted_remote_endpoints,
|
||||
master_url,
|
||||
master_urls,
|
||||
seed_master_set,
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! SSRF guard for caller-supplied remote storage endpoints.
|
||||
//!
|
||||
//! `FetchAndWriteNeedle` accepts an S3 endpoint URL chosen by the caller and
|
||||
//! dials it directly from the volume server, which typically has network
|
||||
//! access to cluster-internal hosts. Without validation a caller could point
|
||||
//! the server at loopback / link-local / RFC 1918 / cloud-metadata addresses
|
||||
//! and read internal services (SSRF). This mirrors the Go volume server's
|
||||
//! `validateRemoteEndpoint` (`weed/server/volume_grpc_remote.go`); operators
|
||||
//! that legitimately fetch from private hosts opt out with
|
||||
//! `-volume.allowUntrustedRemoteEndpoints`.
|
||||
//!
|
||||
//! NOTE: the Go server additionally pins the validated endpoint against DNS
|
||||
//! rebinding with a custom dialer that re-checks the resolved IP at TCP connect
|
||||
//! time (`guardedDialer`). The `aws-sdk-s3` client used here builds its own
|
||||
//! connector, so that connect-time re-validation is not yet ported; the
|
||||
//! up-front resolve-and-check below still blocks the common SSRF vectors. A
|
||||
//! narrow TOCTOU window (a hostname that resolves to a public IP here and then
|
||||
//! flips to a blocked one when the SDK dials) remains as a follow-up.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
/// AWS/Azure/GCP IPv4 instance-metadata-service (IMDS) address. It is
|
||||
/// link-local and thus already covered by [`is_link_local`], but is named
|
||||
/// explicitly so the rejection reason is unambiguous in logs.
|
||||
const IMDS_IPV4: IpAddr = IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254));
|
||||
|
||||
/// Hostnames that target cloud instance metadata services, blocked regardless
|
||||
/// of how they resolve because some environments alias the IMDS address under
|
||||
/// a name.
|
||||
fn is_blocked_imds_host(host: &str) -> bool {
|
||||
matches!(host, "metadata.google.internal" | "metadata")
|
||||
}
|
||||
|
||||
/// Whether `ip` is in a link-local range: IPv4 169.254.0.0/16, IPv6 fe80::/10
|
||||
/// (unicast) and interface-local / link-local multicast (scope 1 and 2).
|
||||
fn is_link_local(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => v4.is_link_local(),
|
||||
IpAddr::V6(v6) => {
|
||||
let seg0 = v6.segments()[0];
|
||||
if (seg0 & 0xffc0) == 0xfe80 {
|
||||
return true; // fe80::/10 link-local unicast
|
||||
}
|
||||
if (seg0 & 0xff00) == 0xff00 {
|
||||
// ffXS:: multicast; reject interface-local (scope 1) and
|
||||
// link-local (scope 2) the way Go's IsInterfaceLocalMulticast /
|
||||
// IsLinkLocalMulticast do.
|
||||
let scope = seg0 & 0x000f;
|
||||
return scope == 1 || scope == 2;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ip` is in a private range: IPv4 RFC 1918, IPv6 fc00::/7 unique-local
|
||||
/// (matching Go's `net.IP.IsPrivate`).
|
||||
fn is_private(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => v4.is_private(),
|
||||
IpAddr::V6(v6) => (v6.segments()[0] & 0xfe00) == 0xfc00,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ip` is in the RFC 6598 carrier-grade NAT range (100.64.0.0/10).
|
||||
/// The IPv4 private check does not cover CGNAT, so check it explicitly.
|
||||
fn is_cgnat(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => {
|
||||
let o = v4.octets();
|
||||
o[0] == 100 && (o[1] & 0xc0) == 0x40 // second octet 64..=127
|
||||
}
|
||||
IpAddr::V6(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an error if `ip` is not safe to dial from a server that can reach
|
||||
/// cluster-internal hosts. Mirrors Go's `checkBlockedIP`.
|
||||
pub fn check_blocked_ip(endpoint: &str, ip: IpAddr) -> Result<(), String> {
|
||||
// Normalize IPv4-mapped IPv6 (`::ffff:a.b.c.d`) to its IPv4 form so the
|
||||
// IPv4 deny rules apply. The OS routes these to the embedded IPv4 address,
|
||||
// so without this `::ffff:127.0.0.1` / `::ffff:169.254.169.254` would slip
|
||||
// past the IPv6-only checks. Mirrors Go's reliance on net.IP.To4().
|
||||
let ip = match ip {
|
||||
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||
Some(v4) => IpAddr::V4(v4),
|
||||
None => IpAddr::V6(v6),
|
||||
},
|
||||
other => other,
|
||||
};
|
||||
if ip == IMDS_IPV4 {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} targets instance metadata service {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if ip.is_loopback() {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to loopback address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if ip.is_unspecified() {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to unspecified address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_link_local(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to link-local address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_private(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to private address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_cgnat(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to CGNAT address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Outcome of the synchronous, DNS-free portion of endpoint validation.
|
||||
#[derive(Debug)]
|
||||
enum HostCheck {
|
||||
/// Host was a literal IP and already passed [`check_blocked_ip`].
|
||||
Validated,
|
||||
/// Host is a name that must be resolved and each address checked.
|
||||
NeedsResolution(String),
|
||||
}
|
||||
|
||||
/// Validate the scheme and host without touching DNS. Pure and unit-testable.
|
||||
fn precheck_endpoint(endpoint: &str) -> Result<HostCheck, String> {
|
||||
let trimmed = endpoint.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("remote endpoint is empty".to_string());
|
||||
}
|
||||
|
||||
let Some(scheme_end) = trimmed.find("://") else {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} must use http or https",
|
||||
endpoint
|
||||
));
|
||||
};
|
||||
let scheme = trimmed[..scheme_end].to_ascii_lowercase();
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} must use http or https, got {:?}",
|
||||
endpoint,
|
||||
&trimmed[..scheme_end]
|
||||
));
|
||||
}
|
||||
|
||||
// Authority is everything up to the first '/', '?', or '#'.
|
||||
let after = &trimmed[scheme_end + 3..];
|
||||
let authority_end = after
|
||||
.find(|c| c == '/' || c == '?' || c == '#')
|
||||
.unwrap_or(after.len());
|
||||
let authority = &after[..authority_end];
|
||||
|
||||
// Strip optional userinfo ("user:pass@").
|
||||
let host_port = match authority.rfind('@') {
|
||||
Some(at) => &authority[at + 1..],
|
||||
None => authority,
|
||||
};
|
||||
|
||||
// Extract the host, handling bracketed IPv6 literals and host:port.
|
||||
let host = if let Some(rest) = host_port.strip_prefix('[') {
|
||||
match rest.find(']') {
|
||||
Some(end) => &rest[..end],
|
||||
None => {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} has a malformed IPv6 host",
|
||||
endpoint
|
||||
))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match host_port.find(':') {
|
||||
Some(colon) => &host_port[..colon],
|
||||
None => host_port,
|
||||
}
|
||||
};
|
||||
|
||||
if host.is_empty() {
|
||||
return Err(format!("remote endpoint {:?} has no host", endpoint));
|
||||
}
|
||||
|
||||
if is_blocked_imds_host(&host.to_ascii_lowercase()) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} targets instance metadata service",
|
||||
endpoint
|
||||
));
|
||||
}
|
||||
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
check_blocked_ip(endpoint, ip)?;
|
||||
return Ok(HostCheck::Validated);
|
||||
}
|
||||
|
||||
Ok(HostCheck::NeedsResolution(host.to_string()))
|
||||
}
|
||||
|
||||
/// Resolve `host` to its addresses with a short timeout, matching Go's 2s
|
||||
/// resolver deadline.
|
||||
async fn resolve_host(host: &str) -> Result<Vec<IpAddr>, String> {
|
||||
let lookup = tokio::net::lookup_host((host, 0u16));
|
||||
let addrs = tokio::time::timeout(std::time::Duration::from_secs(2), lookup)
|
||||
.await
|
||||
.map_err(|_| format!("resolve remote endpoint host {:?}: timed out", host))?
|
||||
.map_err(|e| format!("resolve remote endpoint host {:?}: {}", host, e))?;
|
||||
Ok(addrs.map(|sock| sock.ip()).collect())
|
||||
}
|
||||
|
||||
/// Returns an error if `endpoint` is not safe to dial from a server with access
|
||||
/// to cluster-internal hosts. Rejects empty / non-http(s) endpoints,
|
||||
/// loopback / unspecified / link-local / RFC 1918 / CGNAT addresses, and
|
||||
/// well-known IMDS hostnames. Hostnames are resolved and every returned address
|
||||
/// is checked. Mirrors Go's `validateRemoteEndpoint`.
|
||||
pub async fn validate_remote_endpoint(endpoint: &str) -> Result<(), String> {
|
||||
match precheck_endpoint(endpoint)? {
|
||||
HostCheck::Validated => Ok(()),
|
||||
HostCheck::NeedsResolution(host) => {
|
||||
let addrs = resolve_host(&host).await?;
|
||||
if addrs.is_empty() {
|
||||
return Err(format!(
|
||||
"resolve remote endpoint host {:?}: no addresses",
|
||||
host
|
||||
));
|
||||
}
|
||||
for ip in addrs {
|
||||
check_blocked_ip(endpoint, ip)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ip(s: &str) -> IpAddr {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_blocked_literal_endpoints() {
|
||||
let cases = [
|
||||
("http://127.0.0.1:8080", "loopback"),
|
||||
("http://[::1]:8080", "loopback"),
|
||||
("http://169.254.169.254/", "metadata"),
|
||||
("http://0.0.0.0/", "unspecified"),
|
||||
("http://[fe80::1]/", "link-local"),
|
||||
("http://10.0.0.1/", "private"),
|
||||
("http://172.16.5.5/", "private"),
|
||||
("http://192.168.0.1/", "private"),
|
||||
("http://100.64.0.1/", "CGNAT"),
|
||||
];
|
||||
for (endpoint, want) in cases {
|
||||
let err = precheck_endpoint(endpoint).expect_err(endpoint);
|
||||
assert!(err.contains(want), "{endpoint}: {err:?} missing {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_and_bad_scheme() {
|
||||
assert!(precheck_endpoint("").unwrap_err().contains("empty"));
|
||||
assert!(precheck_endpoint("ftp://example.com/")
|
||||
.unwrap_err()
|
||||
.contains("http or https"));
|
||||
assert!(precheck_endpoint("example.com/")
|
||||
.unwrap_err()
|
||||
.contains("http or https"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_imds_hostnames() {
|
||||
assert!(precheck_endpoint("http://metadata.google.internal/")
|
||||
.unwrap_err()
|
||||
.contains("metadata service"));
|
||||
assert!(precheck_endpoint("http://metadata/")
|
||||
.unwrap_err()
|
||||
.contains("metadata service"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_public_literal_and_defers_hostname() {
|
||||
assert!(matches!(
|
||||
precheck_endpoint("https://52.216.10.10/"),
|
||||
Ok(HostCheck::Validated)
|
||||
));
|
||||
match precheck_endpoint("https://s3.us-east-1.amazonaws.com/") {
|
||||
Ok(HostCheck::NeedsResolution(host)) => {
|
||||
assert_eq!(host, "s3.us-east-1.amazonaws.com")
|
||||
}
|
||||
other => panic!("expected resolution, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_blocked_ip_matches_resolved_categories() {
|
||||
// Mirror Go's "host resolves to X" cases at the address level.
|
||||
assert!(check_blocked_ip("e", ip("127.0.0.1"))
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(check_blocked_ip("e", ip("169.254.10.20"))
|
||||
.unwrap_err()
|
||||
.contains("link-local"));
|
||||
assert!(check_blocked_ip("e", ip("10.1.2.3"))
|
||||
.unwrap_err()
|
||||
.contains("private"));
|
||||
assert!(check_blocked_ip("e", ip("172.20.0.5"))
|
||||
.unwrap_err()
|
||||
.contains("private"));
|
||||
assert!(check_blocked_ip("e", ip("192.168.1.1"))
|
||||
.unwrap_err()
|
||||
.contains("private"));
|
||||
assert!(check_blocked_ip("e", ip("100.64.0.42"))
|
||||
.unwrap_err()
|
||||
.contains("CGNAT"));
|
||||
assert!(check_blocked_ip("e", ip("fc00::1"))
|
||||
.unwrap_err()
|
||||
.contains("private"));
|
||||
assert!(check_blocked_ip("e", ip("52.216.10.10")).is_ok());
|
||||
assert!(check_blocked_ip("e", ip("2606:4700:4700::1111")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ipv4_mapped_ipv6() {
|
||||
// IPv4-mapped IPv6 must be unmapped so the IPv4 rules catch it.
|
||||
assert!(check_blocked_ip("e", ip("::ffff:127.0.0.1"))
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(check_blocked_ip("e", ip("::ffff:169.254.169.254"))
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(check_blocked_ip("e", ip("::ffff:10.0.0.1"))
|
||||
.unwrap_err()
|
||||
.contains("private"));
|
||||
// A mapped public address still passes, and genuine IPv6 loopback is
|
||||
// still caught by the V6 path.
|
||||
assert!(check_blocked_ip("e", ip("::ffff:52.216.10.10")).is_ok());
|
||||
assert!(check_blocked_ip("e", ip("::1"))
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
// Bracketed mapped literal via the full endpoint path.
|
||||
assert!(precheck_endpoint("http://[::ffff:127.0.0.1]/")
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,12 @@
|
||||
//! Provides a trait-based abstraction over cloud storage providers (S3, GCS, Azure, etc.)
|
||||
//! and a registry to create clients from protobuf RemoteConf messages.
|
||||
|
||||
pub mod endpoint_guard;
|
||||
pub mod s3;
|
||||
pub mod s3_tier;
|
||||
|
||||
pub use endpoint_guard::validate_remote_endpoint;
|
||||
|
||||
use crate::pb::remote_pb::{RemoteConf, RemoteStorageLocation};
|
||||
|
||||
/// Error type for remote storage operations.
|
||||
@@ -86,6 +89,26 @@ pub fn make_remote_storage_client(
|
||||
}
|
||||
}
|
||||
|
||||
/// Endpoint URL that the volume server would dial directly for `conf`, or
|
||||
/// `None` for non-S3-compatible backends. Every type handled here routes
|
||||
/// through [`s3::S3RemoteStorageClient`] with a caller-supplied endpoint, so
|
||||
/// the SSRF guard must validate each one. Keep this match in sync with
|
||||
/// [`make_remote_storage_client`].
|
||||
pub fn s3_compatible_endpoint(conf: &RemoteConf) -> Option<&str> {
|
||||
match conf.r#type.as_str() {
|
||||
"s3" => Some(&conf.s3_endpoint),
|
||||
"wasabi" => Some(&conf.wasabi_endpoint),
|
||||
"backblaze" => Some(&conf.backblaze_endpoint),
|
||||
"aliyun" => Some(&conf.aliyun_endpoint),
|
||||
"tencent" => Some(&conf.tencent_endpoint),
|
||||
"baidu" => Some(&conf.baidu_endpoint),
|
||||
"filebase" => Some(&conf.filebase_endpoint),
|
||||
"storj" => Some(&conf.storj_endpoint),
|
||||
"contabo" => Some(&conf.contabo_endpoint),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract S3-compatible credentials from a RemoteConf based on its type.
|
||||
fn extract_s3_credentials(conf: &RemoteConf) -> (String, String, String, String) {
|
||||
match conf.r#type.as_str() {
|
||||
@@ -155,3 +178,37 @@ fn extract_s3_credentials(conf: &RemoteConf) -> (String, String, String, String)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn s3_compatible_endpoint_covers_all_s3_backends() {
|
||||
let s3 = RemoteConf {
|
||||
r#type: "s3".to_string(),
|
||||
s3_endpoint: "http://s3.internal".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&s3), Some("http://s3.internal"));
|
||||
|
||||
// A non-"s3" S3-compatible type still surfaces its own endpoint, so the
|
||||
// SSRF guard cannot be bypassed by picking a different alias.
|
||||
let wasabi = RemoteConf {
|
||||
r#type: "wasabi".to_string(),
|
||||
wasabi_endpoint: "http://wasabi.internal".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
s3_compatible_endpoint(&wasabi),
|
||||
Some("http://wasabi.internal")
|
||||
);
|
||||
|
||||
// Non-S3 backends do not dial a caller-supplied URL directly.
|
||||
let gcs = RemoteConf {
|
||||
r#type: "gcs".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&gcs), None);
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,7 @@ mod tests {
|
||||
white_list: vec![],
|
||||
fix_jpg_orientation: false,
|
||||
read_mode: ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
cpu_profile: String::new(),
|
||||
mem_profile: String::new(),
|
||||
compaction_byte_per_second: 0,
|
||||
|
||||
@@ -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| {
|
||||
@@ -3411,6 +3490,25 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.as_ref()
|
||||
.ok_or_else(|| Status::invalid_argument("remote storage configuration is required"))?;
|
||||
|
||||
// Reject SSRF-prone endpoints unless the operator opted out. Every
|
||||
// S3-compatible backend (s3, wasabi, backblaze, ...) dials a
|
||||
// caller-supplied endpoint URL directly via make_remote_storage_client,
|
||||
// so validate whichever endpoint applies. An empty endpoint means the
|
||||
// provider default (e.g. real AWS S3) and cannot target an internal
|
||||
// host, so skip it. Extends the Go volume server's validateRemoteEndpoint
|
||||
// gate, which only covered type "s3".
|
||||
if !self.state.allow_untrusted_remote_endpoints {
|
||||
if let Some(endpoint) = crate::remote_storage::s3_compatible_endpoint(remote_conf) {
|
||||
if !endpoint.trim().is_empty() {
|
||||
crate::remote_storage::validate_remote_endpoint(endpoint)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::invalid_argument(format!("reject remote endpoint: {}", e))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create remote storage client
|
||||
let client =
|
||||
crate::remote_storage::make_remote_storage_client(remote_conf).map_err(|e| {
|
||||
@@ -4150,17 +4248,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.
|
||||
@@ -4650,6 +4747,7 @@ mod tests {
|
||||
crate::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: crate::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
@@ -4754,6 +4852,7 @@ mod tests {
|
||||
crate::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: crate::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
@@ -4862,6 +4961,7 @@ mod tests {
|
||||
crate::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: crate::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: master_urls.first().cloned().unwrap_or_default(),
|
||||
master_urls,
|
||||
seed_master_set,
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//! matching Go's `server/volume_grpc_client_to_master.go`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use tracing::{error, info, warn};
|
||||
@@ -314,6 +315,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()
|
||||
},
|
||||
);
|
||||
@@ -826,6 +828,27 @@ fn build_heartbeat_with_ec_status(
|
||||
delete_vids.push(vol.id);
|
||||
should_delete_volume = true;
|
||||
} else if !vol.is_expired(volume_size, volume_size_limit) {
|
||||
// Detect phantom volumes: the .dat was unlinked from disk but is still
|
||||
// held open as a deleted FD, so the volume keeps serving and heartbeating
|
||||
// while no disk-path operation can ever succeed. Skip remote-tiered volumes,
|
||||
// whose .dat legitimately lives in cloud storage. Only a present .dat is
|
||||
// cached for 30s; a missing one is re-checked every heartbeat so the volume
|
||||
// stays suppressed until the file returns. See issues/10004
|
||||
if vol.file_count() > 0 && !vol.has_remote_file {
|
||||
const DISK_CHECK_INTERVAL_NS: i64 = 30 * 1_000_000_000;
|
||||
let now_ns = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or(Duration::ZERO)
|
||||
.as_nanos() as i64;
|
||||
if now_ns - vol.last_disk_check_ns.load(Ordering::Relaxed) > DISK_CHECK_INTERVAL_NS {
|
||||
if !Path::new(&vol.file_name(".dat")).exists() {
|
||||
warn!("Volume {}: data file {} missing (held open as deleted FD) - not reporting to master", vol.id.0, vol.file_name(".dat"));
|
||||
continue;
|
||||
}
|
||||
vol.last_disk_check_ns.store(now_ns, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
|
||||
volumes.push(master_pb::VolumeInformationMessage {
|
||||
id: vol.id.0,
|
||||
@@ -1046,6 +1069,7 @@ mod tests {
|
||||
write_queue: std::sync::OnceLock::new(),
|
||||
s3_tier_registry: std::sync::RwLock::new(S3TierRegistry::new()),
|
||||
read_mode: ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
|
||||
@@ -131,6 +131,7 @@ mod tests {
|
||||
white_list: vec![],
|
||||
fix_jpg_orientation: false,
|
||||
read_mode: ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
cpu_profile: String::new(),
|
||||
mem_profile: String::new(),
|
||||
compaction_byte_per_second: 0,
|
||||
|
||||
@@ -77,6 +77,9 @@ pub struct VolumeServerState {
|
||||
pub s3_tier_registry: std::sync::RwLock<crate::remote_storage::s3_tier::S3TierRegistry>,
|
||||
/// Read mode: local, proxy, or redirect for non-local volumes.
|
||||
pub read_mode: ReadMode,
|
||||
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation,
|
||||
/// allowing arbitrary (incl. loopback / link-local / metadata) hosts.
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
/// First master address for volume lookups (e.g., "localhost:9333").
|
||||
pub master_url: String,
|
||||
/// Seed master addresses for UI rendering.
|
||||
|
||||
@@ -205,6 +205,7 @@ mod tests {
|
||||
crate::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: crate::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -503,6 +503,7 @@ pub struct Volume {
|
||||
|
||||
last_modified_ts_seconds: u64,
|
||||
last_append_at_ns: u64,
|
||||
pub last_disk_check_ns: Arc<std::sync::atomic::AtomicI64>, // for phantom volume detection cache
|
||||
|
||||
last_compact_index_offset: u64,
|
||||
last_compact_revision: u16,
|
||||
@@ -575,6 +576,7 @@ impl Volume {
|
||||
location_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
last_modified_ts_seconds: 0,
|
||||
last_append_at_ns: 0,
|
||||
last_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(0)),
|
||||
last_compact_index_offset: 0,
|
||||
last_compact_revision: 0,
|
||||
is_compacting: false,
|
||||
@@ -588,6 +590,37 @@ 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_disk_check_ns: Arc::new(std::sync::atomic::AtomicI64::new(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 +2930,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 +2945,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 +3417,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 +4990,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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ fn test_state_with_guard(
|
||||
seaweed_volume::remote_storage::s3_tier::S3TierRegistry::new(),
|
||||
),
|
||||
read_mode: seaweed_volume::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# FUSE database load / durability / performance benchmark
|
||||
|
||||
Runs **MySQL (InnoDB)** and **SQLite** with their data files on a SeaweedFS **FUSE mount**,
|
||||
with ~1 GB datasets, and answers two questions:
|
||||
|
||||
1. **Durability** — does any committed data get lost across normal shutdown, an unexpected
|
||||
`kill -9`, or a crash during active writes?
|
||||
2. **Performance** — how much slower is the FUSE mount than the local disk for the same
|
||||
workload (bulk load, OLTP commits, scans, raw fsync)?
|
||||
|
||||
Each row carries a CRC32 of an incompressible (so ~1 GB actually hits the volumes)
|
||||
deterministic payload; verification checks `integrity_check`/`CHECK TABLE`, exact row count,
|
||||
contiguous-id prefix, and a per-row CRC recompute.
|
||||
|
||||
## Results (single node, macOS arm64 + macFUSE, weed 4.34, local NVMe, 2026-06-15)
|
||||
|
||||
### Durability — 6/6 PASS, no committed data lost, no corruption
|
||||
| scenario | what | SQLite | MySQL |
|
||||
|---|---|---|---|
|
||||
| A normal shutdown | graceful DB stop, unmount, cluster stop, restart, verify | PASS | PASS |
|
||||
| B unexpected (`kill -9`) | kill -9 db+mount+cluster, restart, recover, verify | PASS | PASS |
|
||||
| C crash during writes | kill -9 mid-load, restart, recover, verify committed prefix | PASS | PASS |
|
||||
|
||||
Scenario C confirmed correct recovery: the in-flight transaction rolled back, every
|
||||
fsync-committed row survived as a contiguous prefix (InnoDB redo recovery ~9 s).
|
||||
|
||||
### Performance — FUSE vs host (same disk, same durability settings)
|
||||
Raw filesystem:
|
||||
| metric | host | FUSE | FUSE slower |
|
||||
|---|---|---|---|
|
||||
| seq write +fsync | 2336 MB/s | 369 MB/s | 6.3x |
|
||||
| seq read (warm) | 3435 MB/s | 1422 MB/s | 2.4x |
|
||||
| fsync latency | 0.13 ms | 1.18 ms | 9x |
|
||||
|
||||
SQLite (1 GB, journal=DELETE, synchronous=FULL):
|
||||
| metric | host | FUSE | FUSE slower |
|
||||
|---|---|---|---|
|
||||
| bulk load | 5.8 s (177 MB/s) | 11.6 s (88 MB/s) | 2.0x |
|
||||
| OLTP 1-row txns | 1987 tx/s | 171 tx/s | 11.6x |
|
||||
| full scan (warm) | 316 MB/s | 427 MB/s | ~equal (python-bound) |
|
||||
|
||||
MySQL/InnoDB (1 GB, trx_commit=1, flush_method=fsync):
|
||||
| metric | host | FUSE | FUSE slower |
|
||||
|---|---|---|---|
|
||||
| bulk load | 24.4 s (42 MB/s) | 32.9 s (31 MB/s) | 1.35x |
|
||||
| OLTP 1-row commits | 10542 tx/s | 1144 tx/s | 9.2x |
|
||||
| full scan | 2419 MB/s | 430 MB/s | 5.6x |
|
||||
|
||||
**Takeaway:** the cost is dominated by fsync/commit latency (0.13 → 1.18 ms, ~9x) because
|
||||
every durable commit uploads the chunk to the volume + persists the filer chunk-manifest over
|
||||
loopback. Small fsync'd transactions are ~9-12x slower; bulk loads (commits amortized) are
|
||||
1.3-2x slower; warm/sequential reads are close to host. These are single-node loopback
|
||||
numbers — a real cluster (remote volumes, replication) adds network RTT + replica fsync per
|
||||
commit.
|
||||
|
||||
## Durability caveat (test scope)
|
||||
`kill -9` terminates the **processes** while the OS keeps running, so everything that reached
|
||||
the OS page cache (all fsync'd data) survives — this faithfully tests process/daemon crashes
|
||||
and is what passed 6/6. It does **not** simulate true **power loss** (page cache lost). The
|
||||
FUSE mount uploads chunks **without** `fsync=true` (`weed/mount/weedfs_write.go` builds
|
||||
`UploadOption` with no `Fsync`), so the volume does not fsync `.dat` per upload and the filer
|
||||
leveldb likely does not sync per write; under a real power cut, recently-"committed" data that
|
||||
only reached the page cache could be lost. A VM hard-reset / power-loss test on real hardware
|
||||
is the follow-up to close that gap.
|
||||
|
||||
## Requirements
|
||||
- `weed` on `$PATH` (or set `WEED=/path/to/weed`)
|
||||
- macFUSE (macOS) or libfuse (Linux)
|
||||
- `python3`, `sqlite3`
|
||||
- MySQL/MariaDB install; set `MYSQL_BASE` to its prefix (default macOS Homebrew
|
||||
`/opt/homebrew/opt/mysql`; must contain `bin/mysqld`, `bin/mysql`, `bin/mysqladmin`).
|
||||
For `mysql_bench.py` on a non-default install, also set `MYSQL_BIN=/path/to/mysql`.
|
||||
|
||||
## Run
|
||||
Runtime artifacts (cluster, mount, logs) go to `$SEAWEED_BENCH_WORK`
|
||||
(default `/tmp/seaweedfs_fuse_db_bench`), kept out of the repo.
|
||||
|
||||
cd test/benchmark/fuse_db
|
||||
bash bin/run_sqlite.sh > results/sqlite.log 2>&1 # SQLite durability suite
|
||||
bash bin/run_mysql.sh > results/mysql.log 2>&1 # MySQL durability suite
|
||||
bash bin/compare.sh > results/compare.log 2>&1 # FUSE vs host performance
|
||||
|
||||
The harness manages only its own processes (via pidfiles) on non-default ports
|
||||
(9555/9560/9565, mysqld 3308); it never runs `pkill weed`, so other SeaweedFS instances on
|
||||
the box are untouched.
|
||||
|
||||
## Files
|
||||
bin/lib.sh cluster/mount/mysqld lifecycle helpers (start/stop/kill, clean state)
|
||||
bin/run_sqlite.sh SQLite 1GB load + A/B/C crash scenarios
|
||||
bin/run_mysql.sh MySQL 1GB load + A/B/C crash scenarios
|
||||
bin/compare.sh FUSE-vs-host driver
|
||||
bin/sqlite_gen.py deterministic incompressible SQLite loader (progress/ref files)
|
||||
bin/sqlite_verify.py SQLite integrity + count + prefix + per-row CRC verifier
|
||||
bin/sqlite_bench.py SQLite load/OLTP/scan timing probe
|
||||
bin/mysql_bench.py MySQL load/OLTP/scan timing probe (via mysql CLI)
|
||||
bin/fsbench.py raw seq-write / fsync-latency / seq-read microbenchmark
|
||||
|
||||
The numbers above are the reference baseline; rerun the scripts to reproduce. Run output is
|
||||
written to results/*.log, which is gitignored (repo-wide *.log rule) -- not checked in.
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
# Identical SQLite + MySQL + raw-fs workloads on HOST (local APFS) vs the SeaweedFS
|
||||
# FUSE mount. Same disk underneath, same DB durability settings -> the delta is the
|
||||
# SeaweedFS+FUSE stack.
|
||||
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$BIN/lib.sh"
|
||||
HOSTDIR=$WORK/hostdir # local disk, NOT under the FUSE mount
|
||||
ROWS=262144; SBATCH=4096; MBATCH=8192; OLTP=2000
|
||||
|
||||
mysqld_init_at() { rm -rf "$1"; mkdir -p "$1"; "$MYSQLD" --initialize-insecure --datadir="$1" \
|
||||
--basedir="$MYSQL_BASE" --log-error="$LOGS/mysql_init_cmp.log"; }
|
||||
mysqld_run() {
|
||||
"$MYSQLD" --datadir="$1" --basedir="$MYSQL_BASE" --socket="$MYSQL_SOCK" --port=$MYSQL_PORT \
|
||||
--bind-address=127.0.0.1 --innodb_flush_log_at_trx_commit=1 --innodb_flush_method=fsync \
|
||||
--innodb_doublewrite=ON --innodb_buffer_pool_size=256M --secure-file-priv="" \
|
||||
--log-error="$LOGS/mysqld_cmp.log" >> "$LOGS/mysqld_cmp.out" 2>&1 &
|
||||
echo $! > "$PIDS/mysql.pid"; mysql_wait; }
|
||||
|
||||
echo "###### FUSE vs HOST $(date) ######"
|
||||
echo "ROWS=$ROWS payload=4096B incompressible SQLite(journal=DELETE,sync=FULL) InnoDB(trx_commit=1,flush=fsync)"
|
||||
|
||||
# ===================== HOST (local APFS, no SeaweedFS) =====================
|
||||
clean_state >/dev/null 2>&1
|
||||
rm -rf "$HOSTDIR"; mkdir -p "$HOSTDIR/sqlite" "$HOSTDIR/fsb"
|
||||
echo; echo "===== HOST: raw fs ====="; python3 "$BIN/fsbench.py" "$HOSTDIR/fsb"
|
||||
echo; echo "===== HOST: SQLite ====="; python3 "$BIN/sqlite_bench.py" "$HOSTDIR/sqlite/b.db" $ROWS $SBATCH $OLTP
|
||||
echo; echo "===== HOST: MySQL ====="
|
||||
mysqld_init_at "$HOSTDIR/mysql/data"; mysqld_run "$HOSTDIR/mysql/data"
|
||||
python3 "$BIN/mysql_bench.py" "$MYSQL_SOCK" cmp $ROWS $MBATCH $OLTP
|
||||
mysql_stop_graceful
|
||||
|
||||
# ===================== FUSE (SeaweedFS mount) =====================
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
mkdir -p "$MNT/sqlite" "$MNT/fsb"
|
||||
echo; echo "===== FUSE: raw fs ====="; python3 "$BIN/fsbench.py" "$MNT/fsb"
|
||||
echo; echo "===== FUSE: SQLite ====="; python3 "$BIN/sqlite_bench.py" "$MNT/sqlite/b.db" $ROWS $SBATCH $OLTP
|
||||
echo; echo "===== FUSE: MySQL ====="
|
||||
mysqld_init_at "$MNT/mysql/data"; mysqld_run "$MNT/mysql/data"
|
||||
python3 "$BIN/mysql_bench.py" "$MYSQL_SOCK" cmp $ROWS $MBATCH $OLTP
|
||||
mysql_stop_graceful
|
||||
|
||||
stop_all
|
||||
rm -rf "$HOSTDIR"
|
||||
echo; echo "###### compare done ######"
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
# Raw filesystem microbenchmark in one directory. Prints TSV: METRIC<TAB>value<TAB>unit
|
||||
# SEQWRITE MB/s (512MB stream + final fsync)
|
||||
# FSYNC ops/s (500 x: pwrite 4KB at random offset in a 64MB file, then fsync)
|
||||
# SEQREAD MB/s (read the 512MB file back; warm cache)
|
||||
import sys, os, time, random
|
||||
|
||||
d = sys.argv[1]
|
||||
os.makedirs(d, exist_ok=True)
|
||||
big = os.path.join(d, "fsb_big.bin")
|
||||
sm = os.path.join(d, "fsb_sync.bin")
|
||||
|
||||
# SEQWRITE 512MB + fsync
|
||||
n = 512 * 1024 * 1024
|
||||
buf = os.urandom(8 * 1024 * 1024)
|
||||
t = time.time(); f = open(big, "wb"); w = 0
|
||||
while w < n:
|
||||
f.write(buf); w += len(buf)
|
||||
f.flush(); os.fsync(f.fileno()); f.close()
|
||||
dt = time.time() - t
|
||||
print(f"SEQWRITE\t{w/1048576/dt:.0f}\tMB/s")
|
||||
|
||||
# FSYNC latency: 500 x (pwrite 4KB random offset + fsync) on a 64MB file
|
||||
fd = os.open(sm, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
os.ftruncate(fd, 64 * 1024 * 1024)
|
||||
os.fsync(fd)
|
||||
page = os.urandom(4096)
|
||||
N = 500
|
||||
rnd = random.Random(12345)
|
||||
t = time.time()
|
||||
for _ in range(N):
|
||||
off = rnd.randrange(0, 64 * 1024 * 1024 - 4096) & ~0xfff
|
||||
os.pwrite(fd, page, off)
|
||||
os.fsync(fd)
|
||||
dt = time.time() - t
|
||||
os.close(fd)
|
||||
print(f"FSYNC\t{N/dt:.0f}\tops/s")
|
||||
print(f"FSYNCLAT\t{dt/N*1000:.2f}\tms")
|
||||
|
||||
# SEQREAD (warm)
|
||||
t = time.time(); tot = 0
|
||||
with open(big, "rb") as f:
|
||||
while True:
|
||||
b = f.read(8 * 1024 * 1024)
|
||||
if not b: break
|
||||
tot += len(b)
|
||||
dt = time.time() - t
|
||||
print(f"SEQREAD\t{tot/1048576/dt:.0f}\tMB/s")
|
||||
|
||||
for p in (big, sm):
|
||||
try: os.remove(p)
|
||||
except OSError: pass
|
||||
Executable
+214
@@ -0,0 +1,214 @@
|
||||
# Shared config + helpers for the SeaweedFS FUSE load/durability test.
|
||||
# IMPORTANT: this harness manages ONLY its own processes via pidfiles and its own
|
||||
# (non-default) ports. It never runs `pkill weed`, so any other SeaweedFS instances
|
||||
# on the box (e.g. default ports 9333/8888) are safe.
|
||||
#
|
||||
# Config via env:
|
||||
# SEAWEED_BENCH_WORK runtime dir for cluster/mount/logs (default /tmp/...; kept out of the repo)
|
||||
# WEED path to the weed binary (default: from $PATH)
|
||||
# MYSQL_BASE MySQL install prefix (default macOS Homebrew; on Linux e.g. /usr)
|
||||
|
||||
set -u
|
||||
|
||||
WORK="${SEAWEED_BENCH_WORK:-/tmp/seaweedfs_fuse_db_bench}"
|
||||
WEED="${WEED:-$(command -v weed || echo weed)}"
|
||||
RUN=$WORK
|
||||
CLUSTER=$RUN/cluster # weed server -dir (master+volume+filer state) -- local disk
|
||||
MNT=$RUN/mnt # FUSE mount point (the SeaweedFS filesystem under test)
|
||||
LOGS=$RUN/logs
|
||||
LOCAL=$RUN/local # non-FUSE scratch: pidfiles, mysql socket, references
|
||||
PIDS=$LOCAL/pids
|
||||
RESULTS=$RUN/results
|
||||
|
||||
# Isolated, non-default ports (avoid colliding with any running cluster)
|
||||
MASTER_PORT=9555
|
||||
VOLUME_PORT=9560
|
||||
FILER_PORT=9565
|
||||
FILER_GRPC=19565
|
||||
|
||||
# MySQL (macOS Homebrew default; override MYSQL_BASE on Linux, e.g. /usr)
|
||||
MYSQL_BASE="${MYSQL_BASE:-/opt/homebrew/opt/mysql}"
|
||||
MYSQLD=$MYSQL_BASE/bin/mysqld
|
||||
MYSQL=$MYSQL_BASE/bin/mysql
|
||||
export MYSQL_BIN="${MYSQL_BIN:-$MYSQL}" # propagated to mysql_bench.py
|
||||
MYSQLADMIN=$MYSQL_BASE/bin/mysqladmin
|
||||
MYSQL_PORT=3308
|
||||
MYSQL_SOCK=$LOCAL/mysql.sock # socket on LOCAL disk, datadir on FUSE
|
||||
MYSQL_DATADIR=$MNT/mysql/data # on the FUSE mount -- the thing under test
|
||||
|
||||
ts() { date +%H:%M:%S; }
|
||||
say() { echo "[$(ts)] $*"; }
|
||||
|
||||
ensure_dirs() { mkdir -p "$CLUSTER" "$MNT" "$LOGS" "$LOCAL" "$PIDS" "$RESULTS" "$LOCAL/mountcache"; }
|
||||
|
||||
# Portable unmount: fusermount (Linux non-root) -> umount -> diskutil (macOS).
|
||||
fuse_umount() { fusermount -u "$1" 2>/dev/null || fusermount3 -u "$1" 2>/dev/null || umount "$1" 2>/dev/null || diskutil unmount "$1" 2>/dev/null; }
|
||||
fuse_umount_force() { fusermount -uz "$1" 2>/dev/null || fusermount3 -uz "$1" 2>/dev/null || umount -f "$1" 2>/dev/null || diskutil unmount force "$1" 2>/dev/null; }
|
||||
|
||||
# My (and only my) ports. Used for the kill-by-port safety net in clean_state.
|
||||
MY_PORTS="$MASTER_PORT $VOLUME_PORT $FILER_PORT 19555 19560 $FILER_GRPC $MYSQL_PORT"
|
||||
port_busy() { lsof -ti TCP:"$1" >/dev/null 2>&1; }
|
||||
wait_port_free() { # $1=port $2=max-halfsec
|
||||
local n=${2:-40}; for i in $(seq 1 "$n"); do port_busy "$1" || return 0; sleep 0.5; done; return 1; }
|
||||
|
||||
# ---- cluster (master+volume+filer in one process) ----
|
||||
cluster_start() {
|
||||
ensure_dirs
|
||||
if ! wait_port_free "$MASTER_PORT" 30; then
|
||||
say "ERROR master port $MASTER_PORT still busy (pid $(lsof -ti TCP:$MASTER_PORT|tr '\n' ' ')); not starting"; return 1
|
||||
fi
|
||||
say "starting weed server (master:$MASTER_PORT volume:$VOLUME_PORT filer:$FILER_PORT)"
|
||||
"$WEED" server -ip=127.0.0.1 -dir="$CLUSTER" \
|
||||
-master.port=$MASTER_PORT -volume.port=$VOLUME_PORT \
|
||||
-filer -filer.port=$FILER_PORT \
|
||||
-volume.max=50 -master.volumeSizeLimitMB=1024 \
|
||||
>> "$LOGS/cluster.log" 2>&1 &
|
||||
echo $! > "$PIDS/cluster.pid"
|
||||
cluster_wait
|
||||
}
|
||||
cluster_wait() {
|
||||
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null)
|
||||
for i in $(seq 1 120); do
|
||||
# the process we launched must still be alive -- guards against a foreign
|
||||
# process answering on the port after ours fataled (e.g. bind conflict)
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
say "ERROR cluster process $pid died during startup"; tail -15 "$LOGS/cluster.log"; return 1
|
||||
fi
|
||||
if curl -s "http://127.0.0.1:$MASTER_PORT/cluster/status" >/dev/null 2>&1 \
|
||||
&& curl -s "http://127.0.0.1:$FILER_PORT/" >/dev/null 2>&1; then
|
||||
say "cluster ready (pid $pid)"; return 0
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
say "ERROR cluster not ready"; tail -20 "$LOGS/cluster.log"; return 1
|
||||
}
|
||||
cluster_stop_graceful() {
|
||||
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null) || return 0
|
||||
[ -n "${pid:-}" ] || return 0
|
||||
say "graceful stop cluster pid $pid (SIGTERM)"
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
for i in $(seq 1 60); do kill -0 "$pid" 2>/dev/null || { rm -f "$PIDS/cluster.pid"; return 0; }; sleep 0.5; done
|
||||
say "cluster still alive after 30s; SIGKILL"; kill -9 "$pid" 2>/dev/null; rm -f "$PIDS/cluster.pid"
|
||||
}
|
||||
cluster_kill_hard() {
|
||||
local pid; pid=$(cat "$PIDS/cluster.pid" 2>/dev/null) || return 0
|
||||
[ -n "${pid:-}" ] && { say "HARD kill -9 cluster pid $pid"; kill -9 "$pid" 2>/dev/null; }
|
||||
rm -f "$PIDS/cluster.pid"
|
||||
}
|
||||
|
||||
# ---- FUSE mount ----
|
||||
mount_start() {
|
||||
ensure_dirs
|
||||
say "mounting FUSE at $MNT (filer 127.0.0.1:$FILER_PORT)"
|
||||
"$WEED" mount -filer=127.0.0.1:$FILER_PORT -dir="$MNT" \
|
||||
-dirAutoCreate -cacheDir="$LOCAL/mountcache" \
|
||||
>> "$LOGS/mount.log" 2>&1 &
|
||||
echo $! > "$PIDS/mount.pid"
|
||||
mount_wait
|
||||
}
|
||||
mount_wait() {
|
||||
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
|
||||
for i in $(seq 1 120); do
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
say "ERROR mount process $pid died during startup"; tail -15 "$LOGS/mount.log"; return 1
|
||||
fi
|
||||
if mount | grep -q "$MNT" && ls "$MNT" >/dev/null 2>&1; then say "mount ready (pid $pid)"; return 0; fi
|
||||
sleep 0.5
|
||||
done
|
||||
say "ERROR mount not ready"; tail -20 "$LOGS/mount.log"; return 1
|
||||
}
|
||||
mount_stop_graceful() {
|
||||
say "graceful unmount $MNT"
|
||||
fuse_umount "$MNT"
|
||||
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
|
||||
if [ -n "${pid:-}" ]; then
|
||||
for i in $(seq 1 40); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done
|
||||
kill -0 "$pid" 2>/dev/null && { kill -TERM "$pid" 2>/dev/null; sleep 1; }
|
||||
fi
|
||||
rm -f "$PIDS/mount.pid"
|
||||
}
|
||||
mount_kill_hard() {
|
||||
local pid; pid=$(cat "$PIDS/mount.pid" 2>/dev/null)
|
||||
[ -n "${pid:-}" ] && { say "HARD kill -9 mount pid $pid"; kill -9 "$pid" 2>/dev/null; }
|
||||
rm -f "$PIDS/mount.pid"
|
||||
# clean up the stale mountpoint
|
||||
fuse_umount_force "$MNT"
|
||||
}
|
||||
|
||||
# ---- MySQL ----
|
||||
mysql_init() {
|
||||
ensure_dirs
|
||||
rm -rf "$MNT/mysql"; mkdir -p "$MNT/mysql"
|
||||
say "initializing MySQL datadir on FUSE: $MYSQL_DATADIR"
|
||||
"$MYSQLD" --initialize-insecure --datadir="$MYSQL_DATADIR" --basedir="$MYSQL_BASE" \
|
||||
--log-error="$LOGS/mysql-init.log"
|
||||
}
|
||||
mysql_start() {
|
||||
say "starting mysqld (port $MYSQL_PORT, datadir on FUSE, flush_log_at_trx_commit=1, flush_method=fsync)"
|
||||
"$MYSQLD" --datadir="$MYSQL_DATADIR" --basedir="$MYSQL_BASE" \
|
||||
--socket="$MYSQL_SOCK" --port=$MYSQL_PORT --bind-address=127.0.0.1 \
|
||||
--innodb_flush_log_at_trx_commit=1 --innodb_flush_method=fsync \
|
||||
--innodb_doublewrite=ON --innodb_buffer_pool_size=256M \
|
||||
--secure-file-priv="" --log-error="$LOGS/mysqld.log" \
|
||||
>> "$LOGS/mysqld.out" 2>&1 &
|
||||
echo $! > "$PIDS/mysql.pid"
|
||||
mysql_wait
|
||||
}
|
||||
mysql_wait() {
|
||||
for i in $(seq 1 120); do
|
||||
"$MYSQLADMIN" --socket="$MYSQL_SOCK" -uroot ping >/dev/null 2>&1 && { say "mysqld ready"; return 0; }
|
||||
sleep 0.5
|
||||
done
|
||||
say "ERROR mysqld not ready"; tail -30 "$LOGS/mysqld.log"; return 1
|
||||
}
|
||||
mysql_stop_graceful() {
|
||||
say "graceful mysqld shutdown"
|
||||
"$MYSQLADMIN" --socket="$MYSQL_SOCK" -uroot shutdown 2>/dev/null
|
||||
local pid; pid=$(cat "$PIDS/mysql.pid" 2>/dev/null)
|
||||
if [ -n "${pid:-}" ]; then for i in $(seq 1 60); do kill -0 "$pid" 2>/dev/null || break; sleep 0.5; done; fi
|
||||
rm -f "$PIDS/mysql.pid"
|
||||
}
|
||||
mysql_kill() {
|
||||
local pid; pid=$(cat "$PIDS/mysql.pid" 2>/dev/null)
|
||||
[ -n "${pid:-}" ] && { say "HARD kill -9 mysqld pid $pid"; kill -9 "$pid" 2>/dev/null; }
|
||||
rm -f "$PIDS/mysql.pid"
|
||||
}
|
||||
mq() { "$MYSQL" --socket="$MYSQL_SOCK" -uroot "$@"; }
|
||||
|
||||
# ---- whole-node unexpected shutdown (simultaneous -9) ----
|
||||
hard_kill_all() {
|
||||
say "=== UNEXPECTED SHUTDOWN: kill -9 db + mount + cluster ==="
|
||||
mysql_kill
|
||||
mount_kill_hard
|
||||
cluster_kill_hard
|
||||
kill_my_ports # safety net in case any pidfile was stale
|
||||
}
|
||||
|
||||
# stop everything I started (graceful, pidfile-based)
|
||||
stop_all() { mysql_stop_graceful; mount_stop_graceful; cluster_stop_graceful; }
|
||||
|
||||
# safety net: kill anything still bound to MY (non-default) ports
|
||||
kill_my_ports() {
|
||||
for p in $MY_PORTS; do
|
||||
local pids; pids=$(lsof -ti TCP:"$p" 2>/dev/null)
|
||||
[ -n "$pids" ] && { say "killing leftover pid(s) $pids on my port $p"; kill -9 $pids 2>/dev/null; }
|
||||
done
|
||||
}
|
||||
|
||||
# ---- clean slate (wipe all test state; never touches user data) ----
|
||||
clean_state() {
|
||||
say "cleaning test state"
|
||||
stop_all
|
||||
fuse_umount_force "$MNT"
|
||||
kill_my_ports
|
||||
for p in $MASTER_PORT $VOLUME_PORT $FILER_PORT; do wait_port_free "$p" 40 || say "WARN port $p still busy"; done
|
||||
rm -rf "$CLUSTER" "$MNT" "$LOCAL/mountcache" "$PIDS" 2>/dev/null
|
||||
ensure_dirs
|
||||
}
|
||||
|
||||
status_report() {
|
||||
echo "---- status ----"
|
||||
echo "df $MNT:"; df -h "$MNT" 2>/dev/null | tail -1
|
||||
echo "cluster dir size:"; du -sh "$CLUSTER" 2>/dev/null
|
||||
echo "volumes:"; curl -s "http://127.0.0.1:$MASTER_PORT/dir/status" 2>/dev/null | python3 -c 'import sys,json;d=json.load(sys.stdin);print(" topology free/max:",d.get("Topology",{}).get("Free"),d.get("Topology",{}).get("Max"))' 2>/dev/null
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
# MySQL performance probe via the mysql CLI (no driver needed). Times each phase
|
||||
# in Python. Prints TSV: METRIC<TAB>secs<TAB>rate
|
||||
# LOAD : bulk-load <rows> rows (4096B incompressible AES payload), <batch>-row txns
|
||||
# OLTP : <oltp> single-row autocommit INSERTs (each fsyncs redo, trx_commit=1) -> tx/s
|
||||
# SCAN : SUM(CRC32(payload)) over the table (reads every payload) -> MB/s
|
||||
import os, re, sys, subprocess, time
|
||||
|
||||
sock = sys.argv[1]
|
||||
db = sys.argv[2]
|
||||
rows = int(sys.argv[3])
|
||||
batch = int(sys.argv[4])
|
||||
oltp = int(sys.argv[5])
|
||||
MYSQL = os.environ.get("MYSQL_BIN", "mysql") # lib.sh exports MYSQL_BIN; else use PATH
|
||||
|
||||
if not re.fullmatch(r"[A-Za-z0-9_]+", db): # db is interpolated into SQL
|
||||
raise SystemExit(f"invalid database name: {db!r}")
|
||||
|
||||
def run(sql):
|
||||
r = subprocess.run([MYSQL, "--socket", sock, "-uroot"], input=sql.encode(),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=1800)
|
||||
if r.returncode != 0:
|
||||
sys.stderr.write(r.stderr.decode()[:500]); raise SystemExit("mysql failed")
|
||||
|
||||
run(f"DROP DATABASE IF EXISTS {db}; CREATE DATABASE {db};"
|
||||
f"CREATE TABLE {db}.t(id INT PRIMARY KEY,payload BLOB,chk BIGINT) ENGINE=InnoDB;"
|
||||
f"CREATE TABLE {db}.o(id INT AUTO_INCREMENT PRIMARY KEY,v INT) ENGINE=InnoDB;")
|
||||
|
||||
mb = rows * 4096 / 1048576
|
||||
stmts = ["SET SESSION cte_max_recursion_depth=1000000;"]
|
||||
o = 0
|
||||
while o < rows:
|
||||
b = min(batch, rows - o)
|
||||
stmts.append(
|
||||
f"INSERT INTO {db}.t(id,payload,chk) "
|
||||
f"WITH RECURSIVE seq(n) AS (SELECT 0 UNION ALL SELECT n+1 FROM seq WHERE n<{b-1}) "
|
||||
f"SELECT n+{o},AES_ENCRYPT(REPEAT('a',4080),SHA2(n+{o},256)),"
|
||||
f"CRC32(AES_ENCRYPT(REPEAT('a',4080),SHA2(n+{o},256))) FROM seq;")
|
||||
o += b
|
||||
t = time.time(); run("\n".join(stmts)); dt = time.time() - t
|
||||
print(f"LOAD\t{dt:.1f}\t{mb/dt:.0f} MB/s")
|
||||
|
||||
sql = "\n".join(f"INSERT INTO {db}.o(v) VALUES({i});" for i in range(oltp))
|
||||
t = time.time(); run(sql); dt = time.time() - t
|
||||
print(f"OLTP\t{dt:.2f}\t{oltp/dt:.0f} tx/s")
|
||||
|
||||
t = time.time(); run(f"SELECT SUM(CRC32(payload)) FROM {db}.t;"); dt = time.time() - t
|
||||
print(f"SCAN\t{dt:.1f}\t{mb/dt:.0f} MB/s")
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/bin/bash
|
||||
# MySQL (InnoDB) ~1GB load test on the SeaweedFS FUSE mount + crash suite.
|
||||
# Datadir lives on the FUSE mount; innodb_flush_log_at_trx_commit=1 +
|
||||
# innodb_flush_method=fsync => every commit fsyncs the redo log through FUSE.
|
||||
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$BIN/lib.sh"
|
||||
|
||||
TOTAL=262144 # 262144 * 4096B payload = ~1GiB row data (InnoDB on-disk larger)
|
||||
BATCH=8192 # 32 committed transactions
|
||||
PROG=$LOCAL/mysql_progress.txt
|
||||
PASS=0; FAIL=0
|
||||
chk() { if [ "$1" -eq 0 ]; then echo ">>> $2: PASS"; PASS=$((PASS+1)); else echo ">>> $2: FAIL"; FAIL=$((FAIL+1)); fi; }
|
||||
|
||||
mysql_schema() {
|
||||
mq -e "CREATE DATABASE IF NOT EXISTS loadtest;
|
||||
DROP TABLE IF EXISTS loadtest.t;
|
||||
CREATE TABLE loadtest.t(id INT PRIMARY KEY, payload BLOB, chk BIGINT) ENGINE=InnoDB;"
|
||||
}
|
||||
mysql_load() { # loads TOTAL rows in BATCH-sized committed inserts; progress -> $PROG
|
||||
local O=0 B rem
|
||||
: > "$PROG"
|
||||
while [ $O -lt $TOTAL ]; do
|
||||
B=$BATCH; rem=$((TOTAL-O)); [ $rem -lt $B ] && B=$rem
|
||||
# incompressible + deterministic payload: AES-128-ECB (no IV -> deterministic)
|
||||
# of a fixed 4080B plaintext, keyed per-id -> 4096B ciphertext that defeats
|
||||
# gzip on the volumes. Identical expr for payload and chk, so CRC32(payload)
|
||||
# recomputed at verify must equal stored chk.
|
||||
mq -e "SET SESSION cte_max_recursion_depth=1000000;
|
||||
INSERT INTO loadtest.t(id,payload,chk)
|
||||
WITH RECURSIVE seq(n) AS (SELECT 0 UNION ALL SELECT n+1 FROM seq WHERE n < $((B-1)))
|
||||
SELECT n+$O,
|
||||
AES_ENCRYPT(REPEAT('a',4080), SHA2(n+$O,256)),
|
||||
CRC32(AES_ENCRYPT(REPEAT('a',4080), SHA2(n+$O,256)))
|
||||
FROM seq;" \
|
||||
|| { echo "INSERT failed at offset $O"; return 1; }
|
||||
# durable + atomic progress (matches sqlite_gen.py) so the crash-test lower
|
||||
# bound is never stale or torn: write tmp, fsync, rename.
|
||||
O=$((O+B)); printf '%s' "$O" > "$PROG.tmp"
|
||||
python3 -c "import os,sys; fd=os.open(sys.argv[1],os.O_RDONLY); os.fsync(fd); os.close(fd)" "$PROG.tmp"
|
||||
mv -f "$PROG.tmp" "$PROG"
|
||||
done
|
||||
}
|
||||
mysql_verify() { # $1=expected $2=mode(exact|atleast) ; returns 0 on PASS
|
||||
local exp=$1 mode=$2 cnt sumchk corrupt minid maxid checktbl ok=0
|
||||
read -r cnt sumchk corrupt minid maxid <<EOF
|
||||
$(mq -N -e "SELECT COUNT(*),COALESCE(SUM(chk),0),COALESCE(SUM(chk<>CRC32(payload)),0),COALESCE(MIN(id),-1),COALESCE(MAX(id),-1) FROM loadtest.t;")
|
||||
EOF
|
||||
checktbl=$(mq -N -e "CHECK TABLE loadtest.t;" | awk '{print $NF}')
|
||||
echo " rows=$cnt corrupt=$corrupt minid=$minid maxid=$maxid CHECK=$checktbl (want $mode $exp)"
|
||||
[ "$checktbl" = "OK" ] || { echo " -> CHECK TABLE failed"; ok=1; }
|
||||
[ "$corrupt" = "0" ] || { echo " -> payload corruption in $corrupt rows"; ok=1; }
|
||||
if [ "$mode" = exact ]; then
|
||||
[ "$cnt" = "$exp" ] || { echo " -> row count mismatch"; ok=1; }
|
||||
{ [ "$minid" = 0 ] && [ "$maxid" = "$((exp-1))" ]; } || { echo " -> not contiguous 0..$((exp-1))"; ok=1; }
|
||||
else
|
||||
[ "$cnt" -ge "$exp" ] 2>/dev/null || { echo " -> LOST COMMITTED DATA (cnt<$exp)"; ok=1; }
|
||||
{ [ "$minid" = 0 ] && [ "$maxid" = "$((cnt-1))" ]; } || { echo " -> not contiguous prefix"; ok=1; }
|
||||
fi
|
||||
return $ok
|
||||
}
|
||||
|
||||
echo "######## MySQL FUSE load test $(date) ########"
|
||||
|
||||
# ---------- fresh cluster + mysql + 1GB load ----------
|
||||
clean_state; cluster_start || exit 1; mount_start || exit 1
|
||||
mysql_init || { echo "mysql_init failed"; tail -20 "$LOGS/mysql-init.log"; exit 1; }
|
||||
mysql_start || exit 1
|
||||
mysql_schema
|
||||
say "loading ~1GB into InnoDB"
|
||||
t0=$SECONDS
|
||||
mysql_load || echo "load reported an error"
|
||||
say "load done in $((SECONDS-t0))s"
|
||||
mq -N -e "SELECT CONCAT('innodb rows=',COUNT(*),' data_len=',ROUND(SUM(LENGTH(payload))/1048576),'MB') FROM loadtest.t;"
|
||||
du -sh "$MYSQL_DATADIR"; status_report
|
||||
|
||||
# ---------- Scenario A: normal (graceful) shutdown + restart ----------
|
||||
echo; echo "==================== SCENARIO A: NORMAL SHUTDOWN ===================="
|
||||
mysql_stop_graceful
|
||||
mount_stop_graceful
|
||||
cluster_stop_graceful
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1; mysql_start || exit 1
|
||||
mysql_verify $TOTAL exact; chk $? "A/normal-shutdown"
|
||||
|
||||
# ---------- Scenario B: unexpected shutdown (kill -9 everything) ----------
|
||||
echo; echo "============== SCENARIO B: UNEXPECTED SHUTDOWN (kill -9) =============="
|
||||
hard_kill_all
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
say "restarting mysqld -> InnoDB crash recovery runs"
|
||||
mysql_start || { echo "mysqld failed to recover"; tail -30 "$LOGS/mysqld.log"; chk 1 "B/unexpected-shutdown"; }
|
||||
if mq -e "SELECT 1" >/dev/null 2>&1; then mysql_verify $TOTAL exact; chk $? "B/unexpected-shutdown"; fi
|
||||
|
||||
# ---------- Scenario C: crash DURING active writes ----------
|
||||
echo; echo "=========== SCENARIO C: CRASH DURING ACTIVE WRITES (kill -9) ==========="
|
||||
mysql_stop_graceful
|
||||
clean_state; cluster_start || exit 1; mount_start || exit 1
|
||||
mysql_init || exit 1; mysql_start || exit 1; mysql_schema
|
||||
say "loading in background; will crash storage + mysqld mid-write"
|
||||
mysql_load > "$LOGS/mysql_load_c.log" 2>&1 &
|
||||
LPID=$!
|
||||
while :; do
|
||||
p=$(cat "$PROG" 2>/dev/null || echo 0); p=${p:-0}
|
||||
[ "$p" -ge $((TOTAL/2)) ] && break
|
||||
kill -0 $LPID 2>/dev/null || { say "loader exited early"; break; }
|
||||
sleep 0.2
|
||||
done
|
||||
LB=$(cat "$PROG" 2>/dev/null); LB=${LB:-0} # empty file (killed mid-write) -> 0
|
||||
say "durable committed lower-bound at crash = $LB rows; crashing now"
|
||||
hard_kill_all
|
||||
kill -9 $LPID 2>/dev/null; wait $LPID 2>/dev/null
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
say "restarting mysqld -> InnoDB recovery; in-flight txn must roll back, committed must survive"
|
||||
mysql_start || { echo "recovery failed"; tail -30 "$LOGS/mysqld.log"; chk 1 "C/crash-during-write"; }
|
||||
if mq -e "SELECT 1" >/dev/null 2>&1; then mysql_verify "$LB" atleast; chk $? "C/crash-during-write"; fi
|
||||
|
||||
echo; echo "######## MySQL RESULT: PASS=$PASS FAIL=$FAIL ########"
|
||||
mysql_stop_graceful; mount_stop_graceful; cluster_stop_graceful
|
||||
exit $FAIL
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
# SQLite ~1GB load test on the SeaweedFS FUSE mount + crash suite.
|
||||
BIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$BIN/lib.sh"
|
||||
|
||||
TOTAL=262144 # 262144 * 4096B payload = ~1GiB of row data
|
||||
BATCH=4096 # 64 committed transactions (each fsync'd, synchronous=FULL)
|
||||
DB=$MNT/sqlite/load.db
|
||||
PROG=$LOCAL/sqlite_progress.txt
|
||||
REF=$LOCAL/sqlite_ref.txt
|
||||
PASS=0; FAIL=0
|
||||
chk() { if [ "$1" -eq 0 ]; then echo ">>> $2: PASS"; PASS=$((PASS+1)); else echo ">>> $2: FAIL"; FAIL=$((FAIL+1)); fi; }
|
||||
|
||||
echo "######## SQLite FUSE load test $(date) ########"
|
||||
|
||||
# ---------- fresh cluster + 1GB load ----------
|
||||
clean_state; cluster_start || exit 1; mount_start || exit 1
|
||||
mkdir -p "$MNT/sqlite"
|
||||
say "loading ~1GB into SQLite (journal=DELETE synchronous=FULL)"
|
||||
t0=$SECONDS
|
||||
python3 "$BIN/sqlite_gen.py" "$DB" $TOTAL $BATCH "$PROG" "$REF" FULL DELETE | tail -3
|
||||
say "load done in $((SECONDS-t0))s; file size:"; ls -lh "$DB"; du -sh "$MNT/sqlite"
|
||||
status_report
|
||||
|
||||
# ---------- Scenario A: normal (graceful) shutdown + restart ----------
|
||||
echo; echo "==================== SCENARIO A: NORMAL SHUTDOWN ===================="
|
||||
mount_stop_graceful
|
||||
cluster_stop_graceful
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
say "verifying after graceful restart"
|
||||
python3 "$BIN/sqlite_verify.py" "$DB" $TOTAL exact; chk $? "A/normal-shutdown"
|
||||
|
||||
# ---------- Scenario B: unexpected shutdown (kill -9) + restart ----------
|
||||
echo; echo "============== SCENARIO B: UNEXPECTED SHUTDOWN (kill -9) =============="
|
||||
hard_kill_all
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
say "verifying after kill -9 + restart"
|
||||
python3 "$BIN/sqlite_verify.py" "$DB" $TOTAL exact; chk $? "B/unexpected-shutdown"
|
||||
|
||||
# ---------- Scenario C: crash DURING active writes ----------
|
||||
echo; echo "=========== SCENARIO C: CRASH DURING ACTIVE WRITES (kill -9) ==========="
|
||||
clean_state; cluster_start || exit 1; mount_start || exit 1
|
||||
mkdir -p "$MNT/sqlite"; : > "$PROG"
|
||||
say "starting loader in background; will crash storage mid-write"
|
||||
python3 "$BIN/sqlite_gen.py" "$DB" $TOTAL $BATCH "$PROG" "" FULL DELETE > "$LOGS/sqlite_gen_c.log" 2>&1 &
|
||||
GENPID=$!
|
||||
# wait until at least half is durably committed
|
||||
while :; do
|
||||
p=$(cat "$PROG" 2>/dev/null || echo 0); p=${p:-0}
|
||||
[ "$p" -ge $((TOTAL/2)) ] && break
|
||||
kill -0 $GENPID 2>/dev/null || { say "loader exited early"; break; }
|
||||
sleep 0.2
|
||||
done
|
||||
LB=$(cat "$PROG" 2>/dev/null); LB=${LB:-0} # empty file (killed mid-write) -> 0
|
||||
say "durable committed lower-bound at crash = $LB rows; crashing storage now"
|
||||
hard_kill_all # storage dies under the still-writing loader
|
||||
kill -9 $GENPID 2>/dev/null; wait $GENPID 2>/dev/null
|
||||
sleep 1
|
||||
cluster_start || exit 1; mount_start || exit 1
|
||||
say "verifying recovery (committed prefix must survive, integrity must hold)"
|
||||
python3 "$BIN/sqlite_verify.py" "$DB" "$LB" atleast; chk $? "C/crash-during-write"
|
||||
|
||||
echo; echo "######## SQLite RESULT: PASS=$PASS FAIL=$FAIL ########"
|
||||
mount_stop_graceful; cluster_stop_graceful
|
||||
exit $FAIL
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
# SQLite performance probe at one db path. Prints TSV: METRIC<TAB>secs<TAB>rate
|
||||
# LOAD : bulk-load <rows> rows (4096B incompressible payload) in <batch>-row txns
|
||||
# OLTP : <oltp> single-row INSERTs, each its own fsync'd autocommit txn -> tx/s
|
||||
# SCAN : full table scan reading every payload (warm) -> MB/s
|
||||
# journal=DELETE, synchronous=FULL (durable: fsync per commit).
|
||||
import sys, os, sqlite3, time, random
|
||||
|
||||
db = sys.argv[1]
|
||||
rows = int(sys.argv[2])
|
||||
batch = int(sys.argv[3])
|
||||
oltp = int(sys.argv[4])
|
||||
|
||||
for ext in ("", "-journal", "-wal", "-shm"):
|
||||
try: os.remove(db + ext)
|
||||
except OSError: pass
|
||||
|
||||
con = sqlite3.connect(db, isolation_level=None)
|
||||
con.execute("PRAGMA journal_mode=DELETE;")
|
||||
con.execute("PRAGMA synchronous=FULL;")
|
||||
con.execute("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB, chk INTEGER);")
|
||||
|
||||
# LOAD
|
||||
mb = rows * 4096 / 1048576
|
||||
t = time.time(); done = 0
|
||||
rnd = random.Random(12345) # reuse one PRNG; this probe doesn't verify payloads
|
||||
while done < rows:
|
||||
end = min(done + batch, rows)
|
||||
data = [(i, rnd.randbytes(4096), 0) for i in range(done, end)]
|
||||
con.execute("BEGIN")
|
||||
con.executemany("INSERT INTO t VALUES(?,?,?)", data)
|
||||
con.execute("COMMIT")
|
||||
done = end
|
||||
dt = time.time() - t
|
||||
print(f"LOAD\t{dt:.1f}\t{mb/dt:.0f} MB/s")
|
||||
|
||||
# OLTP: each INSERT autocommits (isolation_level=None) -> 1 fsync'd txn each
|
||||
con.execute("CREATE TABLE o(id INTEGER PRIMARY KEY, v INTEGER);")
|
||||
t = time.time()
|
||||
for i in range(oltp):
|
||||
con.execute("INSERT INTO o(v) VALUES(?)", (i,))
|
||||
dt = time.time() - t
|
||||
print(f"OLTP\t{dt:.2f}\t{oltp/dt:.0f} tx/s")
|
||||
|
||||
# SCAN (warm): read every payload
|
||||
t = time.time(); nbytes = 0
|
||||
for rid, p, c in con.execute("SELECT id,payload,chk FROM t"):
|
||||
nbytes += len(p)
|
||||
dt = time.time() - t
|
||||
print(f"SCAN\t{dt:.1f}\t{nbytes/1048576/dt:.0f} MB/s")
|
||||
con.close()
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# Deterministic ~1GB SQLite load on the FUSE mount.
|
||||
# Each row: id, payload (4096 deterministic bytes derived from id), chk=crc32(payload).
|
||||
# Commits in batches; after each commit, writes the committed row count to a
|
||||
# progress file on LOCAL disk and fsyncs it -> a durable record of what was
|
||||
# committed, used to verify "no committed data lost" after a crash.
|
||||
import sys, os, sqlite3, zlib, random
|
||||
|
||||
db_path = sys.argv[1]
|
||||
total_rows = int(sys.argv[2])
|
||||
batch = int(sys.argv[3])
|
||||
progress_path= sys.argv[4] # LOCAL disk
|
||||
ref_path = sys.argv[5] if len(sys.argv) > 5 else None
|
||||
sync_mode = sys.argv[6] if len(sys.argv) > 6 else "FULL"
|
||||
journal_mode = sys.argv[7] if len(sys.argv) > 7 else "DELETE"
|
||||
|
||||
# Validate before interpolating into PRAGMAs: a typo must not silently weaken
|
||||
# durability and invalidate the comparison / crash-survival claims.
|
||||
if sync_mode.upper() not in {"OFF", "NORMAL", "FULL", "EXTRA"}:
|
||||
raise SystemExit(f"invalid synchronous mode: {sync_mode!r}")
|
||||
if journal_mode.upper() not in {"DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL", "OFF"}:
|
||||
raise SystemExit(f"invalid journal mode: {journal_mode!r}")
|
||||
|
||||
def payload(i: int) -> bytes:
|
||||
# deterministic but incompressible (PRNG seeded by id) -> 4096 bytes that
|
||||
# actually consume ~1GB on the volume servers (defeats gzip storage).
|
||||
return random.Random(i).randbytes(4096)
|
||||
|
||||
con = sqlite3.connect(db_path, isolation_level=None)
|
||||
con.execute(f"PRAGMA journal_mode={journal_mode};")
|
||||
con.execute(f"PRAGMA synchronous={sync_mode};")
|
||||
con.execute("CREATE TABLE IF NOT EXISTS t(id INTEGER PRIMARY KEY, payload BLOB, chk INTEGER);")
|
||||
|
||||
def write_progress(n):
|
||||
# atomic: write tmp + fsync + rename, so a kill -9 mid-write can't leave an
|
||||
# empty/torn progress file (the crash-test lower bound must stay trustworthy).
|
||||
tmp = progress_path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
f.write(str(n)); f.flush(); os.fsync(f.fileno())
|
||||
os.replace(tmp, progress_path)
|
||||
|
||||
done = 0
|
||||
sum_chk = 0
|
||||
sum_id = 0
|
||||
while done < total_rows:
|
||||
end = min(done + batch, total_rows)
|
||||
rows = []
|
||||
for i in range(done, end):
|
||||
p = payload(i); c = zlib.crc32(p)
|
||||
rows.append((i, p, c)); sum_chk += c; sum_id += i
|
||||
con.execute("BEGIN;")
|
||||
con.executemany("INSERT INTO t(id,payload,chk) VALUES(?,?,?);", rows)
|
||||
con.execute("COMMIT;")
|
||||
done = end
|
||||
write_progress(done)
|
||||
print(f"committed {done}/{total_rows}", flush=True)
|
||||
|
||||
if ref_path:
|
||||
with open(ref_path, "w") as f:
|
||||
f.write(f"{total_rows} {sum_chk} {sum_id}\n"); f.flush(); os.fsync(f.fileno())
|
||||
con.close()
|
||||
print("DONE", flush=True)
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
# Verify a SQLite DB after a crash/restart.
|
||||
# - PRAGMA integrity_check (structural consistency of the b-tree / pages)
|
||||
# - row count / sum(chk) / sum(id) vs expected
|
||||
# - recompute crc32(payload) for every row vs stored chk (byte corruption)
|
||||
#
|
||||
# usage: sqlite_verify.py <db> <expected_rows> [mode]
|
||||
# mode=exact (default): count must == expected_rows (normal/unexpected shutdown
|
||||
# of a fully-loaded DB -- nothing may be lost or extra).
|
||||
# mode=atleast: expected_rows is a LOWER BOUND (durable committed progress at
|
||||
# crash time). count must be >= expected_rows and form a contiguous
|
||||
# prefix 0..count-1 (the in-flight txn may or may not have committed,
|
||||
# but no committed row may be lost and recovery must be consistent).
|
||||
import sys, sqlite3, zlib, random
|
||||
|
||||
db_path = sys.argv[1]
|
||||
expected_rows = int(sys.argv[2])
|
||||
mode = sys.argv[3] if len(sys.argv) > 3 else "exact"
|
||||
if mode not in ("exact", "atleast"): # a typo must not silently relax checks
|
||||
raise SystemExit(f"invalid mode: {mode!r} (want exact|atleast)")
|
||||
|
||||
def payload(i: int) -> bytes:
|
||||
return random.Random(i).randbytes(4096)
|
||||
|
||||
con = sqlite3.connect(db_path)
|
||||
ok = True
|
||||
|
||||
ic = con.execute("PRAGMA integrity_check;").fetchone()[0]
|
||||
print(f"integrity_check: {ic}")
|
||||
if ic != "ok": ok = False
|
||||
|
||||
cnt = con.execute("SELECT COUNT(*) FROM t;").fetchone()[0]
|
||||
minid = con.execute("SELECT MIN(id) FROM t;").fetchone()[0]
|
||||
maxid = con.execute("SELECT MAX(id) FROM t;").fetchone()[0]
|
||||
sum_chk= con.execute("SELECT COALESCE(SUM(chk),0) FROM t;").fetchone()[0]
|
||||
sum_id = con.execute("SELECT COALESCE(SUM(id),0) FROM t;").fetchone()[0]
|
||||
|
||||
if mode == "exact":
|
||||
target = expected_rows
|
||||
if cnt != expected_rows:
|
||||
print(f"rows: got={cnt} expected={expected_rows} MISMATCH"); ok = False
|
||||
else:
|
||||
print(f"rows: got={cnt} expected={expected_rows} OK")
|
||||
else: # atleast
|
||||
print(f"rows: got={cnt} committed-lower-bound={expected_rows} "
|
||||
f"{'OK' if cnt >= expected_rows else 'LOST COMMITTED DATA'}")
|
||||
if cnt < expected_rows: ok = False
|
||||
target = cnt
|
||||
# contiguous prefix 0..cnt-1 ?
|
||||
if cnt > 0 and (minid != 0 or maxid != cnt - 1):
|
||||
print(f"prefix: MIN={minid} MAX={maxid} expected 0..{cnt-1} NON-CONTIGUOUS"); ok = False
|
||||
else:
|
||||
print(f"prefix: 0..{maxid} contiguous OK")
|
||||
|
||||
exp_sum_chk = sum(zlib.crc32(payload(i)) for i in range(target))
|
||||
exp_sum_id = target * (target - 1) // 2
|
||||
print(f"sum(chk): got={sum_chk} expected={exp_sum_chk} {'OK' if sum_chk==exp_sum_chk else 'MISMATCH'}")
|
||||
print(f"sum(id): got={sum_id} expected={exp_sum_id} {'OK' if sum_id==exp_sum_id else 'MISMATCH'}")
|
||||
if sum_chk != exp_sum_chk or sum_id != exp_sum_id: ok = False
|
||||
|
||||
corrupt = 0; scanned = 0
|
||||
for rid, p, c in con.execute("SELECT id,payload,chk FROM t;"):
|
||||
scanned += 1
|
||||
if zlib.crc32(p) != c: corrupt += 1
|
||||
print(f"payload byte-check: scanned={scanned} corrupt={corrupt} {'OK' if corrupt==0 else 'CORRUPT'}")
|
||||
if corrupt != 0: ok = False
|
||||
|
||||
con.close()
|
||||
print("VERIFY: " + ("PASS" if ok else "FAIL"))
|
||||
sys.exit(0 if ok else 1)
|
||||
+12
-184
@@ -8,207 +8,69 @@ require (
|
||||
github.com/seaweedfs/seaweedfs v0.0.0-00010101000000-000000000000
|
||||
github.com/segmentio/kafka-go v0.4.49
|
||||
github.com/stretchr/testify v1.11.1
|
||||
google.golang.org/grpc v1.80.0
|
||||
google.golang.org/grpc v1.81.1
|
||||
)
|
||||
|
||||
replace github.com/seaweedfs/seaweedfs => ../../
|
||||
|
||||
require (
|
||||
cloud.google.com/go/auth v0.20.0 // indirect
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.39 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.82 // indirect
|
||||
github.com/IBM/go-sdk-core/v5 v5.21.2 // indirect
|
||||
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/bcrypt v0.0.0-20211005172633-e235017c1baf // indirect
|
||||
github.com/ProtonMail/gluon v0.17.1-0.20230724134000-308be39be96e // indirect
|
||||
github.com/ProtonMail/go-crypto v1.4.1 // indirect
|
||||
github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f // indirect
|
||||
github.com/ProtonMail/go-srp v0.0.7 // indirect
|
||||
github.com/ProtonMail/gopenpgp/v2 v2.9.0 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.11.0 // indirect
|
||||
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 // indirect
|
||||
github.com/abbot/go-http-auth v0.4.0 // indirect
|
||||
github.com/adrg/xdg v0.5.3 // indirect
|
||||
github.com/anchore/go-lzo v0.1.0 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirect
|
||||
github.com/aws/smithy-go v1.25.1 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/boombuler/barcode v1.1.0 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
github.com/buengese/sgzip v0.1.1 // indirect
|
||||
github.com/buger/jsonparser v1.1.2 // indirect
|
||||
github.com/bwmarrin/snowflake v0.3.0 // indirect
|
||||
github.com/calebcase/tmpfile v1.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/chilts/sid v0.0.0-20190607042430-660e94789ec9 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.3 // indirect
|
||||
github.com/cloudinary/cloudinary-go/v2 v2.15.0 // indirect
|
||||
github.com/cloudsoda/go-smb2 v0.0.0-20250228001242-d4c70e6251cc // indirect
|
||||
github.com/cloudsoda/sddl v0.0.0-20250224235906-926454e91efc // indirect
|
||||
github.com/cognusion/imaging v1.0.2 // indirect
|
||||
github.com/colinmarc/hdfs/v2 v2.4.0 // indirect
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
|
||||
github.com/creasty/defaults v1.8.0 // indirect
|
||||
github.com/cronokirby/saferith v0.33.1-0.20250226174546-1f11f94ce488 // indirect
|
||||
github.com/cognusion/imaging v1.0.3 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/diskfs/go-diskfs v1.7.0 // indirect
|
||||
github.com/dromara/dongle v1.0.1 // indirect
|
||||
github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.0.5 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/eapache/go-resiliency v1.7.0 // indirect
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
|
||||
github.com/eapache/queue v1.1.0 // indirect
|
||||
github.com/ebitengine/purego v0.10.0 // indirect
|
||||
github.com/emersion/go-message v0.18.2 // indirect
|
||||
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/flynn/noise v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/geoffgarside/ber v1.2.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.9.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-openapi/errors v0.22.6 // indirect
|
||||
github.com/go-openapi/strfmt v0.25.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/go-resty/resty/v2 v2.17.2 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/gofrs/flock v0.13.0 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/s2a-go v0.1.9 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260331173834-036f908d0160 // indirect
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/goidentity/v6 v6.0.1 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
|
||||
github.com/jhump/protoreflect v1.18.0 // indirect
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 // indirect
|
||||
github.com/jlaffaye/ftp v0.2.1-0.20251026020404-6602e981a1bb // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/jtolio/noiseconn v0.0.0-20231127013910-f6d9ecbf1de7 // indirect
|
||||
github.com/jzelinskie/whirlpool v0.0.0-20201016144138-0675e54bb004 // indirect
|
||||
github.com/karlseguin/ccache/v2 v2.0.8 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/reedsolomon v1.14.0 // indirect
|
||||
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988 // indirect
|
||||
github.com/koofr/go-koofrclient v0.0.0-20221207135200-cbd7fc9ad6a6 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lanrat/extsort v1.4.2 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lpar/date v1.0.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260216142805-b3301c5f2a88 // indirect
|
||||
github.com/mailru/easyjson v0.9.1 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.22 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/ncw/swift/v2 v2.0.5 // indirect
|
||||
github.com/oklog/ulid v1.3.1 // indirect
|
||||
github.com/oracle/oci-go-sdk/v65 v65.111.0 // indirect
|
||||
github.com/onsi/ginkgo v1.16.5 // indirect
|
||||
github.com/onsi/gomega v1.37.0 // indirect
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1 // indirect
|
||||
github.com/panjf2000/ants/v2 v2.11.5 // indirect
|
||||
github.com/parquet-go/bitpack v1.0.0 // indirect
|
||||
github.com/parquet-go/jsonlite v1.0.0 // indirect
|
||||
github.com/parquet-go/parquet-go v0.28.0 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/parquet-go/parquet-go v0.30.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
|
||||
github.com/peterh/liner v1.2.2 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.26 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pkg/sftp v1.13.10 // indirect
|
||||
github.com/pkg/xattr v0.4.12 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.27 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/pquerna/otp v1.5.0 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.5 // indirect
|
||||
github.com/prometheus/procfs v0.20.1 // indirect
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
|
||||
github.com/rclone/Proton-API-Bridge v1.0.3 // indirect
|
||||
github.com/rclone/go-proton-api v1.0.2 // indirect
|
||||
github.com/rclone/rclone v1.74.1 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rdleal/intervalst v1.5.0 // indirect
|
||||
github.com/relvacode/iso8601 v1.7.0 // indirect
|
||||
github.com/rfjakob/eme v1.2.0 // indirect
|
||||
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/samber/lo v1.52.0 // indirect
|
||||
github.com/seaweedfs/goexif v1.0.3 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.3 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
|
||||
github.com/smarty/assertions v1.16.0 // indirect
|
||||
github.com/sony/gobreaker v1.0.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
@@ -216,60 +78,26 @@ require (
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 // indirect
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20251120131202-6845944c051c // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.16 // indirect
|
||||
github.com/tklauser/numcpus v0.11.0 // indirect
|
||||
github.com/twpayne/go-geom v1.6.1 // indirect
|
||||
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
|
||||
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43 // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
github.com/unknwon/goconfig v1.0.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/viant/ptrie v1.0.1 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
github.com/yunify/qingstor-sdk-go/v3 v3.2.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
github.com/zeebo/errs v1.4.0 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.etcd.io/bbolt v1.4.3 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.9 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
|
||||
go.opentelemetry.io/otel v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.43.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.50.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/image v0.39.0 // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/term v0.42.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/api v0.278.0 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/image v0.41.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/validator.v2 v2.0.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
moul.io/http2curl/v2 v2.3.0 // indirect
|
||||
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||
storj.io/common v0.0.0-20260225132117-99155641c30a // indirect
|
||||
storj.io/drpc v0.0.35-0.20250513201419-f7819ea69b55 // indirect
|
||||
storj.io/eventkit v0.0.0-20250410172343-61f26d3de156 // indirect
|
||||
storj.io/infectious v0.0.2 // indirect
|
||||
storj.io/picobuf v0.0.4 // indirect
|
||||
storj.io/uplink v1.14.0 // indirect
|
||||
)
|
||||
+38
-838
File diff suppressed because it is too large.
Load diff
@@ -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"`
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory" // register the memory credential store
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
)
|
||||
|
||||
// TestGetObjectStoreUserDetailsIncludesInlinePolicies verifies that inline user
|
||||
// policies — which are stored separately from the identity record and are
|
||||
// authoritative at S3 enforcement time (they take precedence over the legacy
|
||||
// Actions list) — are surfaced in the admin user details. They were previously
|
||||
// invisible in the admin API/UI, so an operator could not tell what actually
|
||||
// governed a user's access.
|
||||
func TestGetObjectStoreUserDetailsIncludesInlinePolicies(t *testing.T) {
|
||||
cm, err := credential.NewCredentialManagerWithDefaults(credential.StoreTypeMemory)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init credential manager: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
const username = "svc-app"
|
||||
if err := cm.CreateUser(ctx, &iam_pb.Identity{Name: username}); err != nil {
|
||||
t.Fatalf("failed to create user: %v", err)
|
||||
}
|
||||
|
||||
const inlinePolicyName = "svc-app-policy"
|
||||
doc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: "Allow",
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::ml-artifacts/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := cm.PutUserInlinePolicy(ctx, username, inlinePolicyName, doc); err != nil {
|
||||
t.Fatalf("failed to put inline policy: %v", err)
|
||||
}
|
||||
|
||||
s := &AdminServer{credentialManager: cm}
|
||||
details, err := s.GetObjectStoreUserDetails(username)
|
||||
if err != nil {
|
||||
t.Fatalf("GetObjectStoreUserDetails failed: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, p := range details.PolicyNames {
|
||||
if p == inlinePolicyName {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected inline policy %q in details.PolicyNames, got %v", inlinePolicyName, details.PolicyNames)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
@@ -190,6 +191,17 @@ func (s *AdminServer) GetObjectStoreUserDetails(username string) (*UserDetails,
|
||||
PolicyNames: identity.PolicyNames,
|
||||
}
|
||||
|
||||
// Inline user policies are stored separately from the identity record and
|
||||
// are authoritative at enforcement time (they take precedence over the
|
||||
// legacy Actions list). Surface their names alongside attached policies so
|
||||
// the admin reflects the user's actual permissions rather than only the
|
||||
// (potentially overridden) Actions.
|
||||
if inlinePolicyNames, err := s.credentialManager.ListUserInlinePolicies(ctx, username); err != nil {
|
||||
glog.Warningf("failed to list inline policies for user %s: %v", username, err)
|
||||
} else if len(inlinePolicyNames) > 0 {
|
||||
details.PolicyNames = append(details.PolicyNames, inlinePolicyNames...)
|
||||
}
|
||||
|
||||
// Set email from account if available
|
||||
if identity.Account != nil {
|
||||
details.Email = identity.Account.EmailAddress
|
||||
|
||||
@@ -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
+21
-2
@@ -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") != ""
|
||||
|
||||
@@ -547,7 +565,8 @@ func loggingMiddleware(next http.Handler) http.Handler {
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
if status >= 200 && status < 300 {
|
||||
// Only log errors; 2xx/3xx (including 304 Not Modified cache hits) are normal.
|
||||
if status < 400 {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package command
|
||||
|
||||
// Register the tiered-storage backends here, at the binary's composition root,
|
||||
// so library consumers of weed/storage don't pull the backend SDKs.
|
||||
import _ "github.com/seaweedfs/seaweedfs/weed/storage/backend/all"
|
||||
@@ -165,7 +165,6 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
panic(fmt.Errorf("dirIdleEvictSec: %s", err))
|
||||
}
|
||||
case "concurrentWriters":
|
||||
i++
|
||||
if parsed, err := strconv.ParseInt(parameter.value, 0, 32); err == nil {
|
||||
intValue := int(parsed)
|
||||
mountOptions.concurrentWriters = &intValue
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build darwin || freebsd || linux
|
||||
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunFuseDoesNotSkipOptionAfterConcurrentWriters(t *testing.T) {
|
||||
oldUmask := mountOptions.umaskString
|
||||
oldWriters := mountOptions.concurrentWriters
|
||||
oldReaders := mountOptions.concurrentReaders
|
||||
oldFuseCommandPid := mountOptions.fuseCommandPid
|
||||
oldDir := mountOptions.dir
|
||||
defer func() {
|
||||
mountOptions.umaskString = oldUmask
|
||||
mountOptions.concurrentWriters = oldWriters
|
||||
mountOptions.concurrentReaders = oldReaders
|
||||
mountOptions.fuseCommandPid = oldFuseCommandPid
|
||||
mountOptions.dir = oldDir
|
||||
|
||||
recovered := recover()
|
||||
if recovered == nil {
|
||||
t.Fatal("expected invalid concurrentReaders option to be parsed")
|
||||
}
|
||||
if !strings.Contains(fmt.Sprint(recovered), "concurrentReaders") {
|
||||
t.Fatalf("expected concurrentReaders parse error, got %v", recovered)
|
||||
}
|
||||
}()
|
||||
|
||||
runFuse(cmdMount, []string{
|
||||
"/mnt",
|
||||
"-o",
|
||||
"child=1,concurrentWriters=2,concurrentReaders=bad,umask=bad",
|
||||
})
|
||||
}
|
||||
+25
-1
@@ -548,6 +548,7 @@ func initMiniAdminFlags() {
|
||||
miniAdminOptions.adminPassword = cmdMini.Flag.String("admin.password", "", "admin interface password (if empty, auth is disabled)")
|
||||
miniAdminOptions.readOnlyUser = cmdMini.Flag.String("admin.readOnlyUser", "", "read-only user username (optional, for view-only access)")
|
||||
miniAdminOptions.readOnlyPassword = cmdMini.Flag.String("admin.readOnlyPassword", "", "read-only user password (optional, for view-only access; requires admin.password to be set)")
|
||||
miniAdminOptions.urlPrefix = cmdMini.Flag.String("admin.urlPrefix", "", "URL path prefix when running the admin UI behind a reverse proxy under a subdirectory (e.g. /seaweedfs)")
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -1164,6 +1165,7 @@ func runMini(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
util.LoadConfiguration("master", false)
|
||||
util.LoadConfiguration("volume", false)
|
||||
util.LoadConfiguration("admin", false)
|
||||
miniOptions.v.applyDiskIOProbeConfig()
|
||||
|
||||
ensureMiniVolumeGrowthDefaults()
|
||||
@@ -1487,6 +1489,18 @@ func startS3Service() {
|
||||
miniS3Options.startS3Server()
|
||||
}
|
||||
|
||||
// applyMiniAdminCredentialFallback fills the admin credential flags from
|
||||
// security.toml [admin] / WEED_ADMIN_* env vars when they were not set on the
|
||||
// command line, mirroring the standalone `weed admin` command. CLI flags take
|
||||
// precedence. Note the read-only viper keys (admin.readonly.*) differ from the
|
||||
// mini flag names (admin.readOnly*).
|
||||
func applyMiniAdminCredentialFallback(options *AdminOptions) {
|
||||
applyViperFallback(cmdMini, options.adminUser, "admin.user", "admin.user")
|
||||
applyViperFallback(cmdMini, options.adminPassword, "admin.password", "admin.password")
|
||||
applyViperFallback(cmdMini, options.readOnlyUser, "admin.readOnlyUser", "admin.readonly.user")
|
||||
applyViperFallback(cmdMini, options.readOnlyPassword, "admin.readOnlyPassword", "admin.readonly.password")
|
||||
}
|
||||
|
||||
// startMiniAdminWithWorker starts the admin server with one worker
|
||||
func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
defer close(allServicesReady) // Ensure channel is always closed on all paths
|
||||
@@ -1503,6 +1517,10 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
// Set admin options
|
||||
*miniAdminOptions.master = masterAddr
|
||||
|
||||
// Resolve admin credentials from security.toml [admin] / WEED_ADMIN_* env
|
||||
// vars, matching the standalone `weed admin` command.
|
||||
applyMiniAdminCredentialFallback(&miniAdminOptions)
|
||||
|
||||
// Security validation: prevent empty username when password is set
|
||||
if *miniAdminOptions.adminPassword != "" && *miniAdminOptions.adminUser == "" {
|
||||
glog.Fatalf("Error: -admin.user cannot be empty when -admin.password is set")
|
||||
@@ -1532,6 +1550,12 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
*miniAdminOptions.dataDir = filepath.Join(*miniDataFolders, "admin")
|
||||
}
|
||||
|
||||
// Normalize URL prefix the same way `weed admin` does.
|
||||
urlPrefix := strings.TrimRight(*miniAdminOptions.urlPrefix, "/")
|
||||
if urlPrefix != "" && !strings.HasPrefix(urlPrefix, "/") {
|
||||
urlPrefix = "/" + urlPrefix
|
||||
}
|
||||
|
||||
// Start admin server in background. trackMiniClient lets the Ctrl+C
|
||||
// handler wait for startAdminServer's graceful shutdown before filer/
|
||||
// volume/master tear down.
|
||||
@@ -1546,7 +1570,7 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
if miniS3Options.portIceberg != nil {
|
||||
icebergPort = *miniS3Options.portIceberg
|
||||
}
|
||||
if err := startAdminServer(ctx, miniAdminOptions, *miniEnableAdminUI, icebergPort, ""); err != nil {
|
||||
if err := startAdminServer(ctx, miniAdminOptions, *miniEnableAdminUI, icebergPort, urlPrefix); err != nil {
|
||||
glog.Errorf("Admin server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
|
||||
// weed mini must resolve admin credentials from security.toml [admin] /
|
||||
// WEED_ADMIN_* env vars the same way the standalone `weed admin` command does.
|
||||
// This exercises the production fallback so the flag-name -> viper-key mapping
|
||||
// stays correct, in particular the read-only keys where the mini flag
|
||||
// (admin.readOnlyUser) and viper key (admin.readonly.user) differ.
|
||||
func TestApplyMiniAdminCredentialFallbackFromEnv(t *testing.T) {
|
||||
adminUser, adminPassword, readOnlyUser, readOnlyPassword := "admin", "", "", ""
|
||||
options := &AdminOptions{
|
||||
adminUser: &adminUser,
|
||||
adminPassword: &adminPassword,
|
||||
readOnlyUser: &readOnlyUser,
|
||||
readOnlyPassword: &readOnlyPassword,
|
||||
}
|
||||
|
||||
t.Setenv("WEED_ADMIN_USER", "env-admin")
|
||||
t.Setenv("WEED_ADMIN_PASSWORD", "env-secret")
|
||||
t.Setenv("WEED_ADMIN_READONLY_USER", "env-ro")
|
||||
t.Setenv("WEED_ADMIN_READONLY_PASSWORD", "env-ro-secret")
|
||||
|
||||
applyMiniAdminCredentialFallback(options)
|
||||
|
||||
checks := []struct {
|
||||
name string
|
||||
got string
|
||||
want string
|
||||
}{
|
||||
{"adminUser", *options.adminUser, "env-admin"},
|
||||
{"adminPassword", *options.adminPassword, "env-secret"},
|
||||
{"readOnlyUser", *options.readOnlyUser, "env-ro"},
|
||||
{"readOnlyPassword", *options.readOnlyPassword, "env-ro-secret"},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if c.got != c.want {
|
||||
t.Errorf("%s = %q, want %q", c.name, c.got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -4,7 +4,16 @@
|
||||
# /etc/seaweedfs/security.toml
|
||||
# this file is read by master, volume server, filer, and worker
|
||||
|
||||
# comma separated origins allowed to make requests to the filer and s3 gateway.
|
||||
# Any value below can also be supplied as an environment variable instead of
|
||||
# living in this file: prefix the key with WEED_, upper-case it, and replace
|
||||
# "." with "_". This is the recommended way to inject the secrets in here from
|
||||
# a Kubernetes Secret (env valueFrom.secretKeyRef) rather than a ConfigMap.
|
||||
# The JWT signing keys map to:
|
||||
# WEED_JWT_SIGNING_KEY, WEED_JWT_SIGNING_READ_KEY (master <-> volume)
|
||||
# WEED_JWT_FILER_SIGNING_KEY, WEED_JWT_FILER_SIGNING_READ_KEY (s3/clients <-> filer)
|
||||
# A set env var wins over the file, so the file can stay empty (or absent).
|
||||
|
||||
# comma separated origins allowed to make requests to the filer and s3 gateway.
|
||||
# enter in this format: https://domain.com, or http://localhost:port
|
||||
[cors.allowed_origins]
|
||||
values = "*"
|
||||
|
||||
@@ -23,7 +23,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/server/constants"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
||||
@@ -248,9 +247,6 @@ var (
|
||||
volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
|
||||
|
||||
ecBitrotChecksum = cmdVolume.Flag.Bool("ec.bitrotChecksum", true, "write a bitrot checksum sidecar (.ecsum) when generating EC shards, enabling silent-corruption detection on scrub/rebuild")
|
||||
ecBitrotBlockSizeMB = cmdVolume.Flag.Int("ec.bitrotBlockSizeMB", 16, "EC bitrot checksum block granularity in MiB; must be a power of two and at least 1")
|
||||
)
|
||||
|
||||
func runVolume(cmd *Command, args []string) bool {
|
||||
@@ -285,24 +281,6 @@ func runVolume(cmd *Command, args []string) bool {
|
||||
*v.mastersString = *v.mserverString
|
||||
}
|
||||
|
||||
// Apply EC bitrot checksum settings.
|
||||
erasure_coding.BitrotProtectionEnabled = *ecBitrotChecksum
|
||||
// Bound-check before the multiply so a huge value cannot overflow int64 past
|
||||
// the power-of-two check. Cap = shared MaxBitrotBlockSize, kept in sync with
|
||||
// ValidateBitrotManifest.
|
||||
const maxBitrotBlockSizeMB = erasure_coding.MaxBitrotBlockSize / (1024 * 1024)
|
||||
if mb := *ecBitrotBlockSizeMB; mb >= 1 && mb <= maxBitrotBlockSizeMB {
|
||||
if blockSize := int64(mb) * 1024 * 1024; blockSize&(blockSize-1) == 0 {
|
||||
erasure_coding.BitrotBlockSize = blockSize
|
||||
} else if mb != 16 {
|
||||
glog.Warningf("ignoring invalid -ec.bitrotBlockSizeMB=%d (must be a power of two); using %d MiB",
|
||||
mb, erasure_coding.BitrotBlockSize/(1024*1024))
|
||||
}
|
||||
} else if *ecBitrotBlockSizeMB != 16 {
|
||||
glog.Warningf("ignoring out-of-range -ec.bitrotBlockSizeMB=%d (must be a power of two in [1, %d] MiB); using %d MiB",
|
||||
*ecBitrotBlockSizeMB, maxBitrotBlockSizeMB, erasure_coding.BitrotBlockSize/(1024*1024))
|
||||
}
|
||||
|
||||
minFreeSpaces := util.MustParseMinFreeSpace(*minFreeSpace, *minFreeSpacePercent)
|
||||
v.masters = pb.ServerAddresses(*v.mastersString).ToAddresses()
|
||||
v.startVolumeServer(*volumeFolders, *maxVolumeCounts, *volumeWhiteListOption, minFreeSpaces)
|
||||
|
||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user