mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-26 06:07:13 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adfd731bb8 | ||
|
|
917a87928c | ||
|
|
8fa769f29a | ||
|
|
7c635c4508 | ||
|
|
fbdcec1cba | ||
|
|
0accff0e4a | ||
|
|
9021225591 | ||
|
|
5b42287c22 | ||
|
|
3392493f0a | ||
|
|
d82b3a8d6a | ||
|
|
39e9294907 | ||
|
|
3825035f07 | ||
|
|
83b7ea5e7b | ||
|
|
eae8f33db5 | ||
|
|
2c2b2d4d3e | ||
|
|
cd15ae1395 | ||
|
|
3f6410fdc3 | ||
|
|
87fdea5330 | ||
|
|
303c2be38d | ||
|
|
9b9fdb5b76 | ||
|
|
7e4691f2dc | ||
|
|
391f543ff2 | ||
|
|
afcc491517 | ||
|
|
a5d0e4a735 | ||
|
|
a17dca7009 | ||
|
|
024b59fb31 | ||
|
|
5af7d12f04 | ||
|
|
4385b86bf1 | ||
|
|
c00aa90990 | ||
|
|
e332b97d52 | ||
|
|
868849392c | ||
|
|
a4415c39aa | ||
|
|
9914e6af30 | ||
|
|
cc5ef1b741 | ||
|
|
37b6a14b0d | ||
|
|
cee2bf697c | ||
|
|
285025eb73 | ||
|
|
77ac781bbd | ||
|
|
f72983c1fd | ||
|
|
cfc08fbf6c | ||
|
|
d57de6dc20 | ||
|
|
4476cb282b | ||
|
|
b63610cf8f | ||
|
|
c61d227613 | ||
|
|
7c252e1f16 | ||
|
|
7c5296dfb1 | ||
|
|
58c3fa802c | ||
|
|
d3f80444df | ||
|
|
0dc65e7069 | ||
|
|
18c6c24e47 | ||
|
|
120901c883 | ||
|
|
a79880ed41 | ||
|
|
f5aa776742 | ||
|
|
f3d6633aac | ||
|
|
68794fb94c | ||
|
|
af8d4e00ee | ||
|
|
41b6ad002b | ||
|
|
a761441926 | ||
|
|
37e6263efe | ||
|
|
3d872a1416 | ||
|
|
4d04609bb8 |
No files matched your search
@@ -1,49 +0,0 @@
|
||||
name: EC Integration Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/admin/**'
|
||||
- 'weed/worker/**'
|
||||
- 'test/erasure_coding/admin_dockertest/**'
|
||||
- '.github/workflows/ec-integration.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/admin/**'
|
||||
- 'weed/worker/**'
|
||||
- 'test/erasure_coding/admin_dockertest/**'
|
||||
- '.github/workflows/ec-integration.yml'
|
||||
|
||||
jobs:
|
||||
ec-integration-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build weed binary
|
||||
run: |
|
||||
cd weed
|
||||
go build -o ../weed_bin
|
||||
|
||||
- name: Run EC integration tests
|
||||
run: |
|
||||
cd test/erasure_coding/admin_dockertest
|
||||
go test -v -timeout 15m ec_integration_test.go
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ec-test-logs
|
||||
path: test/erasure_coding/admin_dockertest/tmp/logs/
|
||||
retention-days: 7
|
||||
@@ -0,0 +1,110 @@
|
||||
name: "S3 SDK V2 Route Disambiguation Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'test/s3/sdk_v2_routing/**'
|
||||
- '.github/workflows/s3-sdk-v2-routing-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/s3api/**'
|
||||
- 'test/s3/sdk_v2_routing/**'
|
||||
- '.github/workflows/s3-sdk-v2-routing-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref || github.ref }}/s3-sdk-v2-routing-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
s3-sdk-v2-routing-tests:
|
||||
name: S3 SDK V2 Routing Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install SeaweedFS
|
||||
run: |
|
||||
cd weed && go install -buildvcs=false
|
||||
|
||||
- name: Start weed mini (S3 on :8333)
|
||||
# Pins the regression for issue #9559: AWS SDK V2 / Hadoop s3a
|
||||
# listing a bucket literally named "buckets" must get an XML
|
||||
# ListObjectsV2 response, not the JSON ListTableBuckets body
|
||||
# served by the S3 Tables REST endpoint on the same path.
|
||||
run: |
|
||||
mkdir -p /tmp/seaweedfs-sdk-v2-routing
|
||||
cat > /tmp/seaweedfs-sdk-v2-routing-s3.json <<'JSON'
|
||||
{
|
||||
"identities": [
|
||||
{
|
||||
"name": "admin",
|
||||
"credentials": [
|
||||
{"accessKey": "some_access_key1", "secretKey": "some_secret_key1"}
|
||||
],
|
||||
"actions": ["Admin", "Read", "Write"]
|
||||
}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
AWS_ACCESS_KEY_ID=some_access_key1 \
|
||||
AWS_SECRET_ACCESS_KEY=some_secret_key1 \
|
||||
weed mini \
|
||||
-dir=/tmp/seaweedfs-sdk-v2-routing \
|
||||
-s3.port=8333 \
|
||||
-s3.config=/tmp/seaweedfs-sdk-v2-routing-s3.json \
|
||||
-ip=127.0.0.1 \
|
||||
> /tmp/weed-mini.log 2>&1 &
|
||||
echo $! > /tmp/weed-mini.pid
|
||||
|
||||
for i in $(seq 1 30); do
|
||||
if curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8333/ | grep -qE "^(200|403)$"; then
|
||||
echo "weed mini is ready"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "weed mini failed to start within 30s"
|
||||
tail -50 /tmp/weed-mini.log
|
||||
exit 1
|
||||
|
||||
- name: Run SDK V2 routing tests
|
||||
env:
|
||||
S3_ENDPOINT: http://127.0.0.1:8333
|
||||
AWS_ACCESS_KEY_ID: some_access_key1
|
||||
AWS_SECRET_ACCESS_KEY: some_secret_key1
|
||||
AWS_REGION: us-east-1
|
||||
run: go test -v -timeout=5m ./test/s3/sdk_v2_routing/...
|
||||
|
||||
- name: Stop weed mini
|
||||
if: always()
|
||||
run: |
|
||||
if [ -f /tmp/weed-mini.pid ]; then
|
||||
kill "$(cat /tmp/weed-mini.pid)" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
- name: Show server log on failure
|
||||
if: failure()
|
||||
run: |
|
||||
echo "=== weed mini log (last 200 lines) ==="
|
||||
tail -n 200 /tmp/weed-mini.log 2>/dev/null || echo "no log available"
|
||||
|
||||
- name: Archive log
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: s3-sdk-v2-routing-server-log
|
||||
path: /tmp/weed-mini.log
|
||||
retention-days: 3
|
||||
@@ -0,0 +1,120 @@
|
||||
name: "Samba on FUSE Integration"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, main ]
|
||||
paths:
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/cluster/**'
|
||||
- 'test/samba/**'
|
||||
- '.github/workflows/samba-integration.yml'
|
||||
pull_request:
|
||||
branches: [ master, main ]
|
||||
paths:
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/cluster/**'
|
||||
- 'test/samba/**'
|
||||
- '.github/workflows/samba-integration.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: samba-integration/${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
samba-integration:
|
||||
name: samba-integration
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Start local Docker registry
|
||||
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
driver-opts: network=host
|
||||
|
||||
- name: Build weed race binary
|
||||
run: |
|
||||
cd docker
|
||||
make binary_race
|
||||
|
||||
- name: Build SeaweedFS e2e image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: docker
|
||||
file: docker/Dockerfile.e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:e2e
|
||||
push: true
|
||||
cache-from: type=gha,scope=samba-e2e
|
||||
cache-to: type=gha,mode=max,scope=samba-e2e
|
||||
|
||||
- name: Tag e2e image for docker compose
|
||||
run: |
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:e2e
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:e2e chrislusf/seaweedfs:e2e
|
||||
|
||||
- name: Build samba image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: test/samba
|
||||
build-contexts: |
|
||||
chrislusf/seaweedfs:e2e=docker-image://localhost:5000/chrislusf/seaweedfs:e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:samba
|
||||
push: true
|
||||
cache-from: type=gha,scope=samba-harness
|
||||
cache-to: type=gha,mode=max,scope=samba-harness
|
||||
|
||||
- name: Tag samba image for docker compose
|
||||
run: |
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:samba
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:samba chrislusf/seaweedfs:samba
|
||||
|
||||
- name: Start SeaweedFS cluster and Samba
|
||||
run: |
|
||||
docker compose -f test/samba/docker-compose.yml up --wait
|
||||
|
||||
- name: Run Samba test battery
|
||||
run: |
|
||||
set -o pipefail
|
||||
docker compose -f test/samba/docker-compose.yml exec -T samba \
|
||||
/run_inside_container.sh 2>&1 | tee /tmp/samba-output.log
|
||||
|
||||
- name: Collect logs
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p /tmp/samba-docker-logs
|
||||
for svc in master volume filer samba; do
|
||||
docker compose -f test/samba/docker-compose.yml logs "$svc" \
|
||||
> "/tmp/samba-docker-logs/${svc}.log" 2>&1 || true
|
||||
done
|
||||
|
||||
- name: Tear down
|
||||
if: always()
|
||||
run: |
|
||||
docker compose -f test/samba/docker-compose.yml down -v
|
||||
|
||||
- name: Upload logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: samba-integration-results
|
||||
path: |
|
||||
/tmp/samba-output.log
|
||||
/tmp/samba-docker-logs/
|
||||
retention-days: 7
|
||||
@@ -509,20 +509,22 @@ SeaweedFS Filer uses off-the-shelf stores, such as MySql, Postgres, Sqlite, Mong
|
||||
|
||||
### Compared to MinIO ###
|
||||
|
||||
MinIO follows AWS S3 closely and is ideal for testing for S3 API. It has good UI, policies, versionings, etc. SeaweedFS is trying to catch up here. It is also possible to put MinIO as a gateway in front of SeaweedFS later.
|
||||
Please note, as Apr 25, 2026 MinIO ceased developement. It's strongly discouraged to use that unmaintained software with multiple security bugs.
|
||||
|
||||
MinIO metadata are in simple files. Each file write will incur extra writes to corresponding meta file.
|
||||
MinIO followed AWS S3 closely and was ideal for testing for S3 API. It had good UI, policies, versionings, etc. SeaweedFS is trying to catch up here.
|
||||
|
||||
MinIO does not have optimization for lots of small files. The files are simply stored as is to local disks.
|
||||
MinIO metadata were in simple files. Each file write will incur extra writes to corresponding meta file.
|
||||
|
||||
MinIO did not have optimization for lots of small files. The files were simply stored as is to local disks.
|
||||
Plus the extra meta file and shards for erasure coding, it only amplifies the LOSF problem.
|
||||
|
||||
MinIO has multiple disk IO to read one file. SeaweedFS has O(1) disk reads, even for erasure coded files.
|
||||
MinIO had multiple disk IO to read one file. SeaweedFS has O(1) disk reads, even for erasure coded files.
|
||||
|
||||
MinIO has full-time erasure coding. SeaweedFS uses replication on hot data for faster speed and optionally applies erasure coding on warm data.
|
||||
MinIO had full-time erasure coding. SeaweedFS uses replication on hot data for faster speed and optionally applies erasure coding on warm data.
|
||||
|
||||
MinIO does not have POSIX-like API support.
|
||||
MinIO did not have POSIX-like API support.
|
||||
|
||||
MinIO has specific requirements on storage layout. It is not flexible to adjust capacity. In SeaweedFS, just start one volume server pointing to the master. That's all.
|
||||
MinIO had specific requirements on storage layout. It is not flexible to adjust capacity. In SeaweedFS, just start one volume server pointing to the master. That's all.
|
||||
|
||||
## Dev Plan ##
|
||||
|
||||
|
||||
@@ -42,6 +42,10 @@ RUN if [ -f "/prebuilt/weed-volume-${TARGETARCH}" ]; then \
|
||||
echo "Skipping Rust build for $TARGETARCH (unsupported)" && \
|
||||
touch /weed-volume; \
|
||||
fi
|
||||
# Pre-built binaries arrive via GitHub Actions artifacts, which drop the
|
||||
# executable bit, so the copied file is 0644 and exec fails with "Permission
|
||||
# denied". Restore it (no-op for the empty placeholder, which stays size 0).
|
||||
RUN chmod 0755 /weed-volume
|
||||
|
||||
FROM alpine AS final
|
||||
LABEL author="Chris Lu"
|
||||
|
||||
@@ -15,7 +15,6 @@ require (
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/eapache/go-resiliency v1.6.0 // indirect
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
|
||||
@@ -92,13 +91,13 @@ require (
|
||||
gocloud.dev v0.45.0
|
||||
gocloud.dev/pubsub/natspubsub v0.45.0
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.45.0
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/crypto v0.51.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.39.0
|
||||
golang.org/x/net v0.53.0
|
||||
golang.org/x/net v0.54.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.43.0
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/sys v0.44.0
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.278.0
|
||||
@@ -123,11 +122,11 @@ require (
|
||||
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.6
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0
|
||||
github.com/cognusion/imaging v1.0.2
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
|
||||
github.com/cognusion/imaging v1.0.3
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.44.1
|
||||
github.com/go-git/go-billy/v5 v5.9.0
|
||||
@@ -141,12 +140,12 @@ require (
|
||||
github.com/linkedin/goavro/v2 v2.15.0
|
||||
github.com/minio/crc64nvme v1.1.1
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1
|
||||
github.com/parquet-go/parquet-go v0.28.0
|
||||
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/rdleal/intervalst v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/redis/go-redis/v9 v9.19.0
|
||||
github.com/schollz/progressbar/v3 v3.19.0
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.3
|
||||
github.com/shirou/gopsutil/v4 v4.26.3
|
||||
@@ -298,13 +297,13 @@ require (
|
||||
cloud.google.com/go/iam v1.7.0 // indirect
|
||||
cloud.google.com/go/monitoring v1.24.3 // indirect
|
||||
filippo.io/edwards25519 v1.1.1 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
|
||||
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
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0
|
||||
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/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.82 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 // indirect
|
||||
@@ -324,17 +323,17 @@ require (
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
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.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // 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/configsources v1.4.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // 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/internal/v4a v1.4.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.17 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
@@ -499,7 +498,7 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.43.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
golang.org/x/term v0.42.0
|
||||
golang.org/x/term v0.43.0
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
|
||||
|
||||
@@ -553,22 +553,22 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
|
||||
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1 h1:jHb/wfvRikGdxMXYV3QG/SzUOPYN9KEUUuC0Yd0/vC0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1/go.mod h1:pzBXCYn05zvYIrwLgtK8Ap8QcjRg+0i76tMQdWN6wOk=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0 h1:m/sWOGCREuSBqg2htVQTBY8nOZpyajYztF0vUvSZTuM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0/go.mod h1:Pu5Zksi2KrU7LPbZbNINx6fuVrUp/ffvpxdDj+i8LeE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 h1:FbH3BbSb4bvGluTesZZ+ttN/MDsnMmQP36OSnDuSXqw=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1/go.mod h1:9V2j0jn9jDEkCkv8w/bKTNppX/d0FVA1ud77xCIP4KA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBADtcH2rRqPxYB1Ljwms5gFA2LqrM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0 h1:BM85pSYlVYQHdq00nxyPoOkyLF5NArJG3bOsrmbwr4k=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0/go.mod h1:QYjP2cB7ZYtS/8jAbE0VSBZde/tjExqGjp+8JY6/+ts=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 h1:tZh20RjgfMxKBxJiIS75iTVAKIUxrST5X2dVHMTptL4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4/go.mod h1:vGYAk36rhMVCfTP7v+RVruCR0zmPe6S+36KRpDCLySw=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
@@ -581,8 +581,8 @@ github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDP
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
|
||||
@@ -715,10 +715,10 @@ 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.6 h1:1AX0AthnBQzMx1vbmir3Y4WsnJgiydmnJjiLu+LvXOg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6/go.mod h1:dy0UzBIfwSeot4grGvY1AqFWN5zgziMmWGzysDnHFcQ=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14/go.mod h1:U4/V0uKxh0Tl5sxmCBZ3AecYny4UNlVmObYjKuuaiOo=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8THYELoX6gVcUvgl6fI=
|
||||
@@ -727,24 +727,24 @@ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeD
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21/go.mod h1:YWNWJQNjKigKY1RHVJCuupeWDrrHjRqHm0N9rdrWzYI=
|
||||
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/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 h1:qYQ4pzQ2Oz6WpQ8T3HvGHnZydA72MnLuFK9tJwmrbHw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6/go.mod h1:O3h0IK87yXci+kg6flUKzJnWeziQUKciKrLjcatSNcY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 h1:rWyie/PxDRIdhNf4DzRk0lvjVOqFJuNnO8WwaIRVxzQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22/go.mod h1:zd/JsJ4P7oGfUhXn1VyLqaRZwPmZwg44Jf2dS84Dm3Y=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3xgIJMSC8S6hEVq+38DcvUlgFY0FM6mSI5oto=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 h1:hlSuz394kV0vhv9drL5lhuEFbEOEP1VyQpy15qWh1Pk=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 h1:QKZH0S178gCmFEgst8hN0mCX1KxLgHBKKY/CLqwP8lg=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9/go.mod h1:7yuQJoT+OoH8aqIxw9vwF+8KpvLZ8AWmvmUWHsGQZvI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.7 h1:fovS7qGMT+BBSuifkySdVaMWxXTyaYT6qaBx/1y6Ij4=
|
||||
@@ -866,8 +866,8 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP
|
||||
github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
|
||||
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2 h1:8Vfw2iNEpYIV6aLtMwT5UOGuPmp9MKlEKWKFTuB+MPU=
|
||||
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2/go.mod h1:P9WiZOdQ1R/ZZDL0WzF5wlyRvrjtfhNOwMZymFpBwjE=
|
||||
github.com/cognusion/imaging v1.0.2 h1:BQwBV8V8eF3+dwffp8Udl9xF1JKh5Z0z5JkJwAi98Mc=
|
||||
github.com/cognusion/imaging v1.0.2/go.mod h1:mj7FvH7cT2dlFogQOSUQRtotBxJ4gFQ2ySMSmBm5dSk=
|
||||
github.com/cognusion/imaging v1.0.3 h1:nHyIeEVDV8JkBbuhgx8iSBW72W8rHbDEyruA0Jh7Lnk=
|
||||
github.com/cognusion/imaging v1.0.3/go.mod h1:38tFLFhGK81ORThZG8dVXPtp1uhd+3xM1WXuMn+unOA=
|
||||
github.com/colinmarc/hdfs/v2 v2.4.0 h1:v6R8oBx/Wu9fHpdPoJJjpGSUxo8NhHIwrwsfhFvU9W0=
|
||||
github.com/colinmarc/hdfs/v2 v2.4.0/go.mod h1:0NAO+/3knbMx6+5pCv+Hcbaz4xn/Zzbn9+WIib2rKVI=
|
||||
github.com/compose-spec/compose-go/v2 v2.9.0 h1:UHSv/QHlo6QJtrT4igF1rdORgIUhDo1gWuyJUoiNNIM=
|
||||
@@ -1667,8 +1667,8 @@ github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxP
|
||||
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
|
||||
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
|
||||
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
|
||||
github.com/parquet-go/parquet-go v0.28.0 h1:ECyksyv8T2pOrlLsN7aWJIoQakyk/HtxQ2lchgS4els=
|
||||
github.com/parquet-go/parquet-go v0.28.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
|
||||
github.com/parquet-go/parquet-go v0.30.1 h1:Oy6ganNrAdFiVwy7wNmWagfPTWA2X9Z3tVHBc7JtuX8=
|
||||
github.com/parquet-go/parquet-go v0.30.1/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
|
||||
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
|
||||
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
@@ -1795,8 +1795,8 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X
|
||||
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=
|
||||
github.com/rdleal/intervalst v1.5.0/go.mod h1:xO89Z6BC+LQDH+IPQQw/OESt5UADgFD41tYMUINGpxQ=
|
||||
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||
github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k=
|
||||
github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/redis/rueidis v1.0.71 h1:pODtnAR5GAB7j4ekhldZ29HKOxe4Hph0GTDGk1ayEQY=
|
||||
github.com/redis/rueidis v1.0.71/go.mod h1:lfdcZzJ1oKGKL37vh9fO3ymwt+0TdjkkUCJxbgpmcgQ=
|
||||
github.com/redis/rueidis/rueidiscompat v1.0.71 h1:wNZ//kEjMZgBM0KCk7ncOX8KmAgROU2kDdDNpwheG4w=
|
||||
@@ -2216,8 +2216,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
@@ -2352,8 +2352,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.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
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/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=
|
||||
@@ -2511,8 +2511,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa h1:efT73AJZfAAUV7SOip6pWGkwJDzIGiKBZGVzHYa+ve4=
|
||||
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=
|
||||
@@ -2531,8 +2531,8 @@ golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -2553,8 +2553,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.26"
|
||||
appVersion: "4.28"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.26.0
|
||||
version: 4.28.0
|
||||
@@ -137,6 +137,9 @@ spec:
|
||||
- "/bin/sh"
|
||||
- "-ec"
|
||||
- |
|
||||
{{- if $volume.rust }}
|
||||
exec /usr/bin/weed-volume \
|
||||
{{- else }}
|
||||
exec /usr/bin/weed \
|
||||
{{- if $volume.logs }}
|
||||
-logdir=/logs \
|
||||
@@ -149,6 +152,7 @@ spec:
|
||||
-v={{ $.Values.global.seaweedfs.loggingLevel }} \
|
||||
{{- end }}
|
||||
volume \
|
||||
{{- end }}
|
||||
-port={{ $volume.port }} \
|
||||
{{- if $volume.metricsPort }}
|
||||
-metricsPort={{ $volume.metricsPort }} \
|
||||
@@ -180,7 +184,7 @@ spec:
|
||||
{{- if $volume.imagesFixOrientation }}
|
||||
-images.fix.orientation \
|
||||
{{- end }}
|
||||
{{- if $volume.pulseSeconds }}
|
||||
{{- if and $volume.pulseSeconds (not $volume.rust) }}
|
||||
-pulseSeconds={{ $volume.pulseSeconds }} \
|
||||
{{- end }}
|
||||
{{- if $volume.index }}
|
||||
|
||||
@@ -305,6 +305,11 @@ volume:
|
||||
enabled: true
|
||||
imageOverride: null
|
||||
restartPolicy: null
|
||||
# Run the Rust volume server (/usr/bin/weed-volume) instead of the Go one.
|
||||
# Requires an image that ships the Rust binary (amd64/arm64). The Go-only
|
||||
# log flags (-logtostderr/-logdir/-v) and -pulseSeconds are dropped; set log
|
||||
# level via the RUST_LOG env var in extraEnvironmentVars if needed.
|
||||
rust: false
|
||||
port: 8080
|
||||
grpcPort: 18080
|
||||
metricsPort: 9327
|
||||
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
rpc AppendToEntry (AppendToEntryRequest) returns (AppendToEntryResponse) {
|
||||
}
|
||||
|
||||
@@ -208,6 +211,8 @@ message FuseAttributes {
|
||||
int32 mtime_ns = 19; // nanosecond component of mtime (0-999999999)
|
||||
int32 ctime_ns = 20; // nanosecond component of ctime (0-999999999)
|
||||
int32 crtime_ns = 21; // nanosecond component of crtime (0-999999999)
|
||||
int64 atime = 22; // unix time in seconds, last access time
|
||||
int32 atime_ns = 23; // nanosecond component of atime (0-999999999)
|
||||
}
|
||||
|
||||
message CreateEntryRequest {
|
||||
@@ -247,6 +252,16 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
int64 client_atime_ns = 3; // nanoseconds since epoch; filer may override with relatime
|
||||
}
|
||||
message TouchAccessTimeResponse {
|
||||
int64 persisted_atime_ns = 1; // nanoseconds since epoch; 0 if no update was performed
|
||||
bool updated = 2;
|
||||
}
|
||||
|
||||
message AppendToEntryRequest {
|
||||
string directory = 1;
|
||||
string entry_name = 2;
|
||||
|
||||
@@ -212,6 +212,13 @@ impl CompactNeedleMap {
|
||||
self.idx_file_offset = offset;
|
||||
}
|
||||
|
||||
/// True when an .idx file writer is attached. A read-only load leaves
|
||||
/// this `false` — set_writable() must reattach a writer or subsequent
|
||||
/// puts silently skip the disk append.
|
||||
pub fn has_idx_writer(&self) -> bool {
|
||||
self.idx_file.is_some()
|
||||
}
|
||||
|
||||
// ---- Map operations ----
|
||||
|
||||
/// Insert or update an entry. Appends to .idx file if present.
|
||||
@@ -705,6 +712,11 @@ impl RedbNeedleMap {
|
||||
self.idx_file_offset = offset;
|
||||
}
|
||||
|
||||
/// True when an .idx file writer is attached. See CompactNeedleMap.
|
||||
pub fn has_idx_writer(&self) -> bool {
|
||||
self.idx_file.is_some()
|
||||
}
|
||||
|
||||
// ---- Map operations ----
|
||||
|
||||
/// Insert or update an entry. Writes to idx file first, then redb.
|
||||
@@ -1000,6 +1012,14 @@ impl NeedleMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when an .idx file writer is attached.
|
||||
pub fn has_idx_writer(&self) -> bool {
|
||||
match self {
|
||||
NeedleMap::InMemory(nm) => nm.has_idx_writer(),
|
||||
NeedleMap::Redb(nm) => nm.has_idx_writer(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Content byte count.
|
||||
pub fn content_size(&self) -> u64 {
|
||||
match self {
|
||||
|
||||
@@ -2122,7 +2122,34 @@ impl Volume {
|
||||
}
|
||||
|
||||
/// Mark this volume as writable (allow writes and deletes).
|
||||
///
|
||||
/// If the volume booted with .vif ReadOnly=true, `load_index` built the
|
||||
/// needle map without an .idx writer attached, so subsequent puts would
|
||||
/// silently skip the on-disk append and only mutate in-memory state —
|
||||
/// surviving until the next restart, then vanishing. Re-attach a writer
|
||||
/// here so writes persist again.
|
||||
pub fn set_writable(&mut self) -> Result<(), VolumeError> {
|
||||
// Attach the writer (if missing) before flipping the flag — otherwise
|
||||
// a transient open/metadata failure would leave the volume marked
|
||||
// writable with no .idx writer, and subsequent puts would silently
|
||||
// skip the on-disk append and vanish on the next restart.
|
||||
let needs_idx_writer = self
|
||||
.nm
|
||||
.as_ref()
|
||||
.map(|nm| !nm.has_idx_writer())
|
||||
.unwrap_or(false);
|
||||
if needs_idx_writer {
|
||||
let idx_path = self.file_name(".idx");
|
||||
let write_file = OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.create(true)
|
||||
.open(&idx_path)?;
|
||||
let idx_size = write_file.metadata()?.len();
|
||||
if let Some(ref mut nm) = self.nm {
|
||||
nm.set_idx_file(Box::new(write_file), idx_size);
|
||||
}
|
||||
}
|
||||
self.no_write_or_delete = false;
|
||||
self.save_vif()
|
||||
}
|
||||
@@ -3565,6 +3592,118 @@ mod tests {
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
}
|
||||
|
||||
// Guard the Rust integrity-check tombstone path against the Go regression
|
||||
// where verifyDeletedNeedleIntegrity forwarded TombstoneFileSize into the
|
||||
// needle-size check, mismatched against the on-disk Size=0 header, and
|
||||
// sent every volume with a trailing deletion read-only on load. The Rust
|
||||
// check guards its size comparison with !size.is_deleted(); this test
|
||||
// keeps that guarantee from silently regressing.
|
||||
#[test]
|
||||
fn test_check_volume_data_integrity_with_deletion_tombstone() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
{
|
||||
let mut v = make_test_volume(dir);
|
||||
for i in 1..=3 {
|
||||
let data = format!("data {}", i);
|
||||
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.delete_needle(&mut Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(2),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
!v.is_no_write_or_delete(),
|
||||
"volume should not be read-only after reload with trailing deletion tombstone"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_empty_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "zero-size volume without index"
|
||||
// case (weed/storage/volume_checking_test.go): a freshly created /
|
||||
// pre-allocated volume has a superblock-only .dat and a zero-size .idx,
|
||||
// and must scrub clean instead of being flagged as corrupt.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
|
||||
// .dat holds only the superblock; .idx is empty.
|
||||
assert_eq!(v.dat_file_size().unwrap(), SUPER_BLOCK_SIZE as u64);
|
||||
|
||||
let (files_checked, broken) = v.scrub().unwrap();
|
||||
assert_eq!(files_checked, 0);
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"empty volume should scrub clean, got {:?}",
|
||||
broken
|
||||
);
|
||||
|
||||
// The index-only mode must agree.
|
||||
let (idx_checked, idx_broken) = v.scrub_index().unwrap();
|
||||
assert_eq!(idx_checked, 0);
|
||||
assert!(
|
||||
idx_broken.is_empty(),
|
||||
"empty volume should scrub_index clean, got {:?}",
|
||||
idx_broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_healthy_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "healthy volume" case: a volume
|
||||
// with live needles scrubs clean and the .dat size accounting matches.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=5 {
|
||||
let data = format!("needle data {}", i);
|
||||
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();
|
||||
|
||||
let (files_checked, broken) = v.scrub().unwrap();
|
||||
assert_eq!(files_checked, 5);
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"healthy volume should scrub clean, got {:?}",
|
||||
broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_volume_multiple_needles() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -4191,6 +4330,91 @@ mod tests {
|
||||
assert!(v.no_write_can_delete);
|
||||
}
|
||||
|
||||
// A volume booted with .vif ReadOnly=true used to come back stuck —
|
||||
// load_index_inmemory built the CompactNeedleMap without an .idx writer
|
||||
// attached, and set_writable only flipped the flag and rewrote .vif.
|
||||
// The next put silently skipped the .idx append, so the write landed in
|
||||
// memory only and was lost on the next restart.
|
||||
#[test]
|
||||
fn test_set_writable_reattaches_idx_writer_after_persisted_readonly() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
{
|
||||
let mut v = make_test_volume(dir);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: b"initial".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.set_read_only_persist(true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
v.no_write_or_delete,
|
||||
"reloaded volume should be read-only from .vif"
|
||||
);
|
||||
assert!(
|
||||
!v.nm.as_ref().unwrap().has_idx_writer(),
|
||||
"read-only load should not attach an .idx writer"
|
||||
);
|
||||
|
||||
v.set_writable().unwrap();
|
||||
assert!(!v.is_read_only());
|
||||
assert!(
|
||||
v.nm.as_ref().unwrap().has_idx_writer(),
|
||||
"set_writable must reattach the .idx writer or post-restart writes vanish"
|
||||
);
|
||||
|
||||
let mut n = Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(2),
|
||||
data: b"after-mark-writable".to_vec(),
|
||||
data_size: 19,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
// Reload one more time — the .idx must contain the post-mark-writable
|
||||
// entry, not just have it in memory.
|
||||
drop(v);
|
||||
let v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut probe = Needle {
|
||||
id: NeedleId(2),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut probe).unwrap();
|
||||
assert_eq!(std::str::from_utf8(&probe.data).unwrap(), "after-mark-writable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_vif_defaults_local_version_and_bytes_offset() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// TestMultiDiskECBalanceNoShardLoss is the end-to-end regression for issue 9593.
|
||||
// It runs a real cluster of multi-disk volume servers (3 servers x 4 disks),
|
||||
// EC-encodes a volume, then runs ec.balance, asserting hard invariants the older
|
||||
// integration tests only logged:
|
||||
//
|
||||
// - after encode the full set of 14 EC shards exists,
|
||||
// - ec.balance never loses a shard (still 14 distinct shards afterwards),
|
||||
// - shards end up spread across more than one disk per node, and
|
||||
// - cluster.status counts physical disks (not one per node) and matches the
|
||||
// real on-disk distribution.
|
||||
func TestMultiDiskECBalanceNoShardLoss(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping multi-disk EC integration test in short mode")
|
||||
}
|
||||
|
||||
testDir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startMultiDiskCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForServer("127.0.0.1:9334", 30*time.Second))
|
||||
for i := 0; i < 3; i++ {
|
||||
require.NoError(t, waitForServer(fmt.Sprintf("127.0.0.1:809%d", i), 30*time.Second))
|
||||
}
|
||||
t.Log("waiting for multi-disk volume servers to register...")
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&shell.ShellOptions{
|
||||
Masters: stringPtr("127.0.0.1:9334"),
|
||||
GrpcDialOption: grpc.WithInsecure(),
|
||||
FilerGroup: stringPtr("default"),
|
||||
})
|
||||
connectToMasterAndSync(ctx, t, commandEnv)
|
||||
|
||||
// Upload enough small files that the volume holds real data to encode.
|
||||
var volumeId needle.VolumeId
|
||||
for retry := 0; retry < 5; retry++ {
|
||||
volumeId, err = uploadTestDataToMaster([]byte(strings.Repeat("multidisk-ec-9593 ", 64)), "127.0.0.1:9334")
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
require.NoError(t, err, "failed to upload test data")
|
||||
for i := 0; i < 40; i++ {
|
||||
if _, e := uploadTestDataToMaster([]byte(strings.Repeat("filler ", 128)), "127.0.0.1:9334"); e != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
t.Logf("using volume %d", volumeId)
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Populate every server's disks with volumes so the encode can see and target
|
||||
// each physical disk. The master only enumerates disks that already hold a
|
||||
// volume or EC shard — an empty disk leaves no trace in the topology (heartbeats
|
||||
// aggregate capacity per disk type, not per physical disk). ec.encode therefore
|
||||
// spreads a volume's shards only across the disks the master already knows hold
|
||||
// data on each node; if a node's data sits on a single disk, all its shards land
|
||||
// there and ec.balance cannot redistribute them (it has no within-node
|
||||
// cross-disk move). So spreading must be set up before encoding.
|
||||
//
|
||||
// volume.grow only tops up toward a writable target and stops on the first
|
||||
// allocation error, so a single -count grow can create far fewer volumes than
|
||||
// asked and leave a node on one disk. Grow repeatedly on the nodes that have not
|
||||
// spread yet (the volume server places each new volume on its least-loaded disk)
|
||||
// until the master's topology shows every node holding volumes on at least two
|
||||
// physical disks. This makes the multi-disk layout — and thus the post-encode
|
||||
// disk spread — deterministic instead of racing volume-growth and heartbeat.
|
||||
require.Eventually(t, func() bool {
|
||||
spread := nodeVolumeDiskCounts(t, commandEnv)
|
||||
if len(spread) == 3 && allAtLeast(spread, 2) {
|
||||
return true
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
server := fmt.Sprintf("127.0.0.1:809%d", i)
|
||||
if spread[server] < 2 {
|
||||
captureCommandOutput(t, shell.Commands[findCommandIndex("volume.grow")],
|
||||
[]string{"-collection", "test", "-dataNode", server, "-count", "4"}, commandEnv)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 60*time.Second, 2*time.Second,
|
||||
"volumes never spread across >=2 disks on all 3 nodes")
|
||||
|
||||
locked, unlock := tryLockWithTimeout(t, commandEnv, 15*time.Second)
|
||||
require.True(t, locked, "could not acquire shell lock")
|
||||
defer unlock()
|
||||
|
||||
// EC-encode the volume.
|
||||
out, err := captureCommandOutput(t, shell.Commands[findCommandIndex("ec.encode")],
|
||||
[]string{"-volumeId", fmt.Sprintf("%d", volumeId), "-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.encode output:\n%s", out)
|
||||
require.NoError(t, err, "ec.encode failed")
|
||||
|
||||
// All 14 shards must exist after encoding.
|
||||
require.Eventually(t, func() bool {
|
||||
return len(collectDistinctShardIDs(testDir, uint32(volumeId))) == erasureShardCount
|
||||
}, 30*time.Second, time.Second, "expected all %d EC shards after encode, got %v",
|
||||
erasureShardCount, collectDistinctShardIDs(testDir, uint32(volumeId)))
|
||||
|
||||
beforeBalance := collectDistinctShardIDs(testDir, uint32(volumeId))
|
||||
t.Logf("after encode: %d distinct shards on %d disks", len(beforeBalance), disksWithShards(testDir, uint32(volumeId)))
|
||||
|
||||
// Run ec.balance.
|
||||
out, err = captureCommandOutput(t, shell.Commands[findCommandIndex("ec.balance")],
|
||||
[]string{"-collection", "test", "-force"}, commandEnv)
|
||||
t.Logf("ec.balance output:\n%s", out)
|
||||
require.NoError(t, err, "ec.balance failed")
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// The core regression: ec.balance must not lose any shard.
|
||||
afterBalance := collectDistinctShardIDs(testDir, uint32(volumeId))
|
||||
require.Equal(t, erasureShardCount, len(afterBalance),
|
||||
"ec.balance lost shards on multi-disk nodes: had %v, now %v", sortedKeysOf(beforeBalance), sortedKeysOf(afterBalance))
|
||||
|
||||
// Shards must be spread across more than one physical disk per node overall.
|
||||
usedDisks := disksWithShards(testDir, uint32(volumeId))
|
||||
assert.Greater(t, usedDisks, 3, "EC shards should span more than one disk per node (got %d disks across 3 nodes)", usedDisks)
|
||||
|
||||
// cluster.status must count physical disks, not collapse to one per node: it
|
||||
// must report at least the disks actually holding this volume's shards (which
|
||||
// is already >3 across the 3 nodes). Before the fix it reported 3 (node count).
|
||||
require.Eventually(t, func() bool {
|
||||
n, ok := clusterStatusDiskCount(t, commandEnv)
|
||||
return ok && n >= usedDisks
|
||||
}, 30*time.Second, 2*time.Second, "cluster.status never reported the >=%d physical disks holding shards (multi-disk count)", usedDisks)
|
||||
|
||||
n, _ := clusterStatusDiskCount(t, commandEnv)
|
||||
t.Logf("cluster.status reports %d physical disks (>= %d holding this volume's shards)", n, usedDisks)
|
||||
}
|
||||
|
||||
const erasureShardCount = 14 // 10 data + 4 parity
|
||||
|
||||
// collectDistinctShardIDs returns the set of EC shard ids present for a volume
|
||||
// across every disk of every server in the multi-disk test layout.
|
||||
func collectDistinctShardIDs(testDir string, volumeId uint32) map[int]bool {
|
||||
ids := map[int]bool{}
|
||||
for server := 0; server < 3; server++ {
|
||||
for disk := 0; disk < 4; disk++ {
|
||||
diskDir := filepath.Join(testDir, fmt.Sprintf("server%d_disk%d", server, disk))
|
||||
files, err := listECShardFiles(diskDir, volumeId)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, f := range files {
|
||||
i := strings.LastIndex(f, ".ec")
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(f[i+3:]); err == nil && n >= 0 && n < erasureShardCount {
|
||||
ids[n] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// disksWithShards counts how many physical disks hold at least one shard.
|
||||
func disksWithShards(testDir string, volumeId uint32) int {
|
||||
n := 0
|
||||
for _, disks := range countShardsPerDisk(testDir, volumeId) {
|
||||
for _, c := range disks {
|
||||
if c > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// nodeVolumeDiskCounts returns, per volume server id, how many distinct physical
|
||||
// disks hold at least one volume according to the master's topology. The master
|
||||
// only enumerates disks that already hold a volume or EC shard (heartbeats
|
||||
// aggregate capacity per disk type, not per physical disk), so this reports the
|
||||
// disks ec.encode can actually spread a volume's shards across on each node.
|
||||
func nodeVolumeDiskCounts(t *testing.T, commandEnv *shell.CommandEnv) map[string]int {
|
||||
t.Helper()
|
||||
var resp *master_pb.VolumeListResponse
|
||||
err := commandEnv.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
|
||||
var e error
|
||||
resp, e = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})
|
||||
return e
|
||||
})
|
||||
counts := map[string]int{}
|
||||
if err != nil || resp.GetTopologyInfo() == nil {
|
||||
return counts
|
||||
}
|
||||
for _, dc := range resp.GetTopologyInfo().GetDataCenterInfos() {
|
||||
for _, r := range dc.GetRackInfos() {
|
||||
for _, dn := range r.GetDataNodeInfos() {
|
||||
disks := map[uint32]bool{}
|
||||
for _, di := range dn.GetDiskInfos() {
|
||||
for _, vi := range di.GetVolumeInfos() {
|
||||
disks[vi.GetDiskId()] = true
|
||||
}
|
||||
}
|
||||
counts[dn.Id] = len(disks)
|
||||
}
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
func allAtLeast(counts map[string]int, min int) bool {
|
||||
for _, c := range counts {
|
||||
if c < min {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var diskCountRe = regexp.MustCompile(`(\d+)\s+disks?`)
|
||||
|
||||
// clusterStatusDiskCount runs cluster.status and parses the reported disk count.
|
||||
func clusterStatusDiskCount(t *testing.T, commandEnv *shell.CommandEnv) (int, bool) {
|
||||
t.Helper()
|
||||
out, err := captureCommandOutput(t, shell.Commands[findCommandIndex("cluster.status")], []string{}, commandEnv)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
m := diskCountRe.FindStringSubmatch(out)
|
||||
if m == nil {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.Atoi(m[1])
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
func sortedKeysOf(m map[int]bool) []int {
|
||||
out := make([]int, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
for i := 1; i < len(out); i++ {
|
||||
for j := i; j > 0 && out[j-1] > out[j]; j-- {
|
||||
out[j-1], out[j] = out[j], out[j-1]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -207,8 +207,10 @@ func buildVolumeListResponse(t *testing.T, spec topologySpec, volumeID uint32) *
|
||||
t.Helper()
|
||||
|
||||
volumeSizeLimitMB := uint64(100)
|
||||
volumeSize := uint64(90) * 1024 * 1024
|
||||
volumeModifiedAt := time.Now().Add(-10 * time.Minute).Unix()
|
||||
// Exceed the default fullness (0.95) and quiet (1h) thresholds so volumes are
|
||||
// EC-eligible.
|
||||
volumeSize := uint64(96) * 1024 * 1024
|
||||
volumeModifiedAt := time.Now().Add(-2 * time.Hour).Unix()
|
||||
|
||||
diskTypes := spec.diskTypes
|
||||
if len(diskTypes) == 0 {
|
||||
|
||||
@@ -29,9 +29,11 @@ func TestErasureCodingDetectionLargeTopology(t *testing.T) {
|
||||
}
|
||||
|
||||
nodesPerRack := serverCount / rackCount
|
||||
eligibleSize := uint64(90) * 1024 * 1024
|
||||
// Eligible volumes must exceed the default fullness (0.95) and quiet (1h)
|
||||
// thresholds; ineligible ones fall below the fullness threshold.
|
||||
eligibleSize := uint64(96) * 1024 * 1024
|
||||
ineligibleSize := uint64(10) * 1024 * 1024
|
||||
modifiedAt := time.Now().Add(-10 * time.Minute).Unix()
|
||||
modifiedAt := time.Now().Add(-2 * time.Hour).Unix()
|
||||
|
||||
volumeID := uint32(1)
|
||||
dataCenters := make([]*master_pb.DataCenterInfo, 0, 1)
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
mathrand "math/rand"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// uniqueResourceSuffix returns a lowercased per-test, per-invocation suffix
|
||||
// safe for use in IAM resource and S3 bucket names. Avoids EntityAlreadyExists
|
||||
// / BucketAlreadyExists collisions when integration jobs retry or run in
|
||||
// parallel against a shared stack.
|
||||
func uniqueResourceSuffix(t *testing.T) string {
|
||||
name := strings.ToLower(t.Name())
|
||||
name = strings.ReplaceAll(name, "/", "-")
|
||||
name = strings.ReplaceAll(name, "_", "-")
|
||||
return fmt.Sprintf("%s-%d", name, mathrand.Intn(10000))
|
||||
}
|
||||
|
||||
// isAccessDenied returns true when err is an AWS error with code "AccessDenied".
|
||||
// Used to gate deny-path polling so transient setup errors don't end the
|
||||
// Eventually loop prematurely.
|
||||
func isAccessDenied(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
awsErr, ok := err.(awserr.Error)
|
||||
return ok && awsErr.Code() == "AccessDenied"
|
||||
}
|
||||
|
||||
// TestIAMUserInlinePolicySourceIpCondition verifies that an aws:SourceIp condition
|
||||
// on a user inline policy is honored. Tests run from localhost (127.0.0.1), so a
|
||||
// policy that only allows access from a non-loopback CIDR must deny the request,
|
||||
// and a policy that allows access from 127.0.0.0/8 must allow it.
|
||||
func TestIAMUserInlinePolicySourceIpCondition(t *testing.T) {
|
||||
framework := NewS3IAMTestFramework(t)
|
||||
defer framework.Cleanup()
|
||||
|
||||
iamClient, err := framework.CreateIAMClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
|
||||
suffix := uniqueResourceSuffix(t)
|
||||
userName := "user-" + suffix
|
||||
policyName := "policy-" + suffix
|
||||
bucketName := "bucket-" + suffix
|
||||
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
|
||||
keyResp, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{
|
||||
UserName: aws.String(userName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
accessKeyId := *keyResp.AccessKey.AccessKeyId
|
||||
secretKey := *keyResp.AccessKey.SecretAccessKey
|
||||
|
||||
userS3 := createS3Client(t, accessKeyId, secretKey)
|
||||
|
||||
adminS3, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, framework.CreateBucketWithCleanup(adminS3, bucketName))
|
||||
|
||||
t.Cleanup(func() {
|
||||
if _, err := iamClient.DeleteUserPolicy(&iam.DeleteUserPolicyInput{
|
||||
UserName: aws.String(userName),
|
||||
PolicyName: aws.String(policyName),
|
||||
}); err != nil {
|
||||
t.Logf("cleanup: failed to delete user policy: %v", err)
|
||||
}
|
||||
if _, err := iamClient.DeleteAccessKey(&iam.DeleteAccessKeyInput{
|
||||
UserName: aws.String(userName),
|
||||
AccessKeyId: keyResp.AccessKey.AccessKeyId,
|
||||
}); err != nil {
|
||||
t.Logf("cleanup: failed to delete access key: %v", err)
|
||||
}
|
||||
if _, err := iamClient.DeleteUser(&iam.DeleteUserInput{UserName: aws.String(userName)}); err != nil {
|
||||
t.Logf("cleanup: failed to delete user: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
policyDoc := func(cidrs ...string) string {
|
||||
quoted := make([]string, len(cidrs))
|
||||
for i, c := range cidrs {
|
||||
quoted[i] = `"` + c + `"`
|
||||
}
|
||||
return `{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:*",
|
||||
"Resource":["arn:aws:s3:::` + bucketName + `","arn:aws:s3:::` + bucketName + `/*"],
|
||||
"Condition":{"IpAddress":{"aws:SourceIp":[` + strings.Join(quoted, ",") + `]}}
|
||||
}]
|
||||
}`
|
||||
}
|
||||
|
||||
t.Run("denies_when_source_ip_does_not_match", func(t *testing.T) {
|
||||
// SourceIp 198.51.100.0/24 is RFC5737 TEST-NET-2; the test client is on
|
||||
// loopback (127.0.0.1 or ::1 depending on resolver), so the condition
|
||||
// must fail and the action must be denied.
|
||||
_, err = iamClient.PutUserPolicy(&iam.PutUserPolicyInput{
|
||||
UserName: aws.String(userName),
|
||||
PolicyName: aws.String(policyName),
|
||||
PolicyDocument: aws.String(policyDoc("198.51.100.0/24")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var lastErr error
|
||||
require.Eventually(t, func() bool {
|
||||
_, lastErr = userS3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("denied.txt"),
|
||||
Body: aws.ReadSeekCloser(strings.NewReader("nope")),
|
||||
})
|
||||
return isAccessDenied(lastErr)
|
||||
}, 10*time.Second, 500*time.Millisecond,
|
||||
"PutObject must be denied with AccessDenied when aws:SourceIp condition does not match (last error: %v)", lastErr)
|
||||
})
|
||||
|
||||
t.Run("allows_when_source_ip_matches", func(t *testing.T) {
|
||||
// Cover both IPv4 and IPv6 loopback: on CI runners `localhost` may
|
||||
// resolve to ::1 first, in which case a 127.0.0.0/8-only allow would
|
||||
// silently never match and the test would hang.
|
||||
_, err = iamClient.PutUserPolicy(&iam.PutUserPolicyInput{
|
||||
UserName: aws.String(userName),
|
||||
PolicyName: aws.String(policyName),
|
||||
PolicyDocument: aws.String(policyDoc("127.0.0.0/8", "::1/128")),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
_, err := userS3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("allowed.txt"),
|
||||
Body: aws.ReadSeekCloser(strings.NewReader("ok")),
|
||||
})
|
||||
return err == nil
|
||||
}, 10*time.Second, 500*time.Millisecond,
|
||||
"PutObject must succeed when aws:SourceIp condition matches the loopback range")
|
||||
})
|
||||
}
|
||||
|
||||
// TestIAMGroupInlinePolicyEnforcement verifies that PutGroupPolicy is supported
|
||||
// and that the resulting inline policy is enforced for members of the group,
|
||||
// including its Condition block.
|
||||
func TestIAMGroupInlinePolicyEnforcement(t *testing.T) {
|
||||
framework := NewS3IAMTestFramework(t)
|
||||
defer framework.Cleanup()
|
||||
|
||||
iamClient, err := framework.CreateIAMClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
|
||||
suffix := uniqueResourceSuffix(t)
|
||||
groupName := "group-" + suffix
|
||||
userName := "user-" + suffix
|
||||
policyName := "policy-" + suffix
|
||||
bucketName := "bucket-" + suffix
|
||||
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
|
||||
keyResp, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{
|
||||
UserName: aws.String(userName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = iamClient.CreateGroup(&iam.CreateGroupInput{GroupName: aws.String(groupName)})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = iamClient.AddUserToGroup(&iam.AddUserToGroupInput{
|
||||
GroupName: aws.String(groupName),
|
||||
UserName: aws.String(userName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
userS3 := createS3Client(t, *keyResp.AccessKey.AccessKeyId, *keyResp.AccessKey.SecretAccessKey)
|
||||
|
||||
adminS3, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, framework.CreateBucketWithCleanup(adminS3, bucketName))
|
||||
|
||||
t.Cleanup(func() {
|
||||
if _, err := iamClient.DeleteGroupPolicy(&iam.DeleteGroupPolicyInput{
|
||||
GroupName: aws.String(groupName),
|
||||
PolicyName: aws.String(policyName),
|
||||
}); err != nil {
|
||||
t.Logf("cleanup: failed to delete group policy: %v", err)
|
||||
}
|
||||
if _, err := iamClient.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{
|
||||
GroupName: aws.String(groupName),
|
||||
UserName: aws.String(userName),
|
||||
}); err != nil {
|
||||
t.Logf("cleanup: failed to remove user from group: %v", err)
|
||||
}
|
||||
if _, err := iamClient.DeleteAccessKey(&iam.DeleteAccessKeyInput{
|
||||
UserName: aws.String(userName),
|
||||
AccessKeyId: keyResp.AccessKey.AccessKeyId,
|
||||
}); err != nil {
|
||||
t.Logf("cleanup: failed to delete access key: %v", err)
|
||||
}
|
||||
if _, err := iamClient.DeleteUser(&iam.DeleteUserInput{UserName: aws.String(userName)}); err != nil {
|
||||
t.Logf("cleanup: failed to delete user: %v", err)
|
||||
}
|
||||
if _, err := iamClient.DeleteGroup(&iam.DeleteGroupInput{GroupName: aws.String(groupName)}); err != nil {
|
||||
t.Logf("cleanup: failed to delete group: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
// Cover both IPv4 and IPv6 loopback in the allow CIDR list: on CI runners
|
||||
// `localhost` may resolve to ::1 first, in which case a 127.0.0.0/8-only
|
||||
// allow would silently never match and the test would hang.
|
||||
allowDoc := `{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:*",
|
||||
"Resource":["arn:aws:s3:::` + bucketName + `","arn:aws:s3:::` + bucketName + `/*"],
|
||||
"Condition":{"IpAddress":{"aws:SourceIp":["127.0.0.0/8","::1/128"]}}
|
||||
}]
|
||||
}`
|
||||
denyDoc := `{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:*",
|
||||
"Resource":["arn:aws:s3:::` + bucketName + `","arn:aws:s3:::` + bucketName + `/*"],
|
||||
"Condition":{"IpAddress":{"aws:SourceIp":"198.51.100.0/24"}}
|
||||
}]
|
||||
}`
|
||||
|
||||
t.Run("crud_round_trip", func(t *testing.T) {
|
||||
_, err := iamClient.PutGroupPolicy(&iam.PutGroupPolicyInput{
|
||||
GroupName: aws.String(groupName),
|
||||
PolicyName: aws.String(policyName),
|
||||
PolicyDocument: aws.String(allowDoc),
|
||||
})
|
||||
require.NoError(t, err, "PutGroupPolicy must succeed (no longer NotImplemented)")
|
||||
|
||||
listResp, err := iamClient.ListGroupPolicies(&iam.ListGroupPoliciesInput{
|
||||
GroupName: aws.String(groupName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
found := false
|
||||
for _, name := range listResp.PolicyNames {
|
||||
if name != nil && *name == policyName {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.True(t, found, "ListGroupPolicies must return the freshly added policy")
|
||||
|
||||
getResp, err := iamClient.GetGroupPolicy(&iam.GetGroupPolicyInput{
|
||||
GroupName: aws.String(groupName),
|
||||
PolicyName: aws.String(policyName),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, getResp.PolicyDocument)
|
||||
assert.Contains(t, *getResp.PolicyDocument, "aws:SourceIp",
|
||||
"GetGroupPolicy must round-trip the Condition block")
|
||||
})
|
||||
|
||||
t.Run("enforces_allow_when_condition_matches", func(t *testing.T) {
|
||||
_, err := iamClient.PutGroupPolicy(&iam.PutGroupPolicyInput{
|
||||
GroupName: aws.String(groupName),
|
||||
PolicyName: aws.String(policyName),
|
||||
PolicyDocument: aws.String(allowDoc),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
_, err := userS3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("group-allowed.txt"),
|
||||
Body: aws.ReadSeekCloser(strings.NewReader("ok")),
|
||||
})
|
||||
return err == nil
|
||||
}, 10*time.Second, 500*time.Millisecond,
|
||||
"group member must be allowed when the group policy condition matches")
|
||||
})
|
||||
|
||||
t.Run("enforces_deny_when_condition_does_not_match", func(t *testing.T) {
|
||||
_, err := iamClient.PutGroupPolicy(&iam.PutGroupPolicyInput{
|
||||
GroupName: aws.String(groupName),
|
||||
PolicyName: aws.String(policyName),
|
||||
PolicyDocument: aws.String(denyDoc),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var lastErr error
|
||||
require.Eventually(t, func() bool {
|
||||
_, lastErr = userS3.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("group-denied.txt"),
|
||||
Body: aws.ReadSeekCloser(strings.NewReader("nope")),
|
||||
})
|
||||
return isAccessDenied(lastErr)
|
||||
}, 10*time.Second, 500*time.Millisecond,
|
||||
"group member must be denied with AccessDenied when the group policy condition does not match (last error: %v)", lastErr)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# AWS SDK V2 Route Disambiguation Integration Tests
|
||||
#
|
||||
# Pins the regression for the route collision between the regular S3 API
|
||||
# and the S3 Tables REST API on shared top-level paths (/buckets,
|
||||
# /get-table). The tests use the real AWS SDK V2 for Go so the SDK's own
|
||||
# XML deserializer is the assertion — a JSON body produces an SDK error
|
||||
# before any test code runs.
|
||||
#
|
||||
# Prerequisites:
|
||||
# - SeaweedFS running with S3 API enabled on port 8333
|
||||
# - Go 1.21+
|
||||
#
|
||||
# Usage:
|
||||
# make test - Run the SDK V2 routing tests
|
||||
# make test-verbose - Run with verbose output
|
||||
# make clean - Clean test cache
|
||||
|
||||
.PHONY: all test test-verbose clean help
|
||||
|
||||
S3_ENDPOINT ?= http://127.0.0.1:8333
|
||||
|
||||
all: test
|
||||
|
||||
test:
|
||||
@echo "Running SDK V2 routing tests against $(S3_ENDPOINT)..."
|
||||
S3_ENDPOINT=$(S3_ENDPOINT) go test -v -timeout 5m ./...
|
||||
|
||||
test-verbose:
|
||||
S3_ENDPOINT=$(S3_ENDPOINT) go test -v -timeout 5m -count=1 ./...
|
||||
|
||||
clean:
|
||||
go clean -testcache
|
||||
|
||||
help:
|
||||
@echo "AWS SDK V2 Route Disambiguation Tests"
|
||||
@echo "Targets:"
|
||||
@echo " test Run the routing tests"
|
||||
@echo " test-verbose Run with verbose output"
|
||||
@echo " clean Clean test cache"
|
||||
@echo "Environment Variables:"
|
||||
@echo " S3_ENDPOINT S3 endpoint URL (default: http://127.0.0.1:8333)"
|
||||
@@ -0,0 +1,210 @@
|
||||
// Package sdkv2routing_test exercises route disambiguation between the
|
||||
// regular S3 API and the S3 Tables REST API on top-level paths the two
|
||||
// share (/buckets, /get-table). The bug it pins:
|
||||
//
|
||||
// When a user has an S3 bucket named "buckets" (or "get-table"), a
|
||||
// path-style ListObjectsV2 request sent by AWS SDK V2 / Hadoop s3a /
|
||||
// Spark would be routed to the S3 Tables ListTableBuckets handler and
|
||||
// receive a JSON body. AWS SDK V2 then fails XML parsing with
|
||||
// "Unexpected character '{' (code 123) in prolog".
|
||||
//
|
||||
// These tests use the real AWS SDK V2 for Go, so the SDK's own
|
||||
// deserializer is the assertion: if the server returns the wrong
|
||||
// content type, the SDK errors out before any test assertion runs.
|
||||
package sdkv2routing_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "http://127.0.0.1:8333"
|
||||
defaultAccessKey = "some_access_key1"
|
||||
defaultSecretKey = "some_secret_key1"
|
||||
defaultRegion = "us-east-1"
|
||||
)
|
||||
|
||||
func getS3Client(t *testing.T) *s3.Client {
|
||||
t.Helper()
|
||||
|
||||
endpoint := os.Getenv("S3_ENDPOINT")
|
||||
if endpoint == "" {
|
||||
endpoint = defaultEndpoint
|
||||
}
|
||||
accessKey := os.Getenv("AWS_ACCESS_KEY_ID")
|
||||
if accessKey == "" {
|
||||
accessKey = defaultAccessKey
|
||||
}
|
||||
secretKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
|
||||
if secretKey == "" {
|
||||
secretKey = defaultSecretKey
|
||||
}
|
||||
region := os.Getenv("AWS_REGION")
|
||||
if region == "" {
|
||||
region = defaultRegion
|
||||
}
|
||||
|
||||
cfg, err := config.LoadDefaultConfig(context.TODO(),
|
||||
config.WithRegion(region),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
|
||||
config.WithEndpointResolverWithOptions(aws.EndpointResolverWithOptionsFunc(
|
||||
func(service, region string, options ...interface{}) (aws.Endpoint, error) {
|
||||
return aws.Endpoint{
|
||||
URL: endpoint,
|
||||
SigningRegion: defaultRegion,
|
||||
HostnameImmutable: true,
|
||||
}, nil
|
||||
})),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
// ensureBucket creates bucket if it doesn't already exist. It tolerates
|
||||
// BucketAlreadyOwnedByYou / BucketAlreadyExists so the tests are
|
||||
// idempotent across local re-runs.
|
||||
func ensureBucket(t *testing.T, ctx context.Context, client *s3.Client, bucket string) {
|
||||
t.Helper()
|
||||
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)})
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, "BucketAlreadyOwnedByYou") || strings.Contains(msg, "BucketAlreadyExists") {
|
||||
return
|
||||
}
|
||||
t.Fatalf("CreateBucket(%q) failed: %v", bucket, err)
|
||||
}
|
||||
|
||||
// deleteBucket best-effort cleans up a bucket and any objects in it.
|
||||
// Test does not fail if cleanup fails — the next run is idempotent.
|
||||
func deleteBucket(ctx context.Context, client *s3.Client, bucket string) {
|
||||
paginator := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{Bucket: aws.String(bucket)})
|
||||
for paginator.HasMorePages() {
|
||||
page, err := paginator.NextPage(ctx)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, obj := range page.Contents {
|
||||
client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: obj.Key})
|
||||
}
|
||||
}
|
||||
client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
|
||||
}
|
||||
|
||||
// TestListObjectsV2_OnBucketNamedBuckets is the direct reproducer for
|
||||
// issue #9559: Spark / Hadoop s3a does a ListObjectsV2 against bucket
|
||||
// "buckets" via AWS SDK V2, which fails with
|
||||
// "Could not parse XML response. ... Unexpected character '{' (code 123)
|
||||
// in prolog" when SeaweedFS routes the request to the JSON-returning
|
||||
// ListTableBuckets handler. The SDK's response deserializer is the
|
||||
// real assertion here — a JSON body produces an SDK error before we
|
||||
// reach require.NoError.
|
||||
func TestListObjectsV2_OnBucketNamedBuckets(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
client := getS3Client(t)
|
||||
|
||||
const bucket = "buckets"
|
||||
ensureBucket(t, ctx, client, bucket)
|
||||
t.Cleanup(func() { deleteBucket(ctx, client, bucket) })
|
||||
|
||||
out, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucket),
|
||||
Prefix: aws.String("logs/"),
|
||||
})
|
||||
require.NoError(t, err, "AWS SDK V2 must parse the response as XML")
|
||||
require.NotNil(t, out)
|
||||
}
|
||||
|
||||
// TestPutGetObject_OnBucketNamedBuckets exercises the full read/write
|
||||
// round-trip on the colliding bucket name. PutObject and GetObject go
|
||||
// through different routes than ListObjectsV2, and verifying them
|
||||
// guards against future regressions that re-route only some verbs.
|
||||
func TestPutGetObject_OnBucketNamedBuckets(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
client := getS3Client(t)
|
||||
|
||||
const bucket = "buckets"
|
||||
const key = "logs/hello.txt"
|
||||
const body = "hello from issue 9559"
|
||||
|
||||
ensureBucket(t, ctx, client, bucket)
|
||||
t.Cleanup(func() { deleteBucket(ctx, client, bucket) })
|
||||
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: strings.NewReader(body),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
defer out.Body.Close()
|
||||
|
||||
got, err := io.ReadAll(out.Body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
|
||||
// TestListObjectsV2_OnBucketNamedGetTable covers the second colliding
|
||||
// path. The S3 Tables GET /get-table endpoint shares its path with a
|
||||
// bucket literally named "get-table", which is a legal S3 bucket name.
|
||||
func TestListObjectsV2_OnBucketNamedGetTable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
client := getS3Client(t)
|
||||
|
||||
const bucket = "get-table"
|
||||
ensureBucket(t, ctx, client, bucket)
|
||||
t.Cleanup(func() { deleteBucket(ctx, client, bucket) })
|
||||
|
||||
out, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(bucket)})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out)
|
||||
}
|
||||
|
||||
// TestCreateAndListBuckets_ServiceLevel verifies the SDK's service-level
|
||||
// ListBuckets still parses as XML when a bucket named "buckets" exists.
|
||||
// ListBuckets goes through GET / (root) which is unaffected by the
|
||||
// /buckets route collision — this is a guard against the matcher
|
||||
// accidentally widening to top-level paths.
|
||||
func TestCreateAndListBuckets_ServiceLevel(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
client := getS3Client(t)
|
||||
|
||||
const bucket = "buckets"
|
||||
ensureBucket(t, ctx, client, bucket)
|
||||
t.Cleanup(func() { deleteBucket(ctx, client, bucket) })
|
||||
|
||||
out, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out)
|
||||
|
||||
found := false
|
||||
for _, b := range out.Buckets {
|
||||
if aws.ToString(b.Name) == bucket {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
require.True(t, found, "bucket %q must appear in service-level ListBuckets", bucket)
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
@@ -451,19 +454,22 @@ func icebergPath(prefix, path string) string {
|
||||
return withPrefix
|
||||
}
|
||||
|
||||
// createTableBucket creates a table bucket via the S3Tables REST API
|
||||
// createTableBucket creates a table bucket via the S3Tables REST API.
|
||||
// The request is AWS V4 signed for SERVICE=s3tables so the S3 Tables
|
||||
// route matcher accepts it; signing with regular SERVICE=s3 would let
|
||||
// the request fall through to the S3 CreateBucket handler.
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
// Use S3Tables REST API to create the bucket
|
||||
endpoint := fmt.Sprintf("http://localhost:%d/buckets", env.s3Port)
|
||||
|
||||
reqBody := fmt.Sprintf(`{"name":"%s"}`, bucketName)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, endpoint, strings.NewReader(reqBody))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-amz-json-1.1")
|
||||
signS3TablesRequest(t, req, reqBody)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -480,6 +486,20 @@ func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Logf("Created table bucket %s", bucketName)
|
||||
}
|
||||
|
||||
// signS3TablesRequest signs req with AWS V4 for SERVICE=s3tables. The
|
||||
// underlying weed mini instance runs in default-allow mode so the
|
||||
// signature itself is not verified; only the credential scope matters,
|
||||
// because the S3 Tables route matcher requires SERVICE=s3tables to
|
||||
// distinguish S3 Tables traffic from regular S3 calls on the same paths.
|
||||
func signS3TablesRequest(t *testing.T, req *http.Request, body string) {
|
||||
t.Helper()
|
||||
creds := credentials.NewStaticCredentials("test-ak", "test-sk", "")
|
||||
signer := v4.NewSigner(creds)
|
||||
if _, err := signer.Sign(req, strings.NewReader(body), "s3tables", "us-east-1", time.Now()); err != nil {
|
||||
t.Fatalf("Failed to sign S3 Tables request: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// randomSuffix returns a short random hex suffix for unique resource naming.
|
||||
func randomSuffix() string {
|
||||
return fmt.Sprintf("%x", time.Now().UnixNano()&0xffffffff)
|
||||
|
||||
@@ -411,7 +411,12 @@ func createIcebergTable(t *testing.T, env *TestEnvironment, bucketName, namespac
|
||||
func listFilerContents(t *testing.T, env *TestEnvironment, path string) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("weed", "shell",
|
||||
// Bound diagnostic listing so a hung weed shell during cleanup can't
|
||||
// burn the whole 20-minute test timeout.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "weed", "shell",
|
||||
fmt.Sprintf("-master=%s", env.hostMasterAddress()),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("fs.ls -R %s\nexit\n", path))
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
FROM chrislusf/seaweedfs:e2e
|
||||
|
||||
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
|
||||
--no-install-recommends \
|
||||
--no-install-suggests \
|
||||
samba \
|
||||
smbclient \
|
||||
python3-minimal \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY smb.conf.template /smb.conf.template
|
||||
COPY smb_tests.sh /smb_tests.sh
|
||||
COPY lock_tests.sh /lock_tests.sh
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
COPY run_inside_container.sh /run_inside_container.sh
|
||||
RUN chmod +x /smb_tests.sh /lock_tests.sh /entrypoint.sh /run_inside_container.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -0,0 +1,96 @@
|
||||
# Samba on FUSE integration test
|
||||
|
||||
Exports a SeaweedFS FUSE mount over SMB with Samba's `smbd` and drives it with
|
||||
`smbclient`, verifying that SMB file operations work correctly on top of the
|
||||
mount and that data stays consistent across both protocols.
|
||||
|
||||
## What it checks
|
||||
|
||||
The functional battery in `smb_tests.sh` covers:
|
||||
|
||||
- connecting to the share and listing the root
|
||||
- 1 MiB upload/download round-trip with content verification
|
||||
- subdirectory creation and writes into it
|
||||
- file rename
|
||||
- 64 MiB upload/download (exercises SeaweedFS chunk splitting)
|
||||
- recursive upload of a directory tree
|
||||
- cross-protocol consistency: files written over SMB appear on the FUSE mount
|
||||
with identical content, and files written directly on the FUSE mount are
|
||||
readable over SMB
|
||||
- deleting files and directory trees
|
||||
|
||||
The locking / concurrency battery in `lock_tests.sh` covers the harder cases a
|
||||
network-filesystem backend has to get right:
|
||||
|
||||
- **POSIX `fcntl` byte-range locking** on the FUSE mount: a held exclusive lock
|
||||
denies a conflicting lock, allows a non-overlapping range, and is reacquirable
|
||||
after release (exercises the mount's `SetLk`/`GetLk`)
|
||||
- **Distributed locking** (`-dlm`): a file held open for writing on one mount
|
||||
blocks a writer on a second mount until it is released
|
||||
- **Distributed-lock integrity**: concurrent writers to the same file from two
|
||||
mounts leave exactly one intact payload, never a torn mix
|
||||
- **Concurrency**: parallel writers to distinct files all succeed
|
||||
|
||||
Both FUSE mounts are started with `-dlm` (distributed lock manager). The second
|
||||
mount (`/mnt/seaweedfs2`) exists only to contend with the smbd-backed mount in
|
||||
the distributed-locking tests; both see the same filer path, so `.../share` is
|
||||
the same data on each.
|
||||
|
||||
> Note on DLM semantics: `-dlm` coordinates *write access* (one mount writes a
|
||||
> file at a time) and guarantees writes are not torn. It does not guarantee
|
||||
> which concurrent writer wins or instant cross-mount read convergence — the
|
||||
> holder's buffered data is flushed on close, asynchronously to lock release.
|
||||
> When a holder closes the file, a writer on another mount acquires the freed
|
||||
> lock within ~1s and completes.
|
||||
|
||||
## Layout
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `smb_tests.sh` | SMB functional battery. Shared by both runners. |
|
||||
| `lock_tests.sh` | SMB locking / concurrency battery. Shared by both runners. |
|
||||
| `smb.conf.template` | Samba config; placeholders are filled in at run time. |
|
||||
| `run.sh` | Local runner: `weed mini` + two `-dlm` mounts + `smbd` + both batteries, all as the current user on unprivileged ports. |
|
||||
| `entrypoint.sh` | Container entrypoint: starts two `-dlm` FUSE mounts and runs `smbd`. |
|
||||
| `run_inside_container.sh` | Runs both batteries inside the container against the local `smbd`. |
|
||||
| `Dockerfile` | Adds Samba to the `chrislusf/seaweedfs:e2e` image. |
|
||||
| `docker-compose.yml` | master + volume + filer + samba services. |
|
||||
|
||||
## Running locally
|
||||
|
||||
Requirements: `weed` on `$PATH`, `fusermount3`, and Samba's `smbd` /
|
||||
`smbclient` / `smbpasswd` (Debian/Ubuntu: `apt-get install samba smbclient`).
|
||||
|
||||
```sh
|
||||
test/samba/run.sh
|
||||
```
|
||||
|
||||
No `sudo` is needed: `smbd` runs as the current user on port 4450 and all state
|
||||
lives under a temp work dir that is cleaned up on exit.
|
||||
|
||||
## Running with Docker
|
||||
|
||||
Mirrors the CI job. Requires `/dev/fuse` and `SYS_ADMIN` (provided in the
|
||||
compose file).
|
||||
|
||||
```sh
|
||||
# build the base e2e image first (from the repo's docker/ dir)
|
||||
docker compose -f test/samba/docker-compose.yml up --wait
|
||||
docker compose -f test/samba/docker-compose.yml exec -T samba /run_inside_container.sh
|
||||
docker compose -f test/samba/docker-compose.yml down -v
|
||||
```
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/samba-integration.yml` runs on changes to `weed/mount/**`,
|
||||
`weed/filer/**`, or `test/samba/**`. It builds the e2e image, builds the Samba
|
||||
harness image on top, brings up the cluster, runs the battery, and uploads
|
||||
server logs as artifacts.
|
||||
|
||||
## Notes
|
||||
|
||||
- The share disables Samba's DOS-attribute / xattr mapping and oplocks. The
|
||||
SeaweedFS FUSE mount does not implement that surface, and leaving it on
|
||||
produces `NT_STATUS_NOT_SUPPORTED` errors unrelated to data integrity.
|
||||
- The share path is a subdirectory of the mount (`.../share`) so the runner can
|
||||
verify SMB-side operations directly on the FUSE side.
|
||||
@@ -0,0 +1,60 @@
|
||||
services:
|
||||
master:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 master -ip=master -ip.bind=0.0.0.0 -raftBootstrap"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:9333/cluster/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 30
|
||||
start_period: 10s
|
||||
|
||||
volume:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 volume -master=master:9333 -ip=volume -ip.bind=0.0.0.0 -preStopSeconds=1"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:8080/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 15
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
master:
|
||||
condition: service_healthy
|
||||
|
||||
filer:
|
||||
image: chrislusf/seaweedfs:e2e
|
||||
command: "-v=4 filer -master=master:9333 -ip=filer -ip.bind=0.0.0.0"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "-I", "http://localhost:8888/healthz"]
|
||||
interval: 2s
|
||||
timeout: 10s
|
||||
retries: 15
|
||||
start_period: 5s
|
||||
depends_on:
|
||||
volume:
|
||||
condition: service_healthy
|
||||
|
||||
samba:
|
||||
image: chrislusf/seaweedfs:samba
|
||||
build:
|
||||
context: .
|
||||
environment:
|
||||
FILER: filer:8888
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
devices:
|
||||
- /dev/fuse
|
||||
security_opt:
|
||||
- apparmor:unconfined
|
||||
healthcheck:
|
||||
test:
|
||||
- "CMD-SHELL"
|
||||
- "mountpoint -q /mnt/seaweedfs && mountpoint -q /mnt/seaweedfs2 && smbclient -L 127.0.0.1 -p 445 -U smbtest%smbtest -m SMB3 >/dev/null 2>&1"
|
||||
interval: 3s
|
||||
timeout: 10s
|
||||
retries: 20
|
||||
start_period: 15s
|
||||
depends_on:
|
||||
filer:
|
||||
condition: service_healthy
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Entrypoint for the samba test container.
|
||||
#
|
||||
# Mounts SeaweedFS over FUSE twice, both with distributed locking (-dlm) so the
|
||||
# locking tests can exercise cross-mount write coordination:
|
||||
# - MOUNT_DIR (/mnt/seaweedfs) is exported over SMB by smbd
|
||||
# - MOUNT2_DIR (/mnt/seaweedfs2) is a second, independent mount of the same
|
||||
# filer used to contend with the SMB writer
|
||||
#
|
||||
# Both mounts see the same filer path, so .../share is the same data on each.
|
||||
# smbd runs in the foreground (as root, which owns the mounts), so the share
|
||||
# uses "force user = root".
|
||||
set -euo pipefail
|
||||
|
||||
FILER="${FILER:-filer:8888}"
|
||||
MOUNT_DIR="${MOUNT_DIR:-/mnt/seaweedfs}"
|
||||
MOUNT2_DIR="${MOUNT2_DIR:-/mnt/seaweedfs2}"
|
||||
SHARE_DIR="${MOUNT_DIR}/share"
|
||||
STATE_DIR="${STATE_DIR:-/var/lib/samba-test}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:-smbtest}"
|
||||
SMB_PASS="${SMB_PASS:-smbtest}"
|
||||
|
||||
mkdir -p "${MOUNT_DIR}" "${MOUNT2_DIR}" \
|
||||
"${STATE_DIR}/private" "${STATE_DIR}/state" "${STATE_DIR}/cache" \
|
||||
"${STATE_DIR}/lock" "${STATE_DIR}/pid" "${STATE_DIR}/ncalrpc"
|
||||
|
||||
# mount_seaweedfs <mountpoint> <logfile> — mount with -dlm and wait for it.
|
||||
mount_seaweedfs() {
|
||||
local dir="$1" log="$2"
|
||||
echo "==> Mounting SeaweedFS (${FILER}) at ${dir} with -dlm"
|
||||
weed -v=1 mount \
|
||||
-filer="${FILER}" \
|
||||
-dir="${dir}" \
|
||||
-filer.path=/ \
|
||||
-dirAutoCreate \
|
||||
-allowOthers \
|
||||
-dlm \
|
||||
>"${log}" 2>&1 &
|
||||
local pid=$!
|
||||
for _ in $(seq 1 120); do
|
||||
if mountpoint -q "${dir}"; then
|
||||
return 0
|
||||
fi
|
||||
if ! kill -0 "${pid}" 2>/dev/null; then
|
||||
echo "weed mount (${dir}) exited early; log tail:" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FUSE mount ${dir} did not come up" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
}
|
||||
|
||||
mount_seaweedfs "${MOUNT_DIR}" /var/log/weed-mount.log
|
||||
mount_seaweedfs "${MOUNT2_DIR}" /var/log/weed-mount2.log
|
||||
|
||||
mkdir -p "${SHARE_DIR}"
|
||||
chmod 0777 "${SHARE_DIR}"
|
||||
|
||||
# --- configure and start smbd ----------------------------------------------
|
||||
echo "==> Configuring Samba share on port ${SMB_PORT}"
|
||||
sed -e "s#@SHARE_PATH@#${SHARE_DIR}#g" \
|
||||
-e "s#@STATE_DIR@#${STATE_DIR}#g" \
|
||||
-e "s#@SMB_PORT@#${SMB_PORT}#g" \
|
||||
-e "s#@FORCE_USER@#root#g" \
|
||||
/smb.conf.template >/etc/samba/smb.conf
|
||||
|
||||
id -u "${SMB_USER}" >/dev/null 2>&1 || useradd -M -s /usr/sbin/nologin "${SMB_USER}"
|
||||
printf '%s\n%s\n' "${SMB_PASS}" "${SMB_PASS}" | smbpasswd -a -s "${SMB_USER}"
|
||||
|
||||
echo "==> Starting smbd"
|
||||
exec smbd -F --no-process-group -s /etc/samba/smb.conf
|
||||
Executable
+218
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Locking / concurrency test battery for Samba on a SeaweedFS FUSE mount.
|
||||
#
|
||||
# Covers the challenges a network-filesystem backend has to get right:
|
||||
# 1. POSIX fcntl byte-range locking on the FUSE mount (SetLk/GetLk)
|
||||
# 2. Distributed locking (-dlm): a write held open on one mount blocks a
|
||||
# writer on another mount until it is released
|
||||
# 3. Distributed locking integrity: concurrent writers to the same file from
|
||||
# two mounts produce intact (non-torn) data
|
||||
# 4. Concurrent writers to distinct files all succeed
|
||||
#
|
||||
# Required env:
|
||||
# SMB_USER, SMB_PASS samba credentials
|
||||
# MOUNT_SHARE dir on the smbd-backed FUSE mount (mount 1)
|
||||
# MOUNT2_SHARE dir on the second FUSE mount (mount 2)
|
||||
# Optional env:
|
||||
# SMB_HOST (127.0.0.1), SMB_SHARE (seaweedfs), SMB_PORT (445)
|
||||
set -uo pipefail
|
||||
|
||||
SMB_HOST="${SMB_HOST:-127.0.0.1}"
|
||||
SMB_SHARE="${SMB_SHARE:-seaweedfs}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:?SMB_USER is required}"
|
||||
SMB_PASS="${SMB_PASS:?SMB_PASS is required}"
|
||||
MOUNT_SHARE="${MOUNT_SHARE:?MOUNT_SHARE is required}"
|
||||
MOUNT2_SHARE="${MOUNT2_SHARE:?MOUNT2_SHARE is required}"
|
||||
|
||||
WORK="$(mktemp -d /tmp/samba-locktest.XXXXXX)"
|
||||
trap 'rm -rf "${WORK}"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
pass() { printf ' [PASS] %s\n' "$1"; PASS=$((PASS + 1)); }
|
||||
fail() { printf ' [FAIL] %s\n' "$1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
smb() {
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -c "$1"
|
||||
}
|
||||
md5() { md5sum "$1" | awk '{print $1}'; }
|
||||
|
||||
# 1. POSIX fcntl byte-range locking on the FUSE mount ------------------------
|
||||
# Exercises the mount's SetLk/GetLk via two processes contending over fcntl
|
||||
# (F_SETLK) byte-range locks. python3's fcntl.lockf issues real POSIX locks.
|
||||
echo "==> 1. POSIX fcntl byte-range locking (FUSE mount SetLk/GetLk)"
|
||||
lockfile="${MOUNT_SHARE}/fcntl_lock.dat"
|
||||
: >"${lockfile}"
|
||||
fcntl_out="$(python3 - "${lockfile}" <<'PY'
|
||||
import fcntl, os, sys
|
||||
|
||||
path = sys.argv[1]
|
||||
parent_to_child_r, parent_to_child_w = os.pipe() # release signal
|
||||
child_to_parent_r, child_to_parent_w = os.pipe() # locked signal
|
||||
|
||||
pid = os.fork()
|
||||
if pid == 0: # child: hold an exclusive lock on [0,100)
|
||||
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX, 100, 0, 0)
|
||||
os.write(child_to_parent_w, b"L")
|
||||
os.read(parent_to_child_r, 1) # wait until parent says release
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
os.close(fd)
|
||||
os._exit(0)
|
||||
|
||||
# parent
|
||||
os.read(child_to_parent_r, 1) # wait until child holds the lock
|
||||
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
results = []
|
||||
|
||||
# a. a conflicting exclusive lock must be denied while the child holds it
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 0, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
results.append(("conflicting exclusive lock denied while held", False))
|
||||
except OSError:
|
||||
results.append(("conflicting exclusive lock denied while held", True))
|
||||
|
||||
# b. a non-overlapping range must be grantable
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 200, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 200, 0)
|
||||
results.append(("non-overlapping range lock granted", True))
|
||||
except OSError:
|
||||
results.append(("non-overlapping range lock granted", False))
|
||||
|
||||
# c. after the holder releases, the lock must be acquirable
|
||||
os.write(parent_to_child_w, b"R")
|
||||
os.waitpid(pid, 0)
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 100, 0, 0)
|
||||
fcntl.lockf(fd, fcntl.LOCK_UN, 100, 0, 0)
|
||||
results.append(("lock acquirable after holder releases", True))
|
||||
except OSError:
|
||||
results.append(("lock acquirable after holder releases", False))
|
||||
|
||||
for name, ok in results:
|
||||
print((" [PASS] " if ok else " [FAIL] ") + name)
|
||||
sys.exit(0 if all(ok for _, ok in results) else 1)
|
||||
PY
|
||||
)"
|
||||
echo "${fcntl_out}"
|
||||
PASS=$((PASS + $(grep -c '\[PASS\]' <<<"${fcntl_out}")))
|
||||
FAIL=$((FAIL + $(grep -c '\[FAIL\]' <<<"${fcntl_out}")))
|
||||
|
||||
# 2. Distributed lock blocks a cross-mount writer, then hands it off ----------
|
||||
# mount 2 holds a file open for writing (holding the DLM lock on its path).
|
||||
# An SMB put of the same file goes through mount 1 and must (a) block while
|
||||
# mount 2 holds it and (b) succeed once mount 2 releases, leaving the SMB
|
||||
# writer's payload on disk. smbclient gets a long client timeout (-t) so we are
|
||||
# testing the lock handoff itself, not smbclient's own ~20s default timeout.
|
||||
echo "==> 2. distributed lock: cross-mount write coordination"
|
||||
dlmfile="dlm_coord.bin"
|
||||
newdata="${WORK}/dlm_new.bin"
|
||||
head -c 4096 /dev/urandom >"${newdata}"
|
||||
|
||||
# Hold the file open for writing on mount 2 via fd 9 -> holds the DLM lock.
|
||||
exec 9>"${MOUNT2_SHARE}/${dlmfile}"
|
||||
printf 'held-by-mount2' >&9
|
||||
|
||||
# Start the SMB write; record its real exit code when it returns. The subshell
|
||||
# must NOT inherit fd 9 (9>&-): otherwise the SMB writer keeps the file open and
|
||||
# waits on a DLM lock held by its own inherited descriptor, deadlocking the
|
||||
# handoff this test is meant to exercise.
|
||||
rm -f "${WORK}/dlm_put.rc"
|
||||
(
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -t 120 \
|
||||
-c "put ${newdata} ${dlmfile}" >/dev/null 2>&1
|
||||
echo "$?" >"${WORK}/dlm_put.rc"
|
||||
) 9>&- &
|
||||
smb_bg=$!
|
||||
|
||||
sleep 4
|
||||
if [[ ! -f "${WORK}/dlm_put.rc" ]]; then
|
||||
pass "SMB write blocks while another mount holds the file open"
|
||||
else
|
||||
fail "SMB write returned early instead of blocking (rc=$(cat "${WORK}/dlm_put.rc"))"
|
||||
fi
|
||||
|
||||
# Release mount 2's DLM lock; the blocked SMB write must now complete.
|
||||
exec 9>&-
|
||||
|
||||
# Wait (bounded) for the SMB put to finish so a stuck handoff fails the test
|
||||
# instead of hanging the suite.
|
||||
put_rc="timeout"
|
||||
for _ in $(seq 1 20); do
|
||||
if [[ -f "${WORK}/dlm_put.rc" ]]; then
|
||||
put_rc="$(cat "${WORK}/dlm_put.rc")"
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
kill "${smb_bg}" 2>/dev/null
|
||||
wait "${smb_bg}" 2>/dev/null
|
||||
|
||||
if [[ "${put_rc}" == "0" ]]; then
|
||||
pass "blocked SMB write succeeds after the other mount releases"
|
||||
else
|
||||
fail "blocked SMB write succeeds after the other mount releases (rc=${put_rc})"
|
||||
fi
|
||||
|
||||
# A correct handoff leaves the SMB writer's payload on disk: mount 1 acquired
|
||||
# the lock and wrote after mount 2 released.
|
||||
got="${WORK}/dlm_got.bin"
|
||||
if smb "get ${dlmfile} ${got}" >/dev/null 2>&1 && [[ "$(md5 "${got}")" == "$(md5 "${newdata}")" ]]; then
|
||||
pass "post-release content is the SMB writer's payload (correct handoff)"
|
||||
else
|
||||
fail "post-release content is the SMB writer's payload (correct handoff)"
|
||||
fi
|
||||
|
||||
# 3. Distributed lock integrity: concurrent writers, same file ---------------
|
||||
# An SMB writer (mount 1) and a direct writer (mount 2) race on one file. DLM
|
||||
# serializes them, so the result must be exactly one of the two payloads.
|
||||
echo "==> 3. distributed lock: concurrent writers produce intact data"
|
||||
racefile="dlm_race.bin"
|
||||
payloadA="${WORK}/dlm_raceA.bin"
|
||||
head -c 1048576 /dev/urandom >"${payloadA}"
|
||||
payloadB="direct-write-from-mount2-payload"
|
||||
(smb "put ${payloadA} ${racefile}" >/dev/null 2>&1) &
|
||||
(printf '%s' "${payloadB}" >"${MOUNT2_SHARE}/${racefile}") &
|
||||
wait
|
||||
racegot="${WORK}/dlm_race_got.bin"
|
||||
if smb "get ${racefile} ${racegot}" >/dev/null 2>&1 &&
|
||||
{ [[ "$(md5 "${racegot}")" == "$(md5 "${payloadA}")" ]] || [[ "$(cat "${racegot}")" == "${payloadB}" ]]; }; then
|
||||
pass "concurrent same-file writers leave one intact payload"
|
||||
else
|
||||
fail "concurrent same-file writers leave one intact payload"
|
||||
fi
|
||||
|
||||
# 4. Concurrent writers to distinct files ------------------------------------
|
||||
echo "==> 4. concurrent writers to distinct files"
|
||||
n=6
|
||||
declare -a srcs=()
|
||||
for i in $(seq 1 "${n}"); do
|
||||
s="${WORK}/cc_${i}.bin"
|
||||
head -c 1048576 /dev/urandom >"${s}"
|
||||
srcs+=("${s}")
|
||||
(smb "put ${s} concurrent_${i}.bin" >/dev/null 2>&1) &
|
||||
done
|
||||
wait
|
||||
all_ok=true
|
||||
for i in $(seq 1 "${n}"); do
|
||||
g="${WORK}/cc_got_${i}.bin"
|
||||
if ! smb "get concurrent_${i}.bin ${g}" >/dev/null 2>&1 ||
|
||||
[[ "$(md5 "${srcs[$((i - 1))]}")" != "$(md5 "${g}")" ]]; then
|
||||
all_ok=false
|
||||
fi
|
||||
done
|
||||
if ${all_ok}; then
|
||||
pass "${n} concurrent distinct-file writes all intact"
|
||||
else
|
||||
fail "${n} concurrent distinct-file writes all intact"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "==> Summary: ${PASS} passed, ${FAIL} failed"
|
||||
[[ "${FAIL}" -eq 0 ]]
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Run the SMB (Samba) integration test against a SeaweedFS FUSE mount.
|
||||
#
|
||||
# Pipeline:
|
||||
# 1. start a self-contained "weed mini" (master + volume + filer in one)
|
||||
# 2. mount the filesystem with "weed mount"
|
||||
# 3. export a subdirectory of the mount over SMB with smbd
|
||||
# 4. drive the share with smbclient (test/samba/smb_tests.sh)
|
||||
#
|
||||
# Everything runs as the current user on unprivileged ports, so no sudo is
|
||||
# required. State lives under a temp work dir and is removed on exit.
|
||||
#
|
||||
# Requirements: weed in $PATH, fusermount3, and Samba's smbd / smbclient /
|
||||
# smbpasswd (Debian/Ubuntu: apt-get install samba smbclient).
|
||||
#
|
||||
# Usage:
|
||||
# test/samba/run.sh
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
WEED_BIN="${WEED_BIN:-weed}"
|
||||
WORK_DIR="${WORK_DIR:-$(mktemp -d /tmp/seaweedfs-samba.XXXXXX)}"
|
||||
MOUNT_DIR="${MOUNT_DIR:-${WORK_DIR}/mnt}"
|
||||
MOUNT2_DIR="${MOUNT2_DIR:-${WORK_DIR}/mnt2}"
|
||||
DATA_DIR="${DATA_DIR:-${WORK_DIR}/data}"
|
||||
LOG_DIR="${LOG_DIR:-${WORK_DIR}/logs}"
|
||||
STATE_DIR="${WORK_DIR}/samba"
|
||||
SHARE_DIR="${MOUNT_DIR}/share"
|
||||
SHARE_DIR2="${MOUNT2_DIR}/share"
|
||||
|
||||
FILER_PORT="${FILER_PORT:-28888}"
|
||||
FILER_ADDR="127.0.0.1:${FILER_PORT}"
|
||||
SMB_PORT="${SMB_PORT:-4450}"
|
||||
SMB_SHARE="seaweedfs"
|
||||
SMB_USER="${SMB_USER:-$(id -un)}"
|
||||
SMB_PASS="${SMB_PASS:-seaweedfs}"
|
||||
|
||||
SMBD_BIN="$(command -v smbd || echo /usr/sbin/smbd)"
|
||||
SMBPASSWD_BIN="$(command -v smbpasswd || echo /usr/bin/smbpasswd)"
|
||||
|
||||
CI_LOG_DIR="/tmp/seaweedfs-samba-logs"
|
||||
|
||||
mini_pid=""
|
||||
mount_pid=""
|
||||
mount2_pid=""
|
||||
smbd_pid=""
|
||||
|
||||
unmount_dir() {
|
||||
local dir="$1"
|
||||
if mountpoint -q "${dir}" 2>/dev/null; then
|
||||
fusermount3 -u "${dir}" 2>/dev/null ||
|
||||
fusermount -u "${dir}" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
set +e
|
||||
if [[ -n "${smbd_pid}" ]] && kill -0 "${smbd_pid}" 2>/dev/null; then
|
||||
kill -TERM "${smbd_pid}" 2>/dev/null || true
|
||||
wait "${smbd_pid}" 2>/dev/null || true
|
||||
fi
|
||||
for p in "${mount_pid}" "${mount2_pid}"; do
|
||||
if [[ -n "${p}" ]] && kill -0 "${p}" 2>/dev/null; then
|
||||
kill -TERM "${p}" 2>/dev/null || true
|
||||
wait "${p}" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
unmount_dir "${MOUNT_DIR}"
|
||||
unmount_dir "${MOUNT2_DIR}"
|
||||
if [[ -n "${mini_pid}" ]] && kill -0 "${mini_pid}" 2>/dev/null; then
|
||||
kill -TERM "${mini_pid}" 2>/dev/null || true
|
||||
wait "${mini_pid}" 2>/dev/null || true
|
||||
fi
|
||||
# Copy logs to a fixed path for CI artifact upload.
|
||||
mkdir -p "${CI_LOG_DIR}"
|
||||
cp "${LOG_DIR}"/*.log "${LOG_DIR}"/*.out "${STATE_DIR}/smbd.log" "${CI_LOG_DIR}/" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
mkdir -p "${MOUNT_DIR}" "${MOUNT2_DIR}" "${DATA_DIR}" "${LOG_DIR}" \
|
||||
"${STATE_DIR}/private" "${STATE_DIR}/state" "${STATE_DIR}/cache" \
|
||||
"${STATE_DIR}/lock" "${STATE_DIR}/pid" "${STATE_DIR}/ncalrpc"
|
||||
|
||||
# --- 1. weed mini -----------------------------------------------------------
|
||||
echo "==> Starting weed mini on ${FILER_ADDR}"
|
||||
"${WEED_BIN}" mini \
|
||||
-dir="${DATA_DIR}" \
|
||||
-ip=127.0.0.1 \
|
||||
-filer.port="${FILER_PORT}" \
|
||||
-s3=false \
|
||||
-webdav=false \
|
||||
-admin.ui=false \
|
||||
>"${LOG_DIR}/mini.log" 2>&1 &
|
||||
mini_pid=$!
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
if (echo >"/dev/tcp/127.0.0.1/${FILER_PORT}") 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
if ! kill -0 "${mini_pid}" 2>/dev/null; then
|
||||
echo "weed mini exited early; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/mini.log" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
if ! (echo >"/dev/tcp/127.0.0.1/${FILER_PORT}") 2>/dev/null; then
|
||||
echo "weed mini filer did not become reachable within 30s; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/mini.log" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- 2. weed mount (two mounts, both with -dlm) -----------------------------
|
||||
# mount_with_dlm <mountpoint> <logfile> <pid-var-name>
|
||||
mount_with_dlm() {
|
||||
local dir="$1" log="$2" pidvar="$3" pid
|
||||
echo "==> Mounting SeaweedFS at ${dir} with -dlm"
|
||||
"${WEED_BIN}" mount \
|
||||
-filer="${FILER_ADDR}" \
|
||||
-dir="${dir}" \
|
||||
-filer.path=/ \
|
||||
-dirAutoCreate \
|
||||
-dlm \
|
||||
>"${log}" 2>&1 &
|
||||
pid=$!
|
||||
printf -v "${pidvar}" '%s' "${pid}"
|
||||
for _ in $(seq 1 60); do
|
||||
if mountpoint -q "${dir}"; then
|
||||
return 0
|
||||
fi
|
||||
if ! kill -0 "${pid}" 2>/dev/null; then
|
||||
echo "weed mount (${dir}) exited early; log tail:" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FUSE mount ${dir} did not come up within 30s" >&2
|
||||
tail -n 100 "${log}" >&2 || true
|
||||
exit 1
|
||||
}
|
||||
|
||||
mount_with_dlm "${MOUNT_DIR}" "${LOG_DIR}/mount.log" mount_pid
|
||||
mount_with_dlm "${MOUNT2_DIR}" "${LOG_DIR}/mount2.log" mount2_pid
|
||||
|
||||
mkdir -p "${SHARE_DIR}"
|
||||
|
||||
# --- 3. smbd ----------------------------------------------------------------
|
||||
echo "==> Generating smb.conf and starting smbd on port ${SMB_PORT}"
|
||||
SMB_CONF="${STATE_DIR}/smb.conf"
|
||||
sed -e "s#@SHARE_PATH@#${SHARE_DIR}#g" \
|
||||
-e "s#@STATE_DIR@#${STATE_DIR}#g" \
|
||||
-e "s#@SMB_PORT@#${SMB_PORT}#g" \
|
||||
-e "s#@FORCE_USER@#${SMB_USER}#g" \
|
||||
"${SCRIPT_DIR}/smb.conf.template" >"${SMB_CONF}"
|
||||
|
||||
printf '%s\n%s\n' "${SMB_PASS}" "${SMB_PASS}" |
|
||||
"${SMBPASSWD_BIN}" -c "${SMB_CONF}" -a -s "${SMB_USER}"
|
||||
|
||||
"${SMBD_BIN}" -F --no-process-group -s "${SMB_CONF}" >"${LOG_DIR}/smbd.out" 2>&1 &
|
||||
smbd_pid=$!
|
||||
|
||||
for i in $(seq 1 60); do
|
||||
if (echo >"/dev/tcp/127.0.0.1/${SMB_PORT}") 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
if ! kill -0 "${smbd_pid}" 2>/dev/null; then
|
||||
echo "smbd exited early; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/smbd.out" "${STATE_DIR}/smbd.log" 2>/dev/null >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
if ! (echo >"/dev/tcp/127.0.0.1/${SMB_PORT}") 2>/dev/null; then
|
||||
echo "smbd did not become reachable within 30s; log tail:" >&2
|
||||
tail -n 100 "${LOG_DIR}/smbd.out" "${STATE_DIR}/smbd.log" 2>/dev/null >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- 4. run the test batteries ---------------------------------------------
|
||||
rc=0
|
||||
|
||||
echo "==> Running SMB functional test battery"
|
||||
SMB_HOST=127.0.0.1 \
|
||||
SMB_SHARE="${SMB_SHARE}" \
|
||||
SMB_PORT="${SMB_PORT}" \
|
||||
SMB_USER="${SMB_USER}" \
|
||||
SMB_PASS="${SMB_PASS}" \
|
||||
SHARE_FS_PATH="${SHARE_DIR}" \
|
||||
"${SCRIPT_DIR}/smb_tests.sh" || rc=1
|
||||
|
||||
echo "==> Running SMB locking / concurrency test battery"
|
||||
SMB_HOST=127.0.0.1 \
|
||||
SMB_SHARE="${SMB_SHARE}" \
|
||||
SMB_PORT="${SMB_PORT}" \
|
||||
SMB_USER="${SMB_USER}" \
|
||||
SMB_PASS="${SMB_PASS}" \
|
||||
MOUNT_SHARE="${SHARE_DIR}" \
|
||||
MOUNT2_SHARE="${SHARE_DIR2}" \
|
||||
"${SCRIPT_DIR}/lock_tests.sh" || rc=1
|
||||
|
||||
exit "${rc}"
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Runs the SMB test batteries inside the samba container against the local smbd,
|
||||
# which serves /mnt/seaweedfs/share over a SeaweedFS FUSE mount. A second FUSE
|
||||
# mount (/mnt/seaweedfs2) backs the distributed-locking tests.
|
||||
# Invoked via: docker compose exec samba /run_inside_container.sh
|
||||
set -euo pipefail
|
||||
|
||||
export SMB_HOST=127.0.0.1
|
||||
export SMB_SHARE=seaweedfs
|
||||
export SMB_PORT="${SMB_PORT:-445}"
|
||||
export SMB_USER="${SMB_USER:-smbtest}"
|
||||
export SMB_PASS="${SMB_PASS:-smbtest}"
|
||||
export SHARE_FS_PATH="${SHARE_FS_PATH:-/mnt/seaweedfs/share}"
|
||||
export MOUNT_SHARE="${MOUNT_SHARE:-/mnt/seaweedfs/share}"
|
||||
export MOUNT2_SHARE="${MOUNT2_SHARE:-/mnt/seaweedfs2/share}"
|
||||
|
||||
rc=0
|
||||
echo "############ SMB functional tests ############"
|
||||
/smb_tests.sh || rc=1
|
||||
echo
|
||||
echo "############ SMB locking / concurrency tests ############"
|
||||
/lock_tests.sh || rc=1
|
||||
exit "${rc}"
|
||||
@@ -0,0 +1,52 @@
|
||||
[global]
|
||||
server role = standalone server
|
||||
workgroup = WORKGROUP
|
||||
server string = SeaweedFS FUSE Samba test
|
||||
security = user
|
||||
server min protocol = SMB2
|
||||
smb ports = @SMB_PORT@
|
||||
bind interfaces only = yes
|
||||
interfaces = lo 127.0.0.1
|
||||
|
||||
# Self-contained state so smbd can run rootless and leaves nothing behind
|
||||
# outside the test work directory.
|
||||
private dir = @STATE_DIR@/private
|
||||
state directory = @STATE_DIR@/state
|
||||
cache directory = @STATE_DIR@/cache
|
||||
lock directory = @STATE_DIR@/lock
|
||||
pid directory = @STATE_DIR@/pid
|
||||
ncalrpc dir = @STATE_DIR@/ncalrpc
|
||||
log file = @STATE_DIR@/smbd.log
|
||||
log level = 1
|
||||
usershare max shares = 0
|
||||
|
||||
# No printing subsystem in a file-server test.
|
||||
load printers = no
|
||||
printing = bsd
|
||||
printcap name = /dev/null
|
||||
disable spoolss = yes
|
||||
|
||||
# The SeaweedFS FUSE mount does not implement the full xattr / DOS-attribute
|
||||
# surface Samba uses by default. Disabling these avoids spurious
|
||||
# NT_STATUS_NOT_SUPPORTED / EOPNOTSUPP errors unrelated to data integrity.
|
||||
ea support = no
|
||||
store dos attributes = no
|
||||
map archive = no
|
||||
map hidden = no
|
||||
map system = no
|
||||
map readonly = no
|
||||
|
||||
# A network-filesystem backend should not advertise local oplocks/leases.
|
||||
oplocks = no
|
||||
level2 oplocks = no
|
||||
kernel oplocks = no
|
||||
posix locking = no
|
||||
|
||||
[seaweedfs]
|
||||
path = @SHARE_PATH@
|
||||
comment = SeaweedFS share backed by a FUSE mount
|
||||
browseable = yes
|
||||
read only = no
|
||||
create mask = 0644
|
||||
directory mask = 0755
|
||||
force user = @FORCE_USER@
|
||||
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# SMB protocol test battery against a Samba share backed by a SeaweedFS FUSE
|
||||
# mount. Driven both by the local runner (test/samba/run.sh) and by the Docker
|
||||
# harness (run_inside_container.sh).
|
||||
#
|
||||
# Required env:
|
||||
# SMB_USER samba username
|
||||
# SMB_PASS samba password
|
||||
# Optional env:
|
||||
# SMB_HOST samba host (default 127.0.0.1)
|
||||
# SMB_SHARE share name (default seaweedfs)
|
||||
# SMB_PORT smbd port (default 445)
|
||||
# SHARE_FS_PATH directory on the FUSE mount that backs the share. When set,
|
||||
# the suite also checks cross-protocol consistency: data written
|
||||
# over SMB is visible on the FUSE mount, and vice versa.
|
||||
set -uo pipefail
|
||||
|
||||
SMB_HOST="${SMB_HOST:-127.0.0.1}"
|
||||
SMB_SHARE="${SMB_SHARE:-seaweedfs}"
|
||||
SMB_PORT="${SMB_PORT:-445}"
|
||||
SMB_USER="${SMB_USER:?SMB_USER is required}"
|
||||
SMB_PASS="${SMB_PASS:?SMB_PASS is required}"
|
||||
SHARE_FS_PATH="${SHARE_FS_PATH:-}"
|
||||
|
||||
WORK="$(mktemp -d /tmp/samba-smbtest.XXXXXX)"
|
||||
trap 'rm -rf "${WORK}"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
pass() { printf ' [PASS] %s\n' "$1"; PASS=$((PASS + 1)); }
|
||||
fail() { printf ' [FAIL] %s\n' "$1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
# Run one or more smbclient commands (separated by ';') against the share.
|
||||
smb() {
|
||||
smbclient "//${SMB_HOST}/${SMB_SHARE}" -p "${SMB_PORT}" \
|
||||
-U "${SMB_USER}%${SMB_PASS}" -m SMB3 -c "$1"
|
||||
}
|
||||
|
||||
md5() { md5sum "$1" | awk '{print $1}'; }
|
||||
|
||||
echo "==> Target //${SMB_HOST}/${SMB_SHARE} (port ${SMB_PORT}) as ${SMB_USER}"
|
||||
[[ -n "${SHARE_FS_PATH}" ]] && echo "==> Cross-protocol checks against ${SHARE_FS_PATH}"
|
||||
|
||||
# 1. Connectivity ------------------------------------------------------------
|
||||
echo "==> 1. connectivity"
|
||||
if smb "ls" >/dev/null 2>&1; then
|
||||
pass "connect and list share root"
|
||||
else
|
||||
fail "connect and list share root"
|
||||
fi
|
||||
|
||||
# 2. Upload / download round-trip -------------------------------------------
|
||||
echo "==> 2. upload / download round-trip"
|
||||
src="${WORK}/src.bin"
|
||||
head -c 1048576 /dev/urandom >"${src}" # 1 MiB
|
||||
if smb "put ${src} roundtrip.bin" >/dev/null 2>&1; then
|
||||
pass "put 1 MiB file"
|
||||
else
|
||||
fail "put 1 MiB file"
|
||||
fi
|
||||
got="${WORK}/got.bin"
|
||||
if smb "get roundtrip.bin ${got}" >/dev/null 2>&1 && [[ "$(md5 "${src}")" == "$(md5 "${got}")" ]]; then
|
||||
pass "get returns identical content"
|
||||
else
|
||||
fail "get returns identical content"
|
||||
fi
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ -f "${SHARE_FS_PATH}/roundtrip.bin" ]] && [[ "$(md5 "${SHARE_FS_PATH}/roundtrip.bin")" == "$(md5 "${src}")" ]]; then
|
||||
pass "SMB-written file visible on FUSE mount with identical content"
|
||||
else
|
||||
fail "SMB-written file visible on FUSE mount with identical content"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Directory operations ----------------------------------------------------
|
||||
echo "==> 3. directory operations"
|
||||
if smb "mkdir docs; cd docs; put ${src} nested.bin; ls" >/dev/null 2>&1; then
|
||||
pass "mkdir + put into subdirectory"
|
||||
else
|
||||
fail "mkdir + put into subdirectory"
|
||||
fi
|
||||
if [[ -z "${SHARE_FS_PATH}" || -f "${SHARE_FS_PATH}/docs/nested.bin" ]]; then
|
||||
pass "nested file present"
|
||||
else
|
||||
fail "nested file present"
|
||||
fi
|
||||
|
||||
# 4. Rename ------------------------------------------------------------------
|
||||
echo "==> 4. rename"
|
||||
if smb "rename roundtrip.bin renamed.bin" >/dev/null 2>&1; then
|
||||
pass "rename file"
|
||||
else
|
||||
fail "rename file"
|
||||
fi
|
||||
renback="${WORK}/renamed.bin"
|
||||
if smb "get renamed.bin ${renback}" >/dev/null 2>&1 && [[ "$(md5 "${renback}")" == "$(md5 "${src}")" ]]; then
|
||||
pass "renamed file readable with original content"
|
||||
else
|
||||
fail "renamed file readable with original content"
|
||||
fi
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ -f "${SHARE_FS_PATH}/renamed.bin" && ! -e "${SHARE_FS_PATH}/roundtrip.bin" ]]; then
|
||||
pass "rename reflected on FUSE mount"
|
||||
else
|
||||
fail "rename reflected on FUSE mount"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 5. Large file (exercises SeaweedFS chunking) -------------------------------
|
||||
echo "==> 5. large file (SeaweedFS chunking)"
|
||||
big="${WORK}/big.bin"
|
||||
head -c 67108864 /dev/urandom >"${big}" # 64 MiB
|
||||
bigback="${WORK}/big.back"
|
||||
if smb "put ${big} big.bin" >/dev/null 2>&1 &&
|
||||
smb "get big.bin ${bigback}" >/dev/null 2>&1 &&
|
||||
[[ "$(md5 "${big}")" == "$(md5 "${bigback}")" ]]; then
|
||||
pass "64 MiB put/get round-trip"
|
||||
else
|
||||
fail "64 MiB put/get round-trip"
|
||||
fi
|
||||
|
||||
# 6. Recursive upload --------------------------------------------------------
|
||||
echo "==> 6. recursive upload"
|
||||
tree="${WORK}/tree"
|
||||
mkdir -p "${tree}/a/b"
|
||||
echo one >"${tree}/f1.txt"
|
||||
echo two >"${tree}/a/f2.txt"
|
||||
echo three >"${tree}/a/b/f3.txt"
|
||||
if (cd "${WORK}" && smb "recurse ON; prompt OFF; mput tree" >/dev/null 2>&1) &&
|
||||
{ [[ -z "${SHARE_FS_PATH}" ]] || [[ -f "${SHARE_FS_PATH}/tree/a/b/f3.txt" ]]; }; then
|
||||
pass "recursive mput"
|
||||
else
|
||||
fail "recursive mput"
|
||||
fi
|
||||
|
||||
# 7. Cross-protocol read (FUSE writes, SMB reads) ----------------------------
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
echo "==> 7. cross-protocol read (FUSE write -> SMB read)"
|
||||
echo "written-via-fuse" >"${SHARE_FS_PATH}/from_fuse.txt"
|
||||
cpb="${WORK}/from_fuse.back"
|
||||
if smb "get from_fuse.txt ${cpb}" >/dev/null 2>&1 && grep -q written-via-fuse "${cpb}"; then
|
||||
pass "FUSE-written file readable over SMB"
|
||||
else
|
||||
fail "FUSE-written file readable over SMB"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 8. Delete ------------------------------------------------------------------
|
||||
echo "==> 8. delete"
|
||||
smb "del renamed.bin" >/dev/null 2>&1
|
||||
smb "del big.bin" >/dev/null 2>&1
|
||||
smb "deltree docs" >/dev/null 2>&1
|
||||
smb "deltree tree" >/dev/null 2>&1
|
||||
if [[ -n "${SHARE_FS_PATH}" ]]; then
|
||||
if [[ ! -e "${SHARE_FS_PATH}/renamed.bin" && ! -e "${SHARE_FS_PATH}/big.bin" &&
|
||||
! -e "${SHARE_FS_PATH}/docs" && ! -e "${SHARE_FS_PATH}/tree" ]]; then
|
||||
pass "delete files and directory trees"
|
||||
else
|
||||
fail "delete files and directory trees"
|
||||
fi
|
||||
else
|
||||
if ! smb "get renamed.bin /dev/null" >/dev/null 2>&1; then
|
||||
pass "deleted file no longer retrievable"
|
||||
else
|
||||
fail "deleted file no longer retrievable"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "==> Summary: ${PASS} passed, ${FAIL} failed"
|
||||
[[ "${FAIL}" -eq 0 ]]
|
||||
+12
-5
@@ -51,6 +51,13 @@ func MustAllocatePorts(t *testing.T, count int) []int {
|
||||
// from recycling ports between allocations. Use this when ports will be
|
||||
// passed to weed mini without explicit gRPC port flags, so mini will
|
||||
// derive gRPC ports as HTTP + 10000.
|
||||
//
|
||||
// Listeners are bound on all interfaces (":port") rather than 127.0.0.1
|
||||
// to match weed mini's availability check (isPortAvailable). A port can
|
||||
// be free on loopback but held by another process on a different
|
||||
// interface; reserving only on loopback lets mini's check fail and
|
||||
// trigger gRPC port shifting, which then causes weed shell to dial the
|
||||
// wrong port and hang.
|
||||
func AllocateMiniPorts(count int) ([]int, error) {
|
||||
const (
|
||||
minPort = 10000
|
||||
@@ -75,12 +82,12 @@ func AllocateMiniPorts(count int) ([]int, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
l1, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
l1, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
l2, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", grpcPort))
|
||||
l2, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
|
||||
if err != nil {
|
||||
l1.Close()
|
||||
continue
|
||||
@@ -145,11 +152,11 @@ func AllocatePortSet(miniCount, regularCount int) (mini []int, regular []int, er
|
||||
if reserved[port] || reserved[grpcPort] {
|
||||
continue
|
||||
}
|
||||
l1, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
l1, lErr := net.Listen("tcp", fmt.Sprintf(":%d", port))
|
||||
if lErr != nil {
|
||||
continue
|
||||
}
|
||||
l2, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", grpcPort))
|
||||
l2, lErr := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
|
||||
if lErr != nil {
|
||||
l1.Close()
|
||||
continue
|
||||
@@ -168,7 +175,7 @@ func AllocatePortSet(miniCount, regularCount int) (mini []int, regular []int, er
|
||||
|
||||
regular = make([]int, 0, regularCount)
|
||||
for i := 0; i < regularCount; i++ {
|
||||
l, lErr := net.Listen("tcp", "127.0.0.1:0")
|
||||
l, lErr := net.Listen("tcp", ":0")
|
||||
if lErr != nil {
|
||||
return nil, nil, lErr
|
||||
}
|
||||
|
||||
@@ -136,8 +136,6 @@ func TestEcLifecycleAcrossMultipleDisks(t *testing.T) {
|
||||
conn2, grpcClient2 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn2.Close()
|
||||
|
||||
// VolumeEcShardsInfo only sees one disk's EcVolume; filesystem layout is
|
||||
// the ground truth for the whole-store shard count.
|
||||
postReconcileLayout := scanShardLayout(t, dataDirs, collection, volumeID)
|
||||
if got, want := totalShardsInLayout(postReconcileLayout), erasure_coding.TotalShardsCount; got != want {
|
||||
t.Fatalf("post-reconcile: total shards on disk mismatch: got %d, want %d (layout=%v)", got, want, postReconcileLayout)
|
||||
@@ -148,11 +146,28 @@ func TestEcLifecycleAcrossMultipleDisks(t *testing.T) {
|
||||
if got, want := len(postReconcileLayout[1]), splitAt; got != want {
|
||||
t.Fatalf("post-reconcile: disk 1 shard count drift: got %d, want %d (layout=%v)", got, want, postReconcileLayout)
|
||||
}
|
||||
if _, err := grpcClient2.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
// VolumeEcShardsInfo must walk every DiskLocation and report the full
|
||||
// shard set — the verification step in ec_task.go gates source-volume
|
||||
// deletion on this RPC returning a complete shard inventory.
|
||||
infoResp, err := grpcClient2.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
VolumeId: volumeID,
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardsInfo after redistribute restart: %v", err)
|
||||
}
|
||||
if got, want := len(infoResp.GetEcShardInfos()), erasure_coding.TotalShardsCount; got != want {
|
||||
t.Fatalf("VolumeEcShardsInfo after redistribute restart: got %d shards, want %d (per-disk layout=%v)",
|
||||
got, want, postReconcileLayout)
|
||||
}
|
||||
gotShardIds := make(map[uint32]struct{}, len(infoResp.GetEcShardInfos()))
|
||||
for _, info := range infoResp.GetEcShardInfos() {
|
||||
gotShardIds[info.GetShardId()] = struct{}{}
|
||||
}
|
||||
for shardId := uint32(0); shardId < uint32(erasure_coding.TotalShardsCount); shardId++ {
|
||||
if _, ok := gotShardIds[shardId]; !ok {
|
||||
t.Fatalf("VolumeEcShardsInfo missing shard %d (per-disk layout=%v)", shardId, postReconcileLayout)
|
||||
}
|
||||
}
|
||||
for _, n := range needles {
|
||||
verifyHTTPRead(t, httpClient, clusterHarness.VolumeAdminURL(), n.fid, n.payload, "after-cross-disk-reconcile")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package volume_server_grpc_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
||||
"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"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// TestVolumeEcShardsInfoReturnsAllShardsAcrossDisks drives the full path
|
||||
// behind the ec.encode source-deletion gate. A multi-disk volume server
|
||||
// ends up with EC shards split across disks (each registers its own
|
||||
// EcVolume entry in DiskLocation.ecVolumes), and the volume server's
|
||||
// VolumeEcShardsInfo RPC must walk every DiskLocation rather than
|
||||
// reporting whichever disk Store.FindEcVolume picks first.
|
||||
//
|
||||
// Pre-fix, verifyEcShardsBeforeDelete refused to delete source volumes —
|
||||
// the shard-bitmap union across destinations fell short of dataShards +
|
||||
// parityShards because each destination only reported shards on one of
|
||||
// its disks. With the handler fix, the same VerifyShardsAcrossServers
|
||||
// call returns a complete bitmap and the gate opens.
|
||||
func TestVolumeEcShardsInfoReturnsAllShardsAcrossDisks(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
const (
|
||||
dataDirCount = 2
|
||||
volumeID = uint32(9558)
|
||||
collection = "ec-multi-disk-verify"
|
||||
)
|
||||
|
||||
clusterHarness := framework.StartSingleVolumeClusterWithDataDirs(t, matrix.P1(), dataDirCount)
|
||||
dataDirs := clusterHarness.VolumeDataDirs()
|
||||
if len(dataDirs) != dataDirCount {
|
||||
t.Fatalf("expected %d data dirs, got %d: %v", dataDirCount, len(dataDirs), dataDirs)
|
||||
}
|
||||
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
framework.AllocateVolume(t, grpcClient, volumeID, collection)
|
||||
|
||||
httpClient := framework.NewHTTPClient()
|
||||
needles := []struct {
|
||||
fid string
|
||||
payload []byte
|
||||
}{
|
||||
{framework.NewFileID(volumeID, 9559, 0xC0FFEE01), bytesOfLen(64, 0xB1)},
|
||||
{framework.NewFileID(volumeID, 9560, 0xC0FFEE02), bytesOfLen(8192, 0xB2)},
|
||||
{framework.NewFileID(volumeID, 9561, 0xC0FFEE03), bytesOfLen(131072, 0xB3)},
|
||||
}
|
||||
for _, n := range needles {
|
||||
resp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), n.fid, n.payload)
|
||||
_ = framework.ReadAllAndClose(t, resp)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("upload %s expected 201, got %d", n.fid, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: collection,
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsGenerate: %v", err)
|
||||
}
|
||||
|
||||
// Generate places every shard plus the .ecx/.ecj/.vif on the .dat's
|
||||
// disk (disk 0). Mount all 14 there first so the next step's restart
|
||||
// has a steady starting state.
|
||||
allShards := make([]uint32, erasure_coding.TotalShardsCount)
|
||||
for i := range allShards {
|
||||
allShards[i] = uint32(i)
|
||||
}
|
||||
if _, err := grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: collection,
|
||||
ShardIds: allShards,
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsMount all shards: %v", err)
|
||||
}
|
||||
|
||||
// Drop the .dat so the EC shards are the only data path — mirrors the
|
||||
// real ec.encode flow before verifyEcShardsBeforeDelete fires.
|
||||
if _, err := grpcClient.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
|
||||
VolumeId: volumeID,
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeDelete (drop .dat): %v", err)
|
||||
}
|
||||
|
||||
// Move half the shards onto disk 1, leaving .ecx on disk 0. After
|
||||
// restart, the cross-disk reconcile path attaches each disk's shards
|
||||
// against its own EcVolume entry — the exact in-memory shape the bug
|
||||
// reporter saw on a multi-disk destination.
|
||||
clusterHarness.StopVolumeServer()
|
||||
const splitAt = 7
|
||||
for shard := 0; shard < splitAt; shard++ {
|
||||
movedFile(t, dataDirs[0], dataDirs[1], collection, volumeID, erasure_coding.ToExt(shard))
|
||||
}
|
||||
if fileExistsIn(dataDirs[1], collection, volumeID, ".ecx") {
|
||||
t.Fatalf("setup: .ecx must stay on disk 0 to exercise the multi-disk path")
|
||||
}
|
||||
|
||||
clusterHarness.RestartVolumeServer()
|
||||
conn2, grpcClient2 := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn2.Close()
|
||||
|
||||
postReconcileLayout := scanShardLayout(t, dataDirs, collection, volumeID)
|
||||
if got, want := totalShardsInLayout(postReconcileLayout), erasure_coding.TotalShardsCount; got != want {
|
||||
t.Fatalf("post-reconcile: total shards on disk mismatch: got %d, want %d (layout=%v)", got, want, postReconcileLayout)
|
||||
}
|
||||
if len(postReconcileLayout[0]) == 0 || len(postReconcileLayout[1]) == 0 {
|
||||
t.Fatalf("post-reconcile: expected shards on BOTH disks, got per-disk layout %v", postReconcileLayout)
|
||||
}
|
||||
|
||||
// Direct RPC assertion: VolumeEcShardsInfo must report every shard
|
||||
// the server holds, not just the ones registered against the first
|
||||
// matching DiskLocation.
|
||||
infoResp, err := grpcClient2.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
VolumeId: volumeID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardsInfo: %v", err)
|
||||
}
|
||||
gotShardIds := make([]int, 0, len(infoResp.GetEcShardInfos()))
|
||||
for _, info := range infoResp.GetEcShardInfos() {
|
||||
if info.GetVolumeId() != volumeID {
|
||||
t.Errorf("EcShardInfo VolumeId=%d, want %d", info.GetVolumeId(), volumeID)
|
||||
}
|
||||
gotShardIds = append(gotShardIds, int(info.GetShardId()))
|
||||
}
|
||||
sort.Ints(gotShardIds)
|
||||
wantShardIds := make([]int, erasure_coding.TotalShardsCount)
|
||||
for i := range wantShardIds {
|
||||
wantShardIds[i] = i
|
||||
}
|
||||
if len(gotShardIds) != len(wantShardIds) {
|
||||
t.Fatalf("VolumeEcShardsInfo returned %d shards (ids=%v), want %d (ids=%v) — per-disk layout=%v",
|
||||
len(gotShardIds), gotShardIds, len(wantShardIds), wantShardIds, postReconcileLayout)
|
||||
}
|
||||
for i, sid := range wantShardIds {
|
||||
if gotShardIds[i] != sid {
|
||||
t.Fatalf("VolumeEcShardsInfo shard ids=%v, want %v (per-disk layout=%v)",
|
||||
gotShardIds, wantShardIds, postReconcileLayout)
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
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 {
|
||||
t.Fatalf("verifyEcShardsBeforeDelete-equivalent gate failed: %v\nper-server inventory: %s\nper-disk layout: %v",
|
||||
err, 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)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package volume_server_http_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -44,6 +46,17 @@ func TestReplicatedUploadSucceedsImmediatelyAfterAllocate(t *testing.T) {
|
||||
fid := framework.NewFileID(volumeID, 881001, 0x0B0C0D0E)
|
||||
payload := []byte("replicated-upload-after-allocate")
|
||||
|
||||
// The master only learns about replica locations through volume-server
|
||||
// heartbeats, which lag behind the direct AllocateVolume gRPC calls above.
|
||||
// In production a client obtains its fid from the master assign flow, which
|
||||
// guarantees the master already knows every replica; this test crafts the
|
||||
// fid by hand, so the replicated write would otherwise look up the master
|
||||
// before the second replica is registered and fail with a 500. Wait until
|
||||
// the master reports both replicas before uploading.
|
||||
if !waitForMasterReplicaCount(t, client, clusterHarness.MasterURL(), volumeID, 2, 10*time.Second) {
|
||||
t.Fatalf("master did not report 2 replica locations for volume %d within deadline", volumeID)
|
||||
}
|
||||
|
||||
uploadResp := framework.UploadBytes(t, client, clusterHarness.VolumeAdminURL(0), fid, payload)
|
||||
_ = framework.ReadAllAndClose(t, uploadResp)
|
||||
if uploadResp.StatusCode != http.StatusCreated {
|
||||
@@ -61,3 +74,29 @@ func TestReplicatedUploadSucceedsImmediatelyAfterAllocate(t *testing.T) {
|
||||
t.Fatalf("replica body mismatch: got %q want %q", string(replicaBody), string(payload))
|
||||
}
|
||||
}
|
||||
|
||||
// waitForMasterReplicaCount polls the master volume lookup until it reports at
|
||||
// least want locations for volumeID, or the timeout elapses.
|
||||
func waitForMasterReplicaCount(t testing.TB, client *http.Client, masterURL string, volumeID uint32, want int, timeout time.Duration) bool {
|
||||
t.Helper()
|
||||
|
||||
lookupURL := fmt.Sprintf("%s/dir/lookup?volumeId=%d", masterURL, volumeID)
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp := framework.DoRequest(t, client, mustNewRequest(t, http.MethodGet, lookupURL))
|
||||
body := framework.ReadAllAndClose(t, resp)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var result struct {
|
||||
Locations []struct {
|
||||
Url string `json:"url"`
|
||||
} `json:"locations"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err == nil && len(result.Locations) >= want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// WithMasterClient executes a function with a master client connection
|
||||
@@ -38,6 +40,21 @@ func (s *AdminServer) WithVolumeServerClient(address pb.ServerAddress, f func(cl
|
||||
})
|
||||
}
|
||||
|
||||
// GetMasterClient returns the admin server's wdclient.MasterClient. It is used
|
||||
// by file browser download paths that stream chunks straight from the volume
|
||||
// servers via filer.PrepareStreamContent so they keep working when the filer
|
||||
// has -disableHttp=true.
|
||||
func (s *AdminServer) GetMasterClient() *wdclient.MasterClient {
|
||||
return s.masterClient
|
||||
}
|
||||
|
||||
// GetGrpcDialOption returns the dial option used for all admin-originated
|
||||
// gRPC connections (TLS or insecure). File browser uploads need this when
|
||||
// they perform the assign + volume HTTP POST + create-entry flow.
|
||||
func (s *AdminServer) GetGrpcDialOption() grpc.DialOption {
|
||||
return s.grpcDialOption
|
||||
}
|
||||
|
||||
// GetFilerAddress returns a filer address, discovering from masters if needed
|
||||
func (s *AdminServer) GetFilerAddress() string {
|
||||
// Discover filers from masters
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
@@ -735,8 +734,8 @@ func (s *AdminServer) parseOrBuildClusterContext(raw json.RawMessage) (*plugin_p
|
||||
if len(contextMessage.MasterGrpcAddresses) == 0 {
|
||||
contextMessage.MasterGrpcAddresses = append(contextMessage.MasterGrpcAddresses, fallback.MasterGrpcAddresses...)
|
||||
}
|
||||
if len(contextMessage.FilerGrpcAddresses) == 0 {
|
||||
contextMessage.FilerGrpcAddresses = append(contextMessage.FilerGrpcAddresses, fallback.FilerGrpcAddresses...)
|
||||
if len(contextMessage.FilerAddresses) == 0 {
|
||||
contextMessage.FilerAddresses = append(contextMessage.FilerAddresses, fallback.FilerAddresses...)
|
||||
}
|
||||
if len(contextMessage.VolumeGrpcAddresses) == 0 {
|
||||
contextMessage.VolumeGrpcAddresses = append(contextMessage.VolumeGrpcAddresses, fallback.VolumeGrpcAddresses...)
|
||||
@@ -755,7 +754,7 @@ func (s *AdminServer) parseOrBuildClusterContext(raw json.RawMessage) (*plugin_p
|
||||
func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterContext {
|
||||
clusterContext := &plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: make([]string, 0),
|
||||
FilerGrpcAddresses: make([]string, 0),
|
||||
FilerAddresses: make([]string, 0),
|
||||
VolumeGrpcAddresses: make([]string, 0),
|
||||
S3GrpcAddresses: make([]string, 0),
|
||||
Metadata: map[string]string{
|
||||
@@ -768,20 +767,20 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
clusterContext.MasterGrpcAddresses = append(clusterContext.MasterGrpcAddresses, masterAddress)
|
||||
}
|
||||
|
||||
// Master returns filers in dual-port form (host:httpPort.grpcPort);
|
||||
// workers dial these directly, so collapse to host:grpcPort first.
|
||||
// Master returns filers in pb.ServerAddress form (host:httpPort.grpcPort).
|
||||
// Forward that verbatim; each worker converts to a gRPC or HTTP address as
|
||||
// it needs (dialing wants gRPC, the admin shell wants the ServerAddress).
|
||||
filerSeen := map[string]struct{}{}
|
||||
for _, filer := range s.GetAllFilers() {
|
||||
filer = strings.TrimSpace(filer)
|
||||
if filer == "" {
|
||||
continue
|
||||
}
|
||||
grpcAddr := pb.ServerAddress(filer).ToGrpcAddress()
|
||||
if _, exists := filerSeen[grpcAddr]; exists {
|
||||
if _, exists := filerSeen[filer]; exists {
|
||||
continue
|
||||
}
|
||||
filerSeen[grpcAddr] = struct{}{}
|
||||
clusterContext.FilerGrpcAddresses = append(clusterContext.FilerGrpcAddresses, grpcAddr)
|
||||
filerSeen[filer] = struct{}{}
|
||||
clusterContext.FilerAddresses = append(clusterContext.FilerAddresses, filer)
|
||||
}
|
||||
|
||||
volumeSeen := map[string]struct{}{}
|
||||
@@ -829,7 +828,7 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
}
|
||||
|
||||
sort.Strings(clusterContext.MasterGrpcAddresses)
|
||||
sort.Strings(clusterContext.FilerGrpcAddresses)
|
||||
sort.Strings(clusterContext.FilerAddresses)
|
||||
sort.Strings(clusterContext.VolumeGrpcAddresses)
|
||||
sort.Strings(clusterContext.S3GrpcAddresses)
|
||||
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Admin file browser upload chunk sizing — kept in sync with the values
|
||||
// s3api uses so files end up split into the same fid-sized pieces the rest of
|
||||
// the cluster expects.
|
||||
const (
|
||||
adminUploadChunkSize = 8 * 1024 * 1024
|
||||
adminUploadSmallFileLimit = 256 * 1024
|
||||
)
|
||||
|
||||
// File browser handlers backed by the filer gRPC service. They bypass the
|
||||
// filer's HTTP listener so the UI keeps working when the filer is started
|
||||
// with -disableHttp=true; chunk bytes still flow through the volume server
|
||||
// HTTP endpoints (which run on their own ports).
|
||||
|
||||
// fetchFileContentGrpc reads file content via the filer gRPC service, looking
|
||||
// the entry up and then streaming the chunks straight from the volume servers.
|
||||
// When maxBytes > 0 the stream is truncated to that many bytes — used by the
|
||||
// "is this text?" sniff so unknown-MIME files don't get fully downloaded.
|
||||
func (h *FileBrowserHandlers) fetchFileContentGrpc(ctx context.Context, filePath string, maxBytes int) (string, error) {
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
entry, err := h.lookupEntry(ctx, cleanFilePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if entry.IsDirectory {
|
||||
return "", fmt.Errorf("path is a directory")
|
||||
}
|
||||
|
||||
size := int64(filer.FileSize(entry))
|
||||
streamSize := size
|
||||
if maxBytes > 0 && streamSize > int64(maxBytes) {
|
||||
streamSize = int64(maxBytes)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := h.streamEntryContent(ctx, entry, streamSize, &buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// downloadFileGrpc streams a file via gRPC + volume server HTTP. The
|
||||
// response writer receives the canonical attachment headers and the raw
|
||||
// bytes; this replaces the HTTP-to-filer proxy that used to run in
|
||||
// DownloadFile.
|
||||
func (h *FileBrowserHandlers) downloadFileGrpc(ctx context.Context, filePath string, w http.ResponseWriter) error {
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
entry, err := h.lookupEntry(ctx, cleanFilePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDirectory {
|
||||
return fmt.Errorf("path is a directory")
|
||||
}
|
||||
|
||||
size := int64(filer.FileSize(entry))
|
||||
|
||||
fileName := path.Base(cleanFilePath)
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": fileName}))
|
||||
|
||||
contentType := ""
|
||||
if entry.Attributes != nil {
|
||||
contentType = entry.Attributes.Mime
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
return h.streamEntryContent(ctx, entry, size, w)
|
||||
}
|
||||
|
||||
// uploadFileGrpc streams the upload to volume servers in 8 MiB chunks via the
|
||||
// shared chunked-upload helper, then registers the assembled entry through the
|
||||
// filer gRPC service. Bytes never enter the admin process's heap as a whole —
|
||||
// each chunk is sized to adminUploadChunkSize. Small files (< 256 KiB) are
|
||||
// stored inline on the entry, matching the S3 server's behaviour.
|
||||
func (h *FileBrowserHandlers) uploadFileGrpc(ctx context.Context, filePath string, fileName string, mimeType string, reader io.Reader) error {
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir := path.Dir(cleanFilePath)
|
||||
if dir == "." {
|
||||
dir = "/"
|
||||
}
|
||||
entryName := path.Base(cleanFilePath)
|
||||
if mimeType == "" {
|
||||
mimeType = "application/octet-stream"
|
||||
}
|
||||
|
||||
assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*operation.VolumeAssignRequest, *operation.AssignResult, error) {
|
||||
var assignResp *filer_pb.AssignVolumeResponse
|
||||
err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, assignErr := client.AssignVolume(ctx, &filer_pb.AssignVolumeRequest{
|
||||
Count: int32(count),
|
||||
Path: cleanFilePath,
|
||||
ExpectedDataSize: expectedDataSize,
|
||||
})
|
||||
if assignErr != nil {
|
||||
return assignErr
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return fmt.Errorf("%s", resp.Error)
|
||||
}
|
||||
assignResp = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if assignResp.Location == nil || assignResp.FileId == "" {
|
||||
return nil, nil, fmt.Errorf("assign volume returned empty location")
|
||||
}
|
||||
return nil, &operation.AssignResult{
|
||||
Fid: assignResp.FileId,
|
||||
Url: assignResp.Location.Url,
|
||||
PublicUrl: assignResp.Location.PublicUrl,
|
||||
Count: uint64(count),
|
||||
Auth: security.EncodedJwt(assignResp.Auth),
|
||||
}, nil
|
||||
}
|
||||
|
||||
chunkResult, err := operation.UploadReaderInChunks(ctx, reader, &operation.ChunkedUploadOption{
|
||||
ChunkSize: adminUploadChunkSize,
|
||||
SmallFileLimit: adminUploadSmallFileLimit,
|
||||
SaveSmallInline: true,
|
||||
MimeType: mimeType,
|
||||
AssignFunc: assignFunc,
|
||||
})
|
||||
if err != nil {
|
||||
// Partial chunks come back even on error so we can clean them up rather
|
||||
// than leaving orphaned data on volume servers.
|
||||
if chunkResult != nil && len(chunkResult.FileChunks) > 0 {
|
||||
h.deleteOrphanedChunks(chunkResult.FileChunks)
|
||||
}
|
||||
return fmt.Errorf("upload: %w", err)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
entry := &filer_pb.Entry{
|
||||
Name: entryName,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileSize: uint64(chunkResult.TotalSize),
|
||||
Mtime: now.Unix(),
|
||||
Crtime: now.Unix(),
|
||||
FileMode: 0644,
|
||||
Mime: mimeType,
|
||||
},
|
||||
}
|
||||
if len(chunkResult.SmallContent) > 0 {
|
||||
entry.Content = chunkResult.SmallContent
|
||||
} else {
|
||||
entry.Chunks = chunkResult.FileChunks
|
||||
}
|
||||
|
||||
err = h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, createErr := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
})
|
||||
return createErr
|
||||
})
|
||||
if err != nil {
|
||||
if len(chunkResult.FileChunks) > 0 {
|
||||
h.deleteOrphanedChunks(chunkResult.FileChunks)
|
||||
}
|
||||
return fmt.Errorf("create entry: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteOrphanedChunks best-effort removes the chunk fids when an upload
|
||||
// fails partway through. Errors are logged; we can't surface them past the
|
||||
// caller's primary failure.
|
||||
func (h *FileBrowserHandlers) deleteOrphanedChunks(chunks []*filer_pb.FileChunk) {
|
||||
fileIds := make([]string, 0, len(chunks))
|
||||
for _, c := range chunks {
|
||||
if fid := c.GetFileIdString(); fid != "" {
|
||||
fileIds = append(fileIds, fid)
|
||||
}
|
||||
}
|
||||
if len(fileIds) == 0 {
|
||||
return
|
||||
}
|
||||
master := h.adminServer.GetMasterClient()
|
||||
results := operation.DeleteFileIds(master.GetMaster, false, h.adminServer.GetGrpcDialOption(), fileIds)
|
||||
for _, r := range results {
|
||||
if r.Error != "" {
|
||||
glog.Warningf("admin file browser: orphan chunk %s cleanup: %s", r.FileId, r.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *FileBrowserHandlers) lookupEntry(ctx context.Context, cleanFilePath string) (*filer_pb.Entry, error) {
|
||||
dir := path.Dir(cleanFilePath)
|
||||
if dir == "." {
|
||||
dir = "/"
|
||||
}
|
||||
name := path.Base(cleanFilePath)
|
||||
var entry *filer_pb.Entry
|
||||
err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, lookupErr := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
})
|
||||
if lookupErr != nil {
|
||||
return lookupErr
|
||||
}
|
||||
if resp.Entry == nil {
|
||||
return fmt.Errorf("not found")
|
||||
}
|
||||
entry = resp.Entry
|
||||
return nil
|
||||
})
|
||||
return entry, err
|
||||
}
|
||||
|
||||
func (h *FileBrowserHandlers) streamEntryContent(ctx context.Context, entry *filer_pb.Entry, size int64, w io.Writer) error {
|
||||
if size == 0 {
|
||||
// Inline content (small files stored directly on the entry) skip the
|
||||
// chunk pipeline entirely.
|
||||
if len(entry.Content) > 0 {
|
||||
_, err := w.Write(entry.Content)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(entry.Content) > 0 && len(entry.GetChunks()) == 0 {
|
||||
_, err := w.Write(entry.Content)
|
||||
return err
|
||||
}
|
||||
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(
|
||||
ctx,
|
||||
h.adminServer.GetMasterClient(),
|
||||
volumeServerReadJwt,
|
||||
entry.GetChunks(),
|
||||
0,
|
||||
size,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prepare stream: %w", err)
|
||||
}
|
||||
return streamFn(w)
|
||||
}
|
||||
|
||||
// volumeServerReadJwt mints a per-fileId Bearer token for reads against a
|
||||
// volume server when jwt.signing.read.key is configured. The volume servers
|
||||
// are unaware of jwt.filer_signing.read.key — that one only gates the filer
|
||||
// HTTP surface, which this code path doesn't touch.
|
||||
func volumeServerReadJwt(fileId string) string {
|
||||
v := util.GetViper()
|
||||
signingKey := security.SigningKey(v.GetString("jwt.signing.read.key"))
|
||||
if len(signingKey) == 0 {
|
||||
return ""
|
||||
}
|
||||
expiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
|
||||
return string(security.GenJwtForVolumeServer(signingKey, expiresAfterSec, fileId))
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -21,9 +16,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/view/app"
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/view/layout"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/http/client"
|
||||
)
|
||||
@@ -49,15 +42,6 @@ func NewFileBrowserHandlers(adminServer *dash.AdminServer) *FileBrowserHandlers
|
||||
}
|
||||
}
|
||||
|
||||
// newClientWithTimeout creates a temporary http.Client with the specified timeout,
|
||||
// reusing the TLS transport from the shared httpClient.
|
||||
func (h *FileBrowserHandlers) newClientWithTimeout(timeout time.Duration) http.Client {
|
||||
return http.Client{
|
||||
Transport: h.httpClient.Client.Transport,
|
||||
Timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// ShowFileBrowser renders the file browser page
|
||||
func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Request) {
|
||||
// Get path from query parameter, default to root
|
||||
@@ -309,7 +293,7 @@ func (h *FileBrowserHandlers) UploadFile(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
// Upload file to filer
|
||||
err = h.uploadFileToFiler(fullPath, fileHeader)
|
||||
err = h.uploadFileToFiler(r.Context(), fullPath, fileHeader)
|
||||
|
||||
if err != nil {
|
||||
failedUploads = append(failedUploads, fmt.Sprintf("%s: %v", fileName, err))
|
||||
@@ -346,139 +330,21 @@ func (h *FileBrowserHandlers) UploadFile(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// uploadFileToFiler uploads a file directly to the filer using multipart form data
|
||||
func (h *FileBrowserHandlers) uploadFileToFiler(filePath string, fileHeader *multipart.FileHeader) error {
|
||||
// Get filer address from admin server
|
||||
filerAddress := h.adminServer.GetFilerAddress()
|
||||
if filerAddress == "" {
|
||||
return fmt.Errorf("filer address not configured")
|
||||
}
|
||||
|
||||
// Validate and sanitize the filer address
|
||||
if err := h.validateFilerAddress(filerAddress); err != nil {
|
||||
return fmt.Errorf("invalid filer address: %w", err)
|
||||
}
|
||||
filerHttpAddress := pb.ServerAddress(filerAddress).ToHttpAddress()
|
||||
|
||||
// Validate and sanitize the file path
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
// Open the file
|
||||
// uploadFileToFiler uploads a file to the cluster via filer gRPC + volume
|
||||
// HTTP. This works whether or not the filer is running with -disableHttp=true,
|
||||
// since the bytes never traverse the filer's HTTP listener. The multipart
|
||||
// file is streamed through the chunked uploader, so the admin process never
|
||||
// buffers the entire payload in memory. The caller passes the request
|
||||
// context so a client disconnect cancels the in-flight chunk uploads instead
|
||||
// of letting them run to completion against the volume servers.
|
||||
func (h *FileBrowserHandlers) uploadFileToFiler(ctx context.Context, filePath string, fileHeader *multipart.FileHeader) error {
|
||||
file, err := fileHeader.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Create multipart form data
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
// Create form file field with normalized base filename
|
||||
// Use path.Base (not filepath.Base) since cleanFilePath uses URL path semantics
|
||||
baseFileName := path.Base(cleanFilePath)
|
||||
part, err := writer.CreateFormFile("file", baseFileName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create form file: %w", err)
|
||||
}
|
||||
|
||||
// Copy file content to form
|
||||
_, err = io.Copy(part, file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy file content: %w", err)
|
||||
}
|
||||
|
||||
// Close the writer to finalize the form
|
||||
err = writer.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to close multipart writer: %w", err)
|
||||
}
|
||||
|
||||
// Create the upload URL - the httpClient will normalize to the correct scheme (http/https)
|
||||
// based on the https.client configuration in security.toml
|
||||
uploadURL := filerFileURL(filerHttpAddress, cleanFilePath)
|
||||
|
||||
// Normalize the URL scheme based on TLS configuration
|
||||
uploadURL, err = h.httpClient.NormalizeHttpScheme(uploadURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to normalize URL scheme: %w", err)
|
||||
}
|
||||
|
||||
// Create HTTP request
|
||||
req, err := http.NewRequest("POST", uploadURL, &body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Set content type with boundary
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// Add JWT Token to Authorization Header
|
||||
h.setupFilerJwtAuth(req, "jwt.filer_signing.key", "jwt.filer_signing.expires_after_seconds", "filer upload")
|
||||
|
||||
// Send request using TLS-aware HTTP client with 60s timeout for large file uploads
|
||||
// lgtm[go/ssrf]
|
||||
// Safe: filerAddress validated by validateFilerAddress() to match configured filer
|
||||
// Safe: cleanFilePath validated and cleaned by validateAndCleanFilePath() to prevent path traversal
|
||||
client := h.newClientWithTimeout(60 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to upload file: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check response
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
responseBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("upload failed with status %d: %s", resp.StatusCode, string(responseBody))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateFilerAddress validates that the filer address is safe to use
|
||||
func (h *FileBrowserHandlers) validateFilerAddress(address string) error {
|
||||
if address == "" {
|
||||
return fmt.Errorf("filer address cannot be empty")
|
||||
}
|
||||
|
||||
// CRITICAL: Only allow the configured filer address to prevent SSRF
|
||||
configuredFiler := h.adminServer.GetFilerAddress()
|
||||
normalizedAddress := pb.ServerAddress(address).ToHttpAddress()
|
||||
normalizedConfigured := pb.ServerAddress(configuredFiler).ToHttpAddress()
|
||||
if normalizedAddress != normalizedConfigured {
|
||||
return fmt.Errorf("address does not match configured filer: got %s, expected %s", address, configuredFiler)
|
||||
}
|
||||
|
||||
// Parse the normalized HTTP address to validate it's a proper host:port format.
|
||||
host, port, err := net.SplitHostPort(normalizedAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid address format: %w", err)
|
||||
}
|
||||
|
||||
// Validate host is not empty
|
||||
if host == "" {
|
||||
return fmt.Errorf("host cannot be empty")
|
||||
}
|
||||
|
||||
// Validate port is numeric and in valid range
|
||||
if port == "" {
|
||||
return fmt.Errorf("port cannot be empty")
|
||||
}
|
||||
|
||||
portNum, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid port number: %w", err)
|
||||
}
|
||||
|
||||
if portNum < 1 || portNum > 65535 {
|
||||
return fmt.Errorf("port number must be between 1 and 65535")
|
||||
}
|
||||
|
||||
return nil
|
||||
return h.uploadFileGrpc(ctx, filePath, fileHeader.Filename, fileHeader.Header.Get("Content-Type"), file)
|
||||
}
|
||||
|
||||
// validateAndCleanFilePath validates and cleans the file path to prevent path traversal
|
||||
@@ -507,161 +373,56 @@ func (h *FileBrowserHandlers) validateAndCleanFilePath(filePath string) (string,
|
||||
return cleanPath, nil
|
||||
}
|
||||
|
||||
// filerFileURL joins the filer HTTP address with a validated file path, URL-escaping
|
||||
// the path so that control characters and other bytes that are legal in S3 object keys
|
||||
// cannot inject into the HTTP request target.
|
||||
func filerFileURL(filerHttpAddress, cleanFilePath string) string {
|
||||
return filerHttpAddress + (&url.URL{Path: cleanFilePath}).EscapedPath()
|
||||
}
|
||||
|
||||
// fetchFileContent fetches file content from the filer and returns the content or an error.
|
||||
// fetchFileContent fetches file content via the filer gRPC service. It is
|
||||
// used for the "view as text" path, so the maxBytes cap matches the 1 MB
|
||||
// limit the caller already applies before invoking us.
|
||||
func (h *FileBrowserHandlers) fetchFileContent(filePath string, timeout time.Duration) (string, error) {
|
||||
filerAddress := h.adminServer.GetFilerAddress()
|
||||
if filerAddress == "" {
|
||||
return "", fmt.Errorf("filer address not configured")
|
||||
}
|
||||
|
||||
if err := h.validateFilerAddress(filerAddress); err != nil {
|
||||
return "", fmt.Errorf("invalid filer address configuration: %w", err)
|
||||
}
|
||||
filerHttpAddress := pb.ServerAddress(filerAddress).ToHttpAddress()
|
||||
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create the file URL with proper scheme based on TLS configuration
|
||||
fileURL := filerFileURL(filerHttpAddress, cleanFilePath)
|
||||
fileURL, err = h.httpClient.NormalizeHttpScheme(fileURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to construct file URL: %w", err)
|
||||
}
|
||||
|
||||
// lgtm[go/ssrf]
|
||||
// Safe: filerAddress validated by validateFilerAddress() to match configured filer
|
||||
// Safe: cleanFilePath validated and cleaned by validateAndCleanFilePath() to prevent path traversal
|
||||
client := h.newClientWithTimeout(timeout)
|
||||
req, err := http.NewRequest("GET", fileURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
h.addFilerJwtAuthHeader(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to fetch file from filer: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("filer returned status %d but failed to read response body: %w", resp.StatusCode, err)
|
||||
}
|
||||
return "", fmt.Errorf("filer returned status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
contentBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read file content: %w", err)
|
||||
}
|
||||
|
||||
return string(contentBytes), nil
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
return h.fetchFileContentGrpc(ctx, filePath, 0)
|
||||
}
|
||||
|
||||
// DownloadFile handles file download requests by proxying through the Admin UI server
|
||||
// This ensures mTLS works correctly since the Admin UI server has the client certificates
|
||||
// DownloadFile streams a file straight from the volume servers via the filer
|
||||
// gRPC service, so the admin file browser keeps working even when the filer
|
||||
// is started with -disableHttp=true.
|
||||
func (h *FileBrowserHandlers) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
|
||||
// Get filer address
|
||||
filerAddress := h.adminServer.GetFilerAddress()
|
||||
if filerAddress == "" {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Filer address not configured")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate filer address to prevent SSRF
|
||||
if err := h.validateFilerAddress(filerAddress); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Invalid filer address configuration")
|
||||
return
|
||||
}
|
||||
filerHttpAddress := pb.ServerAddress(filerAddress).ToHttpAddress()
|
||||
|
||||
// Validate and sanitize the file path
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid file path: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Create the download URL with proper scheme based on TLS configuration
|
||||
downloadURL := filerFileURL(filerHttpAddress, cleanFilePath)
|
||||
downloadURL, err = h.httpClient.NormalizeHttpScheme(downloadURL)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to construct download URL: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Proxy the download through the Admin UI server to support mTLS
|
||||
// lgtm[go/ssrf]
|
||||
// Safe: filerAddress validated by validateFilerAddress() to match configured filer
|
||||
// Safe: cleanFilePath validated and cleaned by validateAndCleanFilePath() to prevent path traversal
|
||||
// Use request context so download is cancelled when client disconnects
|
||||
req, err := http.NewRequestWithContext(r.Context(), "GET", downloadURL, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create request: "+err.Error())
|
||||
return
|
||||
}
|
||||
client := h.newClientWithTimeout(5 * time.Minute) // Longer timeout for large file downloads
|
||||
|
||||
h.addFilerJwtAuthHeader(req)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadGateway, "Failed to fetch file from filer: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
writeJSONError(w, resp.StatusCode, fmt.Sprintf("Filer returned status %d but failed to read response body: %v", resp.StatusCode, err))
|
||||
tracker := &responseWriteTracker{ResponseWriter: w}
|
||||
if err := h.downloadFileGrpc(r.Context(), filePath, tracker); err != nil {
|
||||
// Once bytes have been written we can't switch to a JSON error body
|
||||
// without corrupting the partial response — log and stop. Before any
|
||||
// write the response is still uncommitted, so a 502 with details is
|
||||
// safe.
|
||||
if tracker.committed {
|
||||
glog.Errorf("Error streaming file download: %v", err)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, resp.StatusCode, fmt.Sprintf("Filer returned status %d: %s", resp.StatusCode, string(body)))
|
||||
return
|
||||
writeJSONError(w, http.StatusBadGateway, "Failed to fetch file: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Set headers for file download
|
||||
fileName := filepath.Base(cleanFilePath)
|
||||
// Use mime.FormatMediaType for RFC 6266 compliant Content-Disposition,
|
||||
// properly handling non-ASCII characters and special characters
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": fileName}))
|
||||
// responseWriteTracker wraps http.ResponseWriter to record whether the
|
||||
// response has been committed (status line + headers sent). DownloadFile
|
||||
// uses this instead of probing Header() so future header-setting code
|
||||
// reorganization can't silently break the "did we already send bytes?"
|
||||
// detection.
|
||||
type responseWriteTracker struct {
|
||||
http.ResponseWriter
|
||||
committed bool
|
||||
}
|
||||
|
||||
// Use content type from filer response, or default to octet-stream
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
func (t *responseWriteTracker) WriteHeader(code int) {
|
||||
t.committed = true
|
||||
t.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
// Set content length if available
|
||||
if resp.ContentLength > 0 {
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", resp.ContentLength))
|
||||
}
|
||||
|
||||
// Stream the response body to the client
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = io.Copy(w, resp.Body)
|
||||
if err != nil {
|
||||
glog.Errorf("Error streaming file download: %v", err)
|
||||
}
|
||||
func (t *responseWriteTracker) Write(p []byte) (int, error) {
|
||||
t.committed = true
|
||||
return t.ResponseWriter.Write(p)
|
||||
}
|
||||
|
||||
// ViewFile handles file viewing requests (for text files, images, etc.)
|
||||
@@ -883,64 +644,16 @@ func (h *FileBrowserHandlers) formatBytes(bytes int64) string {
|
||||
|
||||
// Helper function to check if a file is likely a text file by checking content
|
||||
func (h *FileBrowserHandlers) isLikelyTextFile(filePath string, maxCheckSize int64) bool {
|
||||
filerAddress := h.adminServer.GetFilerAddress()
|
||||
if filerAddress == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Validate filer address to prevent SSRF
|
||||
if err := h.validateFilerAddress(filerAddress); err != nil {
|
||||
glog.Errorf("Invalid filer address: %v", err)
|
||||
return false
|
||||
}
|
||||
filerHttpAddress := pb.ServerAddress(filerAddress).ToHttpAddress()
|
||||
|
||||
cleanFilePath, err := h.validateAndCleanFilePath(filePath)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
content, err := h.fetchFileContentGrpc(ctx, filePath, int(maxCheckSize))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Create the file URL with proper scheme based on TLS configuration
|
||||
fileURL := filerFileURL(filerHttpAddress, cleanFilePath)
|
||||
fileURL, err = h.httpClient.NormalizeHttpScheme(fileURL)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to normalize URL scheme: %v", err)
|
||||
return false
|
||||
if len(content) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
// lgtm[go/ssrf]
|
||||
// Safe: filerAddress validated by validateFilerAddress() to match configured filer
|
||||
// Safe: cleanFilePath validated and cleaned by validateAndCleanFilePath() to prevent path traversal
|
||||
client := h.newClientWithTimeout(10 * time.Second)
|
||||
req, err := http.NewRequest("GET", fileURL, nil)
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to create request: %v", err)
|
||||
return false
|
||||
}
|
||||
h.addFilerJwtAuthHeader(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return false
|
||||
}
|
||||
|
||||
// Read first few bytes to check if it's text
|
||||
buffer := make([]byte, min(maxCheckSize, 512))
|
||||
n, err := resp.Body.Read(buffer)
|
||||
if err != nil && err != io.EOF {
|
||||
return false
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return true // Empty file can be considered text
|
||||
}
|
||||
|
||||
// Check if content is printable text
|
||||
return h.isPrintableText(buffer[:n])
|
||||
return h.isPrintableText([]byte(content))
|
||||
}
|
||||
|
||||
// Helper function to check if content is printable text
|
||||
@@ -973,35 +686,3 @@ func min(a, b int64) int64 {
|
||||
return b
|
||||
}
|
||||
|
||||
// setupFilerJwtAuth generates a JWT token and adds it to the request Authorization header if configured.
|
||||
func (h *FileBrowserHandlers) setupFilerJwtAuth(req *http.Request, keyPath, expiresPath, operation string) {
|
||||
// Load security configuration
|
||||
v := util.GetViper()
|
||||
|
||||
// Read Filer JWT token from security.toml
|
||||
signingKey := security.SigningKey(v.GetString(keyPath))
|
||||
expiresAfterSec := v.GetInt(expiresPath)
|
||||
|
||||
// Generate JWT token to authenticate with Filer
|
||||
var jwtToken security.EncodedJwt
|
||||
if len(signingKey) > 0 {
|
||||
jwtToken = security.GenJwtForFilerServer(signingKey, expiresAfterSec)
|
||||
glog.V(4).Infof("Generated JWT token for %s (expires in %d sec)", operation, expiresAfterSec)
|
||||
} else {
|
||||
if v.GetString("jwt.signing.key") != "" {
|
||||
glog.Warningf("JWT %s key not configured, but general JWT security is enabled. %s without authentication.", keyPath, operation)
|
||||
} else {
|
||||
glog.V(1).Infof("No JWT signing key configured, %s without authentication", operation)
|
||||
}
|
||||
}
|
||||
|
||||
// Add JWT Token to Authorization Header
|
||||
if jwtToken != "" {
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", string(jwtToken)))
|
||||
glog.V(4).Infof("Added JWT authorization header for %s", operation)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *FileBrowserHandlers) addFilerJwtAuthHeader(req *http.Request) {
|
||||
h.setupFilerJwtAuth(req, "jwt.filer_signing.read.key", "jwt.filer_signing.read.expires_after_seconds", "filer request")
|
||||
}
|
||||
@@ -42,21 +42,3 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilerFileURL_EscapesControlChars(t *testing.T) {
|
||||
cases := []struct {
|
||||
addr string
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{"http://127.0.0.1:8888", "/buckets/profilebuilder/3testGB.zip\n ", "http://127.0.0.1:8888/buckets/profilebuilder/3testGB.zip%0A%20"},
|
||||
{"http://127.0.0.1:8888", "/buckets/profilebuilder/file\rname", "http://127.0.0.1:8888/buckets/profilebuilder/file%0Dname"},
|
||||
{"http://127.0.0.1:8888", "/buckets/profilebuilder/file\x00name", "http://127.0.0.1:8888/buckets/profilebuilder/file%00name"},
|
||||
// Plain path round-trips unchanged.
|
||||
{"http://h:1", "/a/b.txt", "http://h:1/a/b.txt"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := filerFileURL(tc.addr, tc.path); got != tc.want {
|
||||
t.Errorf("filerFileURL(%q, %q) = %q, want %q", tc.addr, tc.path, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@ type MaintenanceIntegration struct {
|
||||
// Active topology for task detection and target selection
|
||||
activeTopology *topology.ActiveTopology
|
||||
|
||||
// Master's default replication, refreshed by the scanner each cycle and
|
||||
// passed to detectors as the replica-placement fallback (matches the shell).
|
||||
defaultReplicaPlacement string
|
||||
|
||||
// Type conversion maps
|
||||
taskTypeMap map[types.TaskType]MaintenanceTaskType
|
||||
revTaskTypeMap map[MaintenanceTaskType]types.TaskType
|
||||
@@ -219,9 +223,10 @@ func (s *MaintenanceIntegration) ScanWithTaskDetectors(volumeMetrics []*types.Vo
|
||||
|
||||
// Create cluster info
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
TotalVolumes: len(filteredMetrics),
|
||||
LastUpdated: time.Now(),
|
||||
ActiveTopology: s.activeTopology, // Provide ActiveTopology for destination planning
|
||||
TotalVolumes: len(filteredMetrics),
|
||||
LastUpdated: time.Now(),
|
||||
ActiveTopology: s.activeTopology, // Provide ActiveTopology for destination planning
|
||||
DefaultReplicaPlacement: s.defaultReplicaPlacement,
|
||||
}
|
||||
|
||||
// Run detection for each registered task type
|
||||
@@ -271,6 +276,12 @@ func (s *MaintenanceIntegration) ScanWithTaskDetectors(volumeMetrics []*types.Vo
|
||||
return allResults, nil
|
||||
}
|
||||
|
||||
// SetDefaultReplicaPlacement records the master's default replication so detectors
|
||||
// can use it as the replica-placement fallback (matching the shell).
|
||||
func (s *MaintenanceIntegration) SetDefaultReplicaPlacement(replicaPlacement string) {
|
||||
s.defaultReplicaPlacement = replicaPlacement
|
||||
}
|
||||
|
||||
// UpdateTopologyInfo updates the volume shard tracker with topology information for empty servers
|
||||
func (s *MaintenanceIntegration) UpdateTopologyInfo(topologyInfo *master_pb.TopologyInfo) error {
|
||||
// Log topology details before update for diagnostics
|
||||
|
||||
@@ -51,6 +51,10 @@ func (ms *MaintenanceScanner) ScanForMaintenanceTasks() ([]*TaskDetectionResult,
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh the master's default replication so detectors can use it as the
|
||||
// replica-placement fallback (matches the shell ec.balance default).
|
||||
ms.integration.SetDefaultReplicaPlacement(ms.getDefaultReplicaPlacement())
|
||||
|
||||
// Use task detection system with complete cluster information
|
||||
results, err := ms.integration.ScanWithTaskDetectors(taskMetrics)
|
||||
if err != nil {
|
||||
@@ -67,6 +71,26 @@ func (ms *MaintenanceScanner) ScanForMaintenanceTasks() ([]*TaskDetectionResult,
|
||||
return []*TaskDetectionResult{}, nil
|
||||
}
|
||||
|
||||
// getDefaultReplicaPlacement reads the master's configured default replication,
|
||||
// used by detectors as the replica-placement fallback. Returns "" on error so
|
||||
// detectors fall back to even spread rather than failing the scan.
|
||||
func (ms *MaintenanceScanner) getDefaultReplicaPlacement() string {
|
||||
var replicaPlacement string
|
||||
err := ms.adminClient.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.GetMasterConfiguration(context.Background(), &master_pb.GetMasterConfigurationRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
replicaPlacement = resp.DefaultReplication
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(1).Infof("could not fetch master default replication: %v", err)
|
||||
return ""
|
||||
}
|
||||
return replicaPlacement
|
||||
}
|
||||
|
||||
// getVolumeHealthMetrics collects health information for all volumes.
|
||||
// Returns metrics in task-system format directly (no intermediate copy) and
|
||||
// the topology info for updating the active topology.
|
||||
|
||||
@@ -113,7 +113,7 @@ func cloneClusterContext(in *plugin_pb.ClusterContext) *plugin_pb.ClusterContext
|
||||
}
|
||||
out := &plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: in.MasterGrpcAddresses,
|
||||
FilerGrpcAddresses: in.FilerGrpcAddresses,
|
||||
FilerAddresses: in.FilerAddresses,
|
||||
VolumeGrpcAddresses: in.VolumeGrpcAddresses,
|
||||
S3GrpcAddresses: in.S3GrpcAddresses,
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ func buildErasureCodingExecutionPlan(params *worker_pb.TaskParams) map[string]in
|
||||
source.DataCenter,
|
||||
source.Rack,
|
||||
source.VolumeId,
|
||||
source.DiskId,
|
||||
source.ShardIds,
|
||||
dataShards,
|
||||
))
|
||||
@@ -132,6 +133,7 @@ func buildErasureCodingExecutionPlan(params *worker_pb.TaskParams) map[string]in
|
||||
target.DataCenter,
|
||||
target.Rack,
|
||||
target.VolumeId,
|
||||
target.DiskId,
|
||||
target.ShardIds,
|
||||
dataShards,
|
||||
))
|
||||
@@ -147,6 +149,7 @@ func buildErasureCodingExecutionPlan(params *worker_pb.TaskParams) map[string]in
|
||||
"target_data_center": strings.TrimSpace(target.DataCenter),
|
||||
"target_rack": strings.TrimSpace(target.Rack),
|
||||
"target_volume_id": int(target.VolumeId),
|
||||
"target_disk_id": int(target.DiskId),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -182,6 +185,7 @@ func buildExecutionEndpoint(
|
||||
dataCenter string,
|
||||
rack string,
|
||||
volumeID uint32,
|
||||
diskID uint32,
|
||||
shardIDs []uint32,
|
||||
dataShardCount int,
|
||||
) map[string]interface{} {
|
||||
@@ -201,6 +205,7 @@ func buildExecutionEndpoint(
|
||||
"data_center": strings.TrimSpace(dataCenter),
|
||||
"rack": strings.TrimSpace(rack),
|
||||
"volume_id": int(volumeID),
|
||||
"disk_id": int(diskID),
|
||||
"shard_ids": allShards,
|
||||
"data_shard_ids": dataShards,
|
||||
"parity_shard_ids": parityShards,
|
||||
|
||||
@@ -423,6 +423,7 @@ func TestTrackExecutionStartStoresErasureCodingExecutionPlan(t *testing.T) {
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack1",
|
||||
VolumeId: 29,
|
||||
DiskId: 5,
|
||||
},
|
||||
},
|
||||
Targets: []*worker_pb.TaskTarget{
|
||||
@@ -431,6 +432,7 @@ func TestTrackExecutionStartStoresErasureCodingExecutionPlan(t *testing.T) {
|
||||
DataCenter: "dc1",
|
||||
Rack: "rack2",
|
||||
VolumeId: 29,
|
||||
DiskId: 2,
|
||||
ShardIds: []uint32{0, 10},
|
||||
},
|
||||
{
|
||||
@@ -438,6 +440,7 @@ func TestTrackExecutionStartStoresErasureCodingExecutionPlan(t *testing.T) {
|
||||
DataCenter: "dc2",
|
||||
Rack: "rack3",
|
||||
VolumeId: 29,
|
||||
DiskId: 3,
|
||||
ShardIds: []uint32{1, 11},
|
||||
},
|
||||
},
|
||||
@@ -486,10 +489,28 @@ func TestTrackExecutionStartStoresErasureCodingExecutionPlan(t *testing.T) {
|
||||
if plan["volume_id"] != float64(29) {
|
||||
t.Fatalf("unexpected execution plan volume id: %+v", plan["volume_id"])
|
||||
}
|
||||
sourcesRaw, ok := plan["sources"].([]interface{})
|
||||
if !ok || len(sourcesRaw) != 1 {
|
||||
t.Fatalf("unexpected sources in execution plan: %+v", plan["sources"])
|
||||
}
|
||||
firstSource, ok := sourcesRaw[0].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("unexpected source payload: %+v", sourcesRaw[0])
|
||||
}
|
||||
if firstSource["disk_id"] != float64(5) {
|
||||
t.Fatalf("unexpected source disk_id: %+v", firstSource["disk_id"])
|
||||
}
|
||||
targets, ok := plan["targets"].([]interface{})
|
||||
if !ok || len(targets) != 2 {
|
||||
t.Fatalf("unexpected targets in execution plan: %+v", plan["targets"])
|
||||
}
|
||||
firstTarget, ok := targets[0].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("unexpected target payload: %+v", targets[0])
|
||||
}
|
||||
if firstTarget["disk_id"] != float64(2) {
|
||||
t.Fatalf("unexpected target disk_id: %+v", firstTarget["disk_id"])
|
||||
}
|
||||
assignments, ok := plan["shard_assignments"].([]interface{})
|
||||
if !ok || len(assignments) != 4 {
|
||||
t.Fatalf("unexpected shard assignments in execution plan: %+v", plan["shard_assignments"])
|
||||
@@ -501,6 +522,16 @@ func TestTrackExecutionStartStoresErasureCodingExecutionPlan(t *testing.T) {
|
||||
if firstAssignment["shard_id"] != float64(0) || firstAssignment["kind"] != "data" {
|
||||
t.Fatalf("unexpected first assignment: %+v", firstAssignment)
|
||||
}
|
||||
if firstAssignment["target_disk_id"] != float64(2) {
|
||||
t.Fatalf("unexpected first assignment target_disk_id: %+v", firstAssignment["target_disk_id"])
|
||||
}
|
||||
secondAssignment, ok := assignments[1].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("unexpected second assignment payload: %+v", assignments[1])
|
||||
}
|
||||
if secondAssignment["shard_id"] != float64(1) || secondAssignment["target_disk_id"] != float64(3) {
|
||||
t.Fatalf("unexpected second assignment: %+v", secondAssignment)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildJobDetailIncludesActivitiesAndRunRecord(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// TestCountTopologyResources_multiDiskPerNode covers the case where the master
|
||||
// keys DiskInfos by disk type, so several same-type physical disks on a node
|
||||
// collapse into a single DiskInfo entry. Counting len(DiskInfos) under-reports
|
||||
// the physical disk count and disagrees with the per-disk activeDisk map that
|
||||
// the rest of the admin topology builds via SplitByPhysicalDisk.
|
||||
func TestCountTopologyResources_multiDiskPerNode(t *testing.T) {
|
||||
makeNode := func(id string) *master_pb.DataNodeInfo {
|
||||
var ecShardInfos []*master_pb.VolumeEcShardInformationMessage
|
||||
for diskId := uint32(0); diskId < 6; diskId++ {
|
||||
ecShardInfos = append(ecShardInfos, &master_pb.VolumeEcShardInformationMessage{
|
||||
Id: diskId + 1,
|
||||
DiskId: diskId,
|
||||
EcIndexBits: 1,
|
||||
})
|
||||
}
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: id,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {Type: "", MaxVolumeCount: 60, EcShardInfos: ecShardInfos},
|
||||
},
|
||||
}
|
||||
}
|
||||
topo := &master_pb.TopologyInfo{
|
||||
Id: "multi_disk_topo",
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
makeNode("node1"), makeNode("node2"), makeNode("node3"),
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
|
||||
dcCount, nodeCount, diskCount := CountTopologyResources(topo)
|
||||
if dcCount != 1 {
|
||||
t.Errorf("dcCount = %d, want 1", dcCount)
|
||||
}
|
||||
if nodeCount != 3 {
|
||||
t.Errorf("nodeCount = %d, want 3", nodeCount)
|
||||
}
|
||||
if diskCount != 18 {
|
||||
t.Errorf("diskCount = %d, want 18 (6 physical disks x 3 nodes)", diskCount)
|
||||
}
|
||||
}
|
||||
@@ -9,74 +9,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// splitDiskInfoByPhysicalDisk returns one master_pb.DiskInfo per physical
|
||||
// disk_id observed in VolumeInfos / EcShardInfos. Multiple same-type physical
|
||||
// disks collapse to one DiskInfo at the master; per-volume/per-shard records
|
||||
// keep the original disk_id and are the authoritative signal here. Capacity
|
||||
// is split evenly — the wire format doesn't carry per-disk capacity yet.
|
||||
func splitDiskInfoByPhysicalDisk(diskInfo *master_pb.DiskInfo) []*master_pb.DiskInfo {
|
||||
if diskInfo == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Records with DiskId=0 and a non-zero outer DiskId belong to the outer
|
||||
// disk — handles older payloads / fixtures that omit the per-record id.
|
||||
normalize := func(id uint32) uint32 {
|
||||
if id == 0 && diskInfo.DiskId != 0 {
|
||||
return diskInfo.DiskId
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
diskIDs := make(map[uint32]struct{})
|
||||
for _, vi := range diskInfo.VolumeInfos {
|
||||
diskIDs[normalize(vi.DiskId)] = struct{}{}
|
||||
}
|
||||
for _, eci := range diskInfo.EcShardInfos {
|
||||
diskIDs[normalize(eci.DiskId)] = struct{}{}
|
||||
}
|
||||
if len(diskIDs) == 0 {
|
||||
diskIDs[diskInfo.DiskId] = struct{}{}
|
||||
}
|
||||
|
||||
if len(diskIDs) == 1 {
|
||||
for diskID := range diskIDs {
|
||||
if diskID == diskInfo.DiskId {
|
||||
return []*master_pb.DiskInfo{diskInfo}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
perDiskVolumes := make(map[uint32][]*master_pb.VolumeInformationMessage)
|
||||
for _, vi := range diskInfo.VolumeInfos {
|
||||
perDiskVolumes[normalize(vi.DiskId)] = append(perDiskVolumes[normalize(vi.DiskId)], vi)
|
||||
}
|
||||
perDiskShards := make(map[uint32][]*master_pb.VolumeEcShardInformationMessage)
|
||||
for _, eci := range diskInfo.EcShardInfos {
|
||||
perDiskShards[normalize(eci.DiskId)] = append(perDiskShards[normalize(eci.DiskId)], eci)
|
||||
}
|
||||
|
||||
count := int64(len(diskIDs))
|
||||
share := func(total int64) int64 { return total / count }
|
||||
|
||||
result := make([]*master_pb.DiskInfo, 0, len(diskIDs))
|
||||
for diskID := range diskIDs {
|
||||
result = append(result, &master_pb.DiskInfo{
|
||||
Type: diskInfo.Type,
|
||||
MaxVolumeCount: share(diskInfo.MaxVolumeCount),
|
||||
VolumeCount: int64(len(perDiskVolumes[diskID])),
|
||||
FreeVolumeCount: share(diskInfo.FreeVolumeCount),
|
||||
ActiveVolumeCount: share(diskInfo.ActiveVolumeCount),
|
||||
RemoteVolumeCount: share(diskInfo.RemoteVolumeCount),
|
||||
VolumeInfos: perDiskVolumes[diskID],
|
||||
EcShardInfos: perDiskShards[diskID],
|
||||
DiskId: diskID,
|
||||
Tags: append([]string(nil), diskInfo.Tags...),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// CountTopologyResources counts datacenters, nodes, and disks in topology info
|
||||
func CountTopologyResources(topologyInfo *master_pb.TopologyInfo) (dcCount, nodeCount, diskCount int) {
|
||||
if topologyInfo == nil {
|
||||
@@ -87,7 +19,12 @@ func CountTopologyResources(topologyInfo *master_pb.TopologyInfo) (dcCount, node
|
||||
for _, rack := range dc.RackInfos {
|
||||
nodeCount += len(rack.DataNodeInfos)
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
diskCount += len(node.DiskInfos)
|
||||
// DiskInfos is keyed by disk type, so same-type physical disks
|
||||
// collapse into one entry. Count physical disks so the number
|
||||
// matches the per-disk activeDisk map.
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
diskCount += len(diskInfo.SplitByPhysicalDisk())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,10 +79,10 @@ func (at *ActiveTopology) UpdateTopology(topologyInfo *master_pb.TopologyInfo) e
|
||||
disks: make(map[uint32]*activeDisk),
|
||||
}
|
||||
|
||||
// One activeDisk per physical disk_id (#9369): the master keys
|
||||
// One activeDisk per physical disk_id: the master keys
|
||||
// DiskInfos by disk type, so same-type disks must be split out.
|
||||
for diskType, diskInfo := range nodeInfo.DiskInfos {
|
||||
perDiskInfos := splitDiskInfoByPhysicalDisk(diskInfo)
|
||||
perDiskInfos := diskInfo.SplitByPhysicalDisk()
|
||||
for _, perDisk := range perDiskInfos {
|
||||
disk := &activeDisk{
|
||||
DiskInfo: &DiskInfo{
|
||||
|
||||
+48
-18
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -37,6 +36,7 @@ type LiveLock struct {
|
||||
expireAtNs int64
|
||||
hostFiler pb.ServerAddress
|
||||
cancelCh chan struct{}
|
||||
renewalDone chan struct{} // closed when the renewal goroutine exits; nil if there is none
|
||||
grpcDialOption grpc.DialOption
|
||||
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
|
||||
self string
|
||||
@@ -83,7 +83,9 @@ func (lc *LockClient) NewBlockingLongLivedLock(key, owner string, lockTTL time.D
|
||||
// Block until acquired
|
||||
lock.retryUntilLocked(lockTTL)
|
||||
// Start renewal goroutine using a ticker for interruptible sleep
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(lock.renewalDone)
|
||||
renewInterval := lockTTL / 2
|
||||
ticker := time.NewTicker(renewInterval)
|
||||
defer ticker.Stop()
|
||||
@@ -119,7 +121,9 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
if lock.lockTTL == 0 {
|
||||
lock.lockTTL = lock_manager.LiveLockTTL
|
||||
}
|
||||
lock.renewalDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(lock.renewalDone)
|
||||
renewInterval := lock.lockTTL / 2
|
||||
isLocked := false
|
||||
lockOwner := ""
|
||||
@@ -149,30 +153,39 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
onLockOwnerChange(lock.LockOwner())
|
||||
lockOwner = lock.LockOwner()
|
||||
}
|
||||
// Sleep until the next attempt, but wake immediately on Stop() so
|
||||
// the goroutine exits and closes renewalDone before Stop()'s bounded
|
||||
// wait elapses. An uninterruptible sleep here (up to 5*renewInterval
|
||||
// when unlocked) can outlast that wait and break the shutdown
|
||||
// synchronization.
|
||||
sleepFor := renewInterval
|
||||
if !isLocked {
|
||||
sleepFor = 5 * renewInterval
|
||||
}
|
||||
timer := time.NewTimer(sleepFor)
|
||||
select {
|
||||
case <-lock.cancelCh:
|
||||
timer.Stop()
|
||||
return
|
||||
default:
|
||||
if isLocked {
|
||||
time.Sleep(renewInterval)
|
||||
} else {
|
||||
time.Sleep(5 * renewInterval)
|
||||
}
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
// retryUntilLocked blocks until the lock is acquired, polling at the steady
|
||||
// short cadence that AttemptToLock already enforces on contention (~1s). It
|
||||
// deliberately avoids util.RetryUntil's exponential backoff (which grows to
|
||||
// several seconds): when a holder on another mount releases the lock, the
|
||||
// waiter must pick it up promptly, otherwise cross-mount write handoff stalls
|
||||
// long enough to time out clients.
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) {
|
||||
util.RetryUntil("create lock:"+lock.key, func() error {
|
||||
return lock.AttemptToLock(lockDuration)
|
||||
}, func(err error) (shouldContinue bool) {
|
||||
if err != nil {
|
||||
glog.Warningf("create lock %s: %s", lock.key, err)
|
||||
for lock.renewToken == "" {
|
||||
if err := lock.AttemptToLock(lockDuration); err != nil {
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
}
|
||||
return lock.renewToken == ""
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
@@ -226,10 +239,27 @@ func (lock *LiveLock) Stop() error {
|
||||
close(lock.cancelCh)
|
||||
}
|
||||
|
||||
// Wait a brief moment for the goroutine to see the closed channel
|
||||
// This reduces the race condition window where the goroutine might
|
||||
// attempt one more lock operation after we've released the lock
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
// Wait for the renewal goroutine to fully exit before unlocking. A renewal
|
||||
// in flight when we close cancelCh rotates renewToken on the server; if we
|
||||
// then unlock with the token we read here, the unlock fails with a token
|
||||
// mismatch and the lock lingers until its TTL expires — blocking other
|
||||
// mounts waiting on the same file. Waiting for the goroutine to return also
|
||||
// makes the renewToken read below race-free (channel close = happens-before).
|
||||
if lock.renewalDone != nil {
|
||||
select {
|
||||
case <-lock.renewalDone:
|
||||
case <-time.After(lock.lockTTL + 2*time.Second):
|
||||
// The renewal goroutine is wedged, almost certainly in a stuck
|
||||
// renewal RPC. Do not unlock here: the renewToken may be rotated
|
||||
// when that RPC finally returns, so an unlock sent now could race
|
||||
// it, be rejected on a stale token, and leave the lock lingering
|
||||
// anyway. cancelCh is closed, so the goroutine stops renewing once
|
||||
// its in-flight call returns and the lock then expires within its
|
||||
// TTL on its own.
|
||||
glog.Warningf("lock %s: renewal goroutine still running at shutdown; letting lock expire via TTL", lock.key)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Also release the lock if held
|
||||
// Note: We intentionally don't clear renewToken here because
|
||||
|
||||
@@ -236,6 +236,12 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
filerSftpOptions.resolvePaths()
|
||||
util.LoadSecurityConfiguration()
|
||||
|
||||
// Share the S3 static identity config file with the filer regardless of
|
||||
// whether the embedded S3 gateway runs on this node: the IAM gRPC service
|
||||
// the admin UI and weed shell talk to is wired up unconditionally, and it
|
||||
// needs the same identities the S3 server would load from -s3.config.
|
||||
f.s3ConfigFile = filerS3Options.config
|
||||
|
||||
switch {
|
||||
case *f.metricsHttpIp != "":
|
||||
// noting to do, use f.metricsHttpIp
|
||||
|
||||
@@ -439,6 +439,13 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
StartTsNs: sourceFilerOffsetTsNs,
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
// While the source has only read activity it emits no metadata events, so
|
||||
// the watermark above never advances and sync_offset would look stuck.
|
||||
// The idle heartbeat moves the gauge to the source's current time once we
|
||||
// are caught up, so now-sync_offset reflects real lag and stays alertable.
|
||||
OnIdleHeartbeat: func(tsNs int64) {
|
||||
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(tsNs))
|
||||
},
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(sourceFiler, sourceGrpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
|
||||
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
@@ -9,12 +10,15 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -27,6 +31,7 @@ var cmdFix = &Command{
|
||||
Short: "run weed tool fix on files or whole folders to recreate index file(s) if corrupted",
|
||||
Long: `Fix runs the SeaweedFS fix command on local dat files ( or remote files) or whole folders to re-create the index .idx file. If fixing remote files, you need to synchronize master.toml to the same directory on the current node as on the master node.
|
||||
You Need to stop the volume server when running this command.
|
||||
Use -ecx to rebuild a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -36,6 +41,9 @@ var (
|
||||
fixIncludeDeleted = cmdFix.Flag.Bool("includeDeleted", true, "include deleted entries in the index file")
|
||||
fixIgnoreError = cmdFix.Flag.Bool("ignoreError", false, "an optional, if true will be processed despite errors")
|
||||
fixRemoteFile = cmdFix.Flag.Bool("remoteFile", false, "an optional, if true will not try to load the local .dat file, but only the remote file")
|
||||
fixGenerateEcx = cmdFix.Flag.Bool("ecx", false, "regenerate a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards (missing shards are reconstructed from parity when enough survive). Run with the volume server stopped.")
|
||||
fixEcDataShards = cmdFix.Flag.Int("ecDataShards", 0, "EC data shard count for -ecx (0 = read from .vif, otherwise default 10)")
|
||||
fixEcParityShards = cmdFix.Flag.Int("ecParityShards", 0, "EC parity shard count for -ecx (0 = read from .vif, infer from shard count, otherwise default 4)")
|
||||
)
|
||||
|
||||
type VolumeFileScanner4Fix struct {
|
||||
@@ -130,6 +138,45 @@ func runFix(cmd *Command, args []string) bool {
|
||||
}
|
||||
doFixOneVolume(basePath, baseFileName, collection, volumeId, *fixIncludeDeleted)
|
||||
}
|
||||
|
||||
if *fixGenerateEcx {
|
||||
if !fixEcxFromShardsInDir(basePath, files) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// fixEcxFromShardsInDir finds EC volumes in files (identified by their .ec00
|
||||
// data shard) and regenerates the .ecx (and .vif when missing) for each,
|
||||
// honoring the -collection and -volumeId filters.
|
||||
func fixEcxFromShardsInDir(basePath string, files []fs.DirEntry) bool {
|
||||
const shard0Ext = ".ec00"
|
||||
for _, file := range files {
|
||||
if !strings.HasSuffix(file.Name(), shard0Ext) {
|
||||
continue
|
||||
}
|
||||
if *fixVolumeCollection != "" {
|
||||
if !strings.HasPrefix(file.Name(), *fixVolumeCollection+"_") {
|
||||
continue
|
||||
}
|
||||
}
|
||||
baseFileName := file.Name()[:len(file.Name())-len(shard0Ext)]
|
||||
collection, volumeIdStr := "", baseFileName
|
||||
if sepIndex := strings.LastIndex(baseFileName, "_"); sepIndex > 0 {
|
||||
collection = baseFileName[:sepIndex]
|
||||
volumeIdStr = baseFileName[sepIndex+1:]
|
||||
}
|
||||
volumeId, parseErr := strconv.ParseInt(volumeIdStr, 10, 64)
|
||||
if parseErr != nil {
|
||||
fmt.Printf("Failed to parse volume id from %s: %v\n", baseFileName, parseErr)
|
||||
return false
|
||||
}
|
||||
if *fixVolumeId != 0 && *fixVolumeId != volumeId {
|
||||
continue
|
||||
}
|
||||
doFixEcxFromShards(basePath, baseFileName, collection, volumeId)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -202,3 +249,252 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doFixEcxFromShards rebuilds the sealed EC index (.ecx) for one EC volume
|
||||
// directly from its local shards when both the .ecx and the original .dat are
|
||||
// gone but the shards survive. When some data shards are missing but at least
|
||||
// dataShards shards survive in total, the missing shards are first reconstructed
|
||||
// from the survivors via Reed-Solomon. It then de-stripes the data shards into a
|
||||
// temporary .dat, scans the needles, and writes a fresh ascending-sorted .ecx
|
||||
// that matches what WriteSortedFileFromIdx emits at encode time (live entries
|
||||
// only). When the .vif is also missing it is regenerated from the inferred EC
|
||||
// ratio and the .dat size discovered during the scan.
|
||||
func doFixEcxFromShards(basePath, baseFileName, collection string, volumeId int64) {
|
||||
base := path.Join(basePath, baseFileName)
|
||||
|
||||
fail := func(err error) {
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
glog.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
ecxName := base + ".ecx"
|
||||
if info, err := os.Stat(ecxName); err == nil && info.Size() > 0 {
|
||||
glog.Infof("volume %d: %s already exists (%d bytes), skipping; remove it first to force regeneration", volumeId, ecxName, info.Size())
|
||||
return
|
||||
}
|
||||
|
||||
// Discover which shards are present and their common size. Reed-Solomon
|
||||
// requires every shard to be the same size.
|
||||
present := make([]bool, erasure_coding.MaxShardCount)
|
||||
presentCount := 0
|
||||
maxPresentIdx := -1
|
||||
var shardSize int64
|
||||
for i := 0; i < erasure_coding.MaxShardCount; i++ {
|
||||
info, statErr := os.Stat(base + erasure_coding.ToExt(i))
|
||||
if statErr != nil || info.Size() == 0 {
|
||||
continue
|
||||
}
|
||||
if shardSize == 0 {
|
||||
shardSize = info.Size()
|
||||
} else if info.Size() != shardSize {
|
||||
fail(fmt.Errorf("volume %d: shard %s size %d does not match %d", volumeId, base+erasure_coding.ToExt(i), info.Size(), shardSize))
|
||||
return
|
||||
}
|
||||
present[i] = true
|
||||
presentCount++
|
||||
maxPresentIdx = i
|
||||
}
|
||||
if presentCount == 0 {
|
||||
fail(fmt.Errorf("volume %d: no EC shards found under %s", volumeId, base))
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve the EC ratio and the original .dat size.
|
||||
// Priority: explicit flags > existing .vif > defaults (10+4).
|
||||
vifName := base + ".vif"
|
||||
vifExists := util.FileExists(vifName)
|
||||
dataShards := erasure_coding.DataShardsCount
|
||||
parityShards := erasure_coding.ParityShardsCount
|
||||
var datFileSize int64
|
||||
if vifExists {
|
||||
// MaybeLoadVolumeInfo returns a non-nil error when the .vif exists but
|
||||
// cannot be read or unmarshalled; fail loudly rather than silently
|
||||
// falling back to defaults (which would be wrong for a custom ratio).
|
||||
if vi, _, found, loadErr := volume_info.MaybeLoadVolumeInfo(vifName); loadErr != nil {
|
||||
fail(fmt.Errorf("volume %d: read %s: %w", volumeId, vifName, loadErr))
|
||||
return
|
||||
} else if found && vi != nil {
|
||||
if cfg := vi.GetEcShardConfig(); cfg != nil && cfg.GetDataShards() > 0 {
|
||||
dataShards = int(cfg.GetDataShards())
|
||||
parityShards = int(cfg.GetParityShards())
|
||||
}
|
||||
datFileSize = vi.GetDatFileSize()
|
||||
}
|
||||
}
|
||||
if *fixEcDataShards > 0 {
|
||||
dataShards = *fixEcDataShards
|
||||
}
|
||||
if *fixEcParityShards > 0 {
|
||||
parityShards = *fixEcParityShards
|
||||
}
|
||||
// Ensure the configured total covers every shard index actually present
|
||||
// (a custom-ratio volume with more than the default 14 shards and no .vif).
|
||||
// This never lowers parity below the default, so the common 10+4 case stays
|
||||
// correct for any subset of missing shards.
|
||||
if maxPresentIdx+1 > dataShards+parityShards {
|
||||
parityShards = maxPresentIdx + 1 - dataShards
|
||||
}
|
||||
if dataShards <= 0 || parityShards <= 0 || dataShards+parityShards > erasure_coding.MaxShardCount {
|
||||
fail(fmt.Errorf("volume %d: cannot determine EC ratio (data=%d parity=%d); set -ecDataShards/-ecParityShards", volumeId, dataShards, parityShards))
|
||||
return
|
||||
}
|
||||
|
||||
// Need at least dataShards shards (any data+parity mix) to recover anything.
|
||||
if presentCount < dataShards {
|
||||
fail(fmt.Errorf("volume %d: only %d shards present, need at least %d (data shards) to recover", volumeId, presentCount, dataShards))
|
||||
return
|
||||
}
|
||||
|
||||
// If any data shard is missing, reconstruct the missing shards from the
|
||||
// survivors via Reed-Solomon before de-striping. This writes the rebuilt
|
||||
// shard files back to disk, fully repairing the volume locally.
|
||||
dataComplete := true
|
||||
for i := 0; i < dataShards; i++ {
|
||||
if !present[i] {
|
||||
dataComplete = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !dataComplete {
|
||||
ctx := &erasure_coding.ECContext{DataShards: dataShards, ParityShards: parityShards}
|
||||
glog.Infof("volume %d: %d/%d shards present; reconstructing missing shards (%s) before index rebuild", volumeId, presentCount, dataShards+parityShards, ctx.String())
|
||||
if _, err := erasure_coding.RebuildEcFilesWithContext(base, ctx); err != nil {
|
||||
fail(fmt.Errorf("volume %d: reconstruct missing shards from %d survivors: %w", volumeId, presentCount, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Collect the data shards (now all present).
|
||||
shardFileNames := make([]string, dataShards)
|
||||
for i := 0; i < dataShards; i++ {
|
||||
shardPath := base + erasure_coding.ToExt(i)
|
||||
if !util.FileExists(shardPath) {
|
||||
fail(fmt.Errorf("volume %d: data shard %s still missing after reconstruction", volumeId, shardPath))
|
||||
return
|
||||
}
|
||||
shardFileNames[i] = shardPath
|
||||
}
|
||||
|
||||
// Without a recorded original size, reconstruct the fully padded layout; the
|
||||
// scan below detects the trailing zero padding and recovers the true size.
|
||||
reconstructSize := datFileSize
|
||||
if reconstructSize <= 0 {
|
||||
reconstructSize = int64(dataShards) * shardSize
|
||||
glog.V(0).Infof("volume %d: no .dat size in .vif; reconstructing padded .dat (%d bytes) from %d data shards", volumeId, reconstructSize, dataShards)
|
||||
}
|
||||
|
||||
// De-stripe the data shards into a temporary .dat next to the shards.
|
||||
tmpBase := base + ".ecxrecover"
|
||||
tmpDat := tmpBase + ".dat"
|
||||
if err := erasure_coding.WriteDatFile(tmpBase, reconstructSize, shardFileNames); err != nil {
|
||||
os.Remove(tmpDat)
|
||||
fail(fmt.Errorf("volume %d: reconstruct .dat from data shards: %w", volumeId, err))
|
||||
return
|
||||
}
|
||||
defer os.Remove(tmpDat)
|
||||
|
||||
realDatSize, version, err := writeEcxFromDat(tmpDat, ecxName)
|
||||
if err != nil {
|
||||
os.Remove(ecxName)
|
||||
fail(fmt.Errorf("volume %d: build .ecx from reconstructed .dat: %w", volumeId, err))
|
||||
return
|
||||
}
|
||||
glog.Infof("volume %d: wrote %s from %d data shards", volumeId, ecxName, dataShards)
|
||||
|
||||
// Regenerate the .vif when missing so the volume can mount and future
|
||||
// rebuilds know the EC ratio and original .dat size.
|
||||
if !vifExists {
|
||||
size := datFileSize
|
||||
if size <= 0 {
|
||||
size = realDatSize
|
||||
}
|
||||
volumeInfo := &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(version),
|
||||
DatFileSize: size,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(dataShards),
|
||||
ParityShards: uint32(parityShards),
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(vifName, volumeInfo); err != nil {
|
||||
fail(fmt.Errorf("volume %d: write %s: %w", volumeId, vifName, err))
|
||||
return
|
||||
}
|
||||
glog.Infof("volume %d: wrote %s (version %d, datFileSize %d, ec %d+%d)", volumeId, vifName, version, size, dataShards, parityShards)
|
||||
}
|
||||
}
|
||||
|
||||
// writeEcxFromDat scans a (reconstructed) .dat and writes an ascending-sorted
|
||||
// .ecx containing only live needles — the same on-disk shape
|
||||
// WriteSortedFileFromIdx produces when an EC volume is first encoded. It returns
|
||||
// the physical .dat size (the offset where the EC zero padding begins) and the
|
||||
// volume version read from the superblock.
|
||||
func writeEcxFromDat(datPath, ecxPath string) (datFileSize int64, version needle.Version, err error) {
|
||||
f, err := os.OpenFile(datPath, os.O_RDONLY, 0644)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("open %s: %w", datPath, err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(f)
|
||||
defer datBackend.Close()
|
||||
|
||||
superBlock, err := super_block.ReadSuperBlock(datBackend)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("read superblock: %w", err)
|
||||
}
|
||||
version = superBlock.Version
|
||||
|
||||
fileSize, _, err := datBackend.GetStat()
|
||||
if err != nil {
|
||||
return 0, version, fmt.Errorf("stat %s: %w", datPath, err)
|
||||
}
|
||||
|
||||
nm := needle_map.NewMemDb()
|
||||
defer nm.Close()
|
||||
|
||||
offset := int64(superBlock.BlockSize())
|
||||
for offset < fileSize {
|
||||
n, _, rest, readErr := needle.ReadNeedleHeader(datBackend, version, offset)
|
||||
if readErr != nil {
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return 0, version, fmt.Errorf("read needle header at offset %d: %w", offset, readErr)
|
||||
}
|
||||
// EC encoding zero-pads the tail of the last block row. An all-zero
|
||||
// header marks the start of that padding, i.e. the end of real needles.
|
||||
if n.Cookie == 0 && n.Id == 0 && n.Size == 0 {
|
||||
break
|
||||
}
|
||||
if n.Size.IsValid() {
|
||||
if pe := nm.Set(n.Id, types.ToOffset(offset), n.Size); pe != nil {
|
||||
return 0, version, fmt.Errorf("set needle %d: %w", n.Id, pe)
|
||||
}
|
||||
} else {
|
||||
// Deleted/invalid: drop it so the .ecx carries only live entries,
|
||||
// matching the encode-time WriteSortedFileFromIdx behavior.
|
||||
if pe := nm.Delete(n.Id); pe != nil {
|
||||
return 0, version, fmt.Errorf("delete needle %d: %w", n.Id, pe)
|
||||
}
|
||||
}
|
||||
offset += types.NeedleHeaderSize + rest
|
||||
}
|
||||
datFileSize = offset
|
||||
|
||||
ecxFile, err := os.OpenFile(ecxPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return 0, version, fmt.Errorf("open %s: %w", ecxPath, err)
|
||||
}
|
||||
defer ecxFile.Close()
|
||||
|
||||
if err := nm.AscendingVisit(func(value needle_map.NeedleValue) error {
|
||||
_, writeErr := ecxFile.Write(value.ToBytes())
|
||||
return writeErr
|
||||
}); err != nil {
|
||||
return 0, version, fmt.Errorf("write %s: %w", ecxPath, err)
|
||||
}
|
||||
|
||||
return datFileSize, version, nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// buildAndEncodeTestEcVolume writes a small volume (.dat + .idx), EC-encodes it
|
||||
// into .ec00..ec13, and produces the canonical sorted .ecx. It returns the base
|
||||
// path, the canonical .ecx bytes, and the original .dat size. A couple of
|
||||
// needles are deleted so the .ecx must exclude them (live entries only).
|
||||
func buildAndEncodeTestEcVolume(t *testing.T, dir, baseName string) (base string, canonicalEcx []byte, origDatSize int64) {
|
||||
t.Helper()
|
||||
base = filepath.Join(dir, baseName)
|
||||
version := needle.GetCurrentVersion()
|
||||
|
||||
df, err := os.OpenFile(base+".dat", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datBackend := backend.NewDiskFile(df)
|
||||
sb := super_block.SuperBlock{
|
||||
Version: version,
|
||||
ReplicaPlacement: &super_block.ReplicaPlacement{},
|
||||
Ttl: &needle.TTL{},
|
||||
}
|
||||
if _, err := datBackend.WriteAt(sb.Bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nm := needle_map.NewMemDb()
|
||||
for i := uint64(1); i <= 12; i++ {
|
||||
n := new(needle.Needle)
|
||||
n.Id = types.Uint64ToNeedleId(i)
|
||||
n.Data = make([]byte, 200+int(i))
|
||||
rand.Read(n.Data)
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
offset, _, _, err := n.Append(datBackend, version)
|
||||
if err != nil {
|
||||
t.Fatalf("append needle %d: %v", i, err)
|
||||
}
|
||||
// Store n.Size (the on-disk header size), exactly what the volume
|
||||
// server records in its .idx (volume_write.go: nm.Put(..., n.Size)).
|
||||
if err := nm.Set(n.Id, types.ToOffset(int64(offset)), n.Size); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Delete ids 3 and 8: append an empty needle (delete record) and drop them
|
||||
// from the index, exactly as the encode-time .ecx would reflect.
|
||||
for _, id := range []uint64{3, 8} {
|
||||
n := new(needle.Needle)
|
||||
n.Id = types.Uint64ToNeedleId(id)
|
||||
if _, _, _, err := n.Append(datBackend, version); err != nil {
|
||||
t.Fatalf("append delete record %d: %v", id, err)
|
||||
}
|
||||
if err := nm.Delete(types.Uint64ToNeedleId(id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := datBackend.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
datInfo, err := df.Stat()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
origDatSize = datInfo.Size()
|
||||
datBackend.Close()
|
||||
|
||||
idxFile, err := os.OpenFile(base+".idx", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := nm.AscendingVisit(func(v needle_map.NeedleValue) error {
|
||||
_, e := idxFile.Write(v.ToBytes())
|
||||
return e
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idxFile.Close()
|
||||
nm.Close()
|
||||
|
||||
if err := erasure_coding.WriteEcFiles(base); err != nil {
|
||||
t.Fatalf("WriteEcFiles: %v", err)
|
||||
}
|
||||
if err := erasure_coding.WriteSortedFileFromIdx(base, ".ecx"); err != nil {
|
||||
t.Fatalf("WriteSortedFileFromIdx: %v", err)
|
||||
}
|
||||
canonicalEcx, err = os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(canonicalEcx) == 0 {
|
||||
t.Fatal("canonical .ecx is empty")
|
||||
}
|
||||
return base, canonicalEcx, origDatSize
|
||||
}
|
||||
|
||||
// TestFixEcxFromShards verifies the .ecx and .vif are rebuilt purely from the
|
||||
// data shards when every index/metadata file has been lost.
|
||||
func TestFixEcxFromShards(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 7
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "7")
|
||||
|
||||
// Disaster: keep only the shards.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat", ".vif"} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "7", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// The reconstructed temporary .dat must not be left behind.
|
||||
if _, err := os.Stat(base + ".ecxrecover.dat"); !os.IsNotExist(err) {
|
||||
t.Fatalf("temporary reconstructed .dat was not cleaned up")
|
||||
}
|
||||
|
||||
// .vif must be regenerated with the default ratio and the original .dat size.
|
||||
vi, _, found, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
|
||||
if err != nil || !found {
|
||||
t.Fatalf(".vif not regenerated: found=%v err=%v", found, err)
|
||||
}
|
||||
if got := int(vi.GetEcShardConfig().GetDataShards()); got != erasure_coding.DataShardsCount {
|
||||
t.Fatalf("data shards = %d, want %d", got, erasure_coding.DataShardsCount)
|
||||
}
|
||||
if got := int(vi.GetEcShardConfig().GetParityShards()); got != erasure_coding.ParityShardsCount {
|
||||
t.Fatalf("parity shards = %d, want %d", got, erasure_coding.ParityShardsCount)
|
||||
}
|
||||
if vi.GetDatFileSize() != origDatSize {
|
||||
t.Fatalf("dat size = %d, want %d", vi.GetDatFileSize(), origDatSize)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFixEcxFromShardsWithVif verifies that when the .vif survives (recording
|
||||
// the exact .dat size and EC ratio) the .ecx is rebuilt from it and the .vif is
|
||||
// left untouched.
|
||||
func TestFixEcxFromShardsWithVif(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 9
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "9")
|
||||
|
||||
// Write a .vif as the volume server would after encoding.
|
||||
if err := volume_info.SaveVolumeInfo(base+".vif", &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(needle.GetCurrentVersion()),
|
||||
DatFileSize: origDatSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(erasure_coding.DataShardsCount),
|
||||
ParityShards: uint32(erasure_coding.ParityShardsCount),
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vifBefore, err := os.ReadFile(base + ".vif")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Lose the index but keep the surviving .vif and shards.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat"} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "9", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// An existing .vif must be left untouched.
|
||||
vifAfter, err := os.ReadFile(base + ".vif")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(vifBefore, vifAfter) {
|
||||
t.Fatalf("existing .vif was modified")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFixEcxFromShardsMissingShards verifies that when some shards (including a
|
||||
// couple of data shards) are lost but at least dataShards survive, the missing
|
||||
// shards are reconstructed from parity and the .ecx is still rebuilt correctly.
|
||||
func TestFixEcxFromShardsMissingShards(t *testing.T) {
|
||||
oldData, oldParity := *fixEcDataShards, *fixEcParityShards
|
||||
*fixEcDataShards, *fixEcParityShards = 0, 0
|
||||
*fixIgnoreError = true
|
||||
t.Cleanup(func() {
|
||||
*fixIgnoreError = false
|
||||
*fixEcDataShards, *fixEcParityShards = oldData, oldParity
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
const volumeId = 11
|
||||
base, canonical, origDatSize := buildAndEncodeTestEcVolume(t, dir, "11")
|
||||
|
||||
// Lose every index/metadata file plus three shards (two data: .ec02, .ec05;
|
||||
// one parity: .ec11), keeping 11 of 14 — enough to reconstruct. The highest
|
||||
// shard (.ec13) is kept so the default 10+4 ratio is inferred without a .vif.
|
||||
for _, ext := range []string{".ecx", ".ecj", ".idx", ".dat", ".vif",
|
||||
erasure_coding.ToExt(2), erasure_coding.ToExt(5), erasure_coding.ToExt(11)} {
|
||||
if err := os.Remove(base + ext); err != nil && !os.IsNotExist(err) {
|
||||
t.Fatalf("remove %s: %v", base+ext, err)
|
||||
}
|
||||
}
|
||||
|
||||
doFixEcxFromShards(dir, "11", "", volumeId)
|
||||
|
||||
recovered, err := os.ReadFile(base + ".ecx")
|
||||
if err != nil {
|
||||
t.Fatalf("recovered .ecx not written: %v", err)
|
||||
}
|
||||
if !bytes.Equal(canonical, recovered) {
|
||||
t.Fatalf(".ecx mismatch: canonical %d bytes, recovered %d bytes", len(canonical), len(recovered))
|
||||
}
|
||||
|
||||
// The missing shards must have been reconstructed on disk.
|
||||
for _, idx := range []int{2, 5, 11} {
|
||||
if info, err := os.Stat(base + erasure_coding.ToExt(idx)); err != nil || info.Size() == 0 {
|
||||
t.Fatalf("missing shard %d was not reconstructed: err=%v", idx, err)
|
||||
}
|
||||
}
|
||||
|
||||
vi, _, found, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
|
||||
if err != nil || !found {
|
||||
t.Fatalf(".vif not regenerated: found=%v err=%v", found, err)
|
||||
}
|
||||
if vi.GetDatFileSize() != origDatSize {
|
||||
t.Fatalf("dat size = %d, want %d", vi.GetDatFileSize(), origDatSize)
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,6 @@ type miniProgress struct {
|
||||
elapsed map[string]time.Duration
|
||||
isTTY bool
|
||||
rendered bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
const miniProgressNameWidth = 12
|
||||
@@ -141,7 +140,6 @@ func (p *miniProgress) update(name, state string) {
|
||||
func (p *miniProgress) starting(name string) { p.update(name, "starting") }
|
||||
func (p *miniProgress) ready(name string) { p.update(name, "ready") }
|
||||
func (p *miniProgress) failed(name string) { p.update(name, "failed") }
|
||||
func (p *miniProgress) stopping(name string) { p.update(name, "stopping") }
|
||||
func (p *miniProgress) stopped(name string) { p.update(name, "stopped") }
|
||||
|
||||
// renderLocked redraws every row in the board. Caller must hold p.mu and
|
||||
@@ -149,9 +147,6 @@ func (p *miniProgress) stopped(name string) { p.update(name, "stopped") }
|
||||
// ESC[2K clears the line — leaving the cursor parked one line below the last
|
||||
// row so the next print (welcome banner, shutdown messages) flows naturally.
|
||||
func (p *miniProgress) renderLocked() {
|
||||
if p.closed {
|
||||
return
|
||||
}
|
||||
if p.rendered {
|
||||
fmt.Printf("\033[%dA", len(p.order))
|
||||
}
|
||||
@@ -194,14 +189,6 @@ func (p *miniProgress) reset(services []string, initialState string) {
|
||||
}
|
||||
}
|
||||
|
||||
// close prevents further redraws (e.g. before a Fatalf so the panic doesn't
|
||||
// repaint the board). Safe to call multiple times.
|
||||
func (p *miniProgress) close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.closed = true
|
||||
}
|
||||
|
||||
// reportMiniStopped marks a service as fully stopped on the progress board.
|
||||
// Safe to call when the board is nil (mini not running) — used from defers
|
||||
// in service goroutines so a normal exit (Ctrl+C, ctx cancel) flips the row.
|
||||
@@ -266,21 +253,6 @@ func resetMiniClients() {
|
||||
miniClients = s
|
||||
}
|
||||
|
||||
// onMiniClientsShutdown runs fn when mini shutdown is triggered, and tracks
|
||||
// it so the interrupt hook can wait for it to drain. No-op outside mini.
|
||||
func onMiniClientsShutdown(fn func()) {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
defer s.wg.Done()
|
||||
<-s.ctx.Done()
|
||||
fn()
|
||||
}()
|
||||
}
|
||||
|
||||
// trackMiniClient registers an externally-managed goroutine (one that
|
||||
// observes miniClientsCtx() itself) so the interrupt hook waits for it.
|
||||
// The caller invokes the returned done func when the goroutine exits.
|
||||
|
||||
@@ -34,6 +34,16 @@ func (store *MemoryStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3ApiC
|
||||
})
|
||||
}
|
||||
|
||||
// Groups are written via CreateGroup / AddUserToGroup / AttachGroupPolicy
|
||||
// (never via SaveConfiguration), so they live in store.groups regardless
|
||||
// of the bulk-config path. Surface them here so consumers that reload
|
||||
// through cm.LoadConfiguration see a faithful snapshot — without this,
|
||||
// iam.groups would never repopulate on memory-store reloads and group
|
||||
// policy evaluation would silently no-op.
|
||||
for _, g := range store.groups {
|
||||
config.Groups = append(config.Groups, cloneGroup(g))
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ type Attr struct {
|
||||
Mtime time.Time // time of last modification
|
||||
Crtime time.Time // time of creation (OS X only)
|
||||
Ctime time.Time // time of last inode change
|
||||
Atime time.Time // time of last access
|
||||
Mode os.FileMode // file mode
|
||||
Uid uint32 // owner uid
|
||||
Gid uint32 // group gid
|
||||
|
||||
@@ -85,6 +85,8 @@ func EntryAttributeToPb(entry *Entry) *filer_pb.FuseAttributes {
|
||||
MtimeNs: int32(entry.Attr.Mtime.Nanosecond()),
|
||||
Ctime: entry.Attr.Ctime.Unix(),
|
||||
CtimeNs: int32(entry.Attr.Ctime.Nanosecond()),
|
||||
Atime: atimeSecondsForPb(entry.Attr),
|
||||
AtimeNs: atimeNanosForPb(entry.Attr),
|
||||
FileMode: uint32(entry.Attr.Mode),
|
||||
Uid: entry.Uid,
|
||||
Gid: entry.Gid,
|
||||
@@ -100,6 +102,20 @@ func EntryAttributeToPb(entry *Entry) *filer_pb.FuseAttributes {
|
||||
}
|
||||
}
|
||||
|
||||
func atimeSecondsForPb(attr Attr) int64 {
|
||||
if attr.Atime.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return attr.Atime.Unix()
|
||||
}
|
||||
|
||||
func atimeNanosForPb(attr Attr) int32 {
|
||||
if attr.Atime.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return int32(attr.Atime.Nanosecond())
|
||||
}
|
||||
|
||||
// EntryAttributeToExistingPb fills an existing FuseAttributes to avoid allocation.
|
||||
// Safe to call with nil attr (will return early without populating).
|
||||
func EntryAttributeToExistingPb(entry *Entry, attr *filer_pb.FuseAttributes) {
|
||||
@@ -111,6 +127,8 @@ func EntryAttributeToExistingPb(entry *Entry, attr *filer_pb.FuseAttributes) {
|
||||
attr.MtimeNs = int32(entry.Attr.Mtime.Nanosecond())
|
||||
attr.Ctime = entry.Attr.Ctime.Unix()
|
||||
attr.CtimeNs = int32(entry.Attr.Ctime.Nanosecond())
|
||||
attr.Atime = atimeSecondsForPb(entry.Attr)
|
||||
attr.AtimeNs = atimeNanosForPb(entry.Attr)
|
||||
attr.FileMode = uint32(entry.Attr.Mode)
|
||||
attr.Uid = entry.Uid
|
||||
attr.Gid = entry.Gid
|
||||
@@ -140,6 +158,11 @@ func PbToEntryAttribute(attr *filer_pb.FuseAttributes) Attr {
|
||||
} else {
|
||||
t.Ctime = t.Mtime
|
||||
}
|
||||
if attr.Atime != 0 || attr.AtimeNs != 0 {
|
||||
t.Atime = time.Unix(attr.Atime, int64(attr.AtimeNs))
|
||||
} else {
|
||||
t.Atime = t.Mtime
|
||||
}
|
||||
t.Mode = os.FileMode(attr.FileMode)
|
||||
t.Uid = attr.Uid
|
||||
t.Gid = attr.Gid
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestEntryCodec_AtimeRoundTrip(t *testing.T) {
|
||||
mtime := time.Unix(1_700_000_000, 123_456_789)
|
||||
atime := time.Unix(1_700_001_000, 987_654_321)
|
||||
|
||||
source := &Entry{
|
||||
FullPath: util.FullPath("/bucket/object"),
|
||||
Attr: Attr{
|
||||
Mtime: mtime,
|
||||
Ctime: mtime,
|
||||
Atime: atime,
|
||||
},
|
||||
}
|
||||
pb := EntryAttributeToPb(source)
|
||||
if pb.Atime != atime.Unix() {
|
||||
t.Fatalf("expected proto atime %d, got %d", atime.Unix(), pb.Atime)
|
||||
}
|
||||
if pb.AtimeNs != int32(atime.Nanosecond()) {
|
||||
t.Fatalf("expected proto atime_ns %d, got %d", atime.Nanosecond(), pb.AtimeNs)
|
||||
}
|
||||
|
||||
decoded := PbToEntryAttribute(pb)
|
||||
if !decoded.Atime.Equal(atime) {
|
||||
t.Fatalf("expected decoded atime %v, got %v", atime, decoded.Atime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEntryCodec_AtimeZeroFallsBackToMtime(t *testing.T) {
|
||||
mtime := time.Unix(1_700_000_000, 0)
|
||||
pb := &filer_pb.FuseAttributes{
|
||||
Mtime: mtime.Unix(),
|
||||
MtimeNs: int32(mtime.Nanosecond()),
|
||||
}
|
||||
decoded := PbToEntryAttribute(pb)
|
||||
if !decoded.Atime.Equal(mtime) {
|
||||
t.Fatalf("expected atime to fall back to mtime %v, got %v", mtime, decoded.Atime)
|
||||
}
|
||||
}
|
||||
|
||||
// Atime in the first second of the unix epoch encodes as Atime=0 with
|
||||
// AtimeNs>0; the decode path must treat that as a valid timestamp rather than
|
||||
// falling back to Mtime.
|
||||
func TestEntryCodec_AtimeSubSecondEpochPreserved(t *testing.T) {
|
||||
mtime := time.Unix(1_700_000_000, 0)
|
||||
pb := &filer_pb.FuseAttributes{
|
||||
Mtime: mtime.Unix(),
|
||||
MtimeNs: int32(mtime.Nanosecond()),
|
||||
Atime: 0,
|
||||
AtimeNs: 500_000,
|
||||
}
|
||||
decoded := PbToEntryAttribute(pb)
|
||||
want := time.Unix(0, 500_000)
|
||||
if !decoded.Atime.Equal(want) {
|
||||
t.Fatalf("expected sub-second-epoch atime %v, got %v", want, decoded.Atime)
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,10 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFr
|
||||
entry.Attr.TtlSec = 0
|
||||
}
|
||||
|
||||
if entry.Attr.Atime.IsZero() {
|
||||
entry.Attr.Atime = entryInitialAtime(entry.Attr)
|
||||
}
|
||||
|
||||
oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
|
||||
|
||||
/*
|
||||
@@ -371,9 +375,19 @@ func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err er
|
||||
return fmt.Errorf("%s: %w", oldEntry.FullPath, filer_pb.ErrExistingIsFile)
|
||||
}
|
||||
}
|
||||
if entry.Attr.Atime.IsZero() {
|
||||
entry.Attr.Atime = entryInitialAtime(entry.Attr)
|
||||
}
|
||||
return f.Store.UpdateEntry(ctx, entry)
|
||||
}
|
||||
|
||||
func entryInitialAtime(attr Attr) time.Time {
|
||||
if !attr.Mtime.IsZero() {
|
||||
return attr.Mtime
|
||||
}
|
||||
return attr.Crtime
|
||||
}
|
||||
|
||||
var (
|
||||
Root = &Entry{
|
||||
FullPath: "/",
|
||||
|
||||
@@ -33,6 +33,8 @@ func (store *MysqlStore) GetName() string {
|
||||
}
|
||||
|
||||
func (store *MysqlStore) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"dsn"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -33,6 +33,8 @@ func (store *MysqlStore2) GetName() string {
|
||||
}
|
||||
|
||||
func (store *MysqlStore2) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"createTable"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -28,6 +28,8 @@ func (store *PostgresStore) GetName() string {
|
||||
}
|
||||
|
||||
func (store *PostgresStore) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
configuration.GetBool(prefix+"enableUpsert"),
|
||||
|
||||
@@ -33,6 +33,8 @@ func (store *PostgresStore2) GetName() string {
|
||||
}
|
||||
|
||||
func (store *PostgresStore2) Initialize(configuration util.Configuration, prefix string) (err error) {
|
||||
// Absent key keeps a pooled default; an explicit 0 disables the idle pool.
|
||||
configuration.SetDefault(prefix+"connection_max_idle", 2)
|
||||
return store.initialize(
|
||||
configuration.GetString(prefix+"createTable"),
|
||||
configuration.GetString(prefix+"upsertQuery"),
|
||||
|
||||
@@ -127,7 +127,7 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
// collect names before name, add them to X
|
||||
namesToX, err := nl.NodeRangeBeforeExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// delete skiplist reference to old node
|
||||
if _, err := nl.skipList.DeleteByKey(prevNodeReference.Key); err != nil {
|
||||
@@ -136,32 +136,32 @@ func (nl *ItemList) WriteName(name string) error {
|
||||
// add namesToY and name to a new X
|
||||
namesToX = append(namesToX, name)
|
||||
if err := nl.ItemAdd([]byte(namesToX[0]), 0, namesToX...); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// remove names less than name from current Y
|
||||
if err := nl.NodeDeleteBeforeExclusive(prevNodeReference, name); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
// point skip list to current Y
|
||||
if err := nl.ItemAdd(lookupKey, prevNodeReference.ElementPointer); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
// collect names after name, add them to Y
|
||||
namesToY, err := nl.NodeRangeAfterExclusive(prevNodeReference, name)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// add namesToY and name to a new Y
|
||||
namesToY = append(namesToY, name)
|
||||
if err := nl.ItemAdd(lookupKey, 0, namesToY...); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
// remove names after name from current X
|
||||
if err := nl.NodeDeleteAfterExclusive(prevNodeReference, name); err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -494,3 +494,26 @@ type ListGroupsForUserResponse struct {
|
||||
} `xml:"ListGroupsForUserResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// TagUserResponse is the response for TagUser action.
|
||||
type TagUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ TagUserResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// UntagUserResponse is the response for UntagUser action.
|
||||
type UntagUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ UntagUserResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// ListUserTagsResponse is the response for ListUserTags action.
|
||||
type ListUserTagsResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ ListUserTagsResponse"`
|
||||
ListUserTagsResult struct {
|
||||
Tags []*IAMTag `xml:"Tags>member"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
Marker string `xml:"Marker,omitempty"`
|
||||
} `xml:"ListUserTagsResult"`
|
||||
CommonResponse
|
||||
}
|
||||
@@ -66,31 +66,6 @@ func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *fil
|
||||
return fh
|
||||
}
|
||||
|
||||
func (i *FileHandleToInode) ReleaseByInode(inode uint64) *FileHandle {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
fh, found := i.inode2fh[inode]
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
// If the counter is already <= 0, a prior Release already started the
|
||||
// drain. Return nil to prevent double-processing (e.g. Forget after Release).
|
||||
if fh.counter <= 0 {
|
||||
return nil
|
||||
}
|
||||
fh.counter--
|
||||
if fh.counter <= 0 {
|
||||
if fh.asyncFlushPending {
|
||||
// Handle stays in fhMap so rename/unlink can find it during drain.
|
||||
return fh
|
||||
}
|
||||
delete(i.inode2fh, inode)
|
||||
delete(i.fh2inode, fh.fh)
|
||||
return fh
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
|
||||
@@ -63,13 +63,11 @@ Side effects: increments the lookup count on success
|
||||
|
||||
*/
|
||||
func (wfs *WFS) Forget(nodeid, nlookup uint64) {
|
||||
// Forget only decrements the kernel's inode lookup count. File handle
|
||||
// lifecycle is driven independently by FUSE Open/Release — touching the
|
||||
// fhMap here would couple two unrelated refcounts and could tear down a
|
||||
// still-live handle if Forget ever raced ahead of Release.
|
||||
wfs.inodeToPath.Forget(nodeid, nlookup, func(dir util.FullPath) {
|
||||
wfs.metaCache.DeleteFolderChildren(context.Background(), dir)
|
||||
})
|
||||
// ReleaseByInode returns nil if the handle is already draining (counter
|
||||
// was already <= 0 from a prior Release). Only non-async handles that
|
||||
// reach counter 0 here need cleanup.
|
||||
if fhToRelease := wfs.fhMap.ReleaseByInode(nodeid); fhToRelease != nil {
|
||||
fhToRelease.ReleaseHandle()
|
||||
}
|
||||
}
|
||||
@@ -104,25 +104,36 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
||||
|
||||
glog.V(4).Infof("flushFileMetadata %s fh %d", fileFullPath, fh.fh)
|
||||
|
||||
entry := fh.GetEntry()
|
||||
if entry == nil {
|
||||
if fh.GetEntry() == nil {
|
||||
return nil
|
||||
}
|
||||
entry.Name = name
|
||||
|
||||
// Do not stamp mtime/ctime here. Write/SetAttr already maintain
|
||||
// them on the entry; overwriting at periodic-flush time clobbered
|
||||
// user-set mtime (utimes/touch -m -d) once the timer fired.
|
||||
// Snapshot the current chunk list. Async uploader goroutines call
|
||||
// entry.AppendChunks while we run CompactFileChunks / MaybeManifestize
|
||||
// below — those steps can take seconds (manifest upload is a round trip).
|
||||
// We must remember the snapshot length so we can splice any chunks that
|
||||
// land after the snapshot back in once we reassign entry.Chunks; without
|
||||
// that, the naked overwrite below clobbers them and the file ends up
|
||||
// missing chunk references for data the volumes already store.
|
||||
var snapshotChunks []*filer_pb.FileChunk
|
||||
var snapshotLen int
|
||||
fh.UpdateEntry(func(e *filer_pb.Entry) {
|
||||
// Do not stamp mtime/ctime here. Write/SetAttr already maintain
|
||||
// them on the entry; overwriting at periodic-flush time clobbered
|
||||
// user-set mtime (utimes/touch -m -d) once the timer fired.
|
||||
e.Name = name
|
||||
snapshotLen = len(e.Chunks)
|
||||
if snapshotLen > 0 {
|
||||
snapshotChunks = append([]*filer_pb.FileChunk(nil), e.Chunks...)
|
||||
}
|
||||
})
|
||||
|
||||
// Get current chunks - these include chunks that have been uploaded
|
||||
// but not yet persisted to filer metadata
|
||||
chunks := entry.GetChunks()
|
||||
if len(chunks) == 0 {
|
||||
if snapshotLen == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Separate manifest and non-manifest chunks
|
||||
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(chunks)
|
||||
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(snapshotChunks)
|
||||
|
||||
// Compact chunks to remove fully overlapped ones
|
||||
compactedChunks, _ := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
|
||||
@@ -133,11 +144,24 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
||||
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
|
||||
}
|
||||
|
||||
entry.Chunks = append(compactedChunks, manifestChunks...)
|
||||
processedPrefix := append(compactedChunks, manifestChunks...)
|
||||
|
||||
// Clone the proto entry so mapPbIdFromLocalToFiler does not mutate the
|
||||
// file handle's live entry (same race as in flushMetadataToFiler).
|
||||
requestEntry := proto.Clone(entry.GetEntry()).(*filer_pb.Entry)
|
||||
// Splice the processed snapshot back in, preserving any chunks that
|
||||
// async uploaders appended after our snapshot, and clone the resulting
|
||||
// entry for the filer request while still holding the lock so the
|
||||
// request can't observe a half-merged state.
|
||||
var requestEntry *filer_pb.Entry
|
||||
fh.UpdateEntry(func(e *filer_pb.Entry) {
|
||||
// e.Chunks[snapshotLen:] is whatever async uploaders appended while
|
||||
// we processed the snapshot. processedPrefix is freshly built and not
|
||||
// referenced elsewhere, so we can append straight onto it.
|
||||
var tail []*filer_pb.FileChunk
|
||||
if len(e.Chunks) > snapshotLen {
|
||||
tail = e.Chunks[snapshotLen:]
|
||||
}
|
||||
e.Chunks = append(processedPrefix, tail...)
|
||||
requestEntry = proto.Clone(e).(*filer_pb.Entry)
|
||||
})
|
||||
request := &filer_pb.CreateEntryRequest{
|
||||
Directory: string(dir),
|
||||
Entry: requestEntry,
|
||||
@@ -161,7 +185,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
||||
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(dir))
|
||||
}
|
||||
|
||||
glog.V(3).Infof("flushed metadata for %s with %d chunks", fileFullPath, len(entry.GetChunks()))
|
||||
glog.V(3).Infof("flushed metadata for %s with %d chunks", fileFullPath, len(requestEntry.GetChunks()))
|
||||
|
||||
// Note: We do NOT clear dirtyMetadata here because:
|
||||
// 1. There may still be dirty pages in the write buffer
|
||||
|
||||
@@ -22,6 +22,9 @@ service SeaweedFiler {
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {
|
||||
}
|
||||
|
||||
rpc TouchAccessTime (TouchAccessTimeRequest) returns (TouchAccessTimeResponse) {
|
||||
}
|
||||
|
||||
rpc AppendToEntry (AppendToEntryRequest) returns (AppendToEntryResponse) {
|
||||
}
|
||||
|
||||
@@ -208,6 +211,8 @@ message FuseAttributes {
|
||||
int32 mtime_ns = 19; // nanosecond component of mtime (0-999999999)
|
||||
int32 ctime_ns = 20; // nanosecond component of ctime (0-999999999)
|
||||
int32 crtime_ns = 21; // nanosecond component of crtime (0-999999999)
|
||||
int64 atime = 22; // unix time in seconds, last access time
|
||||
int32 atime_ns = 23; // nanosecond component of atime (0-999999999)
|
||||
}
|
||||
|
||||
message CreateEntryRequest {
|
||||
@@ -247,6 +252,16 @@ message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
}
|
||||
|
||||
message TouchAccessTimeRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
int64 client_atime_ns = 3; // nanoseconds since epoch; filer may override with relatime
|
||||
}
|
||||
message TouchAccessTimeResponse {
|
||||
int64 persisted_atime_ns = 1; // nanoseconds since epoch; 0 if no update was performed
|
||||
bool updated = 2;
|
||||
}
|
||||
|
||||
message AppendToEntryRequest {
|
||||
string directory = 1;
|
||||
string entry_name = 2;
|
||||
@@ -406,6 +421,7 @@ message SubscribeMetadataRequest {
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
bool client_supports_idle_heartbeat = 13; // server may send empty responses carrying the current time while the client is caught up
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
|
||||
+490
-339
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.33.4
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.34.1
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
SeaweedFiler_ListEntries_FullMethodName = "/filer_pb.SeaweedFiler/ListEntries"
|
||||
SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry"
|
||||
SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry"
|
||||
SeaweedFiler_TouchAccessTime_FullMethodName = "/filer_pb.SeaweedFiler/TouchAccessTime"
|
||||
SeaweedFiler_AppendToEntry_FullMethodName = "/filer_pb.SeaweedFiler/AppendToEntry"
|
||||
SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry"
|
||||
SeaweedFiler_AtomicRenameEntry_FullMethodName = "/filer_pb.SeaweedFiler/AtomicRenameEntry"
|
||||
@@ -58,6 +59,7 @@ type SeaweedFilerClient interface {
|
||||
ListEntries(ctx context.Context, in *ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ListEntriesResponse], error)
|
||||
CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error)
|
||||
UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error)
|
||||
TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(ctx context.Context, in *AppendToEntryRequest, opts ...grpc.CallOption) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error)
|
||||
AtomicRenameEntry(ctx context.Context, in *AtomicRenameEntryRequest, opts ...grpc.CallOption) (*AtomicRenameEntryResponse, error)
|
||||
@@ -145,6 +147,16 @@ func (c *seaweedFilerClient) UpdateEntry(ctx context.Context, in *UpdateEntryReq
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) TouchAccessTime(ctx context.Context, in *TouchAccessTimeRequest, opts ...grpc.CallOption) (*TouchAccessTimeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(TouchAccessTimeResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_TouchAccessTime_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) AppendToEntry(ctx context.Context, in *AppendToEntryRequest, opts ...grpc.CallOption) (*AppendToEntryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AppendToEntryResponse)
|
||||
@@ -442,6 +454,7 @@ type SeaweedFilerServer interface {
|
||||
ListEntries(*ListEntriesRequest, grpc.ServerStreamingServer[ListEntriesResponse]) error
|
||||
CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error)
|
||||
UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error)
|
||||
TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error)
|
||||
AppendToEntry(context.Context, *AppendToEntryRequest) (*AppendToEntryResponse, error)
|
||||
DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error)
|
||||
AtomicRenameEntry(context.Context, *AtomicRenameEntryRequest) (*AtomicRenameEntryResponse, error)
|
||||
@@ -481,91 +494,94 @@ type SeaweedFilerServer interface {
|
||||
type UnimplementedSeaweedFilerServer struct{}
|
||||
|
||||
func (UnimplementedSeaweedFilerServer) LookupDirectoryEntry(context.Context, *LookupDirectoryEntryRequest) (*LookupDirectoryEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method LookupDirectoryEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method LookupDirectoryEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) ListEntries(*ListEntriesRequest, grpc.ServerStreamingServer[ListEntriesResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method ListEntries not implemented")
|
||||
return status.Error(codes.Unimplemented, "method ListEntries not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CreateEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method CreateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method UpdateEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) TouchAccessTime(context.Context, *TouchAccessTimeRequest) (*TouchAccessTimeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TouchAccessTime not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) AppendToEntry(context.Context, *AppendToEntryRequest) (*AppendToEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method AppendToEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method AppendToEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DeleteEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) AtomicRenameEntry(context.Context, *AtomicRenameEntryRequest) (*AtomicRenameEntryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method AtomicRenameEntry not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method AtomicRenameEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) StreamRenameEntry(*StreamRenameEntryRequest, grpc.ServerStreamingServer[StreamRenameEntryResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method StreamRenameEntry not implemented")
|
||||
return status.Error(codes.Unimplemented, "method StreamRenameEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) StreamMutateEntry(grpc.BidiStreamingServer[StreamMutateEntryRequest, StreamMutateEntryResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method StreamMutateEntry not implemented")
|
||||
return status.Error(codes.Unimplemented, "method StreamMutateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method AssignVolume not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method AssignVolume not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method LookupVolume not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method LookupVolume not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) CollectionList(context.Context, *CollectionListRequest) (*CollectionListResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CollectionList not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method CollectionList not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) DeleteCollection(context.Context, *DeleteCollectionRequest) (*DeleteCollectionResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) Statistics(context.Context, *StatisticsRequest) (*StatisticsResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Statistics not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method Statistics not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) GetFilerConfiguration(context.Context, *GetFilerConfigurationRequest) (*GetFilerConfigurationResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetFilerConfiguration not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method GetFilerConfiguration not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) TraverseBfsMetadata(*TraverseBfsMetadataRequest, grpc.ServerStreamingServer[TraverseBfsMetadataResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method TraverseBfsMetadata not implemented")
|
||||
return status.Error(codes.Unimplemented, "method TraverseBfsMetadata not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) SubscribeMetadata(*SubscribeMetadataRequest, grpc.ServerStreamingServer[SubscribeMetadataResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeMetadata not implemented")
|
||||
return status.Error(codes.Unimplemented, "method SubscribeMetadata not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) SubscribeLocalMetadata(*SubscribeMetadataRequest, grpc.ServerStreamingServer[SubscribeMetadataResponse]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeLocalMetadata not implemented")
|
||||
return status.Error(codes.Unimplemented, "method SubscribeLocalMetadata not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) KvGet(context.Context, *KvGetRequest) (*KvGetResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method KvGet not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method KvGet not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) KvPut(context.Context, *KvPutRequest) (*KvPutResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method KvPut not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method KvPut not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) CacheRemoteObjectToLocalCluster(context.Context, *CacheRemoteObjectToLocalClusterRequest) (*CacheRemoteObjectToLocalClusterResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CacheRemoteObjectToLocalCluster not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method CacheRemoteObjectToLocalCluster not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) DistributedLock(context.Context, *LockRequest) (*LockResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DistributedLock not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method DistributedLock not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) DistributedUnlock(context.Context, *UnlockRequest) (*UnlockResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DistributedUnlock not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method DistributedUnlock not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) FindLockOwner(context.Context, *FindLockOwnerRequest) (*FindLockOwnerResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method FindLockOwner not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method FindLockOwner not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) TransferLocks(context.Context, *TransferLocksRequest) (*TransferLocksResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method TransferLocks not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method TransferLocks not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) ReplicateLock(context.Context, *ReplicateLockRequest) (*ReplicateLockResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReplicateLock not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method ReplicateLock not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) MountRegister(context.Context, *MountRegisterRequest) (*MountRegisterResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method MountRegister not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method MountRegister not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) MountList(context.Context, *MountListRequest) (*MountListResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method MountList not implemented")
|
||||
return nil, status.Error(codes.Unimplemented, "method MountList not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) mustEmbedUnimplementedSeaweedFilerServer() {}
|
||||
func (UnimplementedSeaweedFilerServer) testEmbeddedByValue() {}
|
||||
@@ -578,7 +594,7 @@ type UnsafeSeaweedFilerServer interface {
|
||||
}
|
||||
|
||||
func RegisterSeaweedFilerServer(s grpc.ServiceRegistrar, srv SeaweedFilerServer) {
|
||||
// If the following call pancis, it indicates UnimplementedSeaweedFilerServer was
|
||||
// If the following call panics, it indicates UnimplementedSeaweedFilerServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
@@ -653,6 +669,24 @@ func _SeaweedFiler_UpdateEntry_Handler(srv interface{}, ctx context.Context, dec
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_TouchAccessTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(TouchAccessTimeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).TouchAccessTime(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_TouchAccessTime_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).TouchAccessTime(ctx, req.(*TouchAccessTimeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_AppendToEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AppendToEntryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1083,6 +1117,10 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "UpdateEntry",
|
||||
Handler: _SeaweedFiler_UpdateEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "TouchAccessTime",
|
||||
Handler: _SeaweedFiler_TouchAccessTime_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "AppendToEntry",
|
||||
Handler: _SeaweedFiler_AppendToEntry_Handler,
|
||||
|
||||
@@ -38,6 +38,12 @@ type MetadataFollowOption struct {
|
||||
// the server sends log file chunk fids instead of streaming events,
|
||||
// and the client reads directly from volume servers.
|
||||
LogFileReaderFn LogFileReaderFn
|
||||
// OnIdleHeartbeat, when non-nil, opts in to idle heartbeats: while the
|
||||
// subscriber is caught up the server periodically sends an empty response
|
||||
// carrying the current time, and this is called with that timestamp. It is
|
||||
// a freshness signal only and does not advance StartTsNs, so the resume
|
||||
// checkpoint stays on the last real event.
|
||||
OnIdleHeartbeat func(tsNs int64)
|
||||
}
|
||||
|
||||
type ProcessMetadataFunc func(resp *filer_pb.SubscribeMetadataResponse) error
|
||||
@@ -77,6 +83,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
UntilNs: option.StopTsNs,
|
||||
ClientSupportsBatching: true,
|
||||
ClientSupportsMetadataChunks: option.LogFileReaderFn != nil,
|
||||
ClientSupportsIdleHeartbeat: option.OnIdleHeartbeat != nil,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe: %w", err)
|
||||
@@ -138,6 +145,17 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
pendingRefs = nil
|
||||
}
|
||||
|
||||
// Idle heartbeat: the source is caught up and has no new events, so
|
||||
// it sends an empty response carrying the current time. Surface it as
|
||||
// a freshness signal but leave option.StartTsNs untouched so a restart
|
||||
// still resumes from the last real event.
|
||||
if resp.EventNotification == nil && len(resp.Events) == 0 && resp.TsNs > 0 {
|
||||
if option.OnIdleHeartbeat != nil {
|
||||
option.OnIdleHeartbeat(resp.TsNs)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Process the first event (always present in top-level fields)
|
||||
if resp.EventNotification != nil {
|
||||
if err := processEventFn(resp); err != nil {
|
||||
|
||||
@@ -187,6 +187,12 @@ message Identity {
|
||||
repeated string service_account_ids = 6; // IDs of service accounts owned by this user
|
||||
repeated string policy_names = 7;
|
||||
bool is_static = 8; // Loaded from static config file (read-only, not editable via API)
|
||||
repeated UserTag tags = 9;
|
||||
}
|
||||
|
||||
message UserTag {
|
||||
string key = 1;
|
||||
string value = 2;
|
||||
}
|
||||
|
||||
message Credential {
|
||||
|
||||
+259
-193
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,111 @@
|
||||
package master_pb
|
||||
|
||||
import "sort"
|
||||
|
||||
func (v *VolumeLocation) IsEmptyUrl() bool {
|
||||
return v.Url == "" || v.Url == ":0"
|
||||
}
|
||||
|
||||
// SplitByPhysicalDisk returns one DiskInfo per physical disk_id observed in
|
||||
// VolumeInfos / EcShardInfos. The wire format keys DataNodeInfo.DiskInfos by
|
||||
// disk type, so multiple same-type physical disks on one DataNode collapse
|
||||
// into a single DiskInfo entry. Per-volume and per-shard records carry the
|
||||
// real physical DiskId; this helper rebuilds a per-physical-disk view from
|
||||
// those records so consumers (topology indexes, shell output) can target
|
||||
// individual disks instead of treating each node as one big disk.
|
||||
//
|
||||
// ActiveVolumeCount and RemoteVolumeCount are computed exactly from each
|
||||
// disk's VolumeInfos (read-only and remote-backed are known per-volume).
|
||||
// MaxVolumeCount and FreeVolumeCount are not derivable from per-volume
|
||||
// records, so they are split across reconstructed disks with the remainder
|
||||
// distributed to the lowest disk ids — the sums are preserved exactly.
|
||||
func (d *DiskInfo) SplitByPhysicalDisk() []*DiskInfo {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
normalize := func(id uint32) uint32 {
|
||||
if id == 0 && d.DiskId != 0 {
|
||||
return d.DiskId
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
diskIDs := make(map[uint32]struct{})
|
||||
for _, vi := range d.VolumeInfos {
|
||||
diskIDs[normalize(vi.DiskId)] = struct{}{}
|
||||
}
|
||||
for _, eci := range d.EcShardInfos {
|
||||
diskIDs[normalize(eci.DiskId)] = struct{}{}
|
||||
}
|
||||
if len(diskIDs) == 0 {
|
||||
diskIDs[d.DiskId] = struct{}{}
|
||||
}
|
||||
|
||||
if len(diskIDs) == 1 {
|
||||
for diskID := range diskIDs {
|
||||
if diskID == d.DiskId {
|
||||
return []*DiskInfo{d}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
perDiskVolumes := make(map[uint32][]*VolumeInformationMessage)
|
||||
for _, vi := range d.VolumeInfos {
|
||||
id := normalize(vi.DiskId)
|
||||
perDiskVolumes[id] = append(perDiskVolumes[id], vi)
|
||||
}
|
||||
perDiskShards := make(map[uint32][]*VolumeEcShardInformationMessage)
|
||||
for _, eci := range d.EcShardInfos {
|
||||
id := normalize(eci.DiskId)
|
||||
perDiskShards[id] = append(perDiskShards[id], eci)
|
||||
}
|
||||
|
||||
// Sort disk IDs so the remainder distribution is deterministic and the
|
||||
// reconstructed slice is in DiskId order, which is what downstream
|
||||
// renderers expect.
|
||||
ids := make([]uint32, 0, len(diskIDs))
|
||||
for id := range diskIDs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
|
||||
count := int64(len(ids))
|
||||
// share returns total / count, plus one extra for the first
|
||||
// (total % count) entries so the sum of shares equals total. Without
|
||||
// the remainder distribution, splitting 10 across 3 disks would yield
|
||||
// 3+3+3 = 9 and under-report aggregate capacity.
|
||||
share := func(total int64, idx int) int64 {
|
||||
base := total / count
|
||||
if int64(idx) < total%count {
|
||||
return base + 1
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
result := make([]*DiskInfo, 0, len(ids))
|
||||
for i, diskID := range ids {
|
||||
var activeCount, remoteCount int64
|
||||
for _, vi := range perDiskVolumes[diskID] {
|
||||
if !vi.ReadOnly {
|
||||
activeCount++
|
||||
}
|
||||
if vi.RemoteStorageName != "" {
|
||||
remoteCount++
|
||||
}
|
||||
}
|
||||
result = append(result, &DiskInfo{
|
||||
Type: d.Type,
|
||||
MaxVolumeCount: share(d.MaxVolumeCount, i),
|
||||
VolumeCount: int64(len(perDiskVolumes[diskID])),
|
||||
FreeVolumeCount: share(d.FreeVolumeCount, i),
|
||||
ActiveVolumeCount: activeCount,
|
||||
RemoteVolumeCount: remoteCount,
|
||||
VolumeInfos: perDiskVolumes[diskID],
|
||||
EcShardInfos: perDiskShards[diskID],
|
||||
DiskId: diskID,
|
||||
Tags: append([]string(nil), d.Tags...),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package master_pb
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_collapsesOnSingleDisk(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
MaxVolumeCount: 10,
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 1, DiskId: 0},
|
||||
{Id: 2, DiskId: 0},
|
||||
},
|
||||
DiskId: 0,
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 split disk, got %d", len(got))
|
||||
}
|
||||
if got[0] != d {
|
||||
t.Errorf("single-disk input should be returned unchanged; got a copy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_splitsByVolumeDiskId(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
MaxVolumeCount: 60,
|
||||
FreeVolumeCount: 30,
|
||||
ActiveVolumeCount: 12,
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 10, DiskId: 0},
|
||||
{Id: 11, DiskId: 0},
|
||||
{Id: 20, DiskId: 1},
|
||||
{Id: 21, DiskId: 2},
|
||||
{Id: 22, DiskId: 2},
|
||||
{Id: 23, DiskId: 2},
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("want 3 split disks, got %d", len(got))
|
||||
}
|
||||
|
||||
byID := map[uint32]*DiskInfo{}
|
||||
for _, di := range got {
|
||||
byID[di.DiskId] = di
|
||||
}
|
||||
for _, want := range []uint32{0, 1, 2} {
|
||||
if _, ok := byID[want]; !ok {
|
||||
t.Errorf("missing DiskId=%d in split result", want)
|
||||
}
|
||||
}
|
||||
|
||||
if byID[0].VolumeCount != 2 {
|
||||
t.Errorf("disk 0: want 2 volumes, got %d", byID[0].VolumeCount)
|
||||
}
|
||||
if byID[1].VolumeCount != 1 {
|
||||
t.Errorf("disk 1: want 1 volume, got %d", byID[1].VolumeCount)
|
||||
}
|
||||
if byID[2].VolumeCount != 3 {
|
||||
t.Errorf("disk 2: want 3 volumes, got %d", byID[2].VolumeCount)
|
||||
}
|
||||
|
||||
// Capacity is split evenly across the reconstructed disks. With 3 disks
|
||||
// and a max of 60, every reconstructed disk gets 20.
|
||||
for id, di := range byID {
|
||||
if di.MaxVolumeCount != 20 {
|
||||
t.Errorf("disk %d: want MaxVolumeCount=20 (60/3), got %d", id, di.MaxVolumeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// Disk type is preserved on every reconstructed entry so writers that
|
||||
// label by type still see "hdd".
|
||||
for id, di := range byID {
|
||||
if di.Type != "hdd" {
|
||||
t.Errorf("disk %d: want Type=hdd, got %q", id, di.Type)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiskInfoSplitByPhysicalDisk_preservesAggregateCapacityWithRemainder
|
||||
// pins the invariant that the sum of reconstructed counters equals the
|
||||
// original aggregate, even when the count does not divide evenly.
|
||||
func TestDiskInfoSplitByPhysicalDisk_preservesAggregateCapacityWithRemainder(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
MaxVolumeCount: 10,
|
||||
FreeVolumeCount: 7,
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 1, DiskId: 0},
|
||||
{Id: 2, DiskId: 1},
|
||||
{Id: 3, DiskId: 2},
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("want 3 disks, got %d", len(got))
|
||||
}
|
||||
|
||||
var sumMax, sumFree int64
|
||||
for _, di := range got {
|
||||
sumMax += di.MaxVolumeCount
|
||||
sumFree += di.FreeVolumeCount
|
||||
}
|
||||
if sumMax != 10 {
|
||||
t.Errorf("sum of MaxVolumeCount = %d, want 10 (lossless split)", sumMax)
|
||||
}
|
||||
if sumFree != 7 {
|
||||
t.Errorf("sum of FreeVolumeCount = %d, want 7 (lossless split)", sumFree)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiskInfoSplitByPhysicalDisk_countsActiveAndRemoteExactly verifies
|
||||
// the per-disk ActiveVolumeCount and RemoteVolumeCount are derived from
|
||||
// the actual VolumeInfos rather than an even split of the node totals.
|
||||
func TestDiskInfoSplitByPhysicalDisk_countsActiveAndRemoteExactly(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 1, DiskId: 0, ReadOnly: false},
|
||||
{Id: 2, DiskId: 0, ReadOnly: true},
|
||||
{Id: 3, DiskId: 1, ReadOnly: false, RemoteStorageName: "s3"},
|
||||
{Id: 4, DiskId: 2, ReadOnly: false},
|
||||
{Id: 5, DiskId: 2, ReadOnly: false, RemoteStorageName: "s3"},
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
byID := map[uint32]*DiskInfo{}
|
||||
for _, di := range got {
|
||||
byID[di.DiskId] = di
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
id uint32
|
||||
wantActive int64
|
||||
wantRemote int64
|
||||
}{
|
||||
{0, 1, 0},
|
||||
{1, 1, 1},
|
||||
{2, 2, 1},
|
||||
}
|
||||
for _, c := range cases {
|
||||
di := byID[c.id]
|
||||
if di == nil {
|
||||
t.Errorf("missing disk %d", c.id)
|
||||
continue
|
||||
}
|
||||
if di.ActiveVolumeCount != c.wantActive {
|
||||
t.Errorf("disk %d: ActiveVolumeCount = %d, want %d", c.id, di.ActiveVolumeCount, c.wantActive)
|
||||
}
|
||||
if di.RemoteVolumeCount != c.wantRemote {
|
||||
t.Errorf("disk %d: RemoteVolumeCount = %d, want %d", c.id, di.RemoteVolumeCount, c.wantRemote)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_splitsByEcShardDiskId(t *testing.T) {
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
EcShardInfos: []*VolumeEcShardInformationMessage{
|
||||
{Id: 100, DiskId: 4},
|
||||
{Id: 101, DiskId: 4},
|
||||
{Id: 102, DiskId: 5},
|
||||
},
|
||||
}
|
||||
|
||||
got := d.SplitByPhysicalDisk()
|
||||
|
||||
ids := make([]int, 0, len(got))
|
||||
for _, di := range got {
|
||||
ids = append(ids, int(di.DiskId))
|
||||
}
|
||||
sort.Ints(ids)
|
||||
if len(ids) != 2 || ids[0] != 4 || ids[1] != 5 {
|
||||
t.Fatalf("want split disk ids [4,5], got %v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_normalizesZeroToOuterDiskId(t *testing.T) {
|
||||
// Older payloads / fixtures omit the per-record DiskId. The outer DiskId
|
||||
// is the authoritative fallback.
|
||||
d := &DiskInfo{
|
||||
Type: "hdd",
|
||||
DiskId: 7,
|
||||
VolumeInfos: []*VolumeInformationMessage{
|
||||
{Id: 1, DiskId: 0}, // normalize to 7
|
||||
{Id: 2, DiskId: 0}, // normalize to 7
|
||||
},
|
||||
}
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 disk, got %d", len(got))
|
||||
}
|
||||
if got[0].DiskId != 7 {
|
||||
t.Errorf("want DiskId=7 after normalization, got %d", got[0].DiskId)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_nilSafe(t *testing.T) {
|
||||
var d *DiskInfo
|
||||
if got := d.SplitByPhysicalDisk(); got != nil {
|
||||
t.Errorf("nil receiver should return nil slice, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskInfoSplitByPhysicalDisk_emptyDiskReturnsSelf(t *testing.T) {
|
||||
d := &DiskInfo{Type: "hdd", MaxVolumeCount: 10, DiskId: 3}
|
||||
got := d.SplitByPhysicalDisk()
|
||||
if len(got) != 1 || got[0] != d {
|
||||
t.Errorf("empty disk should be passed through unchanged; got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -348,7 +348,9 @@ message JobResult {
|
||||
|
||||
message ClusterContext {
|
||||
repeated string master_grpc_addresses = 1;
|
||||
repeated string filer_grpc_addresses = 2;
|
||||
// Filers in pb.ServerAddress form (host:httpPort.grpcPort). Consumers
|
||||
// convert to a gRPC or HTTP address as needed; see weed/pb/server_address.go.
|
||||
repeated string filer_addresses = 2;
|
||||
repeated string volume_grpc_addresses = 3;
|
||||
map<string, string> metadata = 4;
|
||||
repeated string s3_grpc_addresses = 5;
|
||||
|
||||
@@ -3564,10 +3564,12 @@ func (x *JobResult) GetSummary() string {
|
||||
type ClusterContext struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
MasterGrpcAddresses []string `protobuf:"bytes,1,rep,name=master_grpc_addresses,json=masterGrpcAddresses,proto3" json:"master_grpc_addresses,omitempty"`
|
||||
FilerGrpcAddresses []string `protobuf:"bytes,2,rep,name=filer_grpc_addresses,json=filerGrpcAddresses,proto3" json:"filer_grpc_addresses,omitempty"`
|
||||
VolumeGrpcAddresses []string `protobuf:"bytes,3,rep,name=volume_grpc_addresses,json=volumeGrpcAddresses,proto3" json:"volume_grpc_addresses,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
S3GrpcAddresses []string `protobuf:"bytes,5,rep,name=s3_grpc_addresses,json=s3GrpcAddresses,proto3" json:"s3_grpc_addresses,omitempty"`
|
||||
// Filers in pb.ServerAddress form (host:httpPort.grpcPort). Consumers
|
||||
// convert to a gRPC or HTTP address as needed; see weed/pb/server_address.go.
|
||||
FilerAddresses []string `protobuf:"bytes,2,rep,name=filer_addresses,json=filerAddresses,proto3" json:"filer_addresses,omitempty"`
|
||||
VolumeGrpcAddresses []string `protobuf:"bytes,3,rep,name=volume_grpc_addresses,json=volumeGrpcAddresses,proto3" json:"volume_grpc_addresses,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
S3GrpcAddresses []string `protobuf:"bytes,5,rep,name=s3_grpc_addresses,json=s3GrpcAddresses,proto3" json:"s3_grpc_addresses,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3609,9 +3611,9 @@ func (x *ClusterContext) GetMasterGrpcAddresses() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ClusterContext) GetFilerGrpcAddresses() []string {
|
||||
func (x *ClusterContext) GetFilerAddresses() []string {
|
||||
if x != nil {
|
||||
return x.FilerGrpcAddresses
|
||||
return x.FilerAddresses
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -4273,10 +4275,10 @@ const file_plugin_proto_rawDesc = "" +
|
||||
"\asummary\x18\x02 \x01(\tR\asummary\x1aT\n" +
|
||||
"\x11OutputValuesEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12)\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xd5\x02\n" +
|
||||
"\x05value\x18\x02 \x01(\v2\x13.plugin.ConfigValueR\x05value:\x028\x01\"\xcc\x02\n" +
|
||||
"\x0eClusterContext\x122\n" +
|
||||
"\x15master_grpc_addresses\x18\x01 \x03(\tR\x13masterGrpcAddresses\x120\n" +
|
||||
"\x14filer_grpc_addresses\x18\x02 \x03(\tR\x12filerGrpcAddresses\x122\n" +
|
||||
"\x15master_grpc_addresses\x18\x01 \x03(\tR\x13masterGrpcAddresses\x12'\n" +
|
||||
"\x0ffiler_addresses\x18\x02 \x03(\tR\x0efilerAddresses\x122\n" +
|
||||
"\x15volume_grpc_addresses\x18\x03 \x03(\tR\x13volumeGrpcAddresses\x12@\n" +
|
||||
"\bmetadata\x18\x04 \x03(\v2$.plugin.ClusterContext.MetadataEntryR\bmetadata\x12*\n" +
|
||||
"\x11s3_grpc_addresses\x18\x05 \x03(\tR\x0fs3GrpcAddresses\x1a;\n" +
|
||||
|
||||
@@ -413,6 +413,7 @@ message EcBalanceTaskConfig {
|
||||
string collection_filter = 3; // Collection filter
|
||||
string disk_type = 4; // Disk type filter
|
||||
repeated string preferred_tags = 5; // Preferred disk tags for placement
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
}
|
||||
|
||||
// ========== Task Persistence Messages ==========
|
||||
|
||||
@@ -3297,6 +3297,7 @@ type EcBalanceTaskConfig struct {
|
||||
CollectionFilter string `protobuf:"bytes,3,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Collection filter
|
||||
DiskType string `protobuf:"bytes,4,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"` // Disk type filter
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Preferred disk tags for placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3366,6 +3367,13 @@ func (x *EcBalanceTaskConfig) GetPreferredTags() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskConfig) GetReplicaPlacement() string {
|
||||
if x != nil {
|
||||
return x.ReplicaPlacement
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// MaintenanceTaskData represents complete task state for persistence
|
||||
type MaintenanceTaskData struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4238,13 +4246,14 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x0esource_disk_id\x18\x05 \x01(\rR\fsourceDiskId\x12\x1f\n" +
|
||||
"\vtarget_node\x18\x06 \x01(\tR\n" +
|
||||
"targetNode\x12$\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\xe1\x01\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\x8e\x02\n" +
|
||||
"\x13EcBalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
"\x11collection_filter\x18\x03 \x01(\tR\x10collectionFilter\x12\x1b\n" +
|
||||
"\tdisk_type\x18\x04 \x01(\tR\bdiskType\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\"\xae\a\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"\xae\a\n" +
|
||||
"\x13MaintenanceTaskData\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04type\x18\x02 \x01(\tR\x04type\x12\x1a\n" +
|
||||
|
||||
@@ -19,9 +19,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
adminScriptJobType = "admin_script"
|
||||
maxAdminScriptOutputBytes = 16 * 1024
|
||||
defaultAdminScriptRunMins = 17
|
||||
adminScriptJobType = "admin_script"
|
||||
maxAdminScriptOutputBytes = 16 * 1024
|
||||
defaultAdminScriptRunMins = 17
|
||||
adminScriptDetectTickMinutes = 17
|
||||
)
|
||||
|
||||
@@ -546,13 +546,31 @@ func (h *AdminScriptHandler) buildAdminScriptCommandEnv(
|
||||
ctx context.Context,
|
||||
clusterContext *plugin_pb.ClusterContext,
|
||||
) (*shell.CommandEnv, context.CancelFunc, error) {
|
||||
options, err := h.buildAdminScriptShellOptions(clusterContext)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&options)
|
||||
commandEnv.ForceNoLock()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go commandEnv.MasterClient.KeepConnectedToMaster(ctx)
|
||||
|
||||
return commandEnv, cancel, nil
|
||||
}
|
||||
|
||||
// buildAdminScriptShellOptions maps a cluster context onto shell.ShellOptions.
|
||||
// It is split out from buildAdminScriptCommandEnv so the address handling is
|
||||
// testable without standing up a master client.
|
||||
func (h *AdminScriptHandler) buildAdminScriptShellOptions(clusterContext *plugin_pb.ClusterContext) (shell.ShellOptions, error) {
|
||||
if clusterContext == nil {
|
||||
return nil, nil, fmt.Errorf("cluster context is required")
|
||||
return shell.ShellOptions{}, fmt.Errorf("cluster context is required")
|
||||
}
|
||||
|
||||
masters := normalizeAddressList(clusterContext.MasterGrpcAddresses)
|
||||
if len(masters) == 0 {
|
||||
return nil, nil, fmt.Errorf("missing master addresses for admin script")
|
||||
return shell.ShellOptions{}, fmt.Errorf("missing master addresses for admin script")
|
||||
}
|
||||
|
||||
filerGroup := ""
|
||||
@@ -564,20 +582,17 @@ func (h *AdminScriptHandler) buildAdminScriptCommandEnv(
|
||||
Directory: "/",
|
||||
}
|
||||
|
||||
filers := normalizeAddressList(clusterContext.FilerGrpcAddresses)
|
||||
// FilerAddresses are pb.ServerAddress strings (host:httpPort.grpcPort).
|
||||
// ShellOptions.FilerAddress is itself a ServerAddress; shell commands derive
|
||||
// the gRPC or HTTP port from it as needed, so store it verbatim.
|
||||
filers := normalizeAddressList(clusterContext.FilerAddresses)
|
||||
if len(filers) > 0 {
|
||||
options.FilerAddress = pb.ServerAddress(filers[0])
|
||||
} else {
|
||||
glog.V(1).Infof("admin script worker missing filer address; filer-dependent commands may fail")
|
||||
}
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&options)
|
||||
commandEnv.ForceNoLock()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
go commandEnv.MasterClient.KeepConnectedToMaster(ctx)
|
||||
|
||||
return commandEnv, cancel, nil
|
||||
return options, nil
|
||||
}
|
||||
|
||||
func normalizeAddressList(addresses []string) []string {
|
||||
|
||||
@@ -10,6 +10,36 @@ import (
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func TestAdminScriptFilerAddressKeepsGrpcPortOffConvention(t *testing.T) {
|
||||
// FilerAddresses arrive as pb.ServerAddress (host:httpPort.grpcPort). The
|
||||
// shell derives the gRPC port from FilerAddress via ToGrpcAddress(); it must
|
||||
// land on the real gRPC port even when that port is off the httpPort+10000
|
||||
// convention, not double the offset into a non-existent filer:28890.
|
||||
h := NewAdminScriptHandler(nil)
|
||||
options, err := h.buildAdminScriptShellOptions(&plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: []string{"master:19333"},
|
||||
FilerAddresses: []string{"filer:8888.18890"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("buildAdminScriptShellOptions returned err = %v", err)
|
||||
}
|
||||
if grpc := options.FilerAddress.ToGrpcAddress(); grpc != "filer:18890" {
|
||||
t.Fatalf("filer gRPC address = %q, want filer:18890 (not filer:28890)", grpc)
|
||||
}
|
||||
if http := options.FilerAddress.ToHttpAddress(); http != "filer:8888" {
|
||||
t.Fatalf("filer HTTP address = %q, want filer:8888", http)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminScriptShellOptionsRequireMasters(t *testing.T) {
|
||||
h := NewAdminScriptHandler(nil)
|
||||
if _, err := h.buildAdminScriptShellOptions(&plugin_pb.ClusterContext{
|
||||
FilerAddresses: []string{"filer:8888.18890"},
|
||||
}); err == nil {
|
||||
t.Fatalf("expected error when master addresses are missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminScriptDescriptorDefaults(t *testing.T) {
|
||||
descriptor := NewAdminScriptHandler(nil).Descriptor()
|
||||
if descriptor == nil {
|
||||
|
||||
@@ -59,6 +59,38 @@ func CollectVolumeMetricsFromMasters(
|
||||
// FetchVolumeList dials the given master address (trying both the address as
|
||||
// given and the gRPC port variant) and returns the master's volume list. Used
|
||||
// by detection helpers that already know which master address to talk to.
|
||||
// FetchDefaultReplicaPlacement returns the master's configured default replication
|
||||
// (GetMasterConfiguration), used by detectors as the replica-placement fallback so
|
||||
// the plugin path matches the shell. Returns "" if it cannot be fetched, so callers
|
||||
// fall back to even spread rather than failing detection.
|
||||
func FetchDefaultReplicaPlacement(ctx context.Context, masterAddresses []string, grpcDialOption grpc.DialOption) string {
|
||||
if grpcDialOption == nil {
|
||||
return ""
|
||||
}
|
||||
for _, address := range masterAddresses {
|
||||
for _, candidate := range MasterAddressCandidates(address) {
|
||||
if ctx.Err() != nil {
|
||||
return ""
|
||||
}
|
||||
dialCtx, cancelDial := context.WithTimeout(ctx, 5*time.Second)
|
||||
conn, err := pb.GrpcDial(dialCtx, candidate, false, grpcDialOption)
|
||||
cancelDial()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
client := master_pb.NewSeaweedClient(conn)
|
||||
callCtx, cancelCall := context.WithTimeout(ctx, 10*time.Second)
|
||||
resp, callErr := client.GetMasterConfiguration(callCtx, &master_pb.GetMasterConfigurationRequest{})
|
||||
cancelCall()
|
||||
_ = conn.Close()
|
||||
if callErr == nil {
|
||||
return resp.DefaultReplication
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func FetchVolumeList(ctx context.Context, address string, grpcDialOption grpc.DialOption) (*master_pb.VolumeListResponse, error) {
|
||||
var lastErr error
|
||||
for _, candidate := range MasterAddressCandidates(address) {
|
||||
|
||||
@@ -242,9 +242,11 @@ func (fs *FilerSink) fetchAndWrite(sourceChunk *filer_pb.FileChunk, path string,
|
||||
}
|
||||
|
||||
transferStatus := &ChunkTransferStatus{
|
||||
ChunkFileId: sourceChunk.GetFileIdString(),
|
||||
Path: path,
|
||||
Status: "downloading",
|
||||
ChunkTransferSnapshot: ChunkTransferSnapshot{
|
||||
ChunkFileId: sourceChunk.GetFileIdString(),
|
||||
Path: path,
|
||||
Status: "downloading",
|
||||
},
|
||||
}
|
||||
fs.activeTransfers.Store(sourceChunk.GetFileIdString(), transferStatus)
|
||||
defer fs.activeTransfers.Delete(sourceChunk.GetFileIdString())
|
||||
|
||||
@@ -22,12 +22,9 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// ChunkTransferStatus tracks the progress of a single chunk being replicated.
|
||||
// Fields are guarded by mu: ChunkFileId and Path are immutable after creation,
|
||||
// while BytesReceived, Status, and LastErr are updated by fetchAndWrite and
|
||||
// read by ActiveTransfers.
|
||||
type ChunkTransferStatus struct {
|
||||
mu sync.RWMutex
|
||||
// ChunkTransferSnapshot is a lock-free, copyable view of a chunk transfer's
|
||||
// progress, returned by ActiveTransfers.
|
||||
type ChunkTransferSnapshot struct {
|
||||
ChunkFileId string
|
||||
Path string
|
||||
BytesReceived int64
|
||||
@@ -35,6 +32,15 @@ type ChunkTransferStatus struct {
|
||||
LastErr string
|
||||
}
|
||||
|
||||
// ChunkTransferStatus tracks the progress of a single chunk being replicated.
|
||||
// Fields are guarded by mu: ChunkFileId and Path are immutable after creation,
|
||||
// while BytesReceived, Status, and LastErr are updated by fetchAndWrite and
|
||||
// read by ActiveTransfers.
|
||||
type ChunkTransferStatus struct {
|
||||
mu sync.RWMutex
|
||||
ChunkTransferSnapshot
|
||||
}
|
||||
|
||||
type FilerSink struct {
|
||||
filerSource *source.FilerSource
|
||||
grpcAddress string
|
||||
@@ -134,18 +140,12 @@ func (fs *FilerSink) SetChunkConcurrency(concurrency int) {
|
||||
}
|
||||
|
||||
// ActiveTransfers returns an immutable snapshot of all in-progress chunk transfers.
|
||||
func (fs *FilerSink) ActiveTransfers() []ChunkTransferStatus {
|
||||
var transfers []ChunkTransferStatus
|
||||
func (fs *FilerSink) ActiveTransfers() []ChunkTransferSnapshot {
|
||||
var transfers []ChunkTransferSnapshot
|
||||
fs.activeTransfers.Range(func(key, value any) bool {
|
||||
t := value.(*ChunkTransferStatus)
|
||||
t.mu.RLock()
|
||||
transfers = append(transfers, ChunkTransferStatus{
|
||||
ChunkFileId: t.ChunkFileId,
|
||||
Path: t.Path,
|
||||
BytesReceived: t.BytesReceived,
|
||||
Status: t.Status,
|
||||
LastErr: t.LastErr,
|
||||
})
|
||||
transfers = append(transfers, t.ChunkTransferSnapshot)
|
||||
t.mu.RUnlock()
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// newCopyRequest builds a request that mimics what a CopyObject caller sends:
|
||||
// a PUT to the destination bucket/object with X-Amz-Copy-Source pointing at the
|
||||
// source. The destination is what the Auth middleware would have authorized.
|
||||
func newCopyRequest(t *testing.T, dstBucket, dstObject, copySource string) *http.Request {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPut, "http://s3.local/"+dstBucket+"/"+dstObject, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("X-Amz-Copy-Source", copySource)
|
||||
return req
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_AuthDisabled verifies the source check is a no-op when
|
||||
// the IAM is not enabled (no identities configured).
|
||||
func TestAuthorizeCopySource_AuthDisabled(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.False(t, iam.isEnabled())
|
||||
|
||||
req := newCopyRequest(t, "dst-bucket", "dst-obj", "/src-bucket/src-obj")
|
||||
errCode := iam.AuthorizeCopySource(req, nil, "src-bucket", "src-obj", "")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_NilIdentityDenies verifies that with auth enabled we
|
||||
// fail closed if no identity is available.
|
||||
func TestAuthorizeCopySource_NilIdentityDenies(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.identities = []*Identity{{Name: "anyone"}}
|
||||
iam.isAuthEnabled = true
|
||||
require.True(t, iam.isEnabled())
|
||||
|
||||
req := newCopyRequest(t, "dst-bucket", "dst-obj", "/src-bucket/src-obj")
|
||||
errCode := iam.AuthorizeCopySource(req, nil, "src-bucket", "src-obj", "")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_AdminAllowed verifies admin identities bypass the
|
||||
// source check.
|
||||
func TestAuthorizeCopySource_AdminAllowed(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.identities = []*Identity{{Name: "admin", Actions: []Action{s3_constants.ACTION_ADMIN}}}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
admin := &Identity{Name: "admin", Account: &AccountAdmin, Actions: []Action{s3_constants.ACTION_ADMIN}}
|
||||
req := newCopyRequest(t, "dst-bucket", "dst-obj", "/src-bucket/src-obj")
|
||||
errCode := iam.AuthorizeCopySource(req, admin, "src-bucket", "src-obj", "")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_PrefixScopedIdentity checks that an identity scoped
|
||||
// to prefix-a/* is denied when copying from prefix-b/*, even when its
|
||||
// destination (prefix-a/*) write permission is fine.
|
||||
func TestAuthorizeCopySource_PrefixScopedIdentity(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
scoped := &Identity{
|
||||
Name: "scoped",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{
|
||||
Action("Read:bucket-a/prefix-a/*"),
|
||||
Action("Write:bucket-a/prefix-a/*"),
|
||||
},
|
||||
}
|
||||
iam.identities = []*Identity{scoped}
|
||||
|
||||
t.Run("source within scope is allowed", func(t *testing.T) {
|
||||
req := newCopyRequest(t, "bucket-a", "prefix-a/dst.bin", "/bucket-a/prefix-a/src.bin")
|
||||
errCode := iam.AuthorizeCopySource(req, scoped, "bucket-a", "prefix-a/src.bin", "")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
})
|
||||
|
||||
t.Run("source outside scope is denied", func(t *testing.T) {
|
||||
req := newCopyRequest(t, "bucket-a", "prefix-a/dst.bin", "/bucket-a/prefix-b/src.bin")
|
||||
errCode := iam.AuthorizeCopySource(req, scoped, "bucket-a", "prefix-b/src.bin", "")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode)
|
||||
})
|
||||
|
||||
t.Run("source in different bucket is denied", func(t *testing.T) {
|
||||
req := newCopyRequest(t, "bucket-a", "prefix-a/dst.bin", "/other-bucket/src.bin")
|
||||
errCode := iam.AuthorizeCopySource(req, scoped, "other-bucket", "src.bin", "")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_IAMIntegrationGetsSourceResource verifies that the
|
||||
// STS / IAM path is invoked with the SOURCE bucket/object and a GetObject-style
|
||||
// action — not the destination from the request URL.
|
||||
func TestAuthorizeCopySource_IAMIntegrationGetsSourceResource(t *testing.T) {
|
||||
var capturedAction Action
|
||||
var capturedBucket, capturedObject string
|
||||
var capturedMethod string
|
||||
var capturedURLPath string
|
||||
|
||||
mock := &MockIAMIntegration{
|
||||
authorizeFunc: func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
// Resolve the action like S3IAMIntegration.AuthorizeAction would,
|
||||
// so the assertion reflects the s3:* the policy engine sees.
|
||||
capturedAction = Action(ResolveS3Action(r, string(action), bucket, object))
|
||||
capturedBucket = bucket
|
||||
capturedObject = object
|
||||
if r != nil {
|
||||
capturedMethod = r.Method
|
||||
if r.URL != nil {
|
||||
capturedURLPath = r.URL.Path
|
||||
}
|
||||
}
|
||||
// Deny: simulate a session policy that does not grant Read on src.
|
||||
return s3err.ErrAccessDenied
|
||||
},
|
||||
}
|
||||
|
||||
iam := &IdentityAccessManagement{iamIntegration: mock}
|
||||
iam.identities = []*Identity{{Name: "sts"}}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
stsIdentity := &Identity{
|
||||
Name: "arn:aws:sts::assumed-role/scopedRole/session",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{}, // STS identity
|
||||
PrincipalArn: "arn:aws:sts::assumed-role/scopedRole/session",
|
||||
}
|
||||
|
||||
req := newCopyRequest(t, "bucket-a", "prefix-a/dst.bin", "/bucket-a/prefix-b/src.bin")
|
||||
req.Header.Set("X-Amz-Security-Token", "test-session-token")
|
||||
|
||||
errCode := iam.AuthorizeCopySource(req, stsIdentity, "bucket-a", "prefix-b/src.bin", "")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode)
|
||||
assert.True(t, mock.authCalled, "IAM integration must be invoked for STS source check")
|
||||
|
||||
// Action passed through ResolveS3Action: GET method + ACTION_READ -> s3:GetObject.
|
||||
assert.Equal(t, "s3:GetObject", string(capturedAction))
|
||||
assert.Equal(t, "bucket-a", capturedBucket)
|
||||
assert.Equal(t, "prefix-b/src.bin", capturedObject)
|
||||
assert.Equal(t, http.MethodGet, capturedMethod, "synthetic source request must be a GET")
|
||||
assert.Equal(t, "/bucket-a/prefix-b/src.bin", capturedURLPath, "synthetic URL must target the source")
|
||||
|
||||
// Original request must not be mutated by the source check.
|
||||
assert.Equal(t, http.MethodPut, req.Method)
|
||||
assert.Equal(t, "/bucket-a/prefix-a/dst.bin", req.URL.Path)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_IAMIntegrationAllow verifies the IAM integration can
|
||||
// grant access; the source check then returns ErrNone.
|
||||
func TestAuthorizeCopySource_IAMIntegrationAllow(t *testing.T) {
|
||||
mock := &MockIAMIntegration{
|
||||
authorizeFunc: func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
return s3err.ErrNone
|
||||
},
|
||||
}
|
||||
|
||||
iam := &IdentityAccessManagement{iamIntegration: mock}
|
||||
iam.identities = []*Identity{{Name: "sts"}}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
stsIdentity := &Identity{
|
||||
Name: "arn:aws:sts::assumed-role/role/session",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{},
|
||||
PrincipalArn: "arn:aws:sts::assumed-role/role/session",
|
||||
}
|
||||
|
||||
req := newCopyRequest(t, "bucket-a", "prefix-a/dst.bin", "/bucket-a/prefix-a/src.bin")
|
||||
req.Header.Set("X-Amz-Security-Token", "test-session-token")
|
||||
|
||||
errCode := iam.AuthorizeCopySource(req, stsIdentity, "bucket-a", "prefix-a/src.bin", "")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_VersionIdPropagated verifies that when copying a
|
||||
// specific source version, the IAM check sees a versionId on the synthetic
|
||||
// request so that s3:VersionId conditions and s3:GetObjectVersion resolution
|
||||
// work.
|
||||
func TestAuthorizeCopySource_VersionIdPropagated(t *testing.T) {
|
||||
var capturedAction Action
|
||||
var capturedRawQuery string
|
||||
|
||||
mock := &MockIAMIntegration{
|
||||
authorizeFunc: func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
capturedAction = Action(ResolveS3Action(r, string(action), bucket, object))
|
||||
if r != nil && r.URL != nil {
|
||||
capturedRawQuery = r.URL.RawQuery
|
||||
}
|
||||
return s3err.ErrNone
|
||||
},
|
||||
}
|
||||
|
||||
iam := &IdentityAccessManagement{iamIntegration: mock}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
stsIdentity := &Identity{
|
||||
Name: "arn:aws:sts::assumed-role/role/session",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{},
|
||||
PrincipalArn: "arn:aws:sts::assumed-role/role/session",
|
||||
}
|
||||
|
||||
req := newCopyRequest(t, "bucket-a", "dst.bin", "/bucket-a/src.bin?versionId=abc123")
|
||||
req.Header.Set("X-Amz-Security-Token", "test-session-token")
|
||||
|
||||
errCode := iam.AuthorizeCopySource(req, stsIdentity, "bucket-a", "src.bin", "abc123")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "s3:GetObjectVersion", string(capturedAction), "versioned source should resolve to GetObjectVersion")
|
||||
assert.Equal(t, "versionId=abc123", capturedRawQuery)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_PresignedURLSessionTokenPreserved guards against a
|
||||
// regression where the synthetic source request dropped X-Amz-Security-Token
|
||||
// from the original query string. Presigned URLs carry the STS token there
|
||||
// (not in headers), and VerifyActionPermission/authorizeWithIAM use it to
|
||||
// route the request to IAM authorization.
|
||||
func TestAuthorizeCopySource_PresignedURLSessionTokenPreserved(t *testing.T) {
|
||||
var capturedSessionToken string
|
||||
var capturedRawQuery string
|
||||
|
||||
mock := &MockIAMIntegration{
|
||||
authorizeFunc: func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
if r != nil {
|
||||
capturedSessionToken = r.URL.Query().Get("X-Amz-Security-Token")
|
||||
capturedRawQuery = r.URL.RawQuery
|
||||
}
|
||||
// The IAM mock receives the propagated session token via IAMIdentity too.
|
||||
if identity != nil && identity.SessionToken != "" {
|
||||
capturedSessionToken = identity.SessionToken
|
||||
}
|
||||
return s3err.ErrNone
|
||||
},
|
||||
}
|
||||
|
||||
iam := &IdentityAccessManagement{iamIntegration: mock}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
stsIdentity := &Identity{
|
||||
Name: "arn:aws:sts::assumed-role/role/session",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{},
|
||||
PrincipalArn: "arn:aws:sts::assumed-role/role/session",
|
||||
}
|
||||
|
||||
// Presigned URL: session token is in the query string, no
|
||||
// X-Amz-Security-Token header. The destination URL also carries unrelated
|
||||
// SigV4 query params (X-Amz-Algorithm, etc.) that must not leak into the
|
||||
// synthetic source action resolution.
|
||||
req, err := http.NewRequest(http.MethodPut,
|
||||
"http://s3.local/bucket-a/dst.bin?X-Amz-Algorithm=AWS4-HMAC-SHA256"+
|
||||
"&X-Amz-Credential=stsKey%2F20260518%2Fus-east-1%2Fs3%2Faws4_request"+
|
||||
"&X-Amz-Date=20260518T000000Z&X-Amz-Expires=900"+
|
||||
"&X-Amz-Security-Token=presigned-session-token"+
|
||||
"&X-Amz-SignedHeaders=host&X-Amz-Signature=deadbeef", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("X-Amz-Copy-Source", "/bucket-a/src.bin")
|
||||
|
||||
errCode := iam.AuthorizeCopySource(req, stsIdentity, "bucket-a", "src.bin", "")
|
||||
assert.Equal(t, s3err.ErrNone, errCode)
|
||||
assert.Equal(t, "presigned-session-token", capturedSessionToken,
|
||||
"session token from presigned-URL query must reach the IAM check")
|
||||
// versionId omitted, only the token should be present in the synthetic query.
|
||||
assert.Equal(t, "X-Amz-Security-Token=presigned-session-token", capturedRawQuery)
|
||||
}
|
||||
|
||||
// TestAuthorizeCopySource_PreservesCopySourceHeader verifies that the synthetic
|
||||
// source request still carries the X-Amz-Copy-Source header so policy condition
|
||||
// keys like s3:x-amz-copy-source remain available.
|
||||
func TestAuthorizeCopySource_PreservesCopySourceHeader(t *testing.T) {
|
||||
var capturedCopySource string
|
||||
|
||||
mock := &MockIAMIntegration{
|
||||
authorizeFunc: func(ctx context.Context, identity *IAMIdentity, action Action, bucket, object string, r *http.Request) s3err.ErrorCode {
|
||||
if r != nil {
|
||||
capturedCopySource = r.Header.Get("X-Amz-Copy-Source")
|
||||
}
|
||||
return s3err.ErrNone
|
||||
},
|
||||
}
|
||||
|
||||
iam := &IdentityAccessManagement{iamIntegration: mock}
|
||||
iam.isAuthEnabled = true
|
||||
|
||||
stsIdentity := &Identity{
|
||||
Name: "arn:aws:sts::assumed-role/role/session",
|
||||
Account: &AccountAdmin,
|
||||
Actions: []Action{},
|
||||
PrincipalArn: "arn:aws:sts::assumed-role/role/session",
|
||||
}
|
||||
|
||||
req := newCopyRequest(t, "bucket-a", "dst.bin", "/bucket-a/src.bin")
|
||||
req.Header.Set("X-Amz-Security-Token", "test-session-token")
|
||||
|
||||
_ = iam.AuthorizeCopySource(req, stsIdentity, "bucket-a", "src.bin", "")
|
||||
assert.Equal(t, "/bucket-a/src.bin", capturedCopySource)
|
||||
}
|
||||
+237
-55
@@ -68,6 +68,11 @@ type IdentityAccessManagement struct {
|
||||
// IAM Integration for advanced features
|
||||
iamIntegration IAMIntegration
|
||||
|
||||
// Serializes resyncs of the policy set into the advanced IAM manager so that
|
||||
// concurrent policy updates can't apply stale views out of order. See
|
||||
// resyncIAMManagerPolicies.
|
||||
iamManagerSyncMu sync.Mutex
|
||||
|
||||
// Bucket policy engine for evaluating bucket policies
|
||||
policyEngine *BucketPolicyEngine
|
||||
|
||||
@@ -1042,18 +1047,22 @@ func (iam *IdentityAccessManagement) UpsertIdentity(ident *iam_pb.Identity) erro
|
||||
|
||||
// isEnabled reports whether S3 auth should be enforced for this server.
|
||||
//
|
||||
// Auth is considered enabled if either:
|
||||
// - we have any locally managed identities/credentials (iam.isAuthEnabled), or
|
||||
// - an external IAM integration has been configured (iam.iamIntegration != nil).
|
||||
// Driven solely by isAuthEnabled, which is set when:
|
||||
// - any locally managed identities/credentials are loaded (file/filer/env), or
|
||||
// - the operator passes -s3.iam.config, which triggers EnableAuthEnforcement
|
||||
// at startup time even before any identities sync in.
|
||||
//
|
||||
// The iamIntegration check is intentionally included so that when an external
|
||||
// IAM provider is configured (and the server relies solely on it), auth is
|
||||
// still treated as enabled even if there are no local identities yet or
|
||||
// before any sync logic flips isAuthEnabled to true. Removing this check or
|
||||
// relying only on isAuthEnabled would change when auth is enforced and could
|
||||
// unintentionally allow unauthenticated access in integration-only setups.
|
||||
// Earlier versions also treated `iam.iamIntegration != nil` as a signal to
|
||||
// enforce auth, on the assumption that a non-nil integration implied an
|
||||
// explicitly configured external IAM provider. That assumption broke once
|
||||
// EnableIam (mini's default) started initialising the integration with empty
|
||||
// defaults so the embedded IAM API and OIDC-subscribe paths have somewhere
|
||||
// to plug in. With no signing key and no identities, that path still forced
|
||||
// auth on and rejected every anonymous request to `docker run seaweedfs`
|
||||
// (#9557). The fix is to keep the integration available without flipping
|
||||
// enforcement; explicit setups call EnableAuthEnforcement themselves.
|
||||
func (iam *IdentityAccessManagement) isEnabled() bool {
|
||||
return iam.isAuthEnabled || iam.iamIntegration != nil
|
||||
return iam.isAuthEnabled
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) updateAuthenticationState(identitiesCount int) bool {
|
||||
@@ -1667,10 +1676,18 @@ type inlinePolicyLoader interface {
|
||||
LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error)
|
||||
}
|
||||
|
||||
type groupInlinePolicyLoader interface {
|
||||
LoadGroupInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error)
|
||||
}
|
||||
|
||||
func inlinePolicyRuntimeName(userName, policyName string) string {
|
||||
return "__inline_policy__/" + userName + "/" + policyName
|
||||
}
|
||||
|
||||
func inlineGroupPolicyRuntimeName(groupName, policyName string) string {
|
||||
return "__inline_group_policy__/" + groupName + "/" + policyName
|
||||
}
|
||||
|
||||
func mergePoliciesIntoConfiguration(config *iam_pb.S3ApiConfiguration, policies []*iam_pb.Policy) {
|
||||
if len(policies) == 0 {
|
||||
return
|
||||
@@ -1755,44 +1772,73 @@ func (iam *IdentityAccessManagement) hydrateRuntimePolicies(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
inlineLoader, ok := store.(inlinePolicyLoader)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
inlinePoliciesByUser, err := inlineLoader.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load inline policies for runtime: %w", err)
|
||||
}
|
||||
|
||||
if len(inlinePoliciesByUser) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
identityByName := make(map[string]*iam_pb.Identity, len(config.Identities))
|
||||
for _, identity := range config.Identities {
|
||||
identityByName[identity.Name] = identity
|
||||
}
|
||||
|
||||
inlinePolicies := make([]*iam_pb.Policy, 0)
|
||||
for userName, userPolicies := range inlinePoliciesByUser {
|
||||
identity, found := identityByName[userName]
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
for policyName, policyDocument := range userPolicies {
|
||||
content, err := json.Marshal(policyDocument)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal inline policy %q for user %q: %w", policyName, userName, err)
|
||||
if inlineLoader, ok := store.(inlinePolicyLoader); ok {
|
||||
inlinePoliciesByUser, err := inlineLoader.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load inline policies for runtime: %w", err)
|
||||
}
|
||||
if len(inlinePoliciesByUser) > 0 {
|
||||
identityByName := make(map[string]*iam_pb.Identity, len(config.Identities))
|
||||
for _, identity := range config.Identities {
|
||||
identityByName[identity.Name] = identity
|
||||
}
|
||||
|
||||
runtimePolicyName := inlinePolicyRuntimeName(userName, policyName)
|
||||
inlinePolicies = append(inlinePolicies, &iam_pb.Policy{
|
||||
Name: runtimePolicyName,
|
||||
Content: string(content),
|
||||
})
|
||||
identity.PolicyNames = appendUniquePolicyName(identity.PolicyNames, runtimePolicyName)
|
||||
for userName, userPolicies := range inlinePoliciesByUser {
|
||||
identity, found := identityByName[userName]
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
for policyName, policyDocument := range userPolicies {
|
||||
content, err := json.Marshal(policyDocument)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal inline policy %q for user %q: %w", policyName, userName, err)
|
||||
}
|
||||
|
||||
runtimePolicyName := inlinePolicyRuntimeName(userName, policyName)
|
||||
inlinePolicies = append(inlinePolicies, &iam_pb.Policy{
|
||||
Name: runtimePolicyName,
|
||||
Content: string(content),
|
||||
})
|
||||
identity.PolicyNames = appendUniquePolicyName(identity.PolicyNames, runtimePolicyName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if groupLoader, ok := store.(groupInlinePolicyLoader); ok {
|
||||
groupPoliciesByName, err := groupLoader.LoadGroupInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load group inline policies for runtime: %w", err)
|
||||
}
|
||||
if len(groupPoliciesByName) > 0 {
|
||||
groupByName := make(map[string]*iam_pb.Group, len(config.Groups))
|
||||
for _, group := range config.Groups {
|
||||
groupByName[group.Name] = group
|
||||
}
|
||||
|
||||
for groupName, groupPolicies := range groupPoliciesByName {
|
||||
group, found := groupByName[groupName]
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
for policyName, policyDocument := range groupPolicies {
|
||||
content, err := json.Marshal(policyDocument)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal inline policy %q for group %q: %w", policyName, groupName, err)
|
||||
}
|
||||
|
||||
runtimePolicyName := inlineGroupPolicyRuntimeName(groupName, policyName)
|
||||
inlinePolicies = append(inlinePolicies, &iam_pb.Policy{
|
||||
Name: runtimePolicyName,
|
||||
Content: string(content),
|
||||
})
|
||||
group.PolicyNames = appendUniquePolicyName(group.PolicyNames, runtimePolicyName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1818,6 +1864,28 @@ func (iam *IdentityAccessManagement) syncRuntimePoliciesToIAMManager(ctx context
|
||||
return manager.SyncRuntimePolicies(ctx, policies)
|
||||
}
|
||||
|
||||
// resyncIAMManagerPolicies pushes the current policy set into the advanced IAM
|
||||
// manager's engine. SyncRuntimePolicies treats its argument as the full desired
|
||||
// state, so callers must not pass snapshots captured earlier: two updates that
|
||||
// mutate iam.policies in order could otherwise apply their snapshots in the
|
||||
// opposite order and resurrect a deleted policy or drop a new one. Instead this
|
||||
// serializes on iamManagerSyncMu and reads iam.policies fresh, so whatever the
|
||||
// map holds when the last caller runs becomes the manager's state. Call it after
|
||||
// the iam.policies mutation has been committed (lock released).
|
||||
func (iam *IdentityAccessManagement) resyncIAMManagerPolicies() {
|
||||
if iam == nil {
|
||||
return
|
||||
}
|
||||
iam.iamManagerSyncMu.Lock()
|
||||
defer iam.iamManagerSyncMu.Unlock()
|
||||
iam.m.RLock()
|
||||
policies := iam.collectPoliciesLocked()
|
||||
iam.m.RUnlock()
|
||||
if err := iam.syncRuntimePoliciesToIAMManager(context.Background(), policies); err != nil {
|
||||
glog.Warningf("Failed to sync runtime policies to IAM Manager: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// PruneBucketFromConfiguration removes any identity actions scoped to the given
|
||||
// bucket (e.g. "Read:bucket", "Write:bucket/prefix") from the persisted S3 IAM
|
||||
// configuration. Wildcarded resources and global actions are preserved because
|
||||
@@ -1912,15 +1980,16 @@ func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromCredentialManager
|
||||
glog.Errorf("Failed to hydrate runtime IAM policies: %v", err)
|
||||
return err
|
||||
}
|
||||
if err := iam.syncRuntimePoliciesToIAMManager(context.Background(), s3ApiConfiguration.Policies); err != nil {
|
||||
glog.Errorf("Failed to sync runtime IAM policies to advanced IAM manager: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Install the loaded config into iam.policies first, then resync the advanced
|
||||
// IAM manager from that committed map. Syncing before the load would leave a
|
||||
// window where the manager holds policies the map doesn't, which a concurrent
|
||||
// resync (e.g. SetIAMIntegration or a runtime PutPolicy) would then clobber.
|
||||
if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
|
||||
glog.Errorf("Failed to load S3 API configuration: %v", err)
|
||||
return err
|
||||
}
|
||||
iam.resyncIAMManagerPolicies()
|
||||
|
||||
glog.V(1).Infof("Successfully loaded S3 API configuration from credential manager")
|
||||
return nil
|
||||
@@ -1954,15 +2023,40 @@ func (iam *IdentityAccessManagement) initializeKMSFromJSON(configContent []byte)
|
||||
return kms.LoadKMSFromConfig(kmsVal)
|
||||
}
|
||||
|
||||
// SetIAMIntegration sets the IAM integration for advanced authentication and authorization
|
||||
// SetIAMIntegration sets the IAM integration for advanced authentication and authorization.
|
||||
//
|
||||
// This does NOT flip isAuthEnabled on its own. The advanced IAM machinery is
|
||||
// initialised unconditionally when EnableIam is set (mini's default), even
|
||||
// without an IAM config file, so that the embedded IAM API and OIDC-provider
|
||||
// subscribe paths have somewhere to plug in. In that mode there are no roles,
|
||||
// providers or identities yet, so the legacy "no credentials = allow all"
|
||||
// startup behavior must be preserved — otherwise `docker run seaweedfs` (which
|
||||
// starts `weed mini` with no config) rejects every anonymous request.
|
||||
//
|
||||
// Callers that genuinely require authentication enforcement — an explicit
|
||||
// -s3.iam.config file, or identities loaded from file/filer/env — flip
|
||||
// isAuthEnabled themselves via EnableAuthEnforcement / updateAuthenticationState.
|
||||
func (iam *IdentityAccessManagement) SetIAMIntegration(integration *S3IAMIntegration) {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
iam.iamIntegration = integration
|
||||
// When IAM integration is configured, authentication must be enabled
|
||||
// to ensure requests go through proper auth checks
|
||||
if integration != nil {
|
||||
iam.m.Unlock()
|
||||
// Config loaded before the integration was attached skipped the policy sync
|
||||
// (syncRuntimePoliciesToIAMManager no-ops while iamIntegration is nil), so
|
||||
// flush the policies already in memory into the manager's engine now. This
|
||||
// covers either startup ordering: if the load won the race the policies are
|
||||
// here to push; if SetIAMIntegration won, the load's own resync runs next.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
}
|
||||
|
||||
// EnableAuthEnforcement turns on the auth-required mode unconditionally. Use
|
||||
// from setup paths that have evidence the operator intends to enforce auth
|
||||
// (explicit -s3.iam.config file, etc.) even before any identities are loaded.
|
||||
func (iam *IdentityAccessManagement) EnableAuthEnforcement() {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
if !iam.isAuthEnabled {
|
||||
iam.isAuthEnabled = true
|
||||
hasAnyIdentity.Store(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2148,6 +2242,77 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// AuthorizeCopySource verifies the caller is allowed to read the CopyObject /
|
||||
// UploadPartCopy source. The Auth middleware only checks the destination
|
||||
// (s3:PutObject) because routing keys on the request URL; without this call,
|
||||
// an STS session token scoped to a prefix could copy from any other prefix in
|
||||
// the same bucket.
|
||||
//
|
||||
// The source path is checked against both bucket policy and IAM/identity
|
||||
// permissions, mirroring the normal request-routed flow but with a synthetic
|
||||
// GetObject request so action resolution and ARN building target the source.
|
||||
// Returns s3err.ErrNone when allowed or when auth is disabled.
|
||||
func (iam *IdentityAccessManagement) AuthorizeCopySource(r *http.Request, identity *Identity, srcBucket, srcObject, srcVersionId string) s3err.ErrorCode {
|
||||
if !iam.isEnabled() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if srcBucket == "" {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if identity == nil {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if identity.isAdmin() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
|
||||
srcReq := r.Clone(r.Context())
|
||||
srcURL := &url.URL{
|
||||
Scheme: r.URL.Scheme,
|
||||
Host: r.URL.Host,
|
||||
Path: "/" + srcBucket + "/" + srcObject,
|
||||
}
|
||||
// Build the synthetic source query from scratch so leftover params like
|
||||
// uploadId/partNumber on UploadPartCopy do not steer ResolveS3Action away
|
||||
// from s3:GetObject. The session token must still flow through for
|
||||
// presigned URLs that carry STS credentials in the query string.
|
||||
srcQuery := make(url.Values)
|
||||
if token := r.URL.Query().Get("X-Amz-Security-Token"); token != "" {
|
||||
srcQuery.Set("X-Amz-Security-Token", token)
|
||||
}
|
||||
if srcVersionId != "" {
|
||||
srcQuery.Set("versionId", srcVersionId)
|
||||
}
|
||||
if len(srcQuery) > 0 {
|
||||
srcURL.RawQuery = srcQuery.Encode()
|
||||
}
|
||||
srcReq.URL = srcURL
|
||||
srcReq.Method = http.MethodGet
|
||||
srcReq.RequestURI = ""
|
||||
srcReq.Body = nil
|
||||
srcReq.GetBody = nil
|
||||
srcReq.ContentLength = 0
|
||||
|
||||
action := s3_constants.ACTION_READ
|
||||
|
||||
if iam.policyEngine != nil {
|
||||
principal := buildPrincipalARN(identity, srcReq)
|
||||
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(srcBucket, srcObject, action, principal, srcReq, identity.Claims, nil)
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObject source policy evaluation failed for %s/%s: %v - denying", srcBucket, srcObject, err)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if evaluated {
|
||||
if allowed {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
}
|
||||
|
||||
return iam.VerifyActionPermission(srcReq, identity, Action(action), srcBucket, srcObject)
|
||||
}
|
||||
|
||||
// authorizeWithIAM authorizes requests using the IAM integration policy engine
|
||||
func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode {
|
||||
ctx := r.Context()
|
||||
@@ -2220,7 +2385,6 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
|
||||
// PutPolicy adds or updates a policy
|
||||
func (iam *IdentityAccessManagement) PutPolicy(name string, content string) error {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
if iam.policies == nil {
|
||||
iam.policies = make(map[string]*iam_pb.Policy)
|
||||
}
|
||||
@@ -2231,6 +2395,12 @@ func (iam *IdentityAccessManagement) PutPolicy(name string, content string) erro
|
||||
if err := iam.iamPolicyEngine.SetBucketPolicy(name, content); err != nil {
|
||||
glog.Warningf("IAM policy %q is stored but could not be compiled for cache: %v", name, err)
|
||||
}
|
||||
iam.m.Unlock()
|
||||
// Also sync to the advanced IAM Manager's policy engine so that the
|
||||
// authorizeWithIAM path (used when identity has policy_names) sees the update.
|
||||
// Done after releasing iam.m so the per-request auth RLock path isn't blocked
|
||||
// by the policy recompile.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2247,14 +2417,26 @@ func (iam *IdentityAccessManagement) GetPolicy(name string) (*iam_pb.Policy, err
|
||||
// DeletePolicy removes a policy
|
||||
func (iam *IdentityAccessManagement) DeletePolicy(name string) error {
|
||||
iam.m.Lock()
|
||||
defer iam.m.Unlock()
|
||||
delete(iam.policies, name)
|
||||
if iam.iamPolicyEngine != nil {
|
||||
_ = iam.iamPolicyEngine.DeleteBucketPolicy(name)
|
||||
}
|
||||
iam.m.Unlock()
|
||||
// Also sync the removal to the advanced IAM Manager's policy engine.
|
||||
iam.resyncIAMManagerPolicies()
|
||||
return nil
|
||||
}
|
||||
|
||||
// collectPoliciesLocked returns all policies as a slice for SyncRuntimePolicies.
|
||||
// Caller must hold iam.m (read or write).
|
||||
func (iam *IdentityAccessManagement) collectPoliciesLocked() []*iam_pb.Policy {
|
||||
policies := make([]*iam_pb.Policy, 0, len(iam.policies))
|
||||
for _, p := range iam.policies {
|
||||
policies = append(policies, p)
|
||||
}
|
||||
return policies
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) PutGroup(group *iam_pb.Group) error {
|
||||
if group == nil {
|
||||
return fmt.Errorf("put group failed: nil group")
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newTestIAMManager(t *testing.T) *integration.IAMManager {
|
||||
t.Helper()
|
||||
mgr := integration.NewIAMManager()
|
||||
require.NoError(t, mgr.Initialize(&integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test",
|
||||
SigningKey: []byte("test-signing-key-32-characters!!"),
|
||||
AccountId: "111122223333",
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Allow", StoreType: "memory"},
|
||||
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
return mgr
|
||||
}
|
||||
|
||||
func TestPutPolicy_SyncsToIAMManager(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed, "PutPolicy should sync to IAM Manager policy engine")
|
||||
}
|
||||
|
||||
func TestDeletePolicy_SyncsToIAMManager(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
require.NoError(t, iam.DeletePolicy("BackupAll"))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.False(t, allowed, "DeletePolicy should remove from IAM Manager policy engine")
|
||||
}
|
||||
|
||||
// TestSetIAMIntegration_FlushesLoadedPolicies reproduces the startup race: a
|
||||
// policy is loaded into the IAM cache before the integration is attached (so the
|
||||
// sync was skipped), then SetIAMIntegration must flush it into the manager's
|
||||
// engine. Without the flush, policy_names identities get AccessDenied until an
|
||||
// external IAM change triggers a reload.
|
||||
func TestSetIAMIntegration_FlushesLoadedPolicies(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::backup/*"},
|
||||
},
|
||||
})
|
||||
|
||||
// Integration not attached yet, so this only lands in the legacy engine.
|
||||
require.NoError(t, iam.PutPolicy("BackupAll", string(policyDoc)))
|
||||
|
||||
mgr := newTestIAMManager(t)
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::backup/file.txt",
|
||||
PolicyNames: []string{"BackupAll"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, allowed, "SetIAMIntegration should flush already-loaded policies into the IAM Manager")
|
||||
}
|
||||
|
||||
// TestResyncIAMManager_ReflectsCurrentPolicies pins the property that prevents
|
||||
// the stale-snapshot race: SyncRuntimePolicies replaces the full desired set, so
|
||||
// the resync must derive that set from the live iam.policies map at apply time,
|
||||
// not from a view captured earlier. Here the map is mutated out from under an
|
||||
// already-synced policy, and the next resync must converge the manager onto the
|
||||
// new map rather than reinstating the old state.
|
||||
func TestResyncIAMManager_ReflectsCurrentPolicies(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
doc := func(name string) string {
|
||||
b, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::" + name + "/*"},
|
||||
},
|
||||
})
|
||||
return string(b)
|
||||
}
|
||||
allows := func(name string) bool {
|
||||
allowed, err := mgr.IsActionAllowed(context.Background(), &integration.ActionRequest{
|
||||
Principal: "arn:aws:iam::111122223333:user/test",
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::" + name + "/file.txt",
|
||||
PolicyNames: []string{name},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return allowed
|
||||
}
|
||||
|
||||
require.NoError(t, iam.PutPolicy("alpha", doc("alpha")))
|
||||
require.True(t, allows("alpha"))
|
||||
|
||||
// Swap the map contents without going through PutPolicy/DeletePolicy, then
|
||||
// resync. A snapshot-based sync would push a pre-swap view; the fresh-read
|
||||
// resync must mirror the current map: alpha gone, beta present.
|
||||
iam.m.Lock()
|
||||
delete(iam.policies, "alpha")
|
||||
iam.policies["beta"] = &iam_pb.Policy{Name: "beta", Content: doc("beta")}
|
||||
iam.m.Unlock()
|
||||
iam.resyncIAMManagerPolicies()
|
||||
|
||||
require.False(t, allows("alpha"), "resync should drop a policy no longer in the map")
|
||||
require.True(t, allows("beta"), "resync should add a policy newly in the map")
|
||||
}
|
||||
@@ -45,3 +45,32 @@ func TestLoadIAMManagerFromConfig_EmptyConfigWithFallbackKey(t *testing.T) {
|
||||
_, found := iamManager.LookupAnonymous()
|
||||
assert.False(t, found, "Anonymous identity should not be found when not explicitly configured")
|
||||
}
|
||||
|
||||
// TestSetIAMIntegrationKeepsAuthDisabledWithoutConfig is a regression test for
|
||||
// issue #9557. The `weed mini` defaults (and the bare `docker run seaweedfs`
|
||||
// image) start with EnableIam=true but no IAM config file and no identities.
|
||||
// The advanced-IAM init path used to also flip isAuthEnabled to true via
|
||||
// SetIAMIntegration, which then rejected every anonymous request as
|
||||
// AccessDenied — breaking out-of-the-box S3 access. Setting an integration
|
||||
// must not, on its own, enable auth enforcement; explicit configs use
|
||||
// EnableAuthEnforcement to opt in.
|
||||
func TestSetIAMIntegrationKeepsAuthDisabledWithoutConfig(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
|
||||
option := &S3ApiServerOption{
|
||||
EnableIam: true,
|
||||
}
|
||||
iam := NewIdentityAccessManagementWithStore(option, nil, "memory")
|
||||
|
||||
// Simulate an integration object being plugged in (the constructor in
|
||||
// s3api_server.go does this when EnableIam=true, even with no config file).
|
||||
// We only care that auth stays off — the integration value itself is opaque.
|
||||
iam.SetIAMIntegration(&S3IAMIntegration{})
|
||||
|
||||
assert.False(t, iam.isEnabled(), "Auth must stay disabled when no identities and no IamConfig are configured")
|
||||
|
||||
// And EnableAuthEnforcement does flip it on — this is what the startup
|
||||
// path runs when the operator explicitly passes -s3.iam.config.
|
||||
iam.EnableAuthEnforcement()
|
||||
assert.True(t, iam.isEnabled(), "EnableAuthEnforcement must turn auth on")
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
@@ -248,24 +249,65 @@ type contextKey string
|
||||
const (
|
||||
contextKeyIdentityName contextKey = "s3-identity-name"
|
||||
contextKeyIdentityObject contextKey = "s3-identity-object"
|
||||
contextKeyIdentityHolder contextKey = "s3-identity-holder"
|
||||
)
|
||||
|
||||
// identityHolder is a mutable container for the authenticated identity name,
|
||||
// stored by pointer in the request context. Authentication runs as an inner
|
||||
// handler that records the identity with r.WithContext, which returns a request
|
||||
// copy; that copy's new context values are invisible to outer middleware (e.g.
|
||||
// the audit logger) holding an earlier copy of the request. A pointer to a
|
||||
// holder installed before authentication is shared across all copies, so the
|
||||
// name written by the inner handler is readable by the outer middleware.
|
||||
type identityHolder struct {
|
||||
name atomic.Pointer[string]
|
||||
}
|
||||
|
||||
// EnsureIdentityHolder attaches a mutable identity holder to the request context
|
||||
// if one is not already present, returning the (possibly new) request. Install
|
||||
// it before authentication so the authenticated requester remains recoverable
|
||||
// from the original request, e.g. when emitting an audit entry for a handler
|
||||
// that does not log the requester itself.
|
||||
func EnsureIdentityHolder(r *http.Request) *http.Request {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if h, ok := r.Context().Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
return r
|
||||
}
|
||||
return r.WithContext(context.WithValue(r.Context(), contextKeyIdentityHolder, &identityHolder{}))
|
||||
}
|
||||
|
||||
// SetIdentityNameInContext stores the authenticated identity name in the request context
|
||||
// This is the secure way to propagate identity - headers can be spoofed, context cannot
|
||||
func SetIdentityNameInContext(ctx context.Context, identityName string) context.Context {
|
||||
if identityName != "" {
|
||||
return context.WithValue(ctx, contextKeyIdentityName, identityName)
|
||||
if identityName == "" {
|
||||
return ctx
|
||||
}
|
||||
return ctx
|
||||
// Also record into the mutable holder (if installed) so the name survives the
|
||||
// request-context copy and stays visible to outer middleware such as the
|
||||
// audit logger.
|
||||
if h, ok := ctx.Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
h.name.Store(&identityName)
|
||||
}
|
||||
return context.WithValue(ctx, contextKeyIdentityName, identityName)
|
||||
}
|
||||
|
||||
// GetIdentityNameFromContext retrieves the authenticated identity name from the request context
|
||||
// Returns empty string if no identity is set (unauthenticated request)
|
||||
// This is the secure way to retrieve identity - never read from headers directly
|
||||
func GetIdentityNameFromContext(r *http.Request) string {
|
||||
if name, ok := r.Context().Value(contextKeyIdentityName).(string); ok {
|
||||
// Prefer the per-request context value; fall back to the mutable holder for
|
||||
// callers (e.g. the audit middleware) that hold a copy of the request taken
|
||||
// before authentication set the identity.
|
||||
if name, ok := r.Context().Value(contextKeyIdentityName).(string); ok && name != "" {
|
||||
return name
|
||||
}
|
||||
if h, ok := r.Context().Value(contextKeyIdentityHolder).(*identityHolder); ok && h != nil {
|
||||
if name := h.name.Load(); name != nil {
|
||||
return *name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package s3_constants
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -129,3 +131,55 @@ func TestRemoveDuplicateSlashes(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityHolderPropagation reproduces the audit-log middleware chain: an
|
||||
// outer handler installs the holder, an inner handler authenticates and records
|
||||
// the identity on a request copy, and the outer handler must still recover the
|
||||
// requester from its own (earlier) copy of the request.
|
||||
func TestIdentityHolderPropagation(t *testing.T) {
|
||||
outer := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
|
||||
// Before the holder is installed there is no identity to recover.
|
||||
if got := GetIdentityNameFromContext(outer); got != "" {
|
||||
t.Fatalf("unauthenticated request reports requester %q, want empty", got)
|
||||
}
|
||||
|
||||
outer = EnsureIdentityHolder(outer)
|
||||
|
||||
// The inner handler sets the identity on a copy, mirroring how auth wraps
|
||||
// the request with r.WithContext before invoking the next handler.
|
||||
innerCtx := SetIdentityNameInContext(outer.Context(), "admin")
|
||||
inner := outer.WithContext(innerCtx)
|
||||
|
||||
if got := GetIdentityNameFromContext(inner); got != "admin" {
|
||||
t.Errorf("inner request requester = %q, want admin", got)
|
||||
}
|
||||
if got := GetIdentityNameFromContext(outer); got != "admin" {
|
||||
t.Errorf("outer request requester = %q, want admin (must propagate via holder)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureIdentityHolderIdempotent(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
|
||||
first := EnsureIdentityHolder(req)
|
||||
if first == req {
|
||||
t.Fatal("EnsureIdentityHolder should return a new request when no holder is present")
|
||||
}
|
||||
|
||||
again := EnsureIdentityHolder(first)
|
||||
if again != first {
|
||||
t.Error("EnsureIdentityHolder should be idempotent when a holder is already present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetIdentityNameFromContextWithoutHolder(t *testing.T) {
|
||||
// Without a holder, the per-request context value is still honored so paths
|
||||
// that set identity without installing a holder keep working.
|
||||
req := httptest.NewRequest(http.MethodGet, "/bucket/object", nil)
|
||||
req = req.WithContext(SetIdentityNameInContext(req.Context(), "admin"))
|
||||
|
||||
if got := GetIdentityNameFromContext(req); got != "admin" {
|
||||
t.Errorf("requester = %q, want admin", got)
|
||||
}
|
||||
}
|
||||
@@ -928,8 +928,10 @@ func TestS3IAMOnlyModeRejectsAnonymous(t *testing.T) {
|
||||
s3IAMIntegration := NewS3IAMIntegration(iamManager, "localhost:8888")
|
||||
require.NotNil(t, s3IAMIntegration)
|
||||
|
||||
// Set IAM integration - this should enable auth
|
||||
// Set IAM integration and explicitly enforce auth, matching what the
|
||||
// startup path does when an operator passes -s3.iam.config (#9557).
|
||||
iam.SetIAMIntegration(s3IAMIntegration)
|
||||
iam.EnableAuthEnforcement()
|
||||
|
||||
// Verify auth is enabled
|
||||
require.True(t, iam.isEnabled(), "Auth must be enabled when IAM integration is configured")
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// Stub responses for bucket configuration sub-resources that SeaweedFS does
|
||||
// not store (analytics, inventory, intelligent-tiering, metrics). AWS SDKs
|
||||
// probe these on bucket discovery; returning a well-formed empty list keeps
|
||||
// them happy instead of failing with MethodNotAllowed.
|
||||
|
||||
const s3XMLNamespace = "http://s3.amazonaws.com/doc/2006-03-01/"
|
||||
|
||||
type listBucketAnalyticsConfigurationsResult struct {
|
||||
XMLName xml.Name `xml:"ListBucketAnalyticsConfigurationsResult"`
|
||||
Xmlns string `xml:"xmlns,attr"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
}
|
||||
|
||||
type listInventoryConfigurationsResult struct {
|
||||
XMLName xml.Name `xml:"ListInventoryConfigurationsResult"`
|
||||
Xmlns string `xml:"xmlns,attr"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
}
|
||||
|
||||
type listBucketIntelligentTieringConfigurationsResult struct {
|
||||
XMLName xml.Name `xml:"ListBucketIntelligentTieringConfigurationsResult"`
|
||||
Xmlns string `xml:"xmlns,attr"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
}
|
||||
|
||||
type listBucketMetricsConfigurationsResult struct {
|
||||
XMLName xml.Name `xml:"ListBucketMetricsConfigurationsResult"`
|
||||
Xmlns string `xml:"xmlns,attr"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
}
|
||||
|
||||
// stubBucketGuard fails with NoSuchBucket when the bucket does not exist, so
|
||||
// that AWS's documented precedence (bucket lookup before sub-resource lookup)
|
||||
// is preserved across these stub endpoints.
|
||||
func (s3a *S3ApiServer) stubBucketGuard(w http.ResponseWriter, r *http.Request) bool {
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetAnalyticsConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchConfiguration)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketAnalyticsConfigurations(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, listBucketAnalyticsConfigurationsResult{Xmlns: s3XMLNamespace})
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetInventoryConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchConfiguration)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketInventoryConfigurations(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, listInventoryConfigurationsResult{Xmlns: s3XMLNamespace})
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetIntelligentTieringConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchConfiguration)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketIntelligentTieringConfigurations(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, listBucketIntelligentTieringConfigurationsResult{Xmlns: s3XMLNamespace})
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetMetricsConfiguration(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchConfiguration)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) ListBucketMetricsConfigurations(w http.ResponseWriter, r *http.Request) {
|
||||
if !s3a.stubBucketGuard(w, r) {
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, listBucketMetricsConfigurationsResult{Xmlns: s3XMLNamespace})
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func TestBucketConfigStubs(t *testing.T) {
|
||||
const bucket = "stub-bucket"
|
||||
s3a := &S3ApiServer{
|
||||
iam: &IdentityAccessManagement{isAuthEnabled: true},
|
||||
bucketConfigCache: NewBucketConfigCache(time.Minute),
|
||||
}
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{Name: bucket},
|
||||
})
|
||||
|
||||
listCases := []struct {
|
||||
name string
|
||||
query string
|
||||
rootElement string
|
||||
handler http.HandlerFunc
|
||||
}{
|
||||
{"AnalyticsList", "analytics", "ListBucketAnalyticsConfigurationsResult", s3a.ListBucketAnalyticsConfigurations},
|
||||
{"InventoryList", "inventory", "ListInventoryConfigurationsResult", s3a.ListBucketInventoryConfigurations},
|
||||
{"IntelligentTieringList", "intelligent-tiering", "ListBucketIntelligentTieringConfigurationsResult", s3a.ListBucketIntelligentTieringConfigurations},
|
||||
{"MetricsList", "metrics", "ListBucketMetricsConfigurationsResult", s3a.ListBucketMetricsConfigurations},
|
||||
}
|
||||
for _, tc := range listCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"?"+tc.query, nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
rr := httptest.NewRecorder()
|
||||
tc.handler(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
body := rr.Body.String()
|
||||
if !strings.Contains(body, "<"+tc.rootElement) {
|
||||
t.Fatalf("expected root element %q in body: %s", tc.rootElement, body)
|
||||
}
|
||||
if !strings.Contains(body, "<IsTruncated>false</IsTruncated>") {
|
||||
t.Fatalf("expected IsTruncated=false in body: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
getCases := []struct {
|
||||
name string
|
||||
query string
|
||||
handler http.HandlerFunc
|
||||
}{
|
||||
{"AnalyticsGet", "analytics&id=x", s3a.GetAnalyticsConfiguration},
|
||||
{"InventoryGet", "inventory&id=x", s3a.GetInventoryConfiguration},
|
||||
{"IntelligentTieringGet", "intelligent-tiering&id=x", s3a.GetIntelligentTieringConfiguration},
|
||||
{"MetricsGet", "metrics&id=x", s3a.GetMetricsConfiguration},
|
||||
}
|
||||
for _, tc := range getCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/"+bucket+"?"+tc.query, nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
rr := httptest.NewRecorder()
|
||||
tc.handler(rr, req)
|
||||
|
||||
if rr.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if !strings.Contains(rr.Body.String(), "<Code>NoSuchConfiguration</Code>") {
|
||||
t.Fatalf("expected NoSuchConfiguration code in body: %s", rr.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// putBucketRequestPaymentMaxBodyBytes caps the request body for PutBucketRequestPayment
|
||||
// to prevent DoS via large payloads. The valid payload is a few hundred bytes.
|
||||
const putBucketRequestPaymentMaxBodyBytes = 64 * 1024
|
||||
|
||||
type policyStatusResponse struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ PolicyStatus"`
|
||||
IsPublic bool `xml:"IsPublic"`
|
||||
}
|
||||
|
||||
type accelerateConfigurationResponse struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ AccelerateConfiguration"`
|
||||
Status string `xml:"Status"`
|
||||
}
|
||||
|
||||
type bucketLoggingStatusResponse struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ BucketLoggingStatus"`
|
||||
}
|
||||
|
||||
// GetBucketPolicyStatusHandler reports whether the bucket policy grants public access.
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicyStatus.html
|
||||
func (s3a *S3ApiServer) GetBucketPolicyStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
|
||||
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
policyDoc, err := s3a.getBucketPolicy(bucket)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrPolicyNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucketPolicy)
|
||||
} else if errors.Is(err, ErrBucketNotFound) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
|
||||
} else {
|
||||
glog.Errorf("GetBucketPolicyStatusHandler load policy %s: %v", bucket, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccessResponseXML(w, r, policyStatusResponse{IsPublic: isPolicyPublic(policyDoc)})
|
||||
}
|
||||
|
||||
// isPolicyPublic returns true if any Allow statement grants access to "*" without restricting conditions.
|
||||
func isPolicyPublic(doc *policy_engine.PolicyDocument) bool {
|
||||
if doc == nil {
|
||||
return false
|
||||
}
|
||||
for _, st := range doc.Statement {
|
||||
if st.Effect != policy_engine.PolicyEffectAllow {
|
||||
continue
|
||||
}
|
||||
if len(st.Condition) > 0 {
|
||||
continue
|
||||
}
|
||||
for _, p := range st.Principal.Strings() {
|
||||
if p == "*" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PutBucketRequestPaymentHandler accepts only Payer=BucketOwner; Requester is rejected.
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketRequestPayment.html
|
||||
func (s3a *S3ApiServer) PutBucketRequestPaymentHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
|
||||
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, putBucketRequestPaymentMaxBodyBytes)
|
||||
defer r.Body.Close()
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
|
||||
return
|
||||
}
|
||||
|
||||
var cfg RequestPaymentConfiguration
|
||||
if err := xml.Unmarshal(body, &cfg); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
|
||||
return
|
||||
}
|
||||
|
||||
if cfg.Payer != "BucketOwner" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccessResponseEmpty(w, r)
|
||||
}
|
||||
|
||||
// GetBucketAccelerateConfigurationHandler returns a static Suspended status.
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAccelerateConfiguration.html
|
||||
func (s3a *S3ApiServer) GetBucketAccelerateConfigurationHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, accelerateConfigurationResponse{Status: "Suspended"})
|
||||
}
|
||||
|
||||
// GetBucketLoggingHandler returns an empty BucketLoggingStatus (logging disabled).
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLogging.html
|
||||
func (s3a *S3ApiServer) GetBucketLoggingHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, _ := s3_constants.GetBucketAndObject(r)
|
||||
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, err)
|
||||
return
|
||||
}
|
||||
writeSuccessResponseXML(w, r, bucketLoggingStatusResponse{})
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
)
|
||||
|
||||
func newMiscTestServer(t *testing.T, bucket string) *S3ApiServer {
|
||||
t.Helper()
|
||||
s3a := &S3ApiServer{
|
||||
iam: &IdentityAccessManagement{isAuthEnabled: true},
|
||||
bucketConfigCache: NewBucketConfigCache(time.Minute),
|
||||
}
|
||||
s3a.bucketConfigCache.Set(bucket, &BucketConfig{
|
||||
Name: bucket,
|
||||
Entry: &filer_pb.Entry{Name: bucket},
|
||||
})
|
||||
return s3a
|
||||
}
|
||||
|
||||
func newBucketRequest(method, bucket, query, body string) *http.Request {
|
||||
req := httptest.NewRequest(method, "/"+bucket+"?"+query, strings.NewReader(body))
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": bucket})
|
||||
return req
|
||||
}
|
||||
|
||||
func TestGetBucketPolicyStatusIsPublic(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "public allow star",
|
||||
raw: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}]}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "deny is not public",
|
||||
raw: `{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}]}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "condition makes it non-public",
|
||||
raw: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*","Condition":{"IpAddress":{"aws:SourceIp":"10.0.0.0/8"}}}]}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "specific principal is not public",
|
||||
raw: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"arn:aws:iam::1:user/a","Action":"s3:GetObject","Resource":"arn:aws:s3:::b/*"}]}`,
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var doc policy_engine.PolicyDocument
|
||||
if err := json.Unmarshal([]byte(tc.raw), &doc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if got := isPolicyPublic(&doc); got != tc.want {
|
||||
t.Fatalf("isPolicyPublic = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutBucketRequestPaymentBucketOwner(t *testing.T) {
|
||||
s3a := newMiscTestServer(t, "b")
|
||||
body := `<RequestPaymentConfiguration><Payer>BucketOwner</Payer></RequestPaymentConfiguration>`
|
||||
req := newBucketRequest(http.MethodPut, "b", "requestPayment=", body)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
s3a.PutBucketRequestPaymentHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutBucketRequestPaymentRequesterRejected(t *testing.T) {
|
||||
s3a := newMiscTestServer(t, "b")
|
||||
body := `<RequestPaymentConfiguration><Payer>Requester</Payer></RequestPaymentConfiguration>`
|
||||
req := newBucketRequest(http.MethodPut, "b", "requestPayment=", body)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
s3a.PutBucketRequestPaymentHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "MalformedXML") {
|
||||
t.Fatalf("body missing MalformedXML: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBucketAccelerateConfiguration(t *testing.T) {
|
||||
s3a := newMiscTestServer(t, "b")
|
||||
req := newBucketRequest(http.MethodGet, "b", "accelerate=", "")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
s3a.GetBucketAccelerateConfigurationHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
body, err := io.ReadAll(rec.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
got := string(body)
|
||||
if !strings.Contains(got, "<AccelerateConfiguration") {
|
||||
t.Fatalf("missing root element: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "<Status>Suspended</Status>") {
|
||||
t.Fatalf("missing Suspended status: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, `xmlns="http://s3.amazonaws.com/doc/2006-03-01/"`) {
|
||||
t.Fatalf("missing xmlns: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBucketLogging(t *testing.T) {
|
||||
s3a := newMiscTestServer(t, "b")
|
||||
req := newBucketRequest(http.MethodGet, "b", "logging=", "")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
s3a.GetBucketLoggingHandler(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
got := rec.Body.String()
|
||||
if !strings.Contains(got, "<BucketLoggingStatus") {
|
||||
t.Fatalf("missing root element: %s", got)
|
||||
}
|
||||
if strings.Contains(got, "<LoggingEnabled") {
|
||||
t.Fatalf("unexpected LoggingEnabled element: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, `xmlns="http://s3.amazonaws.com/doc/2006-03-01/"`) {
|
||||
t.Fatalf("missing xmlns: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,9 @@ const (
|
||||
MaxServiceAccountsPerUser = 100 // Maximum service accounts per user
|
||||
MaxDescriptionLength = 1000 // Maximum description length in characters
|
||||
MaxManagedPoliciesPerUser = 10 // Maximum managed policies attached to a user
|
||||
MaxUserTags = 50 // Maximum tags per user
|
||||
MaxUserTagKeyLength = 128 // Maximum tag key length
|
||||
MaxUserTagValueLength = 256 // Maximum tag value length
|
||||
)
|
||||
|
||||
// Type aliases for IAM response types from shared package
|
||||
@@ -132,6 +135,11 @@ type (
|
||||
iamDeleteGroupPolicyResponse = iamlib.DeleteGroupPolicyResponse
|
||||
iamListGroupPoliciesResponse = iamlib.ListGroupPoliciesResponse
|
||||
iamListGroupsForUserResponse = iamlib.ListGroupsForUserResponse
|
||||
// User tag response types
|
||||
iamTagUserResponse = iamlib.TagUserResponse
|
||||
iamUntagUserResponse = iamlib.UntagUserResponse
|
||||
iamListUserTagsResponse = iamlib.ListUserTagsResponse
|
||||
iamTag = iamlib.IAMTag
|
||||
)
|
||||
|
||||
// Helper function wrappers using shared package
|
||||
@@ -206,7 +214,7 @@ func (e *EmbeddedIamApi) writeIamErrorResponse(w http.ResponseWriter, r *http.Re
|
||||
s3err.WriteXMLResponse(w, r, http.StatusNotFound, errorResp)
|
||||
case iam.ErrCodeEntityAlreadyExistsException:
|
||||
s3err.WriteXMLResponse(w, r, http.StatusConflict, errorResp)
|
||||
case iam.ErrCodeMalformedPolicyDocumentException, iam.ErrCodeInvalidInputException:
|
||||
case iam.ErrCodeMalformedPolicyDocumentException, iam.ErrCodeInvalidInputException, "ValidationError":
|
||||
s3err.WriteXMLResponse(w, r, http.StatusBadRequest, errorResp)
|
||||
case "AccessDenied", iam.ErrCodeLimitExceededException:
|
||||
s3err.WriteXMLResponse(w, r, http.StatusForbidden, errorResp)
|
||||
@@ -1159,6 +1167,217 @@ func (e *EmbeddedIamApi) ListUserPolicies(s3cfg *iam_pb.S3ApiConfiguration, valu
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(iamUserDoesNotExist, userName)}
|
||||
}
|
||||
|
||||
// parseTagListParams reads AWS query-encoded "Tags.member.N.Key" / "Tags.member.N.Value"
|
||||
// pairs from form values, returning them in numeric order.
|
||||
func parseTagListParams(values url.Values) ([]*iam_pb.UserTag, *iamError) {
|
||||
type indexed struct {
|
||||
idx int
|
||||
key string
|
||||
value string
|
||||
}
|
||||
indexes := make(map[int]*indexed)
|
||||
for name, vs := range values {
|
||||
if len(vs) == 0 || !strings.HasPrefix(name, "Tags.member.") {
|
||||
continue
|
||||
}
|
||||
rest := strings.TrimPrefix(name, "Tags.member.")
|
||||
dot := strings.Index(rest, ".")
|
||||
if dot < 0 {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.Atoi(rest[:dot])
|
||||
if err != nil || n < 1 {
|
||||
continue
|
||||
}
|
||||
entry, ok := indexes[n]
|
||||
if !ok {
|
||||
entry = &indexed{idx: n}
|
||||
indexes[n] = entry
|
||||
}
|
||||
switch rest[dot+1:] {
|
||||
case "Key":
|
||||
entry.key = vs[0]
|
||||
case "Value":
|
||||
entry.value = vs[0]
|
||||
}
|
||||
}
|
||||
keys := make([]int, 0, len(indexes))
|
||||
for k := range indexes {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Ints(keys)
|
||||
tags := make([]*iam_pb.UserTag, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
t := indexes[k]
|
||||
if t.key == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("tag key cannot be empty")}
|
||||
}
|
||||
if len(t.key) > MaxUserTagKeyLength {
|
||||
return nil, &iamError{Code: "ValidationError", Error: fmt.Errorf("tag key %q exceeds %d characters", t.key, MaxUserTagKeyLength)}
|
||||
}
|
||||
if len(t.value) > MaxUserTagValueLength {
|
||||
return nil, &iamError{Code: "ValidationError", Error: fmt.Errorf("tag value for key %q exceeds %d characters", t.key, MaxUserTagValueLength)}
|
||||
}
|
||||
tags = append(tags, &iam_pb.UserTag{Key: t.key, Value: t.value})
|
||||
}
|
||||
return tags, nil
|
||||
}
|
||||
|
||||
// parseTagKeysParams reads AWS query-encoded "TagKeys.member.N" entries and
|
||||
// validates each entry is a non-empty key within MaxUserTagKeyLength.
|
||||
func parseTagKeysParams(values url.Values) ([]string, *iamError) {
|
||||
entries := make(map[int]string)
|
||||
for name, vs := range values {
|
||||
if len(vs) == 0 || !strings.HasPrefix(name, "TagKeys.member.") {
|
||||
continue
|
||||
}
|
||||
rest := strings.TrimPrefix(name, "TagKeys.member.")
|
||||
n, err := strconv.Atoi(rest)
|
||||
if err != nil || n < 1 {
|
||||
continue
|
||||
}
|
||||
entries[n] = vs[0]
|
||||
}
|
||||
keys := make([]int, 0, len(entries))
|
||||
for k := range entries {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Ints(keys)
|
||||
result := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
key := entries[k]
|
||||
if key == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("tag key cannot be empty")}
|
||||
}
|
||||
if len(key) > MaxUserTagKeyLength {
|
||||
return nil, &iamError{Code: "ValidationError", Error: fmt.Errorf("tag key %q exceeds %d characters", key, MaxUserTagKeyLength)}
|
||||
}
|
||||
result = append(result, key)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// mergeUserTags overwrites existing tags with matching keys and appends new ones,
|
||||
// preserving original order for stable iteration.
|
||||
func mergeUserTags(existing []*iam_pb.UserTag, incoming []*iam_pb.UserTag) []*iam_pb.UserTag {
|
||||
index := make(map[string]int, len(existing))
|
||||
merged := make([]*iam_pb.UserTag, 0, len(existing)+len(incoming))
|
||||
for _, t := range existing {
|
||||
merged = append(merged, &iam_pb.UserTag{Key: t.Key, Value: t.Value})
|
||||
index[t.Key] = len(merged) - 1
|
||||
}
|
||||
for _, t := range incoming {
|
||||
if i, ok := index[t.Key]; ok {
|
||||
merged[i].Value = t.Value
|
||||
continue
|
||||
}
|
||||
index[t.Key] = len(merged)
|
||||
merged = append(merged, &iam_pb.UserTag{Key: t.Key, Value: t.Value})
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
// TagUser adds or updates tags on an IAM user.
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagUser.html
|
||||
func (e *EmbeddedIamApi) TagUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamTagUserResponse, *iamError) {
|
||||
resp := &iamTagUserResponse{}
|
||||
userName := values.Get("UserName")
|
||||
if userName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("UserName is required")}
|
||||
}
|
||||
incoming, iamErr := parseTagListParams(values)
|
||||
if iamErr != nil {
|
||||
return resp, iamErr
|
||||
}
|
||||
if len(incoming) == 0 {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("at least one tag is required")}
|
||||
}
|
||||
// Reject duplicate keys within the same request to match AWS semantics.
|
||||
seen := make(map[string]bool, len(incoming))
|
||||
for _, t := range incoming {
|
||||
if seen[t.Key] {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("duplicate tag key %q", t.Key)}
|
||||
}
|
||||
seen[t.Key] = true
|
||||
}
|
||||
for _, ident := range s3cfg.Identities {
|
||||
if ident.Name != userName {
|
||||
continue
|
||||
}
|
||||
merged := mergeUserTags(ident.Tags, incoming)
|
||||
if len(merged) > MaxUserTags {
|
||||
return resp, &iamError{Code: iam.ErrCodeLimitExceededException, Error: fmt.Errorf("cannot exceed %d tags per user", MaxUserTags)}
|
||||
}
|
||||
ident.Tags = merged
|
||||
return resp, nil
|
||||
}
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(iamUserDoesNotExist, userName)}
|
||||
}
|
||||
|
||||
// UntagUser removes the named tags from an IAM user. Unknown keys are silently ignored.
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_UntagUser.html
|
||||
func (e *EmbeddedIamApi) UntagUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamUntagUserResponse, *iamError) {
|
||||
resp := &iamUntagUserResponse{}
|
||||
userName := values.Get("UserName")
|
||||
if userName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("UserName is required")}
|
||||
}
|
||||
keys, iamErr := parseTagKeysParams(values)
|
||||
if iamErr != nil {
|
||||
return resp, iamErr
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("at least one TagKeys entry is required")}
|
||||
}
|
||||
for _, ident := range s3cfg.Identities {
|
||||
if ident.Name != userName {
|
||||
continue
|
||||
}
|
||||
if len(ident.Tags) == 0 {
|
||||
return resp, nil
|
||||
}
|
||||
toRemove := make(map[string]bool, len(keys))
|
||||
for _, k := range keys {
|
||||
toRemove[k] = true
|
||||
}
|
||||
filtered := make([]*iam_pb.UserTag, 0, len(ident.Tags))
|
||||
for _, t := range ident.Tags {
|
||||
if toRemove[t.Key] {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, t)
|
||||
}
|
||||
ident.Tags = filtered
|
||||
return resp, nil
|
||||
}
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(iamUserDoesNotExist, userName)}
|
||||
}
|
||||
|
||||
// ListUserTags returns the tags attached to an IAM user.
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUserTags.html
|
||||
// Pagination is not implemented: tag counts are bounded by MaxUserTags so the
|
||||
// full set always fits in a single response.
|
||||
func (e *EmbeddedIamApi) ListUserTags(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamListUserTagsResponse, *iamError) {
|
||||
resp := &iamListUserTagsResponse{}
|
||||
userName := values.Get("UserName")
|
||||
if userName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("UserName is required")}
|
||||
}
|
||||
for _, ident := range s3cfg.Identities {
|
||||
if ident.Name != userName {
|
||||
continue
|
||||
}
|
||||
tags := make([]*iamTag, 0, len(ident.Tags))
|
||||
for _, t := range ident.Tags {
|
||||
tags = append(tags, &iamTag{Key: t.Key, Value: t.Value})
|
||||
}
|
||||
resp.ListUserTagsResult.Tags = tags
|
||||
resp.ListUserTagsResult.IsTruncated = false
|
||||
return resp, nil
|
||||
}
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf(iamUserDoesNotExist, userName)}
|
||||
}
|
||||
|
||||
// AttachUserPolicy attaches a managed policy to a user.
|
||||
func (e *EmbeddedIamApi) AttachUserPolicy(ctx context.Context, values url.Values) (*iamAttachUserPolicyResponse, *iamError) {
|
||||
resp := &iamAttachUserPolicyResponse{}
|
||||
@@ -1986,29 +2205,130 @@ func (e *EmbeddedIamApi) ListGroupsForUser(s3cfg *iam_pb.S3ApiConfiguration, val
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// notImplementedError returns a NotImplemented IAM error for the embedded server.
|
||||
func notImplementedGroupInlineError() *iamError {
|
||||
return &iamError{Code: s3err.GetAPIError(s3err.ErrNotImplemented).Code, Error: fmt.Errorf("group inline policies are not supported in embedded IAM mode; use the standalone IAM server or managed policies (AttachGroupPolicy)")}
|
||||
// groupExists returns true if a group of the given name is present in the
|
||||
// supplied S3 IAM configuration.
|
||||
func groupExists(s3cfg *iam_pb.S3ApiConfiguration, groupName string) bool {
|
||||
for _, g := range s3cfg.Groups {
|
||||
if g.Name == groupName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PutGroupPolicy is not supported in embedded IAM mode.
|
||||
// PutGroupPolicy attaches an inline policy to a group. The document (including
|
||||
// any Condition block) is persisted via the credential store and registered
|
||||
// in the IAM policy engine via hydrateRuntimePolicies on the next reload.
|
||||
func (e *EmbeddedIamApi) PutGroupPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamPutGroupPolicyResponse, *iamError) {
|
||||
return &iamPutGroupPolicyResponse{}, notImplementedGroupInlineError()
|
||||
resp := &iamPutGroupPolicyResponse{}
|
||||
groupName := values.Get("GroupName")
|
||||
if groupName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("GroupName is required")}
|
||||
}
|
||||
policyName := values.Get("PolicyName")
|
||||
if policyName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("PolicyName is required")}
|
||||
}
|
||||
if e.credentialManager == nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
|
||||
}
|
||||
policyDocumentString := values.Get("PolicyDocument")
|
||||
policyDocument, err := e.GetPolicyDocument(&policyDocumentString)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
|
||||
}
|
||||
if !groupExists(s3cfg, groupName) {
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("group %s does not exist", groupName)}
|
||||
}
|
||||
if err := e.credentialManager.PutGroupInlinePolicy(context.Background(), groupName, policyName, policyDocument); err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
// DoActions reloads the IAM configuration for PutGroupPolicy, so the
|
||||
// engine registration via hydrateRuntimePolicies happens there. No
|
||||
// internal refresh is needed.
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// GetGroupPolicy is not supported in embedded IAM mode.
|
||||
// GetGroupPolicy returns the JSON document for an inline policy on a group.
|
||||
func (e *EmbeddedIamApi) GetGroupPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamGetGroupPolicyResponse, *iamError) {
|
||||
return &iamGetGroupPolicyResponse{}, notImplementedGroupInlineError()
|
||||
resp := &iamGetGroupPolicyResponse{}
|
||||
groupName := values.Get("GroupName")
|
||||
policyName := values.Get("PolicyName")
|
||||
if groupName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("GroupName is required")}
|
||||
}
|
||||
if policyName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("PolicyName is required")}
|
||||
}
|
||||
if !groupExists(s3cfg, groupName) {
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("group %s does not exist", groupName)}
|
||||
}
|
||||
if e.credentialManager == nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
|
||||
}
|
||||
doc, err := e.credentialManager.GetGroupInlinePolicy(context.Background(), groupName, policyName)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
if doc == nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found on group %s", policyName, groupName)}
|
||||
}
|
||||
docJSON, err := json.Marshal(doc)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
resp.GetGroupPolicyResult.GroupName = groupName
|
||||
resp.GetGroupPolicyResult.PolicyName = policyName
|
||||
resp.GetGroupPolicyResult.PolicyDocument = string(docJSON)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// DeleteGroupPolicy is not supported in embedded IAM mode.
|
||||
// DeleteGroupPolicy removes an inline policy from a group.
|
||||
func (e *EmbeddedIamApi) DeleteGroupPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamDeleteGroupPolicyResponse, *iamError) {
|
||||
return &iamDeleteGroupPolicyResponse{}, notImplementedGroupInlineError()
|
||||
resp := &iamDeleteGroupPolicyResponse{}
|
||||
groupName := values.Get("GroupName")
|
||||
policyName := values.Get("PolicyName")
|
||||
if groupName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("GroupName is required")}
|
||||
}
|
||||
if policyName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("PolicyName is required")}
|
||||
}
|
||||
if !groupExists(s3cfg, groupName) {
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("group %s does not exist", groupName)}
|
||||
}
|
||||
if e.credentialManager == nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
|
||||
}
|
||||
if err := e.credentialManager.DeleteGroupInlinePolicy(context.Background(), groupName, policyName); err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
// DoActions reloads the IAM configuration for DeleteGroupPolicy, so the
|
||||
// engine deregistration via hydrateRuntimePolicies happens there. No
|
||||
// internal refresh is needed.
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListGroupPolicies is not supported in embedded IAM mode.
|
||||
// ListGroupPolicies returns the names of inline policies attached to a group.
|
||||
func (e *EmbeddedIamApi) ListGroupPolicies(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (*iamListGroupPoliciesResponse, *iamError) {
|
||||
return &iamListGroupPoliciesResponse{}, notImplementedGroupInlineError()
|
||||
resp := &iamListGroupPoliciesResponse{}
|
||||
groupName := values.Get("GroupName")
|
||||
if groupName == "" {
|
||||
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("GroupName is required")}
|
||||
}
|
||||
if !groupExists(s3cfg, groupName) {
|
||||
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("group %s does not exist", groupName)}
|
||||
}
|
||||
if e.credentialManager == nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
|
||||
}
|
||||
names, err := e.credentialManager.ListGroupInlinePolicies(context.Background(), groupName)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
resp.ListGroupPoliciesResult.PolicyNames = names
|
||||
resp.ListGroupPoliciesResult.IsTruncated = false
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// handleImplicitUsername adds username who signs the request to values if 'username' is not specified.
|
||||
@@ -2166,6 +2486,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
switch action {
|
||||
case "ListUsers", "ListAccessKeys", "GetUser", "GetUserPolicy", "ListUserPolicies", "ListAttachedUserPolicies", "ListPolicies", "GetPolicy", "ListPolicyVersions", "GetPolicyVersion", "ListServiceAccounts", "GetServiceAccount",
|
||||
"GetGroup", "ListGroups", "ListAttachedGroupPolicies", "GetGroupPolicy", "ListGroupPolicies", "ListGroupsForUser",
|
||||
"ListUserTags",
|
||||
actionListOpenIDConnectProviders, actionGetOpenIDConnectProvider:
|
||||
// Allowed read-only actions
|
||||
default:
|
||||
@@ -2291,6 +2612,25 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
return nil, iamErr
|
||||
}
|
||||
changed = false
|
||||
case "TagUser":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.TagUser(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
case "UntagUser":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.UntagUser(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
case "ListUserTags":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.ListUserTags(s3cfg, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
changed = false
|
||||
case "AttachUserPolicy":
|
||||
var iamErr *iamError
|
||||
response, iamErr = e.AttachUserPolicy(ctx, values)
|
||||
@@ -2492,7 +2832,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
glog.Errorf("Failed to reload IAM configuration after mutation: %v", err)
|
||||
// Don't fail the request since the persistent save succeeded
|
||||
}
|
||||
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "DeletePolicy" || action == "CreateUser" {
|
||||
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "DeletePolicy" || action == "CreateUser" || action == "PutGroupPolicy" || action == "DeleteGroupPolicy" {
|
||||
// Even if changed=false (persisted via credentialManager), we should still reload
|
||||
// if we are utilizing the local in-memory cache for speed
|
||||
if err := e.ReloadConfiguration(); err != nil {
|
||||
|
||||
@@ -72,6 +72,10 @@ func NewEmbeddedIamApiForTest() *EmbeddedIamApiForTest {
|
||||
for i, p := range config.Policies {
|
||||
s3cfg.Policies[i] = proto.Clone(p).(*iam_pb.Policy)
|
||||
}
|
||||
s3cfg.Groups = make([]*iam_pb.Group, len(config.Groups))
|
||||
for i, g := range config.Groups {
|
||||
s3cfg.Groups[i] = proto.Clone(g).(*iam_pb.Group)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -619,37 +623,47 @@ func TestEmbeddedIamListUserPolicies(t *testing.T) {
|
||||
assert.Equal(t, http.StatusNotFound, rr3.Code)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamGroupInlinePoliciesNotImplemented tests that group inline policies
|
||||
// return NotImplemented in embedded IAM mode.
|
||||
func TestEmbeddedIamGroupInlinePoliciesNotImplemented(t *testing.T) {
|
||||
// TestEmbeddedIamGroupInlinePolicies_CRUD exercises the Put/Get/List/Delete
|
||||
// round-trip for group inline policies and verifies that an unknown policy
|
||||
// surfaces as NoSuchEntity (not the legacy NotImplemented).
|
||||
func TestEmbeddedIamGroupInlinePolicies_CRUD(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Groups: []*iam_pb.Group{
|
||||
{Name: "developers", Members: []string{"alice"}},
|
||||
},
|
||||
}
|
||||
api.mockConfig = s3cfg
|
||||
|
||||
notImpl := s3err.GetAPIError(s3err.ErrNotImplemented).Code
|
||||
policyDoc := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::*"}]}`
|
||||
|
||||
_, iamErr := api.PutGroupPolicy(s3cfg, url.Values{
|
||||
"GroupName": {"developers"},
|
||||
"PolicyName": {"DevPolicy"},
|
||||
"PolicyDocument": {`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::*"}]}`},
|
||||
"PolicyDocument": {policyDoc},
|
||||
})
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, notImpl, iamErr.Code)
|
||||
require.Nil(t, iamErr, "PutGroupPolicy must succeed; got: %+v", iamErr)
|
||||
|
||||
_, iamErr = api.GetGroupPolicy(s3cfg, url.Values{"GroupName": {"developers"}, "PolicyName": {"DevPolicy"}})
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, notImpl, iamErr.Code)
|
||||
listResp, iamErr := api.ListGroupPolicies(s3cfg, url.Values{"GroupName": {"developers"}})
|
||||
require.Nil(t, iamErr)
|
||||
assert.Equal(t, []string{"DevPolicy"}, listResp.ListGroupPoliciesResult.PolicyNames)
|
||||
|
||||
getResp, iamErr := api.GetGroupPolicy(s3cfg, url.Values{"GroupName": {"developers"}, "PolicyName": {"DevPolicy"}})
|
||||
require.Nil(t, iamErr)
|
||||
assert.Equal(t, "developers", getResp.GetGroupPolicyResult.GroupName)
|
||||
assert.Equal(t, "DevPolicy", getResp.GetGroupPolicyResult.PolicyName)
|
||||
assert.Contains(t, getResp.GetGroupPolicyResult.PolicyDocument, "s3:GetObject")
|
||||
|
||||
_, iamErr = api.DeleteGroupPolicy(s3cfg, url.Values{"GroupName": {"developers"}, "PolicyName": {"DevPolicy"}})
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, notImpl, iamErr.Code)
|
||||
require.Nil(t, iamErr)
|
||||
|
||||
_, iamErr = api.ListGroupPolicies(s3cfg, url.Values{"GroupName": {"developers"}})
|
||||
assert.NotNil(t, iamErr)
|
||||
assert.Equal(t, notImpl, iamErr.Code)
|
||||
_, iamErr = api.GetGroupPolicy(s3cfg, url.Values{"GroupName": {"developers"}, "PolicyName": {"DevPolicy"}})
|
||||
require.NotNil(t, iamErr)
|
||||
assert.Equal(t, iam.ErrCodeNoSuchEntityException, iamErr.Code)
|
||||
|
||||
_, iamErr = api.GetGroupPolicy(s3cfg, url.Values{"GroupName": {"ghosts"}, "PolicyName": {"DevPolicy"}})
|
||||
require.NotNil(t, iamErr, "GetGroupPolicy on a missing group must error")
|
||||
assert.Equal(t, iam.ErrCodeNoSuchEntityException, iamErr.Code)
|
||||
}
|
||||
|
||||
// TestEmbeddedIamAttachUserPolicy tests attaching a managed policy to a user.
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// postTagAction issues a form-encoded IAM request via the test router.
|
||||
func postTagAction(t *testing.T, api *EmbeddedIamApiForTest, form url.Values) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, "/", strings.NewReader(form.Encode()))
|
||||
require.NoError(t, err)
|
||||
req.PostForm = form
|
||||
req.Form = form
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rr := httptest.NewRecorder()
|
||||
r := mux.NewRouter().SkipClean(true)
|
||||
r.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
|
||||
r.ServeHTTP(rr, req)
|
||||
return rr
|
||||
}
|
||||
|
||||
func findIdentity(cfg *iam_pb.S3ApiConfiguration, name string) *iam_pb.Identity {
|
||||
for _, ident := range cfg.Identities {
|
||||
if ident.Name == name {
|
||||
return ident
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUser(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "alice"}},
|
||||
}
|
||||
|
||||
params := &iam.TagUserInput{
|
||||
UserName: aws.String("alice"),
|
||||
Tags: []*iam.Tag{
|
||||
{Key: aws.String("env"), Value: aws.String("prod")},
|
||||
{Key: aws.String("team"), Value: aws.String("storage")},
|
||||
},
|
||||
}
|
||||
req, _ := iam.New(session.New()).TagUserRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
out := iamTagUserResponse{}
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
ident := findIdentity(api.mockConfig, "alice")
|
||||
require.NotNil(t, ident)
|
||||
require.Len(t, ident.Tags, 2)
|
||||
assert.Equal(t, "env", ident.Tags[0].Key)
|
||||
assert.Equal(t, "prod", ident.Tags[0].Value)
|
||||
assert.Equal(t, "team", ident.Tags[1].Key)
|
||||
assert.Equal(t, "storage", ident.Tags[1].Value)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamListUserTags(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "bob",
|
||||
Tags: []*iam_pb.UserTag{
|
||||
{Key: "env", Value: "stage"},
|
||||
{Key: "owner", Value: "bob"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
params := &iam.ListUserTagsInput{UserName: aws.String("bob")}
|
||||
req, _ := iam.New(session.New()).ListUserTagsRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
out := iamListUserTagsResponse{}
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
require.Len(t, out.ListUserTagsResult.Tags, 2)
|
||||
assert.Equal(t, "env", out.ListUserTagsResult.Tags[0].Key)
|
||||
assert.Equal(t, "stage", out.ListUserTagsResult.Tags[0].Value)
|
||||
assert.False(t, out.ListUserTagsResult.IsTruncated)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamUntagUser(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "carol",
|
||||
Tags: []*iam_pb.UserTag{
|
||||
{Key: "env", Value: "prod"},
|
||||
{Key: "team", Value: "storage"},
|
||||
{Key: "owner", Value: "carol"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
params := &iam.UntagUserInput{
|
||||
UserName: aws.String("carol"),
|
||||
TagKeys: []*string{aws.String("team"), aws.String("missing")},
|
||||
}
|
||||
req, _ := iam.New(session.New()).UntagUserRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
ident := findIdentity(api.mockConfig, "carol")
|
||||
require.NotNil(t, ident)
|
||||
require.Len(t, ident.Tags, 2)
|
||||
keys := []string{ident.Tags[0].Key, ident.Tags[1].Key}
|
||||
assert.ElementsMatch(t, []string{"env", "owner"}, keys)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUserInvalidKeyLength(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "dave"}},
|
||||
}
|
||||
|
||||
longKey := strings.Repeat("k", MaxUserTagKeyLength+1)
|
||||
params := &iam.TagUserInput{
|
||||
UserName: aws.String("dave"),
|
||||
Tags: []*iam.Tag{{Key: aws.String(longKey), Value: aws.String("v")}},
|
||||
}
|
||||
req, _ := iam.New(session.New()).TagUserRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, http.StatusOK, rr.Code)
|
||||
code, _ := extractEmbeddedIamErrorCodeAndMessage(rr)
|
||||
assert.Equal(t, "ValidationError", code)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUserReplacesDuplicate(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "eve",
|
||||
Tags: []*iam_pb.UserTag{{Key: "env", Value: "stage"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
params := &iam.TagUserInput{
|
||||
UserName: aws.String("eve"),
|
||||
Tags: []*iam.Tag{{Key: aws.String("env"), Value: aws.String("prod")}},
|
||||
}
|
||||
req, _ := iam.New(session.New()).TagUserRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
ident := findIdentity(api.mockConfig, "eve")
|
||||
require.NotNil(t, ident)
|
||||
require.Len(t, ident.Tags, 1)
|
||||
assert.Equal(t, "env", ident.Tags[0].Key)
|
||||
assert.Equal(t, "prod", ident.Tags[0].Value)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUserLimitExceeded(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
existing := make([]*iam_pb.UserTag, 0, MaxUserTags)
|
||||
for i := 0; i < MaxUserTags; i++ {
|
||||
existing = append(existing, &iam_pb.UserTag{Key: fmt.Sprintf("k%02d", i), Value: "v"})
|
||||
}
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "frank", Tags: existing}},
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("Action", "TagUser")
|
||||
form.Set("UserName", "frank")
|
||||
form.Set("Tags.member.1.Key", "extra")
|
||||
form.Set("Tags.member.1.Value", "v")
|
||||
rr := postTagAction(t, api, form)
|
||||
|
||||
assert.Equal(t, http.StatusForbidden, rr.Code)
|
||||
code, _ := extractEmbeddedIamErrorCodeAndMessage(rr)
|
||||
assert.Equal(t, iam.ErrCodeLimitExceededException, code)
|
||||
|
||||
ident := findIdentity(api.mockConfig, "frank")
|
||||
require.NotNil(t, ident)
|
||||
assert.Len(t, ident.Tags, MaxUserTags)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamUntagUserNoOpForMissingKey(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "grace",
|
||||
Tags: []*iam_pb.UserTag{{Key: "env", Value: "prod"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("Action", "UntagUser")
|
||||
form.Set("UserName", "grace")
|
||||
form.Set("TagKeys.member.1", "missing")
|
||||
rr := postTagAction(t, api, form)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
ident := findIdentity(api.mockConfig, "grace")
|
||||
require.NotNil(t, ident)
|
||||
require.Len(t, ident.Tags, 1)
|
||||
assert.Equal(t, "env", ident.Tags[0].Key)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUserRejectsDuplicateKeyInRequest(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "henry"}},
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("Action", "TagUser")
|
||||
form.Set("UserName", "henry")
|
||||
form.Set("Tags.member.1.Key", "env")
|
||||
form.Set("Tags.member.1.Value", "stage")
|
||||
form.Set("Tags.member.2.Key", "env")
|
||||
form.Set("Tags.member.2.Value", "prod")
|
||||
rr := postTagAction(t, api, form)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, rr.Code)
|
||||
code, _ := extractEmbeddedIamErrorCodeAndMessage(rr)
|
||||
assert.Equal(t, iam.ErrCodeInvalidInputException, code)
|
||||
}
|
||||
|
||||
func TestEmbeddedIamUntagUserRejectsInvalidKeys(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
form func() url.Values
|
||||
}{
|
||||
{
|
||||
name: "no TagKeys entries",
|
||||
form: func() url.Values {
|
||||
v := url.Values{}
|
||||
v.Set("Action", "UntagUser")
|
||||
v.Set("UserName", "ivy")
|
||||
return v
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "empty TagKeys entry",
|
||||
form: func() url.Values {
|
||||
v := url.Values{}
|
||||
v.Set("Action", "UntagUser")
|
||||
v.Set("UserName", "ivy")
|
||||
v.Set("TagKeys.member.1", "")
|
||||
return v
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "TagKeys entry over MaxUserTagKeyLength",
|
||||
form: func() url.Values {
|
||||
v := url.Values{}
|
||||
v.Set("Action", "UntagUser")
|
||||
v.Set("UserName", "ivy")
|
||||
v.Set("TagKeys.member.1", strings.Repeat("k", MaxUserTagKeyLength+1))
|
||||
return v
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{Name: "ivy"}},
|
||||
}
|
||||
rr := postTagAction(t, api, tc.form())
|
||||
assert.Equal(t, http.StatusBadRequest, rr.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedIamTagUserNotFound(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
|
||||
params := &iam.TagUserInput{
|
||||
UserName: aws.String("ghost"),
|
||||
Tags: []*iam.Tag{{Key: aws.String("env"), Value: aws.String("prod")}},
|
||||
}
|
||||
req, _ := iam.New(session.New()).TagUserRequest(params)
|
||||
require.NoError(t, req.Build())
|
||||
|
||||
rr, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, http.StatusNotFound, rr.Code)
|
||||
code, _ := extractEmbeddedIamErrorCodeAndMessage(rr)
|
||||
assert.Equal(t, iam.ErrCodeNoSuchEntityException, code)
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
s3_constants "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// In-process reproducers for aws:SourceIp condition handling on inline policies.
|
||||
//
|
||||
// These exercise the full chain: PutUserPolicy/PutGroupPolicy → reload →
|
||||
// VerifyActionPermission against a synthetic HTTP request whose RemoteAddr is
|
||||
// 127.0.0.1. The whole point is to prove that the Condition block is honored
|
||||
// (or, before the fix lands, that it is silently dropped).
|
||||
|
||||
const inlineCondTestBucket = "inline-cond-bucket"
|
||||
|
||||
func inlineCondPolicyDoc(cidr string) string {
|
||||
return `{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"Action":"s3:*",
|
||||
"Resource":["arn:aws:s3:::` + inlineCondTestBucket + `","arn:aws:s3:::` + inlineCondTestBucket + `/*"],
|
||||
"Condition":{"IpAddress":{"aws:SourceIp":"` + cidr + `"}}
|
||||
}]
|
||||
}`
|
||||
}
|
||||
|
||||
// inlineCondRequest builds a minimal request that VerifyActionPermission can
|
||||
// evaluate: RemoteAddr set so extractSourceIP returns 127.0.0.1, and the bucket
|
||||
// path so GetBucketAndObject (if reached) is unambiguous.
|
||||
func inlineCondRequest(t *testing.T, method string) *http.Request {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(method, "http://s3.amazonaws.com/"+inlineCondTestBucket+"/obj", nil)
|
||||
require.NoError(t, err)
|
||||
req.Host = "s3.amazonaws.com"
|
||||
req.RemoteAddr = "127.0.0.1:54321"
|
||||
return req
|
||||
}
|
||||
|
||||
// seedInlineCondUser puts a user "alice" with a single access key into both
|
||||
// api.mockConfig and the credential store, then reloads the in-memory IAM so
|
||||
// identity lookups observe her. Returns the loaded Identity.
|
||||
func seedInlineCondUser(t *testing.T, api *EmbeddedIamApiForTest) *Identity {
|
||||
t.Helper()
|
||||
if api.mockConfig == nil {
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
}
|
||||
api.mockConfig.Identities = append(api.mockConfig.Identities, &iam_pb.Identity{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIAALICE", SecretKey: "alice-secret"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, api.credentialManager.SaveConfiguration(context.Background(), api.mockConfig))
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident, "alice must be loaded after reload")
|
||||
return ident
|
||||
}
|
||||
|
||||
// TestUserInlinePolicySourceIpCondition_Denies is the primary reproducer: a
|
||||
// user inline policy with an aws:SourceIp condition that does NOT match the
|
||||
// caller's source IP must result in AccessDenied. Today this passes (bug)
|
||||
// because PutUserPolicy flattens the document into ident.Actions and the
|
||||
// Condition block is dropped.
|
||||
func TestUserInlinePolicySourceIpCondition_Denies(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
seedInlineCondUser(t, api)
|
||||
|
||||
// Allow s3:* on the bucket only when SourceIp is in 198.51.100.0/24 (TEST-NET-2).
|
||||
// 127.0.0.1 must not match, so the action must be denied.
|
||||
_, iamErr := api.PutUserPolicy(api.mockConfig, url.Values{
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"OnlyFromTestNet"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("198.51.100.0/24")},
|
||||
})
|
||||
require.Nil(t, iamErr, "PutUserPolicy must succeed")
|
||||
require.NoError(t, api.PutS3ApiConfiguration(api.mockConfig))
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
|
||||
req := inlineCondRequest(t, http.MethodPut)
|
||||
got := api.iam.VerifyActionPermission(req, ident, s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, got,
|
||||
"PutObject from 127.0.0.1 must be denied: the user inline policy's aws:SourceIp condition (198.51.100.0/24) does not match")
|
||||
}
|
||||
|
||||
// TestUserInlinePolicySourceIpCondition_Allows is the companion: with a
|
||||
// matching CIDR (127.0.0.0/8), the same call must succeed.
|
||||
func TestUserInlinePolicySourceIpCondition_Allows(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
seedInlineCondUser(t, api)
|
||||
|
||||
_, iamErr := api.PutUserPolicy(api.mockConfig, url.Values{
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"FromLoopback"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("127.0.0.0/8")},
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
require.NoError(t, api.PutS3ApiConfiguration(api.mockConfig))
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
|
||||
req := inlineCondRequest(t, http.MethodPut)
|
||||
got := api.iam.VerifyActionPermission(req, ident, s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrNone, got,
|
||||
"PutObject from 127.0.0.1 must be allowed: the user inline policy's aws:SourceIp condition (127.0.0.0/8) matches")
|
||||
}
|
||||
|
||||
// TestGroupInlinePolicy_PutAndEnforce verifies that PutGroupPolicy is supported
|
||||
// (no longer returns NotImplemented) and that an aws:SourceIp condition on the
|
||||
// resulting inline policy is honored for group members.
|
||||
func TestGroupInlinePolicy_PutAndEnforce(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
seedInlineCondUser(t, api)
|
||||
// Groups live in their own credential-store namespace (CreateGroup, not
|
||||
// SaveConfiguration). Seed devs+alice via the dedicated API and refresh
|
||||
// through the framework hook so both mockConfig.Groups and iam.groups
|
||||
// observe the new group.
|
||||
ctx := context.Background()
|
||||
require.NoError(t, api.credentialManager.CreateGroup(ctx, &iam_pb.Group{
|
||||
Name: "devs",
|
||||
Members: []string{"alice"},
|
||||
}))
|
||||
require.NoError(t, api.refreshIAMConfiguration())
|
||||
|
||||
// PutGroupPolicy must succeed. This is the call that returns
|
||||
// NotImplemented today; this test will fail with that error.
|
||||
_, iamErr := api.PutGroupPolicy(api.mockConfig, url.Values{
|
||||
"GroupName": {"devs"},
|
||||
"PolicyName": {"DevsFromLoopback"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("198.51.100.0/24")},
|
||||
})
|
||||
require.Nil(t, iamErr, "PutGroupPolicy must succeed; got: %+v", iamErr)
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
|
||||
// Deny path: condition does not match the loopback caller.
|
||||
req := inlineCondRequest(t, http.MethodPut)
|
||||
got := api.iam.VerifyActionPermission(req, ident, s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, got,
|
||||
"group member from 127.0.0.1 must be denied when the group inline policy's aws:SourceIp condition (198.51.100.0/24) does not match")
|
||||
|
||||
// Round-trip via the store: list & get must observe the new inline policy.
|
||||
listResp, iamErr := api.ListGroupPolicies(api.mockConfig, url.Values{"GroupName": {"devs"}})
|
||||
require.Nil(t, iamErr)
|
||||
assert.Contains(t, listResp.ListGroupPoliciesResult.PolicyNames, "DevsFromLoopback")
|
||||
|
||||
getResp, iamErr := api.GetGroupPolicy(api.mockConfig, url.Values{
|
||||
"GroupName": {"devs"}, "PolicyName": {"DevsFromLoopback"},
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
assert.Contains(t, getResp.GetGroupPolicyResult.PolicyDocument, "aws:SourceIp",
|
||||
"GetGroupPolicy must round-trip the Condition block")
|
||||
|
||||
// Flip the policy to the matching CIDR and verify the allow path.
|
||||
_, iamErr = api.PutGroupPolicy(api.mockConfig, url.Values{
|
||||
"GroupName": {"devs"},
|
||||
"PolicyName": {"DevsFromLoopback"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("127.0.0.0/8")},
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident = api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
got = api.iam.VerifyActionPermission(inlineCondRequest(t, http.MethodPut), ident,
|
||||
s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrNone, got,
|
||||
"group member from 127.0.0.1 must be allowed when the group inline policy's aws:SourceIp condition (127.0.0.0/8) matches")
|
||||
|
||||
// Cleanup: DeleteGroupPolicy must also be implemented and must drop the
|
||||
// engine registration so the action is no longer permitted via this group.
|
||||
_, iamErr = api.DeleteGroupPolicy(api.mockConfig, url.Values{
|
||||
"GroupName": {"devs"}, "PolicyName": {"DevsFromLoopback"},
|
||||
})
|
||||
require.Nil(t, iamErr, "DeleteGroupPolicy must succeed")
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
ident = api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
got = api.iam.VerifyActionPermission(inlineCondRequest(t, http.MethodPut), ident,
|
||||
s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, got,
|
||||
"after DeleteGroupPolicy, the group inline policy must no longer grant access")
|
||||
}
|
||||
|
||||
// TestUserInlinePolicy_ConditionDiscriminatesAllowVsDeny pairs allow and deny
|
||||
// against the same user with the same Actions list. If the engine path is not
|
||||
// in use, both calls would hit the legacy Actions branch and both would be
|
||||
// allowed; the discriminator is that switching the CIDR must flip the result.
|
||||
func TestUserInlinePolicy_ConditionDiscriminatesAllowVsDeny(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
seedInlineCondUser(t, api)
|
||||
|
||||
// Allow from loopback first: must succeed.
|
||||
_, iamErr := api.PutUserPolicy(api.mockConfig, url.Values{
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"P"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("127.0.0.0/8")},
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
require.NoError(t, api.PutS3ApiConfiguration(api.mockConfig))
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
got := api.iam.VerifyActionPermission(inlineCondRequest(t, http.MethodPut), ident,
|
||||
s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
require.Equal(t, s3err.ErrNone, got, "policy with matching CIDR must allow")
|
||||
|
||||
// Replace with non-matching CIDR: must now deny. Same user, same action,
|
||||
// same Actions list (Admin:bucket). Only the Condition block changed.
|
||||
_, iamErr = api.PutUserPolicy(api.mockConfig, url.Values{
|
||||
"UserName": {"alice"},
|
||||
"PolicyName": {"P"},
|
||||
"PolicyDocument": {inlineCondPolicyDoc("198.51.100.0/24")},
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
require.NoError(t, api.PutS3ApiConfiguration(api.mockConfig))
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident = api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
got = api.iam.VerifyActionPermission(inlineCondRequest(t, http.MethodPut), ident,
|
||||
s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
require.Equal(t, s3err.ErrAccessDenied, got,
|
||||
"flipping aws:SourceIp to a non-matching CIDR must flip the decision; "+
|
||||
"this proves the engine (not the legacy Actions list) drives the outcome")
|
||||
}
|
||||
|
||||
// TestUserInlinePolicy_ReloadFromStore verifies that after the IAM is reloaded
|
||||
// (simulating a restart), the stored user inline policy is re-registered and
|
||||
// its Condition block is still enforced. Catches a regression where the engine
|
||||
// state is rebuilt only from managed policies, not inline ones.
|
||||
func TestUserInlinePolicy_ReloadFromStore(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
api.mockConfig = &iam_pb.S3ApiConfiguration{}
|
||||
seedInlineCondUser(t, api)
|
||||
|
||||
// Persist an inline policy via the credential store directly, bypassing
|
||||
// the API. This is the on-disk state a fresh process boots into.
|
||||
var doc policy_engine.PolicyDocument
|
||||
require.NoError(t, doc.UnmarshalJSON([]byte(inlineCondPolicyDoc("198.51.100.0/24"))))
|
||||
require.NoError(t, api.credentialManager.PutUserInlinePolicy(
|
||||
context.Background(), "alice", "OnlyFromTestNet", doc))
|
||||
|
||||
// Simulate restart: full reload from credential store.
|
||||
require.NoError(t, api.iam.LoadS3ApiConfigurationFromCredentialManager())
|
||||
|
||||
ident := api.iam.lookupByIdentityName("alice")
|
||||
require.NotNil(t, ident)
|
||||
|
||||
req := inlineCondRequest(t, http.MethodPut)
|
||||
got := api.iam.VerifyActionPermission(req, ident, s3_constants.ACTION_WRITE, inlineCondTestBucket, "obj")
|
||||
assert.Equal(t, s3err.ErrAccessDenied, got,
|
||||
"after reload, the persisted user inline policy's aws:SourceIp condition must still be honored")
|
||||
}
|
||||
@@ -324,7 +324,7 @@ func removeDuplicateSlashes(object string) string {
|
||||
// hasChildren("bucket", "empty-dir") where no children exist → false
|
||||
//
|
||||
// Performance: ~1-5ms per call (one gRPC LIST request with Limit=1)
|
||||
func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
func (s3a *S3ApiServer) hasChildren(ctx context.Context, bucket, prefix string) bool {
|
||||
// Clean up prefix: remove leading slashes
|
||||
cleanPrefix := strings.TrimPrefix(prefix, "/")
|
||||
|
||||
@@ -332,35 +332,20 @@ func (s3a *S3ApiServer) hasChildren(bucket, prefix string) bool {
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
fullPath := bucketDir + "/" + cleanPrefix
|
||||
|
||||
// Try to list one child object in the directory
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
request := &filer_pb.ListEntriesRequest{
|
||||
Directory: fullPath,
|
||||
Limit: 1,
|
||||
InclusiveStartFrom: true,
|
||||
}
|
||||
|
||||
stream, err := client.ListEntries(context.Background(), request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if we got at least one entry
|
||||
_, err = stream.Recv()
|
||||
if err == io.EOF {
|
||||
return io.EOF // No children
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// List one child object. filer_pb.List cancels the underlying ListEntries
|
||||
// stream when it returns, so gRPC's per-stream client goroutine is not leaked.
|
||||
// The caller's request context is propagated so the probe is cancelled if the
|
||||
// client disconnects.
|
||||
found := false
|
||||
err := filer_pb.List(ctx, s3a, fullPath, "", func(*filer_pb.Entry, bool) error {
|
||||
found = true
|
||||
return nil
|
||||
})
|
||||
}, "", true, 1)
|
||||
|
||||
// If we got an entry (not EOF), then it has children
|
||||
if err == nil {
|
||||
return true
|
||||
return found
|
||||
}
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, filer_pb.ErrNotFound) {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return false
|
||||
}
|
||||
glog.V(1).Infof("hasChildren: list entries failed for %s/%s: %v", bucket, cleanPrefix, err)
|
||||
@@ -2337,7 +2322,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
}
|
||||
if isZeroByteFile {
|
||||
// Check if it has children (making it an implicit directory)
|
||||
if s3a.hasChildren(bucket, object) {
|
||||
if s3a.hasChildren(r.Context(), bucket, object) {
|
||||
// This is an implicit directory with children
|
||||
// Return 404 to force clients (like s3fs) to use LIST-based discovery
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
|
||||
@@ -88,6 +88,14 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
// CopyObject requires s3:GetObject on the source in addition to s3:PutObject
|
||||
// on the destination. The Auth middleware only checked the destination, so
|
||||
// verify the source explicitly here.
|
||||
if errCode := s3a.authorizeCopySource(r, srcBucket, srcObject, srcVersionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Get detailed versioning state for source bucket
|
||||
srcVersioningState, err := s3a.getVersioningState(srcBucket)
|
||||
if err != nil {
|
||||
@@ -547,6 +555,21 @@ func (s3a *S3ApiServer) resolveSuspendedCopySourceEntry(bucket, normalizedObject
|
||||
return s3a.getLatestObjectVersion(bucket, normalizedObject)
|
||||
}
|
||||
|
||||
// authorizeCopySource enforces s3:GetObject on the CopyObject / UploadPartCopy
|
||||
// source. The route's Auth middleware only verifies destination permissions
|
||||
// because the request URL points at the destination; the source from the
|
||||
// X-Amz-Copy-Source header must be authorized separately.
|
||||
func (s3a *S3ApiServer) authorizeCopySource(r *http.Request, srcBucket, srcObject, srcVersionId string) s3err.ErrorCode {
|
||||
if s3a.iam == nil || !s3a.iam.isEnabled() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
var identity *Identity
|
||||
if id, ok := s3_constants.GetIdentityFromContext(r).(*Identity); ok {
|
||||
identity = id
|
||||
}
|
||||
return s3a.iam.AuthorizeCopySource(r, identity, srcBucket, srcObject, srcVersionId)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) canUseMetadataOnlySelfCopy(entry *filer_pb.Entry, r *http.Request, bucket, object string) bool {
|
||||
srcPath := fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), s3_constants.NormalizeObjectKey(object))
|
||||
state := DetectEncryptionStateWithEntry(entry, r, srcPath, srcPath)
|
||||
@@ -604,6 +627,17 @@ type CopyPartResult struct {
|
||||
ETag string `xml:"ETag"`
|
||||
}
|
||||
|
||||
// copyPartLocation returns the destination directory and filename for a
|
||||
// server-side copy part under the destination bucket's .uploads folder. Copy
|
||||
// parts carry a fixed "copy" suffix (rather than the random suffix
|
||||
// genPartUploadPath mints for client uploads) so re-copying a part replaces
|
||||
// its predecessor in place.
|
||||
func (s3a *S3ApiServer) copyPartLocation(dstBucket, uploadID string, partID int) (uploadDir, partName string) {
|
||||
uploadDir = s3a.genUploadsFolder(dstBucket) + "/" + uploadID
|
||||
partName = fmt.Sprintf("%04d_%s.part", partID, "copy")
|
||||
return
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Request) {
|
||||
t := time.Now().UTC().Truncate(time.Millisecond)
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html
|
||||
@@ -649,6 +683,13 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
|
||||
// UploadPartCopy requires s3:GetObject on the source. The Auth middleware
|
||||
// only verified s3:PutObject (s3:UploadPart) on the destination.
|
||||
if errCode := s3a.authorizeCopySource(r, srcBucket, srcObject, srcVersionId); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
partIDString := r.URL.Query().Get("partNumber")
|
||||
uploadID := r.URL.Query().Get("uploadId")
|
||||
|
||||
@@ -815,6 +856,15 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
Extended: make(map[string][]byte),
|
||||
}
|
||||
|
||||
// The copied part lives under the destination bucket's .uploads folder.
|
||||
// Assign destination volumes against that real filer path so they land in
|
||||
// the destination bucket's collection. r.URL.Path is the S3 request URI
|
||||
// (e.g. /bucket/key), not a filer path, so passing it would skip the
|
||||
// filer's bucket-to-collection mapping and route the copied bytes to the
|
||||
// default collection.
|
||||
uploadDir, partName := s3a.copyPartLocation(dstBucket, uploadID, partID)
|
||||
dstPartPath := uploadDir + "/" + partName
|
||||
|
||||
// Handle zero-size files or empty ranges
|
||||
if entry.Attributes.FileSize == 0 || endOffset < startOffset {
|
||||
// For zero-size files or invalid ranges, create an empty part with size 0
|
||||
@@ -822,7 +872,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
dstEntry.Chunks = nil
|
||||
} else {
|
||||
// Copy chunks that overlap with the range
|
||||
dstChunks, err := s3a.copyChunksForRange(entry, startOffset, endOffset, r.URL.Path)
|
||||
dstChunks, err := s3a.copyChunksForRange(entry, startOffset, endOffset, dstPartPath)
|
||||
if err != nil {
|
||||
glog.Errorf("CopyObjectPartHandler copy chunks error: %v", err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -832,9 +882,6 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
// Save the part entry to the multipart uploads folder
|
||||
uploadDir := s3a.genUploadsFolder(dstBucket) + "/" + uploadID
|
||||
partName := fmt.Sprintf("%04d_%s.part", partID, "copy")
|
||||
|
||||
// Check if part exists and remove it first (allow re-copying same part)
|
||||
if exists, _ := s3a.exists(uploadDir, partName, false); exists {
|
||||
if err := s3a.rm(uploadDir, partName, false, false); err != nil {
|
||||
@@ -1249,10 +1296,9 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e
|
||||
|
||||
// validateConditionalCopyHeaders validates the conditional copy headers against the source entry
|
||||
func (s3a *S3ApiServer) validateConditionalCopyHeaders(r *http.Request, entry *filer_pb.Entry) s3err.ErrorCode {
|
||||
// Calculate ETag for the source entry
|
||||
srcPath := util.FullPath(fmt.Sprintf("%s/%s", r.URL.Path, entry.Name))
|
||||
// Calculate ETag for the source entry. ETagEntry derives the tag from the
|
||||
// chunks/Md5/remote-etag only, so no path is needed here.
|
||||
filerEntry := &filer.Entry{
|
||||
FullPath: srcPath,
|
||||
Attr: filer.Attr{
|
||||
FileSize: entry.Attributes.FileSize,
|
||||
Mtime: time.Unix(entry.Attributes.Mtime, 0),
|
||||
@@ -2246,7 +2292,10 @@ func (s3a *S3ApiServer) copyCrossEncryptionChunk(chunk *filer_pb.FileChunk, sour
|
||||
|
||||
// copyChunksWithSSEC handles SSE-C aware copying with smart fast/slow path selection
|
||||
// Returns chunks and destination metadata that should be applied to the destination entry
|
||||
func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Request) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
// dstPath is the destination object's filer path, so volume assignment targets
|
||||
// the destination bucket's collection. The caller must not pass r.URL.Path (the
|
||||
// S3 request URI), which would route copied chunks to the default collection.
|
||||
func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Request, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
||||
|
||||
// Parse SSE-C headers
|
||||
copySourceKey, err := ParseSSECCopySourceHeaders(r)
|
||||
@@ -2274,7 +2323,7 @@ func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Reques
|
||||
|
||||
if isMultipartSSEC {
|
||||
glog.V(2).Infof("Detected multipart SSE-C object with %d encrypted chunks for copy", sseCChunks)
|
||||
return s3a.copyMultipartSSECChunks(entry, copySourceKey, destKey, r.URL.Path)
|
||||
return s3a.copyMultipartSSECChunks(entry, copySourceKey, destKey, dstPath)
|
||||
}
|
||||
|
||||
// Single-part SSE-C object: use original logic
|
||||
@@ -2290,13 +2339,13 @@ func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Reques
|
||||
case SSECCopyStrategyDirect:
|
||||
// FAST PATH: Direct chunk copy
|
||||
glog.V(2).Infof("Using fast path: direct chunk copy for %s", r.URL.Path)
|
||||
chunks, err := s3a.copyChunks(entry, r.URL.Path)
|
||||
chunks, err := s3a.copyChunks(entry, dstPath)
|
||||
return chunks, nil, err
|
||||
|
||||
case SSECCopyStrategyDecryptEncrypt:
|
||||
// SLOW PATH: Decrypt and re-encrypt
|
||||
glog.V(2).Infof("Using slow path: decrypt/re-encrypt for %s", r.URL.Path)
|
||||
chunks, destIV, err := s3a.copyChunksWithReencryption(entry, copySourceKey, destKey, r.URL.Path)
|
||||
chunks, destIV, err := s3a.copyChunksWithReencryption(entry, copySourceKey, destKey, dstPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
Loaded 100 of 216 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user