mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ebe196952 | ||
|
|
8ff23c85b9 |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
[codespell]
|
||||
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
|
||||
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go,./seaweed-block
|
||||
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go
|
||||
check-hidden = true
|
||||
# Ignore camelCase and PascalCase identifiers (very common in Go/Rust/JS
|
||||
# source, e.g. allLocations, publishErr, ReadInside, FlushInterval).
|
||||
|
||||
@@ -15,7 +15,7 @@ runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Install cosign
|
||||
uses: sigstore/cosign-installer@v4.1.4
|
||||
uses: sigstore/cosign-installer@v4.1.3
|
||||
|
||||
- name: Sign
|
||||
shell: bash
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.39.5
|
||||
uses: github/codeql-action/init@v4.39.4
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
with:
|
||||
languages: go
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below).
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4.39.5
|
||||
uses: github/codeql-action/autobuild@v4.39.4
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -55,4 +55,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.39.5
|
||||
uses: github/codeql-action/analyze@v4.39.4
|
||||
@@ -434,7 +434,7 @@ jobs:
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4.39.5
|
||||
uses: github/codeql-action/upload-sarif@v4.39.4
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
|
||||
@@ -515,7 +515,7 @@ jobs:
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4.39.5
|
||||
uses: github/codeql-action/upload-sarif@v4.39.4
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy-${{ matrix.variant }}
|
||||
|
||||
@@ -125,28 +125,6 @@ jobs:
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
mysql:
|
||||
image: mysql:8.4
|
||||
env:
|
||||
MYSQL_ROOT_PASSWORD: root
|
||||
ports:
|
||||
- 3306:3306
|
||||
options: >-
|
||||
--health-cmd "mysqladmin ping -uroot -proot"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v7
|
||||
@@ -158,8 +136,6 @@ jobs:
|
||||
- name: Test
|
||||
env:
|
||||
RUN_REDIS_TESTS: "1"
|
||||
RUN_POSTGRES_TESTS: "1"
|
||||
RUN_MYSQL_TESTS: "1"
|
||||
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
|
||||
|
||||
test-32bit:
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
name: "postgres_flat Filer Store Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/postgres_flat/**'
|
||||
- 'test/s3/versioning/**'
|
||||
- 'test/testutil/**'
|
||||
- 'test/volume_server/framework/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/postgres-flat-tests.yml'
|
||||
- '.github/actions/fix-fusermount-setuid/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'test/postgres_flat/**'
|
||||
- 'test/s3/versioning/**'
|
||||
- 'test/testutil/**'
|
||||
- 'test/volume_server/framework/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- '.github/workflows/postgres-flat-tests.yml'
|
||||
- '.github/actions/fix-fusermount-setuid/**'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
postgres-flat:
|
||||
name: S3 and POSIX over postgres_flat
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 20
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
- name: Repair the fusermount3 setuid bit
|
||||
uses: ./.github/actions/fix-fusermount-setuid
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: go build -o weed/weed -buildvcs=false ./weed
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
RUN_POSTGRES_TESTS: "1"
|
||||
WEED_BINARY: ${{ github.workspace }}/weed/weed
|
||||
run: go test -v -count=1 -timeout=20m ./test/postgres_flat/
|
||||
|
||||
versioning-suite:
|
||||
name: S3 versioning suite over postgres_flat
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd pg_isready
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 20
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: go build -o weed/weed -buildvcs=false ./weed
|
||||
|
||||
- name: Start weed mini on postgres_flat
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/config" "$RUNNER_TEMP/data"
|
||||
: > "$RUNNER_TEMP/config/security.toml"
|
||||
cat > "$RUNNER_TEMP/config/filer.toml" <<'EOF'
|
||||
[postgres_flat]
|
||||
enabled = true
|
||||
hostname = "127.0.0.1"
|
||||
port = 5432
|
||||
username = "postgres"
|
||||
password = "postgres"
|
||||
database = "postgres"
|
||||
sslmode = "disable"
|
||||
EOF
|
||||
weed/weed -config_dir="$RUNNER_TEMP/config" mini -ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-dir="$RUNNER_TEMP/data" -s3.config="$GITHUB_WORKSPACE/docker/compose/s3.json" \
|
||||
-webdav=false -admin.ui=false > "$RUNNER_TEMP/weed.log" 2>&1 &
|
||||
ready() {
|
||||
curl -s -o /dev/null http://127.0.0.1:8333 &&
|
||||
test "$(docker exec ${{ job.services.postgres.id }} psql -U postgres -Atc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'filemeta' AND column_name = 'path'")" = 1
|
||||
}
|
||||
for i in $(seq 90); do ready && break; sleep 1; done
|
||||
ready || { cat "$RUNNER_TEMP/weed.log"; exit 1; }
|
||||
|
||||
- name: Run the S3 versioning suite
|
||||
env:
|
||||
ENABLE_STRESS_TESTS: "true"
|
||||
run: go test -v -count=1 -timeout=25m ./test/s3/versioning/
|
||||
|
||||
- name: Show the server log
|
||||
if: failure()
|
||||
run: tail -200 "$RUNNER_TEMP/weed.log"
|
||||
@@ -4,11 +4,8 @@ name: "S3 digest and FIPS matrix"
|
||||
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
|
||||
# md5 GODEBUG=fips140=off, the default digest
|
||||
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
|
||||
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
|
||||
# GOFIPS140=v1.0.0
|
||||
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
|
||||
# negative-config job checks what strict mode refuses at startup
|
||||
# (test/s3/digest_matrix/negative_config.sh).
|
||||
# fips140only GODEBUG=fips140=only, built with GOFIPS140=v1.0.0
|
||||
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster.
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -118,38 +115,6 @@ jobs:
|
||||
retention-days: 1
|
||||
path: digest-matrix-binaries.tar
|
||||
|
||||
negative-config:
|
||||
name: Strict FIPS mode refusals
|
||||
needs: build
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: digest-matrix-binaries
|
||||
|
||||
- name: Restore binaries
|
||||
run: |
|
||||
tar xf digest-matrix-binaries.tar
|
||||
chmod +x weed/weed seaweed-volume/target/release/weed-volume
|
||||
|
||||
- name: Short keys refused
|
||||
env:
|
||||
WEED: ${{ github.workspace }}/weed/weed
|
||||
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
|
||||
WORK_DIR: /tmp/negative-config
|
||||
run: bash test/s3/digest_matrix/negative_config.sh
|
||||
|
||||
- name: Upload logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: negative-config-logs
|
||||
path: /tmp/negative-config/**/*.log
|
||||
retention-days: 3
|
||||
|
||||
suites:
|
||||
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
|
||||
needs: build
|
||||
@@ -204,7 +169,7 @@ jobs:
|
||||
sed -i "s/assert prefixes == \['foo%2B1\/', 'foo\/', 'quux%20ab\/'\]/assert prefixes == \['foo\/', 'foo%2B1\/', 'quux%20ab\/'\]/" s3-tests/s3tests/functional/test_s3.py
|
||||
sed -i "/# request PartNumber out of range/,+4{s/assert status == 400/assert status == 416/; s/assert error_code == 'InvalidPart'/assert error_code == 'InvalidPartNumber'/}" s3-tests/s3tests/functional/test_s3.py
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: digest-matrix-binaries
|
||||
|
||||
|
||||
@@ -73,20 +73,6 @@ jobs:
|
||||
echo "=== Running S3 Prefix Object Tests ==="
|
||||
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
|
||||
|
||||
- name: Run S3 GetPart Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
run: |
|
||||
set -x
|
||||
go test -v -timeout=180s -run TestS3GetPart ./...
|
||||
|
||||
- name: Run S3 Bucket Default Storage Class Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
run: |
|
||||
set -x
|
||||
go test -v -timeout=180s -run TestS3BucketDefaultStorageClass ./...
|
||||
|
||||
- name: Run IAM Integration Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
|
||||
@@ -93,8 +93,8 @@ RUN mkdir -p /etc/seaweedfs
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# FIPS 140-3 mode is on by default for every process (entrypoint.sh)
|
||||
# To disable: docker run -e WEED_FIPS_MODE=off ...
|
||||
# FIPS 140-3 mode is ON by default (Go 1.24+)
|
||||
# To disable: docker run -e GODEBUG=fips140=off ...
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk upgrade --no-cache && \
|
||||
|
||||
+9
-44
@@ -1,5 +1,14 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Enable FIPS 140-3 mode by default (Go 1.24+)
|
||||
# To disable: docker run -e GODEBUG=fips140=off ...
|
||||
# For strict mode: docker run -e GODEBUG=fips140=only ...
|
||||
# The default goes first: Go applies the last of repeated GODEBUG settings, so
|
||||
# the caller's fips140 value wins.
|
||||
# Transparent huge pages are a host-wide setting this image cannot change; to
|
||||
# turn them off for this process only, append GODEBUG=disablethp=1.
|
||||
export GODEBUG="fips140=on${GODEBUG:+,$GODEBUG}"
|
||||
|
||||
# Fix permissions for mounted volumes
|
||||
# If /data is mounted from host, it might have different ownership
|
||||
# Fix this by ensuring seaweed user owns the directory
|
||||
@@ -28,54 +37,10 @@ if [ "$(id -u)" = "0" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# A restrictive Docker daemon umask can leave these 0600, and the resolver
|
||||
# then falls back to a nameserver on localhost once privileges are dropped.
|
||||
for f in /etc/resolv.conf /etc/hosts; do
|
||||
if [ -f "$f" ] && ! su-exec seaweed test -r "$f"; then
|
||||
chmod a+r "$f" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# Use su-exec to drop privileges and run as seaweed user
|
||||
exec su-exec seaweed "$0" "$@"
|
||||
fi
|
||||
|
||||
# FIPS 140-3 mode is on by default, for the Go processes and the Rust
|
||||
# binaries alike. To pick another mode: docker run -e WEED_FIPS_MODE=off (or
|
||||
# strict). A fips.mode in security.toml alone cannot change it, since Go
|
||||
# processes would still get this mode's fips140 and refuse to start.
|
||||
# WEED_FIPS_MODE_DEFAULT is the mode when nothing else sets one; set it empty
|
||||
# to leave every process in its own default (fips140=off for Go, off for Rust).
|
||||
# A fips140 the caller puts in GODEBUG still picks the mode, for the Rust
|
||||
# binaries as well, unless WEED_FIPS_MODE is set, but is deprecated and warns;
|
||||
# a Go process refuses to start when its fips140 differs from WEED_FIPS_MODE or
|
||||
# fips.mode.
|
||||
# Transparent huge pages are a host-wide setting this image cannot change; to
|
||||
# turn them off for this process only, append GODEBUG=disablethp=1.
|
||||
export WEED_FIPS_MODE_DEFAULT="${WEED_FIPS_MODE_DEFAULT-on}"
|
||||
godebug_fips140="$(printf '%s\n' "$GODEBUG" | tr ',' '\n' | sed -n 's/^fips140=/=/p' | tail -n 1)"
|
||||
case "$godebug_fips140" in
|
||||
=off | =) WEED_FIPS_MODE_DEFAULT=off ;;
|
||||
=on | =debug) WEED_FIPS_MODE_DEFAULT=on ;;
|
||||
=only) WEED_FIPS_MODE_DEFAULT=strict ;;
|
||||
esac
|
||||
if [ -n "$godebug_fips140" ] && [ -z "$WEED_FIPS_MODE" ]; then
|
||||
echo "Warning: choosing the FIPS mode with GODEBUG=fips140 is deprecated; set WEED_FIPS_MODE=off, on or strict, which also covers the Rust binaries when they start without this entrypoint." >&2
|
||||
fi
|
||||
case "${WEED_FIPS_MODE:-$WEED_FIPS_MODE_DEFAULT}" in
|
||||
off) fips140=off ;;
|
||||
on) fips140=on ;;
|
||||
strict) fips140=only ;;
|
||||
*) fips140= ;;
|
||||
esac
|
||||
export GODEBUG="${fips140:+fips140=$fips140}${fips140:+${GODEBUG:+,}}${GODEBUG}"
|
||||
|
||||
for f in /etc/resolv.conf /etc/hosts; do
|
||||
if [ -f "$f" ] && [ ! -r "$f" ]; then
|
||||
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
|
||||
fi
|
||||
done
|
||||
|
||||
isArgPassed() {
|
||||
# Match both `-flag` and `--flag` (and their `=value` forms): the Go fla9
|
||||
# library accepts both, and users may pick either form on the CLI.
|
||||
|
||||
@@ -30,12 +30,10 @@ Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
|
||||
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
|
||||
`vector:9329/metrics` inside the Compose network.
|
||||
|
||||
A native development setup can use `weed mini -vectorBucket=embeddings`. Mini
|
||||
starts `weed-vector` and the `weed-worker` maintenance worker when it finds them
|
||||
beside `weed` or on PATH, and logs and continues without one it cannot find.
|
||||
`-vector.binary` selects an explicit engine binary, and `weed-worker` is also
|
||||
looked up beside it. `-vector=false` leaves both out, and
|
||||
`-vector.metricsPort=9329` enables HTTP readiness and metrics on a compatible
|
||||
engine. The children inherit the cluster's configuration directory and stop with
|
||||
mini. `weed shell` provides `s3vectors -operation <Operation> -file
|
||||
request.json` for the same API operations using trusted cluster credentials.
|
||||
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
|
||||
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
|
||||
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
|
||||
compatible engine. The child inherits the cluster's configuration directory and
|
||||
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
|
||||
provides `s3vectors -operation <Operation> -file request.json` for the same API
|
||||
operations using trusted cluster credentials.
|
||||
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
seaweedfs:
|
||||
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
|
||||
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE -vector=false
|
||||
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
|
||||
environment: &environment
|
||||
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
|
||||
AWS_ACCESS_KEY_ID: vector-demo
|
||||
|
||||
@@ -12,7 +12,6 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
github.com/KimMachineGun/automemlimit v1.0.2
|
||||
github.com/Shopify/sarama v1.38.1
|
||||
github.com/ThreeDotsLabs/watermill v1.5.3
|
||||
github.com/a-h/templ v0.3.1100
|
||||
@@ -22,12 +21,12 @@ require (
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/aws/aws-sdk-go v1.55.8
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
|
||||
github.com/aws/smithy-go v1.28.11
|
||||
github.com/aws/smithy-go v1.28.9
|
||||
github.com/bwmarrin/snowflake v0.3.0
|
||||
github.com/cenkalti/backoff/v4 v4.3.0
|
||||
github.com/cespare/xxhash/v2 v2.3.0
|
||||
@@ -53,13 +52,13 @@ require (
|
||||
github.com/hashicorp/raft v1.8.0
|
||||
github.com/hashicorp/raft-boltdb/v2 v2.4.2
|
||||
github.com/hashicorp/vault/api v1.23.0
|
||||
github.com/jackc/pgx/v5 v5.13.0
|
||||
github.com/jhump/protoreflect v1.19.0
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/jhump/protoreflect v1.18.1
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/k0kubun/pp v3.0.1+incompatible
|
||||
github.com/karlseguin/ccache/v2 v2.0.8
|
||||
github.com/klauspost/compress v1.20.5
|
||||
github.com/klauspost/compress v1.20.3
|
||||
github.com/klauspost/reedsolomon v1.14.2
|
||||
github.com/kurin/blazer v0.5.3
|
||||
github.com/linkedin/goavro/v2 v2.15.0
|
||||
@@ -68,7 +67,7 @@ require (
|
||||
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1
|
||||
github.com/parquet-go/parquet-go v0.33.0
|
||||
github.com/parquet-go/parquet-go v0.32.0
|
||||
github.com/peterh/liner v1.2.3
|
||||
github.com/pierrec/lz4/v4 v4.1.33
|
||||
github.com/pkg/sftp v1.13.12
|
||||
@@ -100,7 +99,6 @@ require (
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365
|
||||
github.com/twmb/avro v1.9.0
|
||||
github.com/twpayne/go-geom v1.6.1
|
||||
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43
|
||||
github.com/valyala/bytebufferpool v1.0.0
|
||||
github.com/viant/ptrie v1.0.1
|
||||
@@ -112,7 +110,7 @@ require (
|
||||
go.etcd.io/etcd/api/v3 v3.7.3
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.4
|
||||
go.etcd.io/etcd/client/v3 v3.7.3
|
||||
go.mongodb.org/mongo-driver v1.17.10
|
||||
go.mongodb.org/mongo-driver v1.17.9
|
||||
go.uber.org/atomic v1.12.0
|
||||
go.yaml.in/yaml/v3 v3.0.6
|
||||
gocloud.dev v0.49.0
|
||||
@@ -122,7 +120,7 @@ require (
|
||||
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/sys v0.50.0
|
||||
golang.org/x/term v0.48.0
|
||||
@@ -173,22 +171,22 @@ require (
|
||||
github.com/abbot/go-http-auth v0.4.0 // indirect
|
||||
github.com/adrg/xdg v0.5.3 // indirect
|
||||
github.com/anchore/go-lzo v0.1.1 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/andybalholm/brotli v1.2.8 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.4 // indirect
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apache/thrift v0.25.0 // 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.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4 // indirect
|
||||
@@ -310,7 +308,7 @@ require (
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260708165336-dd6561bacfa2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jaegertracing/jaeger v1.47.0 // indirect
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
|
||||
@@ -376,10 +374,9 @@ require (
|
||||
github.com/openzipkin/zipkin-go v0.4.3 // indirect
|
||||
github.com/oracle/oci-go-sdk/v65 v65.121.0 // indirect
|
||||
github.com/panjf2000/ants/v2 v2.12.1 // indirect
|
||||
github.com/parquet-go/bitpack v1.1.1 // indirect
|
||||
github.com/parquet-go/jsonlite v1.5.7 // indirect
|
||||
github.com/parquet-go/bitpack v1.0.0 // indirect
|
||||
github.com/parquet-go/jsonlite v1.0.0 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
|
||||
@@ -387,7 +384,6 @@ require (
|
||||
github.com/pierrre/geohash v1.0.0 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
|
||||
github.com/pingcap/goleveldb v0.0.0-20191226122134-f82aafb29989 // indirect
|
||||
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
|
||||
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
@@ -437,6 +433,7 @@ require (
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/twmb/murmur3 v1.1.8 // indirect
|
||||
github.com/twpayne/go-geom v1.6.1 // indirect
|
||||
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
|
||||
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
|
||||
@@ -85,8 +85,6 @@ github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knD
|
||||
github.com/IBM/go-sdk-core/v5 v5.23.1/go.mod h1:yO+OQpByKDLTvpEcsFFexgzpeR8eRfCFWAYzxkAu4bk=
|
||||
github.com/Jille/raft-grpc-transport v1.6.1 h1:gN3sjapb+fVbiebS7AfQQgbV2ecTOI7ur7NPPC7Mhoc=
|
||||
github.com/Jille/raft-grpc-transport v1.6.1/go.mod h1:HbOjEdu/yzCJ/mjTF6wEOJNbAUpHfU2UOA2hVD4CNFg=
|
||||
github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk=
|
||||
github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
|
||||
github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
|
||||
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
|
||||
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
|
||||
@@ -144,8 +142,8 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp
|
||||
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/anchore/go-lzo v0.1.1 h1:IwL/fvkdtlIrYIXck6WxZ3nb8WjjHziYYmGxlooyOnM=
|
||||
github.com/anchore/go-lzo v0.1.1/go.mod h1:3kLx0bve2oN1iDwgM1U5zGku1Tfbdb0No5qp1eL1fIk=
|
||||
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
|
||||
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/brotli v1.2.8 h1:H9F6r7RNwzSRsx/lytpIYkbjNFMt2yNBwsJ2+0gpx78=
|
||||
github.com/andybalholm/brotli v1.2.8/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
|
||||
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
|
||||
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||
@@ -173,10 +171,10 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
|
||||
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
|
||||
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.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
|
||||
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
|
||||
@@ -187,22 +185,22 @@ github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHA
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 h1:q9YuNkYR/7lxflWCcEv3C0cecUt3Zvrh2hn9ZNxieNA=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16/go.mod h1:3BSeJQF55QQI+dDFHx4WTIjTvX/Lvtk8Jaaf/SGAnBM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 h1:D2smhPZgqVLuc8rmuvb6wrG4sgut9iv1BN8W2twFtfo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16/go.mod h1:HheOgBYcgoZgeKSLVEmk9whxHERlVXAKTVWK3xizKeo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 h1:5w2E7ndu7XOt62yvu2vGm/Rv7WDn1oQjrJ7Dt1NTVTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15/go.mod h1:1WgfBCsJYL6E7T2QkkE8kQvo7uG+5+z2LpaQ9L6pjZs=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1 h1:fOeEIKMlgwKbMFSNMM+pLo2NPRJ1dSKbaAuZYGXUVR0=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1/go.mod h1:xHaAZkbYuIc9UtLZxdoeyhzmx06g1paDjPkHgljJU/I=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 h1:4EezYQsIY0xPbD6u7TbQLfnpicSMQgA8n9paomVV4Zo=
|
||||
@@ -215,8 +213,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEB
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
|
||||
github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI=
|
||||
github.com/aws/smithy-go v1.28.11/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
|
||||
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
|
||||
@@ -724,10 +722,10 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
|
||||
github.com/jaegertracing/jaeger v1.47.0/go.mod h1:mHU/OHFML51CijQql4+rLfgPOcIb9MhxOMn+RKQwrJc=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||
@@ -742,8 +740,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||
github.com/jhump/protoreflect v1.19.0 h1:YhKbE78JrjfngcCZfZTIV7rQQGndyqll6fXfaqiOEg4=
|
||||
github.com/jhump/protoreflect v1.19.0/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
|
||||
github.com/jhump/protoreflect v1.18.1 h1:h4odAaLg9wyn7yHxMF7sSkJ7JfLwK1oy37/1Pi212GE=
|
||||
github.com/jhump/protoreflect v1.18.1/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:Dw1rslK/VotaUGYsv53XVWITr+5RCPXfvvlGrM/+B6w=
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1/go.mod h1:D9LBEowZyv8/iSu97FU2zmXG3JxVTmNw21mu63niFzU=
|
||||
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
|
||||
@@ -784,8 +782,8 @@ github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXw
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
|
||||
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
|
||||
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
|
||||
github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/reedsolomon v1.14.2 h1:SafJYwpBBQBI6amHUygcjxZjXeN2HpiENHQDwuPWCCQ=
|
||||
@@ -957,17 +955,15 @@ github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/
|
||||
github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM=
|
||||
github.com/panjf2000/ants/v2 v2.12.1 h1:BWvU2wHpyXWxhhNXsGB6JXLCNbshyLd1QxvoAmZnu10=
|
||||
github.com/panjf2000/ants/v2 v2.12.1/go.mod h1:tSQuaNQ6r6NRhPt+IZVUevvDyFMTs+eS4ztZc52uJTY=
|
||||
github.com/parquet-go/bitpack v1.1.1 h1:mygqlCBk/rnvtqqP5Oy7IkIPAxZ3bDM7V4yce/ms6pE=
|
||||
github.com/parquet-go/bitpack v1.1.1/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
|
||||
github.com/parquet-go/jsonlite v1.5.7 h1:FxIrc2MBZ9QLpljM1+3F3JuCuug+BWOt8Yx+S4o3bl8=
|
||||
github.com/parquet-go/jsonlite v1.5.7/go.mod h1:ZIyft0+sSdvgTu2m6RpqxWx/F3UBNtF3ammevxDJcoE=
|
||||
github.com/parquet-go/parquet-go v0.33.0 h1:iDe13lcW6t0mnZWPqKqWccNa5GdP/L9GNNyzlr8JqNY=
|
||||
github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMPJ6I+/zmNnsOSh4=
|
||||
github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxPcQA=
|
||||
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.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
|
||||
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
|
||||
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
|
||||
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
@@ -1359,8 +1355,8 @@ go.etcd.io/etcd/client/pkg/v3 v3.7.4 h1:633yLMDAQHWqLTRMxUNuZfOy6a4REJPcA3juoMRx
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.4/go.mod h1:I1lMmoiq2SF4Wg0Gru7uXMovS1eEo6wwAxcFPFPk/v0=
|
||||
go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q=
|
||||
go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE=
|
||||
go.mongodb.org/mongo-driver v1.17.10 h1:kdAgQvu8TROXZpSkJQd5wzfaNCCrMbpZyKFtQ6qkPCE=
|
||||
go.mongodb.org/mongo-driver v1.17.10/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
@@ -1505,8 +1501,8 @@ golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
|
||||
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.56"
|
||||
appVersion: "4.55"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.56.0
|
||||
version: 4.55.0
|
||||
@@ -267,18 +267,6 @@ filer:
|
||||
enabled: true
|
||||
```
|
||||
|
||||
### Message queue broker
|
||||
|
||||
An S3 gateway can run a message queue broker beside it, on gRPC port 17777 by default. `s3.mqBroker`, `filer.s3.mqBroker` and `allInOne.s3.mqBroker` choose it:
|
||||
|
||||
- `auto` (the default) runs it only with `global.seaweedfs.enableSecurity`, where the chart gives it mutual TLS through `[grpc.msg_broker]` in security.toml.
|
||||
- `true` runs it either way. Without `enableSecurity` it then accepts any client that can reach the port.
|
||||
- `false` never runs it.
|
||||
|
||||
`s3.mqBrokerPort`, `filer.s3.mqBrokerPort` and `allInOne.s3.mqBrokerPort` set the port, and 0 also turns the broker off. The `allInOne.s3` values inherit the `s3` ones when null. The container port and NetworkPolicy entry appear only when the broker runs.
|
||||
|
||||
Brokers register with the master under the pod IP, and clients and other brokers find them there and dial that address, so the port is deliberately left off the Services; a LoadBalancer or NodePort Service would only publish it outside the cluster. With `networkPolicy.enabled` the chart admits the port from the release's own pods; publishers and subscribers elsewhere need an `extraIngress` rule for it.
|
||||
|
||||
### Enabling Authentication to S3
|
||||
|
||||
To enable authentication for S3, you have two options:
|
||||
@@ -385,16 +373,9 @@ filer:
|
||||
apply without a restart. Other files in the Secret, such as an audit log config, still
|
||||
need one, and so do changes to the values the chart generates its own Secret from, such
|
||||
as `s3.credentials`.
|
||||
- Every reload also re-creates the KMS providers configured in the identities file, and
|
||||
drops the ones it no longer lists. A file whose identities don't parse changes neither.
|
||||
A provider that fails to load keeps its previous instance, unless it's the one S3 uses,
|
||||
which fails the KMS reload. S3 uses `default_provider`, or the first provider by name
|
||||
when it isn't set, so set it when you list more than one, as adding a provider whose
|
||||
name sorts first would switch S3 to it. The `local` provider reads its `keys` list
|
||||
again, so objects encrypted under those keys stay readable. The keys it generates in
|
||||
memory are lost on a reload, as on a restart, so list every key that protects objects
|
||||
you need to keep, and give the alias `aws/s3` to the one that should serve requests
|
||||
naming no key.
|
||||
- Every reload also re-creates the KMS providers configured in the identities file. The
|
||||
`local` provider keeps its keys in memory, so a reload replaces them, as a restart does;
|
||||
use another provider for objects that must stay readable.
|
||||
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
|
||||
so the sidecar can see SeaweedFS. It uses the component's image and container security
|
||||
context, because it must run as the same user as SeaweedFS to signal it. If it can't
|
||||
|
||||
@@ -274,9 +274,6 @@ spec:
|
||||
{{- if gt $s3PreStopSeconds 0 }}
|
||||
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).args }}
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.allInOne.sftp.enabled }}
|
||||
-sftp \
|
||||
@@ -409,10 +406,6 @@ spec:
|
||||
- containerPort: {{ $httpsPort }}
|
||||
name: swfs-s3-tls
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).port }}
|
||||
- containerPort: {{ int . }}
|
||||
name: swfs-mq-broker
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.allInOne.sftp.enabled }}
|
||||
- containerPort: {{ .Values.allInOne.sftp.port | default .Values.sftp.port }}
|
||||
|
||||
@@ -296,9 +296,6 @@ spec:
|
||||
{{- if gt $s3PreStopSeconds 0 }}
|
||||
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).args }}
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
-master={{ include "seaweedfs.masterServerArg" . }} \
|
||||
{{- range .Values.filer.extraArgs }}
|
||||
@@ -366,10 +363,6 @@ spec:
|
||||
- containerPort: {{ .Values.filer.s3.httpsPort }}
|
||||
name: swfs-s3-tls
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).port }}
|
||||
- containerPort: {{ int . }}
|
||||
name: swfs-mq-broker
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- $jwt := (.Values.global.seaweedfs.securityConfig).jwtSigning | default dict }}
|
||||
{{- $isJwtEnabled := or $jwt.filerWrite $jwt.filerRead }}
|
||||
|
||||
@@ -179,9 +179,6 @@ spec:
|
||||
{{- end }}
|
||||
{{- /* rendered even when 0: an if would drop the flag and weed would serve its default */}}
|
||||
-port.lance={{ .Values.s3.lancePort | default 0 }} \
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).args }}
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
{{- range .Values.s3.extraArgs }}
|
||||
{{ . }} \
|
||||
{{- end }}
|
||||
@@ -236,10 +233,6 @@ spec:
|
||||
- containerPort: {{ .Values.s3.lancePort }}
|
||||
name: swfs-lance
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).port }}
|
||||
- containerPort: {{ int . }}
|
||||
name: swfs-mq-broker
|
||||
{{- end }}
|
||||
{{- if .Values.s3.metricsPort }}
|
||||
- containerPort: {{ .Values.s3.metricsPort }}
|
||||
name: metrics
|
||||
|
||||
@@ -283,55 +283,6 @@ true
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
The message queue broker beside an S3 gateway, for (list $ "s3"|"filer"|"allInOne"),
|
||||
as JSON: "args" are its flags and "port" the port it serves, 0 when it cannot run.
|
||||
Unflagged, weed starts it only with grpc.msg_broker TLS, which enableSecurity
|
||||
writes, and on 17777; defaults are left out so images without these flags start.
|
||||
allInOne.s3 inherits s3's mqBroker and mqBrokerPort when null.
|
||||
*/}}
|
||||
{{- define "seaweedfs.mqBroker" -}}
|
||||
{{- $root := index . 0 -}}
|
||||
{{- $component := index . 1 -}}
|
||||
{{- $prefix := "" -}}
|
||||
{{- $name := "s3.mqBroker" -}}
|
||||
{{- $mode := $root.Values.s3.mqBroker -}}
|
||||
{{- $port := $root.Values.s3.mqBrokerPort -}}
|
||||
{{- if eq $component "filer" -}}
|
||||
{{- $prefix = "s3." -}}
|
||||
{{- $name = "filer.s3.mqBroker" -}}
|
||||
{{- $mode = $root.Values.filer.s3.mqBroker -}}
|
||||
{{- $port = $root.Values.filer.s3.mqBrokerPort -}}
|
||||
{{- else if eq $component "allInOne" -}}
|
||||
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBroker) -}}
|
||||
{{- $name = "allInOne.s3.mqBroker" -}}
|
||||
{{- $mode = $root.Values.allInOne.s3.mqBroker -}}
|
||||
{{- end -}}
|
||||
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBrokerPort) -}}
|
||||
{{- $port = $root.Values.allInOne.s3.mqBrokerPort -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- $mode = ternary "auto" (toString $mode | lower) (kindIs "invalid" $mode) -}}
|
||||
{{- if not (has $mode (list "auto" "true" "false")) -}}
|
||||
{{- fail (printf "%s must be auto, true or false, not %q" $name $mode) -}}
|
||||
{{- end -}}
|
||||
{{- $port = int ($port | default 0) -}}
|
||||
{{- $runs := false -}}
|
||||
{{- if and (gt $port 0) (or (eq $mode "true") (and (eq $mode "auto") $root.Values.global.seaweedfs.enableSecurity)) -}}
|
||||
{{- $runs = true -}}
|
||||
{{- end -}}
|
||||
{{- $args := list -}}
|
||||
{{- if or (eq $mode "false") (eq $port 0) -}}
|
||||
{{- $args = append $args (printf "-%smq.broker=false" $prefix) -}}
|
||||
{{- else if eq $mode "true" -}}
|
||||
{{- $args = append $args (printf "-%smq.broker=true" $prefix) -}}
|
||||
{{- end -}}
|
||||
{{- if and $runs (ne $port 17777) -}}
|
||||
{{- $args = append $args (printf "-%smq.broker.port=%d" $prefix $port) -}}
|
||||
{{- end -}}
|
||||
{{- dict "args" (join " " $args) "port" (ternary $port 0 $runs) | toJson -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/* Return the proper volume image */}}
|
||||
{{- define "seaweedfs.volume.image" -}}
|
||||
{{- if .Values.volume.imageOverride -}}
|
||||
|
||||
@@ -26,9 +26,6 @@
|
||||
{{- if and $https (gt (int $https) 0) }}
|
||||
{{- $ports = append $ports $https }}
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list $ "allInOne") | fromJson).port }}
|
||||
{{- $ports = append $ports (int .) }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.allInOne.sftp.enabled }}
|
||||
{{- $ports = append $ports (.Values.allInOne.sftp.port | default .Values.sftp.port) }}
|
||||
@@ -65,9 +62,6 @@
|
||||
{{- if and .Values.filer.s3.httpsPort (gt (int .Values.filer.s3.httpsPort) 0) }}
|
||||
{{- $ports = append $ports .Values.filer.s3.httpsPort }}
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list $ "filer") | fromJson).port }}
|
||||
{{- $ports = append $ports (int .) }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- $targets = append $targets (dict "component" "filer" "ports" $ports) }}
|
||||
{{- end }}
|
||||
@@ -82,9 +76,6 @@
|
||||
{{- if .Values.s3.lancePort }}
|
||||
{{- $ports = append $ports .Values.s3.lancePort }}
|
||||
{{- end }}
|
||||
{{- with (include "seaweedfs.mqBroker" (list $ "s3") | fromJson).port }}
|
||||
{{- $ports = append $ports (int .) }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.metricsPort }}
|
||||
{{- $ports = append $ports .Values.s3.metricsPort }}
|
||||
{{- end }}
|
||||
|
||||
@@ -120,14 +120,6 @@ stringData:
|
||||
cert = "/usr/local/share/ca-certificates/client/tls.crt"
|
||||
key = "/usr/local/share/ca-certificates/client/tls.key"
|
||||
|
||||
{{- /* The broker beside each S3 gateway serves with this identity and
|
||||
dials other brokers with it; weed starts that broker only when this
|
||||
section has a cert and key. Same internal client cert as grpc.s3, which
|
||||
every pod running a gateway already mounts. */}}
|
||||
[grpc.msg_broker]
|
||||
cert = "/usr/local/share/ca-certificates/client/tls.crt"
|
||||
key = "/usr/local/share/ca-certificates/client/tls.key"
|
||||
|
||||
# use this for any place needs a grpc client
|
||||
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
|
||||
[grpc.client]
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const security = "global.seaweedfs.enableSecurity=true"
|
||||
|
||||
type brokerGateway struct {
|
||||
name string
|
||||
settings []string
|
||||
kind string
|
||||
object string
|
||||
prefix string
|
||||
broker string
|
||||
port string
|
||||
}
|
||||
|
||||
var brokerGateways = []brokerGateway{
|
||||
{"s3", []string{"s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-s3", "", "s3.mqBroker", "s3.mqBrokerPort"},
|
||||
{"filer.s3", []string{"filer.s3.enabled=true"}, "StatefulSet", "vector-test-seaweedfs-filer", "s3.", "filer.s3.mqBroker", "filer.s3.mqBrokerPort"},
|
||||
{"allInOne", []string{"allInOne.enabled=true", "allInOne.s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-all-in-one", "", "allInOne.s3.mqBroker", "allInOne.s3.mqBrokerPort"},
|
||||
}
|
||||
|
||||
func firstContainer(workload map[string]interface{}) map[string]interface{} {
|
||||
return workload["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0].(map[string]interface{})
|
||||
}
|
||||
|
||||
// brokerFlags returns the broker flags of the workload's first container.
|
||||
func brokerFlags(workload map[string]interface{}) []string {
|
||||
container := firstContainer(workload)
|
||||
var words []string
|
||||
for _, key := range []string{"command", "args"} {
|
||||
if list, ok := container[key].([]interface{}); ok {
|
||||
for _, word := range list {
|
||||
words = append(words, strings.Fields(word.(string))...)
|
||||
}
|
||||
}
|
||||
}
|
||||
var flags []string
|
||||
for _, word := range words {
|
||||
if strings.Contains(word, "mq.broker") {
|
||||
flags = append(flags, word)
|
||||
}
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
func namedPort(ports []interface{}, name, field string) int {
|
||||
for _, port := range ports {
|
||||
if p := port.(map[string]interface{}); p["name"] == name {
|
||||
return p[field].(int)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func policyAllows(policy map[string]interface{}, want int) bool {
|
||||
rules, _ := policy["spec"].(map[string]interface{})["ingress"].([]interface{})
|
||||
for _, rule := range rules {
|
||||
ports, _ := rule.(map[string]interface{})["ports"].([]interface{})
|
||||
for _, port := range ports {
|
||||
if port.(map[string]interface{})["port"] == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkBroker asserts the flags, that the broker port is declared and
|
||||
// admitted exactly when the broker runs, so a broker that runs with its port
|
||||
// blocked fails, and that no Service ever carries it.
|
||||
func checkBroker(t *testing.T, gateway brokerGateway, label string, settings []string, wantFlags []string, wantPort int) {
|
||||
t.Helper()
|
||||
_, documents := render(t, append(append([]string{"networkPolicy.enabled=true"}, gateway.settings...), settings...)...)
|
||||
label = fmt.Sprintf("%s %s", gateway.name, label)
|
||||
|
||||
workload := findDocument(documents, gateway.kind, gateway.object)
|
||||
if workload == nil {
|
||||
t.Fatalf("%s: no %s %s", label, gateway.kind, gateway.object)
|
||||
}
|
||||
if got := brokerFlags(workload); strings.Join(got, " ") != strings.Join(wantFlags, " ") {
|
||||
t.Errorf("%s: broker flags %q, want %q", label, got, wantFlags)
|
||||
}
|
||||
|
||||
containerPorts, _ := firstContainer(workload)["ports"].([]interface{})
|
||||
if got := namedPort(containerPorts, "swfs-mq-broker", "containerPort"); got != wantPort {
|
||||
t.Errorf("%s: containerPort %d, want %d", label, got, wantPort)
|
||||
}
|
||||
|
||||
// Clients find brokers through the master and dial the pod, so a Service
|
||||
// port would only publish the broker through a LoadBalancer or NodePort.
|
||||
for _, document := range documents {
|
||||
if document["kind"] != "Service" {
|
||||
continue
|
||||
}
|
||||
for _, port := range document["spec"].(map[string]interface{})["ports"].([]interface{}) {
|
||||
p := port.(map[string]interface{})
|
||||
if p["name"] == "swfs-mq-broker" || p["port"] == 17777 || p["targetPort"] == 17777 || (wantPort != 0 && (p["port"] == wantPort || p["targetPort"] == wantPort)) {
|
||||
t.Errorf("%s: Service %v carries the broker port: %v", label, document["metadata"].(map[string]interface{})["name"], p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
policy := findDocument(documents, "NetworkPolicy", gateway.object)
|
||||
if policy == nil {
|
||||
t.Fatalf("%s: no NetworkPolicy %s", label, gateway.object)
|
||||
}
|
||||
if wantPort != 0 && !policyAllows(policy, wantPort) {
|
||||
t.Errorf("%s: NetworkPolicy does not admit broker port %d", label, wantPort)
|
||||
}
|
||||
for _, port := range []int{17777, 18887} {
|
||||
if port != wantPort && policyAllows(policy, port) {
|
||||
t.Errorf("%s: NetworkPolicy admits %d with no broker on it", label, port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMqBrokerModes(t *testing.T) {
|
||||
for _, gateway := range brokerGateways {
|
||||
on := "-" + gateway.prefix + "mq.broker=true"
|
||||
off := "-" + gateway.prefix + "mq.broker=false"
|
||||
port := "-" + gateway.prefix + "mq.broker.port=18887"
|
||||
cases := []struct {
|
||||
label string
|
||||
settings []string
|
||||
wantFlags []string
|
||||
wantPort int
|
||||
}{
|
||||
{"auto without security", nil, nil, 0},
|
||||
{"auto with security", []string{security}, nil, 17777},
|
||||
{"auto with security, custom port", []string{security, gateway.port + "=18887"}, []string{port}, 18887},
|
||||
{"auto without security, custom port", []string{gateway.port + "=18887"}, nil, 0},
|
||||
{"true", []string{gateway.broker + "=true"}, []string{on}, 17777},
|
||||
{"true, custom port", []string{gateway.broker + "=true", gateway.port + "=18887"}, []string{on, port}, 18887},
|
||||
{"false with security", []string{security, gateway.broker + "=false"}, []string{off}, 0},
|
||||
{"true, port 0", []string{gateway.broker + "=true", gateway.port + "=0"}, []string{off}, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
checkBroker(t, gateway, c.label, c.settings, c.wantFlags, c.wantPort)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMqBrokerAllInOneInherits(t *testing.T) {
|
||||
allInOne := brokerGateways[2]
|
||||
cases := []struct {
|
||||
label string
|
||||
settings []string
|
||||
wantFlags []string
|
||||
wantPort int
|
||||
}{
|
||||
{"null inherits s3.mqBroker=true", []string{"s3.mqBroker=true"}, []string{"-mq.broker=true"}, 17777},
|
||||
{"null inherits s3.mqBroker=false", []string{security, "s3.mqBroker=false"}, []string{"-mq.broker=false"}, 0},
|
||||
{"explicit auto overrides s3.mqBroker=false", []string{security, "s3.mqBroker=false", "allInOne.s3.mqBroker=auto"}, nil, 17777},
|
||||
{"null inherits s3.mqBrokerPort", []string{security, "s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
|
||||
{"explicit port overrides s3.mqBrokerPort=0", []string{security, "s3.mqBrokerPort=0", "allInOne.s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
|
||||
}
|
||||
for _, c := range cases {
|
||||
checkBroker(t, allInOne, c.label, c.settings, c.wantFlags, c.wantPort)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMqBrokerTLSOnlyWithSecurity(t *testing.T) {
|
||||
for _, secured := range []bool{false, true} {
|
||||
// filer JWT signing writes security.toml without enableSecurity
|
||||
settings := []string{"s3.enabled=true", "global.seaweedfs.securityConfig.jwtSigning.filerWrite=true"}
|
||||
if secured {
|
||||
settings = append(settings, security)
|
||||
}
|
||||
_, documents := render(t, settings...)
|
||||
secret := findDocument(documents, "Secret", "vector-test-seaweedfs-security-config")
|
||||
if secret == nil {
|
||||
t.Fatalf("security %v: no security config Secret", secured)
|
||||
}
|
||||
toml := secret["stringData"].(map[string]interface{})["security.toml"].(string)
|
||||
section := "[grpc.msg_broker]\ncert = \"/usr/local/share/ca-certificates/client/tls.crt\"\nkey = \"/usr/local/share/ca-certificates/client/tls.key\""
|
||||
if got := strings.Contains(toml, section); got != secured {
|
||||
t.Errorf("security %v: [grpc.msg_broker] with the client cert present = %v\n%s", secured, got, toml)
|
||||
}
|
||||
if !secured && strings.Contains(toml, "[grpc.msg_broker]") {
|
||||
t.Errorf("[grpc.msg_broker] written without enableSecurity")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMqBrokerRejectsUnknownValue(t *testing.T) {
|
||||
if _, err := exec.LookPath("helm"); err != nil {
|
||||
t.Skip("helm is not installed")
|
||||
}
|
||||
output, err := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "s3.mqBroker=yes").CombinedOutput()
|
||||
if err == nil || !strings.Contains(string(output), `s3.mqBroker must be auto, true or false, not "yes"`) {
|
||||
t.Fatalf("s3.mqBroker=yes accepted: %v %s", err, output)
|
||||
}
|
||||
}
|
||||
@@ -1096,9 +1096,6 @@ filer:
|
||||
port: 8333
|
||||
# add additional https port
|
||||
httpsPort: 0
|
||||
# Message queue broker beside the gateway, see s3.mqBroker
|
||||
mqBroker: auto
|
||||
mqBrokerPort: 17777
|
||||
# Suffix of the host name, {bucket}.{domainName}
|
||||
domainName: ""
|
||||
# Seconds the gateway keeps serving after SIGTERM while its health checks
|
||||
@@ -1189,13 +1186,6 @@ s3:
|
||||
# Lance Namespace port; weed serves 9101 by default, 0 disables it
|
||||
# (and the worker's Lance container)
|
||||
lancePort: 9101
|
||||
# Message queue broker beside the gateway: auto runs it only with
|
||||
# global.seaweedfs.enableSecurity, which gives it mTLS; true runs it either
|
||||
# way, without TLS when security is off; false never does.
|
||||
mqBroker: auto
|
||||
# Its gRPC port, 0 turns it off. Clients and other brokers find the broker
|
||||
# through the master and dial the pod IP, so no Service carries this port.
|
||||
mqBrokerPort: 17777
|
||||
loggingOverrideLevel: null
|
||||
# enable user & permission to s3 (need to inject to all services)
|
||||
enableAuth: false
|
||||
@@ -1896,7 +1886,7 @@ worker:
|
||||
# Worker job types - categories or comma-separated list of names/aliases
|
||||
# Categories: all, default, heavy
|
||||
# default: vacuum, volume_balance, ec_balance, admin_script
|
||||
# heavy: erasure_coding, iceberg_maintenance, mq_topic_table
|
||||
# heavy: erasure_coding, iceberg_maintenance
|
||||
# all: every registered job type
|
||||
# Examples: "all", "default", "heavy", "default,iceberg" (default+iceberg), "vacuum,volume_balance"
|
||||
# Refer: https://github.com/seaweedfs/seaweedfs/wiki/Worker
|
||||
@@ -2070,8 +2060,6 @@ allInOne:
|
||||
enabled: false # Whether to enable S3 gateway
|
||||
port: null # S3 gateway port (null inherits from s3.port)
|
||||
httpsPort: null # S3 gateway HTTPS port (null inherits from s3.httpsPort)
|
||||
mqBroker: null # Message queue broker: auto, true or false (null inherits from s3.mqBroker)
|
||||
mqBrokerPort: null # Message queue broker gRPC port (null inherits from s3.mqBrokerPort, 0 turns the broker off)
|
||||
domainName: null # Suffix of the host name (null inherits from s3.domainName)
|
||||
enableAuth: false # Enable user & permission to S3
|
||||
# Set to the name of an existing kubernetes Secret with the s3 json config file
|
||||
|
||||
+1063
-1025
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
@@ -7826,390 +7826,6 @@
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC QPS by method",
|
||||
"description": "gRPC calls to the filer (mounts, S3 gateways, peers, shell), by method.",
|
||||
"type": "timeseries",
|
||||
"id": 271,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 103
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "reqps",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (method) (rate(SeaweedFS_filer_grpc_request_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Errors by method and code",
|
||||
"description": "gRPC calls to the filer that did not end OK. NotFound is mostly lookups of names that do not exist.",
|
||||
"type": "timeseries",
|
||||
"id": 272,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 103
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "reqps",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (method, code) (rate(SeaweedFS_filer_grpc_request_total{code!=\"OK\", cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}} {{code}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Duration p99 by method",
|
||||
"description": "Subscriptions, health watches and client streams are counted but not timed.",
|
||||
"type": "timeseries",
|
||||
"id": 273,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 111
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Duration p50 by method",
|
||||
"description": "Subscriptions, health watches and client streams are counted but not timed.",
|
||||
"type": "timeseries",
|
||||
"id": 274,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 111
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "histogram_quantile(0.50, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -15239,412 +14855,6 @@
|
||||
"pluginVersion": "10.3.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "S3 Notifications",
|
||||
"collapsed": true,
|
||||
"id": 275,
|
||||
"gridPos": {
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 30
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Notification records delivered",
|
||||
"type": "timeseries",
|
||||
"id": 276,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 31
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_delivered_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{target}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Notification lag",
|
||||
"description": "Undelivered bucket event records the forwarder can see: current ranges, ranges held back behind an older generation, and sealed retired ranges. An old range still being sealed after a repartition cannot be read yet and is not counted.",
|
||||
"type": "timeseries",
|
||||
"id": 277,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 31
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (target) (SeaweedFS_s3_notification_lag_records{cluster=~\"$cluster\"})",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{target}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Notification send retries",
|
||||
"type": "timeseries",
|
||||
"id": 278,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 39
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_send_retries_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{target}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Notification records skipped or lost",
|
||||
"type": "timeseries",
|
||||
"id": 279,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 39
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (target, reason) (increase(SeaweedFS_s3_notification_skipped_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{target}} skipped {{reason}}"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (target) (increase(SeaweedFS_s3_notification_retention_gap_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "B",
|
||||
"legendFormat": "{{target}} retention gap"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"refresh": "30s",
|
||||
|
||||
@@ -22,10 +22,6 @@ use std::sync::OnceLock;
|
||||
pub const SETTING: &str = "fips.mode";
|
||||
/// The environment variable that overrides [`SETTING`].
|
||||
pub const ENV: &str = "WEED_FIPS_MODE";
|
||||
/// The environment variable holding the mode that applies when neither
|
||||
/// [`ENV`] nor [`SETTING`] sets one; the Docker image's entrypoint sets it to
|
||||
/// the mode it runs every process in.
|
||||
pub const DEFAULT_ENV: &str = "WEED_FIPS_MODE_DEFAULT";
|
||||
|
||||
/// The modes `fips.mode` names. Unset reads as [`FipsMode::Off`], which is
|
||||
/// how every Rust binary behaved before the setting existed.
|
||||
@@ -129,30 +125,24 @@ impl fmt::Display for Setting {
|
||||
/// Resolves the mode of a process whose own security.toml loader read
|
||||
/// `file_value` for `fips.mode` from `file` (`None` when there is no file or
|
||||
/// it does not set the key): `WEED_FIPS_MODE` when set and non-empty, else
|
||||
/// `file_value` when non-empty, else `WEED_FIPS_MODE_DEFAULT`, the mode the
|
||||
/// Docker image's entrypoint states, else [`FipsMode::Off`]. An unknown value
|
||||
/// is an error naming where it came from.
|
||||
/// `file_value`, else [`FipsMode::Off`]. An unknown value is an error naming
|
||||
/// where it came from.
|
||||
pub fn resolve(
|
||||
file: Option<&Path>,
|
||||
file_value: Option<&str>,
|
||||
env: &dyn Fn(&str) -> Option<OsString>,
|
||||
) -> Result<Setting, FipsModeError> {
|
||||
let from = |name: &'static str| {
|
||||
env(name)
|
||||
.map(|v| v.to_string_lossy().into_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|v| (name.to_string(), v))
|
||||
};
|
||||
let from_env = env(ENV)
|
||||
.map(|v| v.to_string_lossy().into_owned())
|
||||
.filter(|v| !v.is_empty());
|
||||
let from_file = || {
|
||||
let source = match file {
|
||||
Some(path) => format!("{}: {SETTING}", path.display()),
|
||||
None => SETTING.to_string(),
|
||||
};
|
||||
file_value
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| (source, value.to_string()))
|
||||
file_value.map(|value| (source, value.to_string()))
|
||||
};
|
||||
let Some((source, value)) = from(ENV).or_else(from_file).or_else(|| from(DEFAULT_ENV)) else {
|
||||
let Some((source, value)) = from_env.map(|v| (ENV.to_string(), v)).or_else(from_file) else {
|
||||
return Ok(Setting {
|
||||
mode: FipsMode::Off,
|
||||
source: None,
|
||||
@@ -257,28 +247,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_default_applies_only_when_nothing_else_sets_the_mode() {
|
||||
let env = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on")]);
|
||||
let setting = resolve(Some(Path::new(FILE_PATH)), Some(""), &env).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
assert_eq!(setting.to_string(), "FIPS mode on (WEED_FIPS_MODE_DEFAULT)");
|
||||
assert_eq!(resolve(None, None, &env).unwrap().mode, FipsMode::On);
|
||||
assert_eq!(
|
||||
resolve(Some(Path::new(FILE_PATH)), Some("strict"), &env)
|
||||
.unwrap()
|
||||
.mode,
|
||||
FipsMode::Strict
|
||||
);
|
||||
let both = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on"), ("WEED_FIPS_MODE", "off")]);
|
||||
assert_eq!(resolve(None, None, &both).unwrap().mode, FipsMode::Off);
|
||||
let unknown = env_of(&[("WEED_FIPS_MODE_DEFAULT", "yes")]);
|
||||
assert_eq!(
|
||||
resolve(None, None, &unknown).unwrap_err().to_string(),
|
||||
"WEED_FIPS_MODE_DEFAULT is \"yes\"; want off, on or strict"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_environment_variable_counts_as_unset() {
|
||||
let env = env_of(&[("WEED_FIPS_MODE", "")]);
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
//! JWT signing keys under [`FipsMode::Strict`].
|
||||
//!
|
||||
//! FIPS 140 needs HMAC keys of at least 112 bits, and Go's `crypto/hmac`
|
||||
//! panics on a shorter one under `GODEBUG=fips140=only`, so every Go process
|
||||
//! refuses to start when a JWT key in security.toml is shorter
|
||||
//! (`weed/util/fips140_keys.go`). The Rust binaries take `fips.mode = strict`
|
||||
//! to mean the same and apply the same rule with the same wording, so one
|
||||
//! security.toml gets the same answer from a Go and a Rust server.
|
||||
|
||||
use crate::fips::FipsMode;
|
||||
|
||||
/// The shortest HMAC key FIPS 140 allows: 112 bits.
|
||||
pub const MIN_HMAC_KEY_BYTES: usize = 14;
|
||||
|
||||
/// The wiki section on switching JWT signing keys without downtime.
|
||||
pub const JWT_SIGNING_KEYS_WIKI: &str =
|
||||
"https://github.com/seaweedfs/seaweedfs/wiki/Cryptography-and-FIPS-Compliance#jwt-signing-keys";
|
||||
|
||||
/// Every security.toml setting that keys an HS256 JWT, in the order Go checks
|
||||
/// them. Go refuses a short one at startup in any process that reads the file.
|
||||
pub const JWT_KEY_SETTINGS: [&str; 11] = [
|
||||
"jwt.signing.key",
|
||||
"jwt.signing.previous_key",
|
||||
"jwt.signing.read.key",
|
||||
"jwt.signing.read.previous_key",
|
||||
"jwt.filer_signing.key",
|
||||
"jwt.filer_signing.previous_key",
|
||||
"jwt.filer_signing.read.key",
|
||||
"jwt.filer_signing.read.previous_key",
|
||||
"jwt.filer_signing.grpc_key",
|
||||
"jwt.filer_signing.grpc_previous_key",
|
||||
"jwt.filer_signing.subscribe.key",
|
||||
];
|
||||
|
||||
/// Whether `key` is shorter than the FIPS mode allows (14 characters when
|
||||
/// strict).
|
||||
pub fn is_short(mode: FipsMode, key: &[u8]) -> bool {
|
||||
mode == FipsMode::Strict && !key.is_empty() && key.len() < MIN_HMAC_KEY_BYTES
|
||||
}
|
||||
|
||||
/// Go's `CheckFips140HmacKeys`: under strict mode, one message naming each
|
||||
/// setting in `keys` whose key is too short, with its length; otherwise `None`.
|
||||
pub fn short_keys(mode: FipsMode, keys: &[(&str, &[u8])]) -> Option<String> {
|
||||
let short: Vec<String> = keys
|
||||
.iter()
|
||||
.filter(|(_, key)| is_short(mode, key))
|
||||
.map(|(setting, key)| format!("{} ({} characters)", setting, key.len()))
|
||||
.collect();
|
||||
match short.as_slice() {
|
||||
[] => None,
|
||||
[one] => Some(format!(
|
||||
"{} is shorter than the {} characters FIPS 140 needs for HMAC keys",
|
||||
one, MIN_HMAC_KEY_BYTES
|
||||
)),
|
||||
[rest @ .., last] => Some(format!(
|
||||
"{} and {} are shorter than the {} characters FIPS 140 needs for HMAC keys",
|
||||
rest.join(", "),
|
||||
last,
|
||||
MIN_HMAC_KEY_BYTES
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error a server logs before it exits at startup over the short keys in
|
||||
/// `file`; `short` is the message from [`short_keys`].
|
||||
pub fn startup_refusal(file: &str, short: &str) -> String {
|
||||
format!(
|
||||
"{}: this process runs with fips.mode strict, and stops because {}; replace them on every server that uses them, with or without downtime, see {}",
|
||||
file, short, JWT_SIGNING_KEYS_WIKI
|
||||
)
|
||||
}
|
||||
|
||||
/// Go's `shortJwtKeyWarning`: a warning that the key (other than a previous
|
||||
/// key) of `setting` in `file` is too short for strict mode, asking for a
|
||||
/// longer one while the short one still works.
|
||||
pub fn short_key_warning(mode: FipsMode, file: &str, setting: &str, key: &[u8]) -> Option<String> {
|
||||
if mode == FipsMode::Strict
|
||||
|| key.is_empty()
|
||||
|| key.len() >= MIN_HMAC_KEY_BYTES
|
||||
|| setting.ends_with("previous_key")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{}: this process does not run with fips.mode strict, so {} works, but under fips.mode strict this server would not start: the key is shorter than the {} characters FIPS 140 needs for HMAC keys (it has {}); to replace it on every server that uses it without downtime, see {}",
|
||||
file,
|
||||
setting,
|
||||
MIN_HMAC_KEY_BYTES,
|
||||
key.len(),
|
||||
JWT_SIGNING_KEYS_WIKI
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn short_keys_only_under_strict() {
|
||||
let keys: [(&str, &[u8]); 1] = [("jwt.signing.key", b"0123456789")];
|
||||
assert_eq!(short_keys(FipsMode::On, &keys), None);
|
||||
assert_eq!(short_keys(FipsMode::Off, &keys), None);
|
||||
assert_eq!(
|
||||
short_keys(FipsMode::Strict, &keys).as_deref(),
|
||||
Some(
|
||||
"jwt.signing.key (10 characters) is shorter than the 14 characters FIPS 140 needs for HMAC keys"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_keys_names_every_short_key_and_skips_unset_and_long_ones() {
|
||||
let keys: [(&str, &[u8]); 4] = [
|
||||
("jwt.signing.key", b"0123456789"),
|
||||
("jwt.signing.read.key", b""),
|
||||
("jwt.filer_signing.key", b"01234567890123"),
|
||||
("jwt.filer_signing.subscribe.key", b"01234567"),
|
||||
];
|
||||
assert_eq!(
|
||||
short_keys(FipsMode::Strict, &keys).as_deref(),
|
||||
Some(
|
||||
"jwt.signing.key (10 characters) and jwt.filer_signing.subscribe.key (8 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
|
||||
)
|
||||
);
|
||||
let three: [(&str, &[u8]); 3] = [("a", b"1"), ("b", b"12"), ("c", b"123")];
|
||||
assert_eq!(
|
||||
short_keys(FipsMode::Strict, &three).as_deref(),
|
||||
Some(
|
||||
"a (1 characters), b (2 characters) and c (3 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_outside_strict_except_for_previous_keys() {
|
||||
assert!(short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b"0123456789")
|
||||
.unwrap()
|
||||
.starts_with("s.toml: this process does not run with fips.mode strict, so jwt.signing.key works"));
|
||||
assert!(
|
||||
short_key_warning(FipsMode::On, "s.toml", "jwt.signing.key", b"0123456789").is_some()
|
||||
);
|
||||
assert_eq!(
|
||||
short_key_warning(FipsMode::Strict, "s.toml", "jwt.signing.key", b"0123456789"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
short_key_warning(
|
||||
FipsMode::Off,
|
||||
"s.toml",
|
||||
"jwt.signing.previous_key",
|
||||
b"0123456789"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
short_key_warning(
|
||||
FipsMode::Off,
|
||||
"s.toml",
|
||||
"jwt.signing.key",
|
||||
b"01234567890123"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b""),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,9 @@
|
||||
//! rustls provider, which only works if every binary installs the same one.
|
||||
//! The security.toml search path joined them for the same reason: an operator
|
||||
//! mounts the file once and every binary has to look where `weed` looks.
|
||||
//! The FIPS mode joined them because it decides that provider, and the JWT key
|
||||
//! rule for strict mode because every binary that reads the keys applies it.
|
||||
//! The FIPS mode joined them because it decides that provider.
|
||||
|
||||
pub mod address;
|
||||
pub mod fips;
|
||||
pub mod jwt_keys;
|
||||
pub mod security_config;
|
||||
pub mod tls;
|
||||
Generated
-3
@@ -6332,15 +6332,12 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"crc32c",
|
||||
"log",
|
||||
"prost",
|
||||
"protoc-bin-vendored",
|
||||
"reqwest 0.12.28",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"seaweed-common",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
|
||||
@@ -190,12 +190,7 @@ async fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
|
||||
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
|
||||
let mode = weed_lance_worker::tls::install_for_fips_mode(&security)?;
|
||||
weed_lance_worker::security::check_signing_key_flag(
|
||||
mode,
|
||||
"--filer-signing-key (WEED_FILER_SIGNING_KEY)",
|
||||
args.filer_signing_key.as_deref(),
|
||||
)?;
|
||||
weed_lance_worker::tls::install_for_fips_mode(&security)?;
|
||||
let signing_key = SigningKey::new(
|
||||
args.filer_signing_key
|
||||
.or_else(|| security.get("jwt.filer_signing.key")),
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
//! weed-vector-cli under `fips.mode = strict` exits at startup when a JWT
|
||||
//! key is too short for FIPS 140, before it dials anything.
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Runs weed-vector-cli with `args` under `WEED_FIPS_MODE=strict` and a
|
||||
/// security.toml holding `security`, without the caller's other WEED_
|
||||
/// variables, and returns its exit status and stderr. Fails when it is still
|
||||
/// running after 30 s, which means it accepted the keys.
|
||||
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("security.toml");
|
||||
std::fs::write(&file, security).unwrap();
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-vector-cli"));
|
||||
for (name, _) in std::env::vars_os() {
|
||||
if name.to_string_lossy().starts_with("WEED_") {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
let mut child = command
|
||||
.arg("--security-toml")
|
||||
.arg(&file)
|
||||
.args(args)
|
||||
.env("WEED_FIPS_MODE", "strict")
|
||||
.current_dir(dir.path())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
let mut stderr = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut stderr)
|
||||
.unwrap();
|
||||
return (status, stderr);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("weed-vector-cli still running after 30 s: it accepted the short key");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_key_in_security_toml_stops_the_cli() {
|
||||
let (status, stderr) = run_strict(
|
||||
"[jwt.filer_signing]\nkey = \"0123456789\"\n",
|
||||
&["describe", "bucket$table"],
|
||||
);
|
||||
assert!(!status.success(), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("jwt.filer_signing.key (10 characters) is shorter than the 14 characters"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_signing_key_flag_stops_the_cli() {
|
||||
let (status, stderr) = run_strict(
|
||||
"",
|
||||
&["--filer-signing-key", "short", "describe", "bucket$table"],
|
||||
);
|
||||
assert!(!status.success(), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("--filer-signing-key (WEED_FILER_SIGNING_KEY) (5 characters)"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
//! weed-vector under `fips.mode = strict` exits at startup when a JWT key is
|
||||
//! too short for FIPS 140, before it dials the masters.
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Runs weed-vector with `args` under `WEED_FIPS_MODE=strict` and a
|
||||
/// security.toml holding `security`, without the caller's other WEED_
|
||||
/// variables, and returns its exit status and stderr. Fails when it is still
|
||||
/// running after 30 s, which means it accepted the keys.
|
||||
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("security.toml");
|
||||
std::fs::write(&file, security).unwrap();
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-vector"));
|
||||
for (name, _) in std::env::vars_os() {
|
||||
if name.to_string_lossy().starts_with("WEED_") {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
let mut child = command
|
||||
.arg("--security-toml")
|
||||
.arg(&file)
|
||||
.args(args)
|
||||
.env("WEED_FIPS_MODE", "strict")
|
||||
.current_dir(dir.path())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
let mut stderr = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut stderr)
|
||||
.unwrap();
|
||||
return (status, stderr);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("weed-vector still running after 30 s: it accepted the short key");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_key_in_security_toml_stops_the_engine() {
|
||||
let (status, stderr) = run_strict(
|
||||
"[jwt.signing.read]\nkey = \"0123456789\"\n",
|
||||
&["--masters", "127.0.0.1:9333.19333"],
|
||||
);
|
||||
assert!(!status.success(), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("fips.mode strict")
|
||||
&& stderr
|
||||
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
Generated
-1
@@ -4662,7 +4662,6 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"webpki-roots",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-parser",
|
||||
"xxhash-rust",
|
||||
|
||||
@@ -68,7 +68,6 @@ jsonwebtoken = { version = "10", features = ["rust_crypto"] }
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
rustls-pemfile = "2"
|
||||
webpki-roots = "1"
|
||||
|
||||
# LevelDB (via RocksDB for better Rust support)
|
||||
# Using rusty-leveldb for pure Rust LevelDB
|
||||
|
||||
@@ -289,9 +289,6 @@ message LookupVolumeResponse {
|
||||
repeated Location locations = 2;
|
||||
string error = 3;
|
||||
string auth = 4;
|
||||
// > 0 when the volume was grown degraded: a write needs this many
|
||||
// writable copies instead of its replica placement's copy count.
|
||||
uint32 min_writable_copies = 5;
|
||||
}
|
||||
repeated VolumeIdLocation volume_id_locations = 1;
|
||||
}
|
||||
@@ -441,7 +438,6 @@ message DataNodeInfo {
|
||||
uint32 grpc_port = 3;
|
||||
int64 last_heartbeat_ns = 5;
|
||||
string address = 4; // ip:port for connecting to the volume server
|
||||
bool maintenance = 6; // the volume server refuses new data while set
|
||||
}
|
||||
message RackInfo {
|
||||
string id = 1;
|
||||
|
||||
@@ -148,7 +148,6 @@ message BatchDeleteRequest {
|
||||
repeated string file_ids = 1;
|
||||
bool skip_cookie_check = 2;
|
||||
bool fsync = 3;
|
||||
bool skip_replica_check = 4; // the caller updates the other copies itself
|
||||
}
|
||||
|
||||
message BatchDeleteResponse {
|
||||
@@ -171,7 +170,6 @@ message VacuumVolumeCheckRequest {
|
||||
message VacuumVolumeCheckResponse {
|
||||
double garbage_ratio = 1;
|
||||
bool disk_space_low = 4; // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
|
||||
bool can_delete_mark = 5; // the volume is read-only through a readonlyCanDelete mark and nothing that refuses deletes — compaction only reclaims what the mark lets go
|
||||
}
|
||||
|
||||
message VacuumVolumeCompactRequest {
|
||||
@@ -633,8 +631,6 @@ message VolumeInfo {
|
||||
bool read_only = 7;
|
||||
EcShardConfig ec_shard_config = 8; // EC shard configuration (optional, null = use default 10+4)
|
||||
bool read_only_can_delete = 9; // with read_only: writes are rejected but deletes still land
|
||||
uint64 vacuumed_max_file_key = 12; // largest needle id the volume's vacuums could have erased; 0 = not known
|
||||
uint32 vacuumed_compaction_revision = 13; // compaction revision the vacuum that wrote vacuumed_max_file_key produced; the record holds only while it equals the volume's
|
||||
}
|
||||
|
||||
// EcShardConfig specifies erasure coding shard configuration
|
||||
|
||||
+175
-588
@@ -31,12 +31,8 @@ fn parse_common_names(value: &str) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The value of the WEED_ variable `key`, or `None` when it is unset or empty:
|
||||
/// Go's viper ignores an empty variable, so the setting keeps its file value.
|
||||
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
|
||||
env(key)
|
||||
.and_then(|value| value.into_string().ok())
|
||||
.filter(|value| !value.is_empty())
|
||||
env(key).and_then(|value| value.into_string().ok())
|
||||
}
|
||||
|
||||
/// SeaweedFS Volume Server (Rust implementation)
|
||||
@@ -179,7 +175,7 @@ pub struct Cli {
|
||||
|
||||
/// Maximum numbers of volumes, count[,count]...
|
||||
/// If set to zero, the limit will be auto configured as free disk space divided by volume size.
|
||||
#[arg(long = "max", default_value = "10")]
|
||||
#[arg(long = "max", default_value = "8")]
|
||||
pub max: String,
|
||||
|
||||
/// Comma separated IP addresses having write permission. No limit if empty.
|
||||
@@ -192,7 +188,7 @@ pub struct Cli {
|
||||
pub min_free_space_percent: String,
|
||||
|
||||
/// Min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB).
|
||||
/// Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.
|
||||
/// Low disk space will mark all volumes as ReadOnly.
|
||||
#[arg(long = "minFreeSpace", default_value = "")]
|
||||
pub min_free_space: String,
|
||||
|
||||
@@ -341,13 +337,6 @@ pub struct VolumeServerConfig {
|
||||
pub tls_policy: TlsPolicy,
|
||||
/// Path to security.toml — stored for SIGHUP reload.
|
||||
pub security_file: String,
|
||||
/// The security.toml the settings came from, for messages that name it.
|
||||
pub security_file_name: String,
|
||||
/// Every JWT key setting, from `SecurityConfig::jwt_keys`, for the strict
|
||||
/// mode check at startup.
|
||||
pub jwt_keys: Vec<(&'static str, Vec<u8>)>,
|
||||
/// The FIPS mode, from the same read of security.toml as `jwt_keys`.
|
||||
pub fips_setting: Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError>,
|
||||
/// If true, FetchAndWriteNeedle skips remote S3 endpoint validation
|
||||
/// (allows loopback / link-local / metadata hosts).
|
||||
pub allow_untrusted_remote_endpoints: bool,
|
||||
@@ -385,27 +374,6 @@ impl MinFreeSpace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Go's util.MinFreeSpaceReleaseMarginPercent.
|
||||
pub const RELEASE_MARGIN_PERCENT: u64 = 1;
|
||||
|
||||
/// Mirrors Go's MinFreeSpace.IsLowFrom: a location that was low stays low
|
||||
/// until free space is RELEASE_MARGIN_PERCENT of the disk above the limit.
|
||||
pub fn is_low_from(&self, was_low: bool, free_bytes: u64, total_bytes: u64) -> bool {
|
||||
let low = self.is_low(free_bytes, total_bytes);
|
||||
if !was_low || low {
|
||||
return low;
|
||||
}
|
||||
match self {
|
||||
MinFreeSpace::Percent(pct) => {
|
||||
free_bytes as f64 / total_bytes as f64 * 100.0
|
||||
< *pct + Self::RELEASE_MARGIN_PERCENT as f64
|
||||
}
|
||||
MinFreeSpace::Bytes(min) => {
|
||||
free_bytes < min.saturating_add(total_bytes / 100 * Self::RELEASE_MARGIN_PERCENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Free bytes above the floor; mirrors Go's MinFreeSpace.AvailableSpace.
|
||||
pub fn available_space(&self, free_bytes: u64, total_bytes: u64) -> u64 {
|
||||
let floor = match self {
|
||||
@@ -985,7 +953,6 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
|
||||
// Parse security config from TOML file
|
||||
let sec = parse_security_config_with_env(&cli.security_file, env);
|
||||
let fips_setting = resolve_fips_setting_with_env(&cli.security_file, &sec, env);
|
||||
|
||||
// Parse whitelist: merge CLI --whiteList with guard.white_list from security.toml
|
||||
let mut white_list: Vec<String> = cli
|
||||
@@ -1042,9 +1009,6 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
debug: cli.debug,
|
||||
debug_port: cli.debug_port,
|
||||
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
|
||||
security_file_name: sec.file_name(),
|
||||
jwt_keys: sec.jwt_keys(),
|
||||
fips_setting,
|
||||
jwt_signing_key: sec.jwt_signing_key,
|
||||
jwt_signing_expires_seconds: sec.jwt_signing_expires,
|
||||
jwt_previous_signing_key: sec.jwt_previous_signing_key,
|
||||
@@ -1076,12 +1040,6 @@ fn default_volume_dir() -> String {
|
||||
std::env::temp_dir().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// The WEED_ variable that overrides `setting`, as Go's viper names it:
|
||||
/// `jwt.filer_signing.key` is `WEED_JWT_FILER_SIGNING_KEY`.
|
||||
fn env_name(setting: &str) -> String {
|
||||
format!("WEED_{}", setting.to_uppercase().replace('.', "_"))
|
||||
}
|
||||
|
||||
/// Parsed security configuration from security.toml.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct SecurityConfig {
|
||||
@@ -1110,12 +1068,6 @@ pub struct SecurityConfig {
|
||||
pub access_ui: bool,
|
||||
/// The file was read; otherwise only defaults and WEED_ overrides are set.
|
||||
pub file_read: bool,
|
||||
/// The file the settings came from, for messages that name it.
|
||||
pub file_used: Option<PathBuf>,
|
||||
/// The `jwt.filer_signing*` keys, by setting. The volume server does not
|
||||
/// use them; they are read so strict mode refuses a short one, as every Go
|
||||
/// process that reads the same security.toml does.
|
||||
pub filer_jwt_keys: Vec<(&'static str, Vec<u8>)>,
|
||||
/// IPs from [guard] white_list in security.toml
|
||||
pub guard_white_list: Vec<String>,
|
||||
/// `[fips] mode` as the file sets it, read like every other key here;
|
||||
@@ -1123,48 +1075,6 @@ pub struct SecurityConfig {
|
||||
pub fips_mode: Option<String>,
|
||||
}
|
||||
|
||||
impl SecurityConfig {
|
||||
/// Sets the `jwt.filer_signing*` key `setting` to `value`, replacing an
|
||||
/// earlier value as a later line or a WEED_ variable does in Go.
|
||||
fn set_filer_jwt_key(&mut self, setting: &'static str, value: &str) {
|
||||
self.filer_jwt_keys.retain(|(s, _)| *s != setting);
|
||||
self.filer_jwt_keys
|
||||
.push((setting, value.as_bytes().to_vec()));
|
||||
}
|
||||
|
||||
/// Every JWT key setting the file and the WEED_ variables set, in the
|
||||
/// order of `seaweed_common::jwt_keys::JWT_KEY_SETTINGS`; an unset key is
|
||||
/// empty.
|
||||
pub fn jwt_keys(&self) -> Vec<(&'static str, Vec<u8>)> {
|
||||
seaweed_common::jwt_keys::JWT_KEY_SETTINGS
|
||||
.iter()
|
||||
.map(|&setting| {
|
||||
let key = match setting {
|
||||
"jwt.signing.key" => self.jwt_signing_key.clone(),
|
||||
"jwt.signing.previous_key" => self.jwt_previous_signing_key.clone(),
|
||||
"jwt.signing.read.key" => self.jwt_read_signing_key.clone(),
|
||||
"jwt.signing.read.previous_key" => self.jwt_previous_read_signing_key.clone(),
|
||||
_ => self
|
||||
.filer_jwt_keys
|
||||
.iter()
|
||||
.find(|(s, _)| *s == setting)
|
||||
.map(|(_, key)| key.clone())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
(setting, key)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The name messages give the file: its path, or "security.toml" when no
|
||||
/// file was read, as Go does.
|
||||
pub fn file_name(&self) -> String {
|
||||
self.file_used
|
||||
.as_ref()
|
||||
.map_or_else(|| "security.toml".to_string(), |p| p.display().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
|
||||
/// Format:
|
||||
/// ```toml
|
||||
@@ -1223,62 +1133,157 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
|
||||
}
|
||||
};
|
||||
|
||||
let table = lowercase_keys(
|
||||
content
|
||||
.parse::<toml::Table>()
|
||||
.unwrap_or_else(|_| lenient_toml_table(&content)),
|
||||
);
|
||||
let setting = |name: &str| toml_setting(&table, name);
|
||||
let text = |name: &str| setting(name).unwrap_or_default();
|
||||
let flag = |name: &str| text(name).parse().unwrap_or(false);
|
||||
let expires =
|
||||
|name: &str, default: i64| setting(name).map_or(0, |v| v.parse().unwrap_or(default));
|
||||
let mut cfg = SecurityConfig::default();
|
||||
|
||||
let mut cfg = SecurityConfig {
|
||||
jwt_signing_key: text("jwt.signing.key").into_bytes(),
|
||||
jwt_previous_signing_key: text("jwt.signing.previous_key").into_bytes(),
|
||||
jwt_signing_expires: expires("jwt.signing.expires_after_seconds", 10),
|
||||
jwt_read_signing_key: text("jwt.signing.read.key").into_bytes(),
|
||||
jwt_previous_read_signing_key: text("jwt.signing.read.previous_key").into_bytes(),
|
||||
jwt_read_signing_expires: expires("jwt.signing.read.expires_after_seconds", 60),
|
||||
https_client_enabled: flag("https.client.enabled"),
|
||||
https_client_cert_file: text("https.client.cert"),
|
||||
https_client_key_file: text("https.client.key"),
|
||||
https_client_ca_file: text("https.client.ca"),
|
||||
grpc_ca_file: text("grpc.ca"),
|
||||
grpc_allowed_wildcard_domain: text("grpc.allowed_wildcard_domain"),
|
||||
grpc_health_check_common_names: parse_common_names(&text("grpc.health_check_commonNames")),
|
||||
https_cert_file: text("https.volume.cert"),
|
||||
https_key_file: text("https.volume.key"),
|
||||
https_ca_file: text("https.volume.ca"),
|
||||
grpc_cert_file: text("grpc.volume.cert"),
|
||||
grpc_key_file: text("grpc.volume.key"),
|
||||
grpc_client_cert_file: text("grpc.volume.client_cert"),
|
||||
grpc_client_key_file: text("grpc.volume.client_key"),
|
||||
// Go only reads CA from [grpc], not [grpc.volume]
|
||||
grpc_volume_allowed_common_names: setting("grpc.volume.allowed_commonNames")
|
||||
.map(|names| names.split(',').map(String::from).collect())
|
||||
.unwrap_or_default(),
|
||||
tls_policy: TlsPolicy {
|
||||
min_version: text("tls.min_version"),
|
||||
max_version: text("tls.max_version"),
|
||||
cipher_suites: text("tls.cipher_suites"),
|
||||
},
|
||||
guard_white_list: text("guard.white_list")
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect(),
|
||||
access_ui: flag("access.ui"),
|
||||
fips_mode: toml_entry(&table, &["fips", "mode"]).map(toml_text),
|
||||
..SecurityConfig::default()
|
||||
};
|
||||
for name in seaweed_common::jwt_keys::JWT_KEY_SETTINGS
|
||||
.iter()
|
||||
.filter(|name| name.starts_with("jwt.filer_signing"))
|
||||
{
|
||||
if let Some(key) = setting(name) {
|
||||
cfg.set_filer_jwt_key(name, &key);
|
||||
#[derive(PartialEq)]
|
||||
enum Section {
|
||||
None,
|
||||
JwtSigning,
|
||||
JwtSigningRead,
|
||||
HttpsClient,
|
||||
Grpc,
|
||||
HttpsVolume,
|
||||
GrpcVolume,
|
||||
Tls,
|
||||
Guard,
|
||||
Access,
|
||||
Fips,
|
||||
}
|
||||
|
||||
let mut section = Section::None;
|
||||
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with('#') || trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[jwt.signing.read]" {
|
||||
section = Section::JwtSigningRead;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[jwt.signing]" {
|
||||
section = Section::JwtSigning;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[https.client]" {
|
||||
section = Section::HttpsClient;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[grpc]" {
|
||||
section = Section::Grpc;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[https.volume]" {
|
||||
section = Section::HttpsVolume;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[grpc.volume]" {
|
||||
section = Section::GrpcVolume;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[tls]" {
|
||||
section = Section::Tls;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[guard]" {
|
||||
section = Section::Guard;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[access]" {
|
||||
section = Section::Access;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[fips]" {
|
||||
section = Section::Fips;
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with('[') {
|
||||
section = Section::None;
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((key, value)) = trimmed.split_once('=') {
|
||||
let key = key.trim();
|
||||
let value: &str = &toml_value_text(value);
|
||||
match section {
|
||||
Section::JwtSigningRead => match key {
|
||||
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
|
||||
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
|
||||
"expires_after_seconds" => {
|
||||
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Section::JwtSigning => match key {
|
||||
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
|
||||
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
|
||||
"expires_after_seconds" => {
|
||||
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Section::HttpsClient => match key {
|
||||
"enabled" => cfg.https_client_enabled = value.parse().unwrap_or(false),
|
||||
"cert" => cfg.https_client_cert_file = value.to_string(),
|
||||
"key" => cfg.https_client_key_file = value.to_string(),
|
||||
"ca" => cfg.https_client_ca_file = value.to_string(),
|
||||
_ => {}
|
||||
},
|
||||
Section::Grpc => match key {
|
||||
"ca" => cfg.grpc_ca_file = value.to_string(),
|
||||
"allowed_wildcard_domain" => {
|
||||
cfg.grpc_allowed_wildcard_domain = value.to_string()
|
||||
}
|
||||
"health_check_commonNames" => {
|
||||
cfg.grpc_health_check_common_names = parse_common_names(value)
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Section::HttpsVolume => match key {
|
||||
"cert" => cfg.https_cert_file = value.to_string(),
|
||||
"key" => cfg.https_key_file = value.to_string(),
|
||||
"ca" => cfg.https_ca_file = value.to_string(),
|
||||
_ => {}
|
||||
},
|
||||
Section::GrpcVolume => match key {
|
||||
"cert" => cfg.grpc_cert_file = value.to_string(),
|
||||
"key" => cfg.grpc_key_file = value.to_string(),
|
||||
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
|
||||
"client_key" => cfg.grpc_client_key_file = value.to_string(),
|
||||
// Go only reads CA from [grpc], not [grpc.volume]
|
||||
"allowed_commonNames" => {
|
||||
cfg.grpc_volume_allowed_common_names =
|
||||
value.split(',').map(|name| name.to_string()).collect();
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Section::Tls => match key {
|
||||
"min_version" => cfg.tls_policy.min_version = value.to_string(),
|
||||
"max_version" => cfg.tls_policy.max_version = value.to_string(),
|
||||
"cipher_suites" => cfg.tls_policy.cipher_suites = value.to_string(),
|
||||
_ => {}
|
||||
},
|
||||
Section::Guard => {
|
||||
if key == "white_list" {
|
||||
cfg.guard_white_list = value
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
Section::Access => {
|
||||
if key == "ui" {
|
||||
cfg.access_ui = value.parse().unwrap_or(false)
|
||||
}
|
||||
}
|
||||
Section::Fips => {
|
||||
if key == "mode" {
|
||||
cfg.fips_mode = Some(value.to_string())
|
||||
}
|
||||
}
|
||||
Section::None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1296,114 +1301,10 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
|
||||
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
|
||||
apply_env_overrides(&mut cfg, env);
|
||||
cfg.file_read = true;
|
||||
cfg.file_used = Some(config_path);
|
||||
|
||||
cfg
|
||||
}
|
||||
|
||||
/// The table header on a trimmed security.toml line, without the trailing
|
||||
/// comment TOML allows after it (`[fips] # policy` is `[fips]`), or `None`
|
||||
/// when the line is not a header. None of the sections read here has a `#`
|
||||
/// in its name.
|
||||
fn section_header(trimmed: &str) -> Option<&str> {
|
||||
if !trimmed.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
let header = trimmed
|
||||
.split_once('#')
|
||||
.map_or(trimmed, |(header, _)| header);
|
||||
Some(header.trim_end())
|
||||
}
|
||||
|
||||
/// The value of the dotted `setting` in `table`, a table from
|
||||
/// `lowercase_keys`, as Go's viper GetString reads it: a value that is not a
|
||||
/// string reads as its TOML text, and an array or a table as unset.
|
||||
fn toml_setting(table: &toml::Table, setting: &str) -> Option<String> {
|
||||
let setting = setting.to_lowercase();
|
||||
let path: Vec<&str> = setting.split('.').collect();
|
||||
match toml_entry(table, &path)? {
|
||||
toml::Value::Array(_) | toml::Value::Table(_) => None,
|
||||
value => Some(toml_text(value)),
|
||||
}
|
||||
}
|
||||
|
||||
fn toml_text(value: &toml::Value) -> String {
|
||||
match value {
|
||||
toml::Value::String(text) => text.clone(),
|
||||
toml::Value::Float(number) => number.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value at `path` in `table`. As in viper, the longest run of leading
|
||||
/// parts that is itself a key wins (`"jwt.signing.key" = ...` over
|
||||
/// `[jwt.signing] key`), and a shorter run is tried when the rest of the path
|
||||
/// is not under it.
|
||||
fn toml_entry<'a>(table: &'a toml::Table, path: &[&str]) -> Option<&'a toml::Value> {
|
||||
(1..=path.len()).rev().find_map(|n| {
|
||||
let value = table.get(&path[..n].join("."))?;
|
||||
match (&path[n..], value) {
|
||||
([], value) => Some(value),
|
||||
(rest, toml::Value::Table(next)) => toml_entry(next, rest),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `table` with every key lowercased, as viper holds a config file. When two
|
||||
/// spellings of a key collide, the one that is not lowercase wins, as it does
|
||||
/// in viper.
|
||||
fn lowercase_keys(table: toml::Table) -> toml::Table {
|
||||
let mut lowered = toml::Table::new();
|
||||
for (key, value) in table {
|
||||
let value = match value {
|
||||
toml::Value::Table(nested) => toml::Value::Table(lowercase_keys(nested)),
|
||||
other => other,
|
||||
};
|
||||
let lower = key.to_lowercase();
|
||||
if key != lower || !lowered.contains_key(&lower) {
|
||||
lowered.insert(lower, value);
|
||||
}
|
||||
}
|
||||
lowered
|
||||
}
|
||||
|
||||
/// The `key = value` lines of a file that is not valid TOML, each under its
|
||||
/// full dotted name (`jwt.signing.key`), so no line can replace the table
|
||||
/// another line's value is in. Go's viper skips such a file; this server keeps
|
||||
/// reading what it can from it, one line at a time.
|
||||
fn lenient_toml_table(content: &str) -> toml::Table {
|
||||
let mut table = toml::Table::new();
|
||||
let mut section = String::new();
|
||||
let mut in_array_of_tables = false;
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with('#') || trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(header) = section_header(trimmed) {
|
||||
in_array_of_tables = header.starts_with("[[");
|
||||
section = header
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.split('.')
|
||||
.map(|part| format!("{}.", part.trim()))
|
||||
.collect();
|
||||
continue;
|
||||
}
|
||||
if in_array_of_tables {
|
||||
continue;
|
||||
}
|
||||
if let Some((key, value)) = trimmed.split_once('=') {
|
||||
table.insert(
|
||||
format!("{section}{}", key.trim()),
|
||||
toml::Value::String(toml_value_text(value)),
|
||||
);
|
||||
}
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
|
||||
/// escapes decoded, literal strings kept as written, a trailing comment
|
||||
/// dropped. Text TOML rejects keeps the plain quote trimming.
|
||||
@@ -1419,40 +1320,31 @@ fn toml_value_text(raw: &str) -> String {
|
||||
}
|
||||
|
||||
/// The FIPS mode this volume server runs in: `WEED_FIPS_MODE`, else
|
||||
/// `fips.mode` in `parsed`, the security.toml `--securityFile` names or the
|
||||
/// search finds, else off. A file that exists but was not read is an error,
|
||||
/// since it may set the mode.
|
||||
/// `fips.mode` in the security.toml `--securityFile` names or the search
|
||||
/// finds, read by the same loader as the JWT keys, else off. A file that
|
||||
/// exists but cannot be read is an error, since it may set the mode.
|
||||
pub fn resolve_fips_setting(
|
||||
security_file: &str,
|
||||
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
|
||||
resolve_fips_setting_with_env(security_file, &process_env)
|
||||
}
|
||||
|
||||
fn resolve_fips_setting_with_env(
|
||||
security_file: &str,
|
||||
parsed: &SecurityConfig,
|
||||
env: EnvLookup<'_>,
|
||||
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
|
||||
let path = parsed
|
||||
.file_used
|
||||
.clone()
|
||||
.or_else(|| resolve_security_config_path(security_file, env).filter(|p| p.exists()));
|
||||
let path = resolve_security_config_path(security_file, env).filter(|p| p.exists());
|
||||
let Some(path) = path else {
|
||||
return seaweed_common::fips::resolve(None, None, env);
|
||||
};
|
||||
fips_setting_from_parsed(path, parsed, env)
|
||||
}
|
||||
|
||||
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
|
||||
/// applied. A parse that could not read the file is an error like the first
|
||||
/// read, so a file that stops being readable between the two reads cannot
|
||||
/// leave the mode off.
|
||||
fn fips_setting_from_parsed(
|
||||
path: PathBuf,
|
||||
parsed: &SecurityConfig,
|
||||
env: EnvLookup<'_>,
|
||||
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
|
||||
if !parsed.file_read {
|
||||
if let Err(e) = std::fs::read_to_string(&path) {
|
||||
return Err(seaweed_common::fips::FipsModeError::File {
|
||||
path,
|
||||
reason: "could not be read".to_string(),
|
||||
reason: e.to_string(),
|
||||
});
|
||||
}
|
||||
seaweed_common::fips::resolve(Some(&path), parsed.fips_mode.as_deref(), env)
|
||||
let file_value = parse_security_config_with_env(&path.to_string_lossy(), env).fips_mode;
|
||||
seaweed_common::fips::resolve(Some(&path), file_value.as_deref(), env)
|
||||
}
|
||||
|
||||
fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBuf> {
|
||||
@@ -1469,13 +1361,6 @@ fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBu
|
||||
/// Apply WEED_ environment variable overrides to a SecurityConfig.
|
||||
/// Matches Go's Viper convention: WEED_ prefix, uppercase, dots replaced with underscores.
|
||||
fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
|
||||
for setting in seaweed_common::jwt_keys::JWT_KEY_SETTINGS {
|
||||
if setting.starts_with("jwt.filer_signing") {
|
||||
if let Some(v) = env_string(env, &env_name(setting)) {
|
||||
cfg.set_filer_jwt_key(setting, &v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_KEY") {
|
||||
cfg.jwt_signing_key = v.into_bytes();
|
||||
}
|
||||
@@ -1828,46 +1713,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_min_free_space_is_low_from_holds_until_margin() {
|
||||
let pct = MinFreeSpace::Percent(7.0);
|
||||
let total = 10_000u64;
|
||||
for (was_low, free, want) in [
|
||||
(false, 699, true),
|
||||
(false, 702, false),
|
||||
(true, 702, true),
|
||||
(true, 799, true),
|
||||
(true, 800, false),
|
||||
(false, 799, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
pct.is_low_from(was_low, free, total),
|
||||
want,
|
||||
"percent was_low={was_low} free={free}"
|
||||
);
|
||||
}
|
||||
|
||||
let gib = 1u64 << 30;
|
||||
let bytes = MinFreeSpace::Bytes(70 * gib);
|
||||
let total = 1000 * gib;
|
||||
for (was_low, free, want) in [
|
||||
(false, 70 * gib - 1, true),
|
||||
(false, 70 * gib, false),
|
||||
(true, 70 * gib + 1, true),
|
||||
(true, 80 * gib - 1, true),
|
||||
(true, 80 * gib, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
bytes.is_low_from(was_low, free, total),
|
||||
want,
|
||||
"bytes was_low={was_low} free={free}"
|
||||
);
|
||||
}
|
||||
|
||||
let near_max = MinFreeSpace::Bytes(u64::MAX - 1);
|
||||
assert!(near_max.is_low_from(true, u64::MAX - 1, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_percent() {
|
||||
let result = parse_min_free_spaces("", "1").unwrap();
|
||||
@@ -2094,58 +1939,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_jwt_keys_include_the_filer_keys_and_their_env_overrides() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
tmp.path(),
|
||||
r#"
|
||||
[jwt.signing]
|
||||
key = "volume-write"
|
||||
previous_key = "volume-write-old"
|
||||
|
||||
[jwt.signing.read]
|
||||
key = "volume-read"
|
||||
|
||||
[jwt.filer_signing]
|
||||
key = "filer-write"
|
||||
grpc_key = "filer-grpc"
|
||||
|
||||
[jwt.filer_signing.read]
|
||||
previous_key = "filer-read-old"
|
||||
|
||||
[jwt.filer_signing.subscribe]
|
||||
key = "filer-subscribe"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
let env = fake_env(&[("WEED_JWT_FILER_SIGNING_KEY", "filer-write-env")]);
|
||||
let cfg = parse_security_config_with_env(path, &env);
|
||||
let keys: Vec<(&str, String)> = cfg
|
||||
.jwt_keys()
|
||||
.into_iter()
|
||||
.map(|(setting, key)| (setting, String::from_utf8(key).unwrap()))
|
||||
.collect();
|
||||
let want = [
|
||||
("jwt.signing.key", "volume-write"),
|
||||
("jwt.signing.previous_key", "volume-write-old"),
|
||||
("jwt.signing.read.key", "volume-read"),
|
||||
("jwt.signing.read.previous_key", ""),
|
||||
("jwt.filer_signing.key", "filer-write-env"),
|
||||
("jwt.filer_signing.previous_key", ""),
|
||||
("jwt.filer_signing.read.key", ""),
|
||||
("jwt.filer_signing.read.previous_key", "filer-read-old"),
|
||||
("jwt.filer_signing.grpc_key", "filer-grpc"),
|
||||
("jwt.filer_signing.grpc_previous_key", ""),
|
||||
("jwt.filer_signing.subscribe.key", "filer-subscribe"),
|
||||
];
|
||||
let want: Vec<(&str, String)> = want.iter().map(|(s, k)| (*s, k.to_string())).collect();
|
||||
assert_eq!(keys, want);
|
||||
assert_eq!(cfg.file_name(), path);
|
||||
assert_eq!(SecurityConfig::default().file_name(), "security.toml");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_security_config_access_ui() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
@@ -2465,39 +2258,6 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
|
||||
assert_eq!(cfg.jwt_signing_key, b"env-secret");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_env_override_keeps_the_file_value() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
tmp.path(),
|
||||
r#"
|
||||
[jwt.signing]
|
||||
key = "file-write"
|
||||
|
||||
[jwt.filer_signing]
|
||||
key = "file-filer"
|
||||
|
||||
[grpc]
|
||||
ca = "/file/ca.pem"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let env = fake_env(&[
|
||||
("WEED_JWT_SIGNING_KEY", ""),
|
||||
("WEED_JWT_FILER_SIGNING_KEY", ""),
|
||||
("WEED_GRPC_CA", ""),
|
||||
]);
|
||||
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &env);
|
||||
assert_eq!(cfg.jwt_signing_key, b"file-write");
|
||||
assert_eq!(cfg.grpc_ca_file, "/file/ca.pem");
|
||||
let filer_key = cfg
|
||||
.jwt_keys()
|
||||
.into_iter()
|
||||
.find(|(setting, _)| *setting == "jwt.filer_signing.key")
|
||||
.map(|(_, key)| key);
|
||||
assert_eq!(filer_key.as_deref(), Some(&b"file-filer"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_previous_signing_keys_from_file_and_env() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
@@ -2549,16 +2309,16 @@ previous_key = "read-old"
|
||||
std::fs::write(tmp.path(), "[fips]\nmode = \"on\"\n").unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
|
||||
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
|
||||
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
let env = fake_env(&[("WEED_FIPS_MODE", "strict")]);
|
||||
let setting = fips_setting_of(path, &env).unwrap();
|
||||
let setting = resolve_fips_setting_with_env(path, &env).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::Strict);
|
||||
let env = fake_env(&[("WEED_FIPS_MODE", "only")]);
|
||||
assert!(fips_setting_of(path, &env).is_err());
|
||||
assert!(resolve_fips_setting_with_env(path, &env).is_err());
|
||||
|
||||
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
|
||||
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
|
||||
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::Off);
|
||||
}
|
||||
|
||||
@@ -2572,163 +2332,11 @@ previous_key = "read-old"
|
||||
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
|
||||
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
|
||||
assert_eq!(cfg.jwt_signing_key, b"unquoted-secret");
|
||||
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
|
||||
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
|
||||
std::fs::write(tmp.path(), "[fips]\nmode = [\"strict\"]\n").unwrap();
|
||||
assert!(fips_setting_of(path, &fake_env(&[])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_file_keeps_a_key_a_later_line_would_shadow() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[jwt]\nsigning = \"x\"\n\
|
||||
[jwt.signing.key]\nx = unquoted\n";
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
|
||||
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
|
||||
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_file_skips_array_of_tables_sections() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
let text = "[jwt.signing]\nkey = \"0123456789abcdef\"\n[[jwt.signing]]\nkey = \"\"\n\
|
||||
[fips]\nmode = \"on\"\n";
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
assert!(text.parse::<toml::Table>().is_err(), "not TOML");
|
||||
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
|
||||
assert_eq!(cfg.jwt_signing_key, b"0123456789abcdef");
|
||||
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_section_headers_with_a_trailing_comment() {
|
||||
use seaweed_common::fips::FipsMode;
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
let text = "[fips] # deployment policy\nmode = \"on\"\n\
|
||||
[jwt.signing] # comment\nkey = \"secret\"\n\
|
||||
[other] # not read\nkey = \"ignored\"\n";
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
assert!(text.parse::<toml::Table>().is_ok(), "TOML, as Go reads it");
|
||||
|
||||
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
|
||||
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
|
||||
assert_eq!(cfg.jwt_signing_key, b"secret");
|
||||
let setting = fips_setting_of(path, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_config_reads_the_toml_forms_go_reads() {
|
||||
for text in [
|
||||
"[jwt.signing]\n\"key\" = \"0123456789\"\n\
|
||||
[jwt.filer_signing]\n'key' = \"0123456789\"\n[fips]\n\"mode\" = \"on\"\n",
|
||||
"[jwt.signing]\nkey = \"\"\"\n0123456789\"\"\"\n\
|
||||
[jwt.filer_signing]\nkey = '''\n0123456789'''\n[fips]\nmode = \"on\"\n",
|
||||
"jwt.signing.key = \"0123456789\"\njwt.filer_signing.key = \"0123456789\"\n\
|
||||
fips.mode = \"on\"\n",
|
||||
"[jwt]\nsigning = { key = \"0123456789\" }\nfiler_signing = { key = \"0123456789\" }\n\
|
||||
[fips]\nmode = \"on\"\n",
|
||||
"[ \"jwt\" . signing ]\nKey = \"0123456789\"\n[jwt.\"filer_signing\"]\nKEY = \"0123456789\"\n\
|
||||
[FIPS]\nMode = \"on\"\n",
|
||||
] {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
assert!(
|
||||
text.parse::<toml::Table>().is_ok(),
|
||||
"TOML, as Go reads it: {text}"
|
||||
);
|
||||
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
|
||||
let keys = cfg.jwt_keys();
|
||||
for setting in ["jwt.signing.key", "jwt.filer_signing.key"] {
|
||||
let key = keys
|
||||
.iter()
|
||||
.find(|(s, _)| *s == setting)
|
||||
.map(|(_, k)| k.as_slice());
|
||||
assert_eq!(key, Some(&b"0123456789"[..]), "{setting} in {text}");
|
||||
}
|
||||
assert_eq!(cfg.fips_mode.as_deref(), Some("on"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
fn fips_setting_of(
|
||||
path: &str,
|
||||
env: EnvLookup<'_>,
|
||||
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
|
||||
resolve_fips_setting_with_env(path, &parse_security_config_with_env(path, env), env)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fips_mode_comes_from_the_read_the_jwt_keys_come_from() {
|
||||
use seaweed_common::fips::FipsMode;
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
std::fs::write(tmp.path(), "[fips]\nmode = \"strict\"\n").unwrap();
|
||||
let parsed = parse_security_config_with_env(path, &fake_env(&[]));
|
||||
std::fs::write(tmp.path(), "[fips]\nmode = \"off\"\n").unwrap();
|
||||
let setting = resolve_fips_setting_with_env(path, &parsed, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::Strict);
|
||||
}
|
||||
|
||||
/// The value Go's viper GetString reads for `jwt.filer_signing.key` from
|
||||
/// security.toml `text`, as this server reads it.
|
||||
fn filer_jwt_key(text: &str) -> Vec<u8> {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
assert!(text.parse::<toml::Table>().is_ok(), "TOML: {text}");
|
||||
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &fake_env(&[]));
|
||||
cfg.jwt_keys()
|
||||
.into_iter()
|
||||
.find(|(s, _)| *s == "jwt.filer_signing.key")
|
||||
.map(|(_, k)| k)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_config_prefers_the_longest_literal_key_as_go_does() {
|
||||
let nested = "[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n";
|
||||
for literal in [
|
||||
"\"jwt.filer_signing.key\" = \"short\"\n",
|
||||
"[jwt]\n\"filer_signing.key\" = \"short\"\n",
|
||||
] {
|
||||
assert_eq!(filer_jwt_key(&format!("{literal}{nested}")), b"short");
|
||||
}
|
||||
assert_eq!(
|
||||
filer_jwt_key(&format!("\"jwt.filer_signing\" = \"x\"\n{nested}")),
|
||||
b"0123456789abcdef"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_config_resolves_key_case_collisions_as_go_does() {
|
||||
for text in [
|
||||
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\nKEY = \"short\"\n",
|
||||
"[jwt.filer_signing]\nKEY = \"short\"\nkey = \"0123456789abcdef\"\n",
|
||||
"[jwt.filer_signing]\nkey = \"0123456789abcdef\"\n[JWT.filer_signing]\nkey = \"short\"\n",
|
||||
] {
|
||||
assert_eq!(filer_jwt_key(text), b"short", "{text}");
|
||||
}
|
||||
assert_eq!(
|
||||
filer_jwt_key("[JWT.Filer_Signing]\nKey = \"0123456789abcdef\"\n"),
|
||||
b"0123456789abcdef"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_config_reads_a_non_string_jwt_key_as_go_does() {
|
||||
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = [\"x\"]\n"), b"");
|
||||
assert_eq!(filer_jwt_key("[jwt.filer_signing.key]\nx = \"y\"\n"), b"");
|
||||
assert_eq!(filer_jwt_key("[jwt.filer_signing]\nkey = 1234\n"), b"1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_security_config_reads_a_float_jwt_key_as_go_does() {
|
||||
let key = filer_jwt_key("[jwt.filer_signing]\nkey = 1234567890123.0\n");
|
||||
assert_eq!(key, b"1234567890123");
|
||||
let key = filer_jwt_key("[jwt.filer_signing]\nkey = \"1234567890123.0\"\n");
|
||||
assert_eq!(key, b"1234567890123.0");
|
||||
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2736,38 +2344,17 @@ previous_key = "read-old"
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(tmp.path(), b"[fips]\nmode = \"on\"\n\xff\xfe\n").unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
let err = fips_setting_of(path, &fake_env(&[])).unwrap_err();
|
||||
let err = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("cannot tell whether it sets fips.mode"),
|
||||
"{err}"
|
||||
);
|
||||
let missing = format!("{path}.missing");
|
||||
let setting = fips_setting_of(&missing, &fake_env(&[])).unwrap();
|
||||
let setting = resolve_fips_setting_with_env(&missing, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fips_mode_refuses_a_parse_that_did_not_read_the_file() {
|
||||
use seaweed_common::fips::FipsMode;
|
||||
let path = PathBuf::from("/etc/seaweedfs/security.toml");
|
||||
let unread = SecurityConfig::default();
|
||||
let err = fips_setting_from_parsed(path.clone(), &unread, &fake_env(&[])).unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("could not be read; cannot tell whether it sets fips.mode"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let read = SecurityConfig {
|
||||
file_read: true,
|
||||
fips_mode: Some("on".to_string()),
|
||||
..SecurityConfig::default()
|
||||
};
|
||||
let setting = fips_setting_from_parsed(path, &read, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_env_override_takes_precedence_over_file() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
|
||||
+24
-131
@@ -57,8 +57,7 @@ fn main() {
|
||||
.init();
|
||||
|
||||
let config = config::parse_cli();
|
||||
install_crypto_provider_for_fips_mode(&config);
|
||||
check_jwt_keys_for_fips_mode(&config);
|
||||
install_crypto_provider_for_fips_mode(&config.security_file);
|
||||
seaweed_volume::server::server_stats::init_process_start();
|
||||
#[cfg(unix)]
|
||||
let cpu_profile = match CpuProfileSession::start(&config) {
|
||||
@@ -106,10 +105,8 @@ fn main() {
|
||||
/// Resolves the FIPS mode from `fips.mode` or `WEED_FIPS_MODE`, logs it and
|
||||
/// installs the matching rustls provider before anything builds TLS; exits
|
||||
/// when the value is unknown.
|
||||
fn install_crypto_provider_for_fips_mode(config: &config::VolumeServerConfig) {
|
||||
let installed = config
|
||||
.fips_setting
|
||||
.clone()
|
||||
fn install_crypto_provider_for_fips_mode(security_file: &str) {
|
||||
let installed = config::resolve_fips_setting(security_file)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|setting| {
|
||||
seaweed_common::tls::install_process_provider(setting.mode)
|
||||
@@ -129,32 +126,6 @@ fn install_crypto_provider_for_fips_mode(config: &config::VolumeServerConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the JWT HMAC signing keys from security.toml and their WEED_
|
||||
/// variables for a length of at least 14 characters, as FIPS 140 requires.
|
||||
/// Under `fips.mode = strict`, if any of them is shorter, it logs an error
|
||||
/// naming each such setting and its length and exits the server with status 1.
|
||||
/// In any other mode the server starts, and each such key except a
|
||||
/// `previous_key` gets a warning that strict mode would refuse it.
|
||||
fn check_jwt_keys_for_fips_mode(config: &config::VolumeServerConfig) {
|
||||
use seaweed_common::jwt_keys;
|
||||
let mode = seaweed_common::fips::process_mode();
|
||||
let file = &config.security_file_name;
|
||||
for (setting, key) in &config.jwt_keys {
|
||||
if let Some(warning) = jwt_keys::short_key_warning(mode, file, setting, key) {
|
||||
warn!("{}", warning);
|
||||
}
|
||||
}
|
||||
let keys: Vec<(&str, &[u8])> = config
|
||||
.jwt_keys
|
||||
.iter()
|
||||
.map(|(setting, key)| (*setting, key.as_slice()))
|
||||
.collect();
|
||||
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
|
||||
error!("{}", jwt_keys::startup_refusal(file, &short));
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
|
||||
/// carrying data and auth headers from https to plaintext.
|
||||
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
|
||||
@@ -198,22 +169,28 @@ fn build_outgoing_http_client(
|
||||
));
|
||||
}
|
||||
|
||||
let ca_pem = if config.https_client_ca_file.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(std::fs::read(&config.https_client_ca_file).map_err(|e| {
|
||||
let mut builder = outgoing_client_builder(redirect_policy);
|
||||
if !config.https_client_ca_file.is_empty() {
|
||||
let ca_pem = std::fs::read(&config.https_client_ca_file).map_err(|e| {
|
||||
format!(
|
||||
"Failed to read HTTPS client CA file '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?)
|
||||
};
|
||||
})?;
|
||||
let cert = reqwest::Certificate::from_pem(&ca_pem).map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse HTTPS client CA PEM '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?;
|
||||
builder = builder.add_root_certificate(cert);
|
||||
}
|
||||
|
||||
let identity = match (
|
||||
match (
|
||||
config.https_client_cert_file.is_empty(),
|
||||
config.https_client_key_file.is_empty(),
|
||||
) {
|
||||
(true, true) => None,
|
||||
(true, true) => {}
|
||||
(false, false) => {
|
||||
let cert_pem = std::fs::read(&config.https_client_cert_file).map_err(|e| {
|
||||
format!(
|
||||
@@ -227,45 +204,6 @@ fn build_outgoing_http_client(
|
||||
config.https_client_key_file, e
|
||||
)
|
||||
})?;
|
||||
Some((cert_pem, key_pem))
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
|
||||
config.https_client_cert_file, config.https_client_key_file
|
||||
)
|
||||
.into());
|
||||
}
|
||||
};
|
||||
|
||||
let mut builder = outgoing_client_builder(redirect_policy);
|
||||
if seaweed_common::fips::process_mode().is_fips() {
|
||||
let tls = fips_outgoing_tls_config(
|
||||
ca_pem.as_deref(),
|
||||
identity.as_ref().map(|(cert, key)| (cert.as_slice(), key.as_slice())),
|
||||
Arc::new(seaweed_common::tls::crypto_provider()),
|
||||
)
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Failed to build the HTTPS client TLS configuration (ca '{}', cert '{}', key '{}'): {}",
|
||||
config.https_client_ca_file,
|
||||
config.https_client_cert_file,
|
||||
config.https_client_key_file,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
builder = builder.use_preconfigured_tls(tls);
|
||||
} else {
|
||||
if let Some(ca_pem) = &ca_pem {
|
||||
let cert = reqwest::Certificate::from_pem(ca_pem).map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse HTTPS client CA PEM '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?;
|
||||
builder = builder.add_root_certificate(cert);
|
||||
}
|
||||
if let Some((cert_pem, key_pem)) = identity {
|
||||
let mut identity_pem = cert_pem;
|
||||
if !identity_pem.ends_with(b"\n") {
|
||||
identity_pem.push(b'\n');
|
||||
@@ -279,45 +217,18 @@ fn build_outgoing_http_client(
|
||||
})?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
|
||||
config.https_client_cert_file, config.https_client_key_file
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok((builder.build()?, scheme.to_string()))
|
||||
}
|
||||
|
||||
/// The outgoing HTTPS client configuration in FIPS mode: the roots, CA and
|
||||
/// identity reqwest would use, with the Extended Master Secret required on
|
||||
/// TLS 1.2 as Go requires it. reqwest leaves `require_ems` at rustls's
|
||||
/// default, which is off for a provider that is not FIPS-validated.
|
||||
fn fips_outgoing_tls_config(
|
||||
ca_pem: Option<&[u8]>,
|
||||
identity: Option<(&[u8], &[u8])>,
|
||||
provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
) -> Result<rustls::ClientConfig, Box<dyn std::error::Error>> {
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
if let Some(ca) = ca_pem {
|
||||
for cert in CertificateDer::pem_slice_iter(ca) {
|
||||
roots.add(cert?)?;
|
||||
}
|
||||
}
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_root_certificates(roots);
|
||||
let mut tls = match identity {
|
||||
Some((cert, key)) => {
|
||||
let chain = CertificateDer::pem_slice_iter(cert).collect::<Result<Vec<_>, _>>()?;
|
||||
builder.with_client_auth_cert(chain, PrivateKeyDer::from_pem_slice(key)?)?
|
||||
}
|
||||
None => builder.with_no_client_auth(),
|
||||
};
|
||||
tls.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
tls.require_ems = true;
|
||||
Ok(tls)
|
||||
}
|
||||
|
||||
fn tls_policy_is_configured(policy: &TlsPolicy) -> bool {
|
||||
!policy.min_version.is_empty()
|
||||
|| !policy.max_version.is_empty()
|
||||
@@ -1370,24 +1281,6 @@ mod tests {
|
||||
assert_eq!(started.elapsed(), super::OUTGOING_CONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fips_outgoing_tls_requires_ems() {
|
||||
let provider = std::sync::Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
));
|
||||
let tls = super::fips_outgoing_tls_config(
|
||||
Some(TEST_CA_PEM.as_bytes()),
|
||||
Some((TEST_LEAF_PEM.as_bytes(), TEST_LEAF_KEY_PEM.as_bytes())),
|
||||
provider.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(tls.require_ems);
|
||||
assert_eq!(tls.alpn_protocols, vec![b"http/1.1".to_vec()]);
|
||||
|
||||
let malformed_ca = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
|
||||
assert!(super::fips_outgoing_tls_config(Some(malformed_ca), None, provider).is_err());
|
||||
}
|
||||
|
||||
fn write_pem(dir: &tempfile::TempDir, name: &str, body: &str) -> String {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, body).unwrap();
|
||||
|
||||
@@ -12,8 +12,6 @@ use std::net::IpAddr;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
|
||||
use seaweed_common::fips::FipsMode;
|
||||
use seaweed_common::jwt_keys;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ============================================================================
|
||||
@@ -186,21 +184,6 @@ pub struct Guard {
|
||||
is_write_active: bool,
|
||||
}
|
||||
|
||||
/// Go's `usablePreviousKey`: under strict mode, a previous key shorter than 14
|
||||
/// characters is dropped with an error naming it (`name`), and the reload goes
|
||||
/// ahead without it.
|
||||
fn usable_previous_key(mode: FipsMode, name: &str, key: SigningKey) -> SigningKey {
|
||||
if jwt_keys::is_short(mode, &key.0) {
|
||||
tracing::error!(
|
||||
"JWT reload: ignoring the {}, which is shorter than the {} characters FIPS 140 needs for HMAC keys; the new keys are in effect",
|
||||
name,
|
||||
jwt_keys::MIN_HMAC_KEY_BYTES
|
||||
);
|
||||
return SigningKey(vec![]);
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
impl Guard {
|
||||
pub fn new(
|
||||
whitelist: &[String],
|
||||
@@ -255,10 +238,7 @@ impl Guard {
|
||||
/// Refresh the JWT signing keys and their expirations in place so operators
|
||||
/// can rotate keys via SIGHUP without restarting the process. Mirrors Go's
|
||||
/// `Guard::UpdateSigningKeys`: it swaps the fields and recomputes
|
||||
/// `is_write_active`. Under `fips.mode = strict`, a new write or read key
|
||||
/// shorter than 14 characters keeps the keys as they were, logs an error and
|
||||
/// returns false; a short previous key is dropped with an error and the
|
||||
/// other keys take effect.
|
||||
/// `is_write_active`.
|
||||
pub fn update_signing_keys(
|
||||
&mut self,
|
||||
signing_key: SigningKey,
|
||||
@@ -267,42 +247,7 @@ impl Guard {
|
||||
read_expires_after_sec: i64,
|
||||
previous_signing_key: SigningKey,
|
||||
previous_read_signing_key: SigningKey,
|
||||
) -> bool {
|
||||
self.update_signing_keys_in_mode(
|
||||
seaweed_common::fips::process_mode(),
|
||||
signing_key,
|
||||
expires_after_sec,
|
||||
read_signing_key,
|
||||
read_expires_after_sec,
|
||||
previous_signing_key,
|
||||
previous_read_signing_key,
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Guard::update_signing_keys`] for the FIPS mode `mode`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn update_signing_keys_in_mode(
|
||||
&mut self,
|
||||
mode: FipsMode,
|
||||
signing_key: SigningKey,
|
||||
expires_after_sec: i64,
|
||||
read_signing_key: SigningKey,
|
||||
read_expires_after_sec: i64,
|
||||
previous_signing_key: SigningKey,
|
||||
previous_read_signing_key: SigningKey,
|
||||
) -> bool {
|
||||
let current: [(&str, &[u8]); 2] = [
|
||||
("signing key", &signing_key.0),
|
||||
("read signing key", &read_signing_key.0),
|
||||
];
|
||||
if let Some(short) = jwt_keys::short_keys(mode, ¤t) {
|
||||
tracing::error!("JWT reload: keeping the keys in effect, because {}", short);
|
||||
return false;
|
||||
}
|
||||
let previous_signing_key =
|
||||
usable_previous_key(mode, "previous signing key", previous_signing_key);
|
||||
let previous_read_signing_key =
|
||||
usable_previous_key(mode, "previous read signing key", previous_read_signing_key);
|
||||
) {
|
||||
self.signing_key = signing_key;
|
||||
self.expires_after_sec = expires_after_sec;
|
||||
self.read_signing_key = read_signing_key;
|
||||
@@ -312,7 +257,6 @@ impl Guard {
|
||||
|
||||
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
|
||||
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether any write-side control is configured: a non-empty whitelist or a
|
||||
@@ -744,64 +688,6 @@ mod tests {
|
||||
assert!(!accepts(&guard, "read-old", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strict_reload_keeps_keys_when_a_current_key_is_short() {
|
||||
let mut guard = Guard::new(
|
||||
&[],
|
||||
SigningKey::from_string("write-key-long-enough"),
|
||||
10,
|
||||
SigningKey::from_string("read-key-long-enough"),
|
||||
60,
|
||||
);
|
||||
for (write, read) in [
|
||||
("0123456789", "read-key-replaced-ok"),
|
||||
("write-key-replaced-ok", "short"),
|
||||
] {
|
||||
assert!(!guard.update_signing_keys_in_mode(
|
||||
FipsMode::Strict,
|
||||
SigningKey::from_string(write),
|
||||
11,
|
||||
SigningKey::from_string(read),
|
||||
61,
|
||||
SigningKey(vec![]),
|
||||
SigningKey(vec![]),
|
||||
));
|
||||
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
|
||||
assert_eq!(guard.read_signing_key.0, b"read-key-long-enough");
|
||||
assert_eq!(guard.expires_after_sec, 10);
|
||||
}
|
||||
assert!(guard.update_signing_keys_in_mode(
|
||||
FipsMode::On,
|
||||
SigningKey::from_string("0123456789"),
|
||||
11,
|
||||
SigningKey(vec![]),
|
||||
61,
|
||||
SigningKey(vec![]),
|
||||
SigningKey(vec![]),
|
||||
));
|
||||
assert_eq!(guard.signing_key.0, b"0123456789");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strict_reload_drops_a_short_previous_key() {
|
||||
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
|
||||
assert!(guard.update_signing_keys_in_mode(
|
||||
FipsMode::Strict,
|
||||
SigningKey::from_string("write-key-long-enough"),
|
||||
10,
|
||||
SigningKey::from_string("read-key-long-enough"),
|
||||
60,
|
||||
SigningKey::from_string("old-short"),
|
||||
SigningKey::from_string("old-read-key-long-enough"),
|
||||
));
|
||||
assert_eq!(guard.signing_key.0, b"write-key-long-enough");
|
||||
assert!(guard.previous_signing_key.is_empty());
|
||||
assert_eq!(
|
||||
guard.previous_read_signing_key.0,
|
||||
b"old-read-key-long-enough"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_signing_keys_toggles_write_active() {
|
||||
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
|
||||
|
||||
@@ -457,12 +457,6 @@ mod tests {
|
||||
grpc_health_check_common_names: vec![],
|
||||
tls_policy: TlsPolicy::default(),
|
||||
security_file: String::new(),
|
||||
security_file_name: String::new(),
|
||||
jwt_keys: Vec::new(),
|
||||
fips_setting: Ok(seaweed_common::fips::Setting {
|
||||
mode: Default::default(),
|
||||
source: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1141,8 +1141,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let mut results = Vec::new();
|
||||
let mut replica_errs: std::collections::HashMap<u32, Result<(), String>> =
|
||||
std::collections::HashMap::new();
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -1164,23 +1162,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
};
|
||||
|
||||
let vid = file_id.volume_id.0;
|
||||
if !req.skip_replica_check && !replica_errs.contains_key(&vid) {
|
||||
let checked =
|
||||
crate::server::handlers::check_delete_replicas(&self.state, vid).await;
|
||||
replica_errs.insert(vid, checked);
|
||||
}
|
||||
if let Some(Err(e)) = replica_errs.get(&vid) {
|
||||
results.push(volume_server_pb::DeleteResult {
|
||||
file_id: fid_str.clone(),
|
||||
status: 503,
|
||||
error: e.clone(),
|
||||
size: 0,
|
||||
version: 0,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut n = Needle {
|
||||
id: file_id.key,
|
||||
cookie: file_id.cookie,
|
||||
@@ -1472,21 +1453,15 @@ impl VolumeServer for VolumeGrpcService {
|
||||
) -> Result<Response<volume_server_pb::VacuumVolumeCheckResponse>, Status> {
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
let store = self.state.store.read().unwrap();
|
||||
let (garbage_ratio, disk_space_low, can_delete_mark) = match store.find_volume(vid) {
|
||||
let (garbage_ratio, disk_space_low) = match store.find_volume(vid) {
|
||||
Some((_, vol)) => {
|
||||
// disk_space_low only counts when it is the sole read-only
|
||||
// cause — an operator mark or I/O quarantine still shields
|
||||
// the volume.
|
||||
let (_, no_write_or_delete, no_write_can_delete, is_low) = vol.read_only_reasons();
|
||||
// A readonlyCanDelete mark keeps taking deletes, so compacting
|
||||
// their space away stays within it; a mark that refuses
|
||||
// deletes or an I/O quarantine still wins. A remote-tiered
|
||||
// volume carries the same flag but cannot be compacted in
|
||||
// place.
|
||||
(
|
||||
vol.garbage_level(),
|
||||
is_low && !no_write_or_delete && !no_write_can_delete,
|
||||
no_write_can_delete && !no_write_or_delete && !vol.has_remote_file(),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
@@ -1496,7 +1471,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
Ok(Response::new(volume_server_pb::VacuumVolumeCheckResponse {
|
||||
garbage_ratio,
|
||||
disk_space_low,
|
||||
can_delete_mark,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -15058,7 +15032,6 @@ mod tests {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
@@ -15078,7 +15051,6 @@ mod tests {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check: true,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.expect_err("a server in maintenance mode must refuse a batch delete");
|
||||
@@ -15130,120 +15102,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Go's TestBatchDelete_WaitsForEveryReplica: a replica the master no
|
||||
/// longer lists would miss the delete, so the delete waits for it.
|
||||
#[tokio::test]
|
||||
async fn test_batch_delete_waits_for_every_replica() {
|
||||
let (service, _tmp) = make_local_service_with_volume("", None);
|
||||
{
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(2),
|
||||
DiskType::HardDrive,
|
||||
&VolumeSpec {
|
||||
replica_placement: Some(
|
||||
crate::storage::super_block::ReplicaPlacement::from_string("001")
|
||||
.unwrap(),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(0x3344),
|
||||
data: b"hello".to_vec(),
|
||||
data_size: 5,
|
||||
..Needle::default()
|
||||
};
|
||||
store
|
||||
.write_volume_needle(VolumeId(2), &mut n, false)
|
||||
.unwrap();
|
||||
for id in [2, 3] {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(0x3344),
|
||||
data: b"hello".to_vec(),
|
||||
data_size: 5,
|
||||
..Needle::default()
|
||||
};
|
||||
store
|
||||
.write_volume_needle(VolumeId(2), &mut n, false)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let urls = Arc::new(std::sync::Mutex::new(vec!["127.0.0.1:1"]));
|
||||
let min_writable_copies = Arc::new(std::sync::atomic::AtomicU32::new(0));
|
||||
*service.state.current_master_url.write().await =
|
||||
crate::server::handlers::tests::spawn_lookup_master({
|
||||
let urls = urls.clone();
|
||||
let min_writable_copies = min_writable_copies.clone();
|
||||
move |vid| {
|
||||
let locations = urls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|url| master_pb::Location {
|
||||
url: url.to_string(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let mut answer =
|
||||
crate::server::handlers::tests::lookup_answer(vid, locations, "");
|
||||
answer.volume_id_locations[0].min_writable_copies =
|
||||
min_writable_copies.load(std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(answer)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let service = &service;
|
||||
let delete = |id: u64| async move {
|
||||
let fid = needle::FileId::new(VolumeId(2), NeedleId(id), Cookie(0x3344)).to_string();
|
||||
let resp = service
|
||||
.batch_delete(Request::new(volume_server_pb::BatchDeleteRequest {
|
||||
file_ids: vec![fid],
|
||||
skip_cookie_check: true,
|
||||
fsync: false,
|
||||
skip_replica_check: id == 3,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
assert_eq!(resp.results.len(), 1, "{:?}", resp.results);
|
||||
(resp.results[0].status, resp.results[0].error.clone())
|
||||
};
|
||||
|
||||
let (status, error) = delete(1).await;
|
||||
assert_eq!(status, 503, "{error}");
|
||||
assert!(error.contains("replication copy count"), "{error}");
|
||||
{
|
||||
let store = service.state.store.read().unwrap();
|
||||
let (_, v) = store.find_volume(VolumeId(2)).unwrap();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut n)
|
||||
.expect("needle deleted while a replica was offline");
|
||||
}
|
||||
|
||||
let (status, error) = delete(3).await;
|
||||
assert_eq!(status, 202, "a delete skipping the replica check: {error}");
|
||||
|
||||
urls.lock().unwrap().push("127.0.0.2:8080");
|
||||
let (status, error) = delete(1).await;
|
||||
assert_eq!(status, 202, "{error}");
|
||||
|
||||
// a volume grown degraded is complete with the copies the master asks for
|
||||
urls.lock().unwrap().pop();
|
||||
min_writable_copies.store(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let (status, error) = delete(2).await;
|
||||
assert_eq!(status, 202, "{error}");
|
||||
}
|
||||
|
||||
/// Go's TestBatchDeleteFsyncsOnlyWhenAsked.
|
||||
#[tokio::test]
|
||||
async fn test_batch_delete_fsyncs_only_when_asked() {
|
||||
@@ -15275,7 +15133,6 @@ mod tests {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check: true,
|
||||
fsync,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
@@ -16463,7 +16320,6 @@ mod tests {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check: false,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
@@ -16547,7 +16403,6 @@ mod tests {
|
||||
file_ids: vec![fid.to_string()],
|
||||
skip_cookie_check: false,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
@@ -17044,22 +16899,21 @@ mod tests {
|
||||
// The .idx sits beside the .dat. It keeps the .ecx rows the .dat holds
|
||||
// and tombstones each journaled one once, however often it was journaled.
|
||||
let mut expected_idx = ecx[..2 * NEEDLE_MAP_ENTRY_SIZE].to_vec();
|
||||
for id in [1, 3] {
|
||||
crate::storage::idx::write_index_entry(
|
||||
&mut expected_idx,
|
||||
NeedleId(id),
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
crate::storage::idx::write_index_entry(
|
||||
&mut expected_idx,
|
||||
NeedleId(1),
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(format!("{data}/1.idx")).unwrap(),
|
||||
expected_idx
|
||||
);
|
||||
assert!(!std::path::Path::new(&format!("{idx}/1.idx")).exists());
|
||||
|
||||
assert_decoded_volume(&service, (2, 2), &[2], &[1, 3]);
|
||||
// Needle 1 is still in the .dat, so it counts as garbage; needle 3 is not.
|
||||
assert_decoded_volume(&service, (2, 1), &[2], &[1, 3]);
|
||||
}
|
||||
|
||||
/// Collected journals land in the idx dir even when the .ecx is beside the
|
||||
@@ -17079,21 +16933,13 @@ mod tests {
|
||||
size_before_needle_3
|
||||
);
|
||||
assert_decoded_volume(&service, (2, 0), &[1, 2], &[3]);
|
||||
|
||||
// the cut tail needle is the largest id the decode erased
|
||||
let store = service.state.store.read().unwrap();
|
||||
let vi = store.find_volume(VolumeId(1)).unwrap().1.volume_info();
|
||||
assert_eq!(
|
||||
(vi.vacuumed_max_file_key, vi.vacuumed_compaction_revision),
|
||||
(3, 1)
|
||||
);
|
||||
}
|
||||
|
||||
/// A tail needle tombstoned in the .ecx itself (Go's RebuildEcxFile) is cut
|
||||
/// from the .dat the same way, so its row loses its offset too, even when
|
||||
/// compaction fails.
|
||||
/// from the .dat the same way, so its row must not survive either, even
|
||||
/// when compaction fails.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_volume_ec_shards_to_volume_cuts_sealed_tail_tombstone() {
|
||||
async fn test_volume_ec_shards_to_volume_drops_sealed_tail_tombstone() {
|
||||
let (service, _tmp, data, idx, size_before_needle_3) =
|
||||
make_split_idx_ec_decode_service(&[], false).await;
|
||||
let ecx_path = format!("{idx}/1.ecx");
|
||||
@@ -17113,19 +16959,11 @@ mod tests {
|
||||
std::fs::metadata(format!("{data}/1.dat")).unwrap().len(),
|
||||
size_before_needle_3
|
||||
);
|
||||
let mut expected_idx = ecx[..2 * NEEDLE_MAP_ENTRY_SIZE].to_vec();
|
||||
crate::storage::idx::write_index_entry(
|
||||
&mut expected_idx,
|
||||
NeedleId(3),
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(format!("{data}/1.idx")).unwrap(),
|
||||
expected_idx
|
||||
ecx[..2 * NEEDLE_MAP_ENTRY_SIZE]
|
||||
);
|
||||
assert_decoded_volume(&service, (2, 1), &[1, 2], &[3]);
|
||||
assert_decoded_volume(&service, (2, 0), &[1, 2], &[3]);
|
||||
}
|
||||
|
||||
/// Go compacts the decoded volume (CompactVolumeFiles), so needles deleted
|
||||
@@ -17164,35 +17002,7 @@ mod tests {
|
||||
[2, 3]
|
||||
);
|
||||
assert!(idx_rows.iter().all(|(_, size)| !size.is_deleted()));
|
||||
// the compaction is a vacuum: it records what it could erase
|
||||
let vif_fields = |vifs: [Option<Vec<u8>>; 2]| {
|
||||
vifs.map(|vif| {
|
||||
vif.map(|vif| {
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&vif).unwrap();
|
||||
let obj = v.as_object_mut().unwrap();
|
||||
let record = (
|
||||
obj.remove("vacuumedMaxFileKey"),
|
||||
obj.remove("vacuumedCompactionRevision"),
|
||||
);
|
||||
obj.remove("bytesOffset");
|
||||
(v, record)
|
||||
})
|
||||
})
|
||||
};
|
||||
let (after, before) = (vif_fields(vifs()), vif_fields(vifs_before));
|
||||
for (after, before) in after.iter().zip(before.iter()) {
|
||||
assert_eq!(
|
||||
after.as_ref().map(|(v, _)| v),
|
||||
before.as_ref().map(|(v, _)| v),
|
||||
"the EC .vif is left alone"
|
||||
);
|
||||
if let Some((_, record)) = after {
|
||||
assert_eq!(
|
||||
record,
|
||||
&(Some(serde_json::json!("3")), Some(serde_json::json!(1)))
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(vifs(), vifs_before, "the EC .vif is left alone");
|
||||
|
||||
assert_decoded_volume(&service, (2, 0), &[2, 3], &[1]);
|
||||
}
|
||||
@@ -17715,7 +17525,6 @@ mod tests {
|
||||
file_ids: vec!["1,b00003344".to_string()],
|
||||
skip_cookie_check: false,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
})
|
||||
};
|
||||
|
||||
@@ -17766,7 +17575,6 @@ mod tests {
|
||||
file_ids: vec!["2,b00003344".to_string()],
|
||||
skip_cookie_check,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
}))
|
||||
.await
|
||||
.unwrap()
|
||||
|
||||
@@ -577,13 +577,12 @@ async fn master_lookup_once(
|
||||
|
||||
/// Look up volume locations over the master's gRPC port, like Go's
|
||||
/// operation.LookupVolumeIds: the master's HTTP port need not speak the
|
||||
/// `[https.client]` scheme. Also returns the master's min_writable_copies
|
||||
/// (0 unless the volume was grown degraded).
|
||||
/// `[https.client]` scheme.
|
||||
async fn lookup_volume(
|
||||
tls: Option<&OutgoingGrpcTlsConfig>,
|
||||
master_url: &str,
|
||||
volume_id: u32,
|
||||
) -> Result<(Vec<VolumeLocation>, u32), String> {
|
||||
) -> Result<Vec<VolumeLocation>, String> {
|
||||
let grpc_addr = parse_grpc_address(master_url)?;
|
||||
let cached = MASTER_LOOKUP_CHANNEL
|
||||
.lock()
|
||||
@@ -619,17 +618,15 @@ async fn lookup_volume(
|
||||
}
|
||||
};
|
||||
let mut locations = Vec::new();
|
||||
let mut min_writable_copies = 0;
|
||||
for found in resp.volume_id_locations {
|
||||
// Mirror Go: a per-volume error in an answered lookup (e.g. a missing
|
||||
// volume) means "no locations"; only a failed call is an error.
|
||||
if !found.error.is_empty() {
|
||||
tracing::debug!("volume {} lookup: {}", volume_id, found.error);
|
||||
}
|
||||
min_writable_copies = min_writable_copies.max(found.min_writable_copies);
|
||||
locations.extend(found.locations.into_iter().map(VolumeLocation::from));
|
||||
}
|
||||
Ok((locations, min_writable_copies))
|
||||
Ok(locations)
|
||||
}
|
||||
|
||||
fn grpc_address_for_location(location: &VolumeLocation) -> Result<String, String> {
|
||||
@@ -681,7 +678,7 @@ async fn batch_delete_file_ids(
|
||||
let locations = if let Some(locations) = lookup_cache.get(&volume_id) {
|
||||
locations.clone()
|
||||
} else {
|
||||
let (locations, _) = lookup_volume(
|
||||
let locations = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
volume_id,
|
||||
@@ -722,7 +719,6 @@ async fn batch_delete_file_ids(
|
||||
file_ids: batch.clone(),
|
||||
skip_cookie_check: true,
|
||||
fsync: false,
|
||||
skip_replica_check: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("batch delete {}: {}", grpc_addr, e))?
|
||||
@@ -744,47 +740,6 @@ async fn batch_delete_file_ids(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mirrors Go's checkDeleteReplicas: refuses a delete the master cannot route
|
||||
/// to every replica, as the HTTP delete path does, so an offline replica does
|
||||
/// not keep the needle once it returns.
|
||||
pub(crate) async fn check_delete_replicas(
|
||||
state: &VolumeServerState,
|
||||
vid: u32,
|
||||
) -> Result<(), String> {
|
||||
let copy_count = {
|
||||
let store = state.store.read().unwrap();
|
||||
match store.find_volume(VolumeId(vid)) {
|
||||
Some((_, v)) => v.super_block().replica_placement.get_copy_count() as u32,
|
||||
None => return Ok(()),
|
||||
}
|
||||
};
|
||||
if copy_count <= 1 {
|
||||
return Ok(());
|
||||
}
|
||||
let (locations, min_writable_copies) = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
vid,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("replicating lookup failed for {}: {}", vid, e))?;
|
||||
let copy_count = match min_writable_copies {
|
||||
n if n > 0 && n < copy_count => n,
|
||||
_ => copy_count,
|
||||
};
|
||||
let deletable = locations
|
||||
.iter()
|
||||
.filter(|loc| !loc.read_only || loc.read_only_can_delete)
|
||||
.count();
|
||||
if deletable < copy_count as usize {
|
||||
return Err(format!(
|
||||
"replication locations [{}] is less than volume {} replication copy count [{}]",
|
||||
deletable, vid, copy_count
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `query` with the fields named in `overrides` replaced by their values.
|
||||
fn override_query_fields(
|
||||
query: &str,
|
||||
@@ -828,41 +783,6 @@ fn replica_request_timeout(body_len: usize) -> std::time::Duration {
|
||||
)
|
||||
}
|
||||
|
||||
/// How a pooled connection the peer has closed fails a request, depending on
|
||||
/// when its close reached this side. Mirrors Go's inner resend in
|
||||
/// `upload_content`.
|
||||
fn is_stale_connection_error(err: &reqwest::Error) -> bool {
|
||||
let mut source = std::error::Error::source(err);
|
||||
while let Some(e) = source {
|
||||
if let Some(io) = e.downcast_ref::<std::io::Error>()
|
||||
&& matches!(
|
||||
io.kind(),
|
||||
std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
source = e.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Sends a replica forward, once more on a new connection when the first
|
||||
/// attempt rode a pooled connection the peer had closed.
|
||||
async fn send_replica_request(
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> reqwest::Result<reqwest::Response> {
|
||||
let resend = request.try_clone();
|
||||
let sent = request.send().await;
|
||||
match resend {
|
||||
Some(resend) if sent.as_ref().is_err_and(is_stale_connection_error) => {
|
||||
tracing::debug!("resend replica request: {:?}", sent.err());
|
||||
resend.send().await
|
||||
}
|
||||
_ => sent,
|
||||
}
|
||||
}
|
||||
|
||||
fn replica_request(
|
||||
client: &reqwest::Client,
|
||||
method: axum::http::Method,
|
||||
@@ -908,7 +828,7 @@ async fn do_replicated_request(
|
||||
body: Option<bytes::Bytes>,
|
||||
replica_jwt: Option<&ReplicaJwt>,
|
||||
) -> Result<(), String> {
|
||||
let (locations, min_writable_copies) = lookup_volume(
|
||||
let locations = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
vid,
|
||||
@@ -919,15 +839,9 @@ async fn do_replicated_request(
|
||||
let copy_count = {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
|
||||
v.super_block().replica_placement.get_copy_count() as u32
|
||||
v.super_block().replica_placement.get_copy_count()
|
||||
})
|
||||
};
|
||||
// A degraded volume is writable with fewer copies, like Go's
|
||||
// getRemoteReplications.
|
||||
let copy_count = match min_writable_copies {
|
||||
n if n > 0 && n < copy_count => n,
|
||||
_ => copy_count,
|
||||
};
|
||||
let allow_delete = method == axum::http::Method::DELETE;
|
||||
let eligible_locations: Vec<_> = locations
|
||||
.into_iter()
|
||||
@@ -1013,7 +927,7 @@ async fn do_replicated_request(
|
||||
}
|
||||
|
||||
futures.push(async move {
|
||||
match send_replica_request(req_builder).await {
|
||||
match req_builder.send().await {
|
||||
Ok(r)
|
||||
if r.status().is_success()
|
||||
|| (allow_delete && r.status() == StatusCode::NOT_FOUND) =>
|
||||
@@ -1095,7 +1009,7 @@ async fn proxy_or_redirect_to_target(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((locs, _)) => locs,
|
||||
Ok(locs) => locs,
|
||||
Err(e) => {
|
||||
tracing::warn!("volume lookup failed for {}: {}", vid.0, e);
|
||||
// Go: master lookup failure is 500 in proxy mode, 404 for redirect
|
||||
@@ -3352,14 +3266,12 @@ pub async fn post_handler(
|
||||
let original_data_size = uncompressed_data.len() as u32;
|
||||
|
||||
// Only compute and validate Content-MD5 when the client provided one
|
||||
// (Go only computes MD5 when Content-MD5 header/field is present).
|
||||
// Under fips.mode strict no MD5 is computed: the client's value is kept
|
||||
// unchecked, as Go does under GODEBUG=fips140=only.
|
||||
// (Go only computes MD5 when Content-MD5 header/field is present)
|
||||
let content_md5 = content_md5.or(parsed_content_md5);
|
||||
let original_content_md5 = match &content_md5 {
|
||||
Some(expected) if strict_fips_mode() => Some(expected.clone()),
|
||||
Some(_) => Some(compute_md5_base64(&uncompressed_data)),
|
||||
None => None,
|
||||
let original_content_md5 = if content_md5.is_some() {
|
||||
Some(compute_md5_base64(&uncompressed_data))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(expected_md5), Some(actual_md5)) = (&content_md5, &original_content_md5)
|
||||
&& expected_md5 != actual_md5
|
||||
@@ -3588,19 +3500,10 @@ pub async fn post_handler(
|
||||
.is_some_and(|(_, v)| v.super_block().replica_placement.get_copy_count() > 1)
|
||||
};
|
||||
|
||||
// A local volume that already refuses writes is refused before the
|
||||
// fan-out, so no replica keeps a needle nothing references.
|
||||
let local_refusal = if needs_replication {
|
||||
let vol = state.store.read().unwrap().writable_volume(vid);
|
||||
vol.and_then(|v| v.check_writable()).err()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// The fan-out runs concurrently with the local needle write, like Go's
|
||||
// ReplicatedWrite: replicas get the stored bytes with their compression
|
||||
// state, so they keep it instead of re-deriving it. The ack waits for both.
|
||||
let replication = if needs_replication && local_refusal.is_none() {
|
||||
let replication = if needs_replication {
|
||||
let state_clone = state.clone();
|
||||
let path_clone = path.clone();
|
||||
let query_clone = match replica_jwt {
|
||||
@@ -3673,14 +3576,12 @@ pub async fn post_handler(
|
||||
None
|
||||
};
|
||||
|
||||
let (write_result, refused_before_append) = match local_refusal {
|
||||
Some(refused) => (Err(refused), true),
|
||||
None => match write_upload_needle(&state, vid, n, fsync).await {
|
||||
let (write_result, refused_before_append) =
|
||||
match write_upload_needle(&state, vid, n, fsync).await {
|
||||
Ok(Ok(written)) => (Ok(written), false),
|
||||
Ok(Err(refused)) => (Err(refused), true),
|
||||
Err(error) => (Err(error), false),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// No leader-known gate: when the lookup cannot run, the write must fail
|
||||
// rather than be acknowledged on fewer copies than required. The local
|
||||
@@ -5026,7 +4927,7 @@ async fn read_remote_chunk_needle(
|
||||
fid: &str,
|
||||
how: RemoteRead,
|
||||
) -> Result<ChunkBytes, String> {
|
||||
let (locations, _) = lookup_volume(
|
||||
let locations = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
vid.0,
|
||||
@@ -5414,12 +5315,6 @@ fn check_content_crc32c(expected: &str, data: &[u8]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether this process runs under `fips.mode = strict`, where it computes no
|
||||
/// MD5.
|
||||
fn strict_fips_mode() -> bool {
|
||||
seaweed_common::fips::process_mode() == seaweed_common::fips::FipsMode::Strict
|
||||
}
|
||||
|
||||
fn compute_md5_base64(data: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
use md5::{Digest, Md5};
|
||||
@@ -5532,7 +5427,7 @@ fn parse_content_disposition_filename(value: &str) -> Option<String> {
|
||||
// ============================================================================
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A replica that reads the forward and never answers. Each request's
|
||||
@@ -5590,67 +5485,6 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A volume grown degraded keeps its placement's copy count in the super
|
||||
/// block; the master's min_writable_copies lets it write with fewer.
|
||||
#[tokio::test]
|
||||
async fn http_replicated_write_uses_the_master_min_writable_copies() {
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use tower::ServiceExt;
|
||||
|
||||
let app = axum::Router::new().fallback(|| async { StatusCode::CREATED });
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let peer = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
for (min_writable_copies, written) in [(0, false), (2, true), (3, false)] {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let mut state = volume_test_state(&tmp);
|
||||
Arc::get_mut(&mut state).unwrap().self_url = "127.0.0.1:8080".to_string();
|
||||
state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.find_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_replica_placement(ReplicaPlacement::from_string("200").unwrap())
|
||||
.unwrap();
|
||||
*state.current_master_url.write().await = spawn_lookup_master(move |vid| {
|
||||
let location = |url: String| master_pb::Location {
|
||||
url,
|
||||
..Default::default()
|
||||
};
|
||||
let mut answer = lookup_answer(
|
||||
vid,
|
||||
vec![
|
||||
location("127.0.0.1:8080".to_string()),
|
||||
location(peer.to_string()),
|
||||
],
|
||||
"",
|
||||
);
|
||||
answer.volume_id_locations[0].min_writable_copies = min_writable_copies;
|
||||
Ok(answer)
|
||||
})
|
||||
.await;
|
||||
|
||||
let response = super::super::volume_server::build_admin_router(state)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(format!("/1,{:x}{TEST_COOKIE:08x}", 0x6e7a_0c04u64))
|
||||
.body(Body::from("x"))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status() == StatusCode::CREATED,
|
||||
written,
|
||||
"{min_writable_copies}: {}",
|
||||
response.status()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A write forward carries a JWT signed for it, not the incoming one, which
|
||||
/// can expire while the body streams in.
|
||||
#[tokio::test]
|
||||
@@ -5742,46 +5576,6 @@ pub(crate) mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A replica that resets the connection mid-body, as one closing a
|
||||
/// pooled connection at its idle timeout does, gets the forward once more.
|
||||
#[tokio::test]
|
||||
async fn test_replicated_write_resends_after_a_connection_reset() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let peer = listener.local_addr().unwrap();
|
||||
let (received, mut receipts) = tokio::sync::mpsc::unbounded_channel();
|
||||
tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut head = vec![0u8; 1024];
|
||||
let _ = socket.read(&mut head).await;
|
||||
socket.set_zero_linger().unwrap();
|
||||
drop(socket);
|
||||
let app = axum::Router::new()
|
||||
.fallback(move |body: bytes::Bytes| {
|
||||
let _ = received.send(body.len());
|
||||
async { StatusCode::CREATED }
|
||||
})
|
||||
.layer(axum::extract::DefaultBodyLimit::disable());
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
let state = remote_manifest_state(&tmp, spawn_lookup(peer).await);
|
||||
let body = bytes::Bytes::from(vec![7u8; 8 << 20]);
|
||||
let sent = do_replicated_request(
|
||||
&state,
|
||||
1,
|
||||
axum::http::Method::POST,
|
||||
"/1,01ab",
|
||||
"",
|
||||
&axum::http::HeaderMap::new(),
|
||||
Some(body.clone()),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
sent.expect("the resend reaches the replica on a new connection");
|
||||
assert_eq!(receipts.try_recv(), Ok(body.len()));
|
||||
}
|
||||
|
||||
/// A peer that accepts the connection but never answers (a silent
|
||||
/// partition after connect) must fail the forward at the bound, not hold
|
||||
/// the write until TCP gives up.
|
||||
@@ -6557,7 +6351,7 @@ pub(crate) mod tests {
|
||||
|
||||
/// Serve `answer` as the master's gRPC LookupVolume. The returned address
|
||||
/// carries an unused HTTP port, so a lookup over HTTP would fail.
|
||||
pub(crate) async fn spawn_lookup_master(
|
||||
async fn spawn_lookup_master(
|
||||
answer: impl Fn(&str) -> Result<master_pb::LookupVolumeResponse, tonic::Status>
|
||||
+ Send
|
||||
+ Sync
|
||||
@@ -6573,7 +6367,7 @@ pub(crate) mod tests {
|
||||
format!("127.0.0.1:1.{}", port)
|
||||
}
|
||||
|
||||
pub(crate) fn lookup_answer(
|
||||
fn lookup_answer(
|
||||
volume_id: &str,
|
||||
locations: Vec<master_pb::Location>,
|
||||
error: &str,
|
||||
@@ -6626,7 +6420,7 @@ pub(crate) mod tests {
|
||||
.await;
|
||||
|
||||
for _ in 0..2 {
|
||||
let (locations, _) = super::lookup_volume(None, &master_url, 31)
|
||||
let locations = super::lookup_volume(None, &master_url, 31)
|
||||
.await
|
||||
.expect("lookup over the master's gRPC port");
|
||||
assert_eq!(locations.len(), 1);
|
||||
@@ -6677,7 +6471,7 @@ pub(crate) mod tests {
|
||||
})
|
||||
.await;
|
||||
|
||||
let (locations, _) = super::lookup_volume(None, &master_url, 7)
|
||||
let locations = super::lookup_volume(None, &master_url, 7)
|
||||
.await
|
||||
.expect("missing volume is not a lookup failure");
|
||||
assert!(locations.is_empty());
|
||||
@@ -9805,7 +9599,7 @@ pub(crate) mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_replicated_write_refusal_is_not_marked() {
|
||||
async fn http_local_refusal_after_replica_append_is_not_marked() {
|
||||
for local_read_only in [true, false] {
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use tower::ServiceExt;
|
||||
@@ -9878,18 +9672,18 @@ pub(crate) mod tests {
|
||||
}
|
||||
);
|
||||
assert!(response.headers().get("x-seaweed-write-outcome").is_none());
|
||||
assert_eq!(peer_volume.dat_file_size().unwrap(), before);
|
||||
if local_read_only {
|
||||
assert_eq!(volume.dat_file_size().unwrap(), before);
|
||||
peer_server.abort();
|
||||
continue;
|
||||
}
|
||||
let (refused, written) = if local_read_only {
|
||||
(&volume, &peer_volume)
|
||||
} else {
|
||||
(&peer_volume, &volume)
|
||||
};
|
||||
assert_eq!(refused.dat_file_size().unwrap(), before);
|
||||
let mut stored = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(TEST_COOKIE),
|
||||
..Needle::default()
|
||||
};
|
||||
volume.read_needle(&mut stored).unwrap();
|
||||
written.read_needle(&mut stored).unwrap();
|
||||
assert_eq!(stored.data, payload);
|
||||
peer_server.abort();
|
||||
}
|
||||
|
||||
@@ -1413,7 +1413,6 @@ fn build_heartbeat_with_ec_status(
|
||||
}
|
||||
|
||||
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
|
||||
let (read_only, read_only_can_delete) = vol.reported_read_only();
|
||||
let volume_message = master_pb::VolumeInformationMessage {
|
||||
id: vol.id.0,
|
||||
size: volume_size,
|
||||
@@ -1421,8 +1420,8 @@ fn build_heartbeat_with_ec_status(
|
||||
file_count: vol.file_count() as u64,
|
||||
delete_count: vol.deleted_count() as u64,
|
||||
deleted_byte_count: vol.deleted_size(),
|
||||
read_only,
|
||||
read_only_can_delete,
|
||||
read_only: vol.is_read_only(),
|
||||
read_only_can_delete: vol.is_no_write_can_delete(),
|
||||
replica_placement: vol.super_block().replica_placement.to_byte() as u32,
|
||||
version: vol.super_block().version.0 as u32,
|
||||
ttl: vol.super_block().ttl.to_u32(),
|
||||
@@ -1869,43 +1868,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_low_disk_volume_reports_can_delete() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
3,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(7), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
store.locations[0]
|
||||
.is_disk_space_low
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert!(heartbeat.volumes[0].read_only);
|
||||
assert!(heartbeat.volumes[0].read_only_can_delete);
|
||||
|
||||
store
|
||||
.find_volume(VolumeId(7))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_no_write_or_delete(true);
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert!(heartbeat.volumes[0].read_only);
|
||||
assert!(!heartbeat.volumes[0].read_only_can_delete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_marks_empty_store_as_has_no_volumes() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -177,12 +177,6 @@ mod tests {
|
||||
grpc_health_check_common_names: vec![],
|
||||
tls_policy: TlsPolicy::default(),
|
||||
security_file: String::new(),
|
||||
security_file_name: String::new(),
|
||||
jwt_keys: Vec::new(),
|
||||
fips_setting: Ok(seaweed_common::fips::Setting {
|
||||
mode: Default::default(),
|
||||
source: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -905,15 +905,6 @@ impl DiskLocation {
|
||||
unused
|
||||
}
|
||||
|
||||
/// Mirrors Go's DiskLocation.updateDiskSpaceLow for a reading with space
|
||||
/// values.
|
||||
fn update_disk_space_low(&self, free: u64, total: u64) -> bool {
|
||||
let was_low = self.is_disk_space_low.load(Ordering::Relaxed);
|
||||
let is_low = self.min_free_space.is_low_from(was_low, free, total);
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
is_low
|
||||
}
|
||||
|
||||
/// Check disk space against min_free_space and update is_disk_space_low.
|
||||
pub fn check_disk_space(&self) {
|
||||
let (total, free) = get_disk_stats(&self.directory);
|
||||
@@ -921,7 +912,8 @@ impl DiskLocation {
|
||||
return;
|
||||
}
|
||||
let used = total.saturating_sub(free);
|
||||
self.update_disk_space_low(free, total);
|
||||
let is_low = self.min_free_space.is_low(free, total);
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
// Go's DiskLocation.AvailableSpace counts only free space above the
|
||||
// -volume.minFreeSpace floor, so space checks stay above it too.
|
||||
self.available_space.store(
|
||||
@@ -1709,40 +1701,6 @@ mod tests {
|
||||
assert_eq!(loc.available_space.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
// Mirrors Go's TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBack: a
|
||||
// location that went low stays low until free space clears the margin.
|
||||
#[test]
|
||||
fn test_disk_space_low_stays_until_free_space_is_clearly_back() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = DiskLocation::new(
|
||||
dir,
|
||||
dir,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(7.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let total = 10_000u64;
|
||||
for (free, want) in [
|
||||
(699, true),
|
||||
(702, true),
|
||||
(698, true),
|
||||
(760, true),
|
||||
(800, false),
|
||||
(702, false),
|
||||
(699, true),
|
||||
] {
|
||||
assert_eq!(
|
||||
loc.update_disk_space_low(free, total),
|
||||
want,
|
||||
"free {free} of {total}"
|
||||
);
|
||||
assert_eq!(loc.is_disk_space_low.load(Ordering::Relaxed), want);
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors Go's CheckDiskSpace pending subtraction: an in-flight copy's
|
||||
// charge stays out of the cache across a probe, so another copy cannot
|
||||
// re-spend the headroom the live reading still shows as free.
|
||||
|
||||
@@ -430,9 +430,8 @@ pub fn write_idx_file_from_ec_index(
|
||||
///
|
||||
/// Copies the `.ecx` rows, then appends one tombstone per row whose needle is
|
||||
/// in `deleted`. A deleted needle at or past `dat_file_size` was cut from the
|
||||
/// `.dat`, so its row becomes a tombstone without the offset: a row pointing
|
||||
/// past the end of the `.dat` makes the volume load read-only, and the id must
|
||||
/// stay in the index for the vacuum record.
|
||||
/// `.dat`, so its row is dropped: a row pointing past the end of the `.dat`
|
||||
/// makes the volume load read-only.
|
||||
pub fn write_idx_file_from_ec_index_with_dirs(
|
||||
ecx_dir: &str,
|
||||
idx_dir: &str,
|
||||
@@ -455,7 +454,6 @@ pub fn write_idx_file_from_ec_index_with_dirs(
|
||||
idx::walk_index_file(&mut ecx_file, 0, |key, offset, size| {
|
||||
let is_deleted = size.is_deleted() || deleted.contains(&key);
|
||||
if is_deleted && offset.to_actual_offset() >= dat_file_size {
|
||||
tombstoned.push(key);
|
||||
return Ok(());
|
||||
}
|
||||
idx::write_index_entry(&mut idx_file, key, offset, size)?;
|
||||
|
||||
@@ -99,12 +99,12 @@ pub(super) fn metrics_from_idx<R: Read + Seek>(
|
||||
let entry = &buf[i * NEEDLE_MAP_ENTRY_SIZE..(i + 1) * NEEDLE_MAP_ENTRY_SIZE];
|
||||
let (key, offset, size) = idx_entry_from_bytes(entry);
|
||||
metric.maybe_set_max_needle_end(offset, size, version);
|
||||
metric.maybe_set_max_file_key(key);
|
||||
let superseded = seen.test_and_add(key.into());
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
// Tombstone: reserves no bytes, only marks the key as seen.
|
||||
continue;
|
||||
}
|
||||
metric.maybe_set_max_file_key(key);
|
||||
metric.file_count.fetch_add(1, Ordering::Relaxed);
|
||||
metric
|
||||
.file_byte_count
|
||||
@@ -157,23 +157,6 @@ mod tests {
|
||||
assert!(false_positives < 500, "false positives: {false_positives}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tombstone_only_key_raises_max_file_key() {
|
||||
let mut idx = Vec::new();
|
||||
for (key, offset, size) in [
|
||||
(1u64, Offset::from_actual_offset(8), Size(100)),
|
||||
(2, Offset::from_actual_offset(136), Size(100)),
|
||||
(3, Offset::default(), Size(-1)),
|
||||
] {
|
||||
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_entry_to_bytes(&mut entry, NeedleId(key), offset, size);
|
||||
idx.extend_from_slice(&entry);
|
||||
}
|
||||
let metric = metrics_from_idx(&mut std::io::Cursor::new(&idx), Version(3)).unwrap();
|
||||
assert_eq!(metric.max_file_key.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(metric.file_count.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
// The deleted count rebuilt from an .idx is an estimate: an index of
|
||||
// unique keys, with no overwrite and no tombstone, still reports a
|
||||
// deletion once the bloom filter yields a false positive. VolumeCopy
|
||||
|
||||
@@ -331,7 +331,6 @@ pub struct VifEcShardConfig {
|
||||
/// Serde-compatible representation of OldVersionVolumeInfo for legacy .vif JSON deserialization.
|
||||
/// Matches Go's protobuf OldVersionVolumeInfo where `DestroyTime` maps to `expire_at_sec`.
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OldVersionVifVolumeInfo {
|
||||
#[serde(default)]
|
||||
pub files: Vec<VifRemoteFile>,
|
||||
@@ -372,8 +371,6 @@ impl OldVersionVifVolumeInfo {
|
||||
read_only: self.read_only,
|
||||
ec_shard_config: None,
|
||||
read_only_can_delete: false,
|
||||
vacuumed_max_file_key: 0,
|
||||
vacuumed_compaction_revision: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,10 +401,6 @@ pub struct VifVolumeInfo {
|
||||
pub ec_shard_config: Option<VifEcShardConfig>,
|
||||
#[serde(default, rename = "readOnlyCanDelete")]
|
||||
pub read_only_can_delete: bool,
|
||||
#[serde(default, rename = "vacuumedMaxFileKey", with = "string_or_u64")]
|
||||
pub vacuumed_max_file_key: u64,
|
||||
#[serde(default, rename = "vacuumedCompactionRevision")]
|
||||
pub vacuumed_compaction_revision: u32,
|
||||
}
|
||||
|
||||
impl VifVolumeInfo {
|
||||
@@ -440,8 +433,6 @@ impl VifVolumeInfo {
|
||||
block_size: c.block_size,
|
||||
}),
|
||||
read_only_can_delete: pb.read_only_can_delete,
|
||||
vacuumed_max_file_key: pb.vacuumed_max_file_key,
|
||||
vacuumed_compaction_revision: pb.vacuumed_compaction_revision,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,8 +467,6 @@ impl VifVolumeInfo {
|
||||
}
|
||||
}),
|
||||
read_only_can_delete: self.read_only_can_delete,
|
||||
vacuumed_max_file_key: self.vacuumed_max_file_key,
|
||||
vacuumed_compaction_revision: self.vacuumed_compaction_revision,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3414,7 +3403,7 @@ impl Volume {
|
||||
Ok(Some(offset))
|
||||
}
|
||||
|
||||
pub(crate) fn check_writable(&self) -> Result<(), VolumeError> {
|
||||
fn check_writable(&self) -> Result<(), VolumeError> {
|
||||
if self.is_closed() {
|
||||
return Err(VolumeError::NotFound);
|
||||
}
|
||||
@@ -4240,13 +4229,6 @@ impl Volume {
|
||||
self.no_write_flags().1
|
||||
}
|
||||
|
||||
/// What the master is told: low disk space still lets deletes through,
|
||||
/// only no_write_or_delete refuses them. Mirrors Go's reportedReadOnly.
|
||||
pub fn reported_read_only(&self) -> (bool, bool) {
|
||||
let (read_only, no_write_or_delete, _, _) = self.read_only_reasons();
|
||||
(read_only, read_only && !no_write_or_delete)
|
||||
}
|
||||
|
||||
pub fn last_compact_revision(&self) -> u16 {
|
||||
self.io.read().unwrap().last_compact_revision
|
||||
}
|
||||
@@ -5261,11 +5243,8 @@ impl Volume {
|
||||
if content.trim().is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
// VifVolumeInfo ignores unknown fields, so an old-format file would
|
||||
// parse as it too and lose its DestroyTime.
|
||||
if serde_json::from_str::<OldVersionVifVolumeInfo>(&content).is_err()
|
||||
&& let Ok(vif_info) = serde_json::from_str::<VifVolumeInfo>(&content)
|
||||
{
|
||||
// Try protobuf-JSON (Go-compatible VolumeInfo via VifVolumeInfo)
|
||||
if let Ok(vif_info) = serde_json::from_str::<VifVolumeInfo>(&content) {
|
||||
let pb_info = vif_info.to_pb();
|
||||
if pb_info.read_only {
|
||||
if pb_info.read_only_can_delete {
|
||||
@@ -6218,9 +6197,8 @@ impl Volume {
|
||||
}
|
||||
|
||||
// Close current files
|
||||
let vacuum_record = {
|
||||
{
|
||||
let mut io = self.io.write().unwrap();
|
||||
let vacuum_record = self.vacuum_record_to_keep(io.nm.as_ref());
|
||||
if let Some(ref mut nm) = io.nm {
|
||||
nm.close();
|
||||
}
|
||||
@@ -6230,8 +6208,7 @@ impl Volume {
|
||||
}
|
||||
io.dat_file = None;
|
||||
io.remote_dat_file = None;
|
||||
vacuum_record
|
||||
};
|
||||
}
|
||||
#[cfg(test)]
|
||||
commit_swap_hook::fire(self.id);
|
||||
|
||||
@@ -6243,9 +6220,6 @@ impl Volume {
|
||||
// compacts to empty.
|
||||
self.write_compact_commit_marker()?;
|
||||
self.apply_compact_swap()?;
|
||||
if let Some((max_key, revision)) = vacuum_record {
|
||||
self.record_vacuumed_max_file_key(max_key, revision);
|
||||
}
|
||||
|
||||
// The write watermark already equals what recover_last_modified_ts
|
||||
// would rescan, so keep the clock instead of paying for the scan
|
||||
@@ -6267,41 +6241,6 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The largest needle id this vacuum could erase, live or deleted, and the
|
||||
/// compaction revision it produces. None once a vacuum of the volume went
|
||||
/// unrecorded: its erased ids are unknown.
|
||||
fn vacuum_record_to_keep(&self, nm: Option<&NeedleMap>) -> Option<(u64, u32)> {
|
||||
let nm = nm?;
|
||||
let revision = self.super_block.read().unwrap().compaction_revision;
|
||||
let vi = self.volume_info.read().unwrap();
|
||||
let mut max_key: u64 = nm.max_file_key().into();
|
||||
if revision > 0 {
|
||||
if vi.vacuumed_compaction_revision != revision as u32 {
|
||||
return None;
|
||||
}
|
||||
max_key = max_key.max(vi.vacuumed_max_file_key);
|
||||
}
|
||||
Some((max_key, revision.wrapping_add(1) as u32))
|
||||
}
|
||||
|
||||
/// Saved after the swap: a record that misses the swap keeps the old
|
||||
/// revision, and volume.check.disk trusts it only at the live one.
|
||||
fn record_vacuumed_max_file_key(&self, max_key: u64, revision: u32) {
|
||||
{
|
||||
let mut vi = self.volume_info.write().unwrap();
|
||||
vi.vacuumed_max_file_key = max_key;
|
||||
vi.vacuumed_compaction_revision = revision;
|
||||
}
|
||||
if let Err(e) = self.save_vif() {
|
||||
warn!(
|
||||
"volume {}: record the vacuumed needle ids in {}: {}",
|
||||
self.id,
|
||||
self.vif_path(),
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write and fsync the .cpc marker, then fsync the directory so the marker
|
||||
/// survives a crash before apply_compact_swap.
|
||||
fn write_compact_commit_marker(&self) -> Result<(), VolumeError> {
|
||||
@@ -11121,121 +11060,6 @@ mod tests {
|
||||
v.cleanup_compact().unwrap();
|
||||
}
|
||||
|
||||
fn write_ids(v: &Volume, ids: &[u64]) {
|
||||
for &id in ids {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data: format!("data-{}", id).into_bytes(),
|
||||
data_size: format!("data-{}", id).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true, false).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_ids(v: &Volume, ids: &[u64]) {
|
||||
for &id in ids {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
..Needle::default()
|
||||
};
|
||||
v.delete_needle(&mut n, false).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn vacuum(v: &Volume) {
|
||||
v.compact_by_index(0, 0, |_| true).unwrap();
|
||||
v.commit_compact().unwrap();
|
||||
}
|
||||
|
||||
fn vacuum_record_on_disk(v: &Volume) -> (u64, u32) {
|
||||
let vif: VifVolumeInfo =
|
||||
serde_json::from_str(&fs::read_to_string(v.vif_path()).unwrap()).unwrap();
|
||||
(vif.vacuumed_max_file_key, vif.vacuumed_compaction_revision)
|
||||
}
|
||||
|
||||
fn assert_vacuum_record(v: &Volume, want: (u64, u32), when: &str) {
|
||||
let vi = v.volume_info();
|
||||
assert_eq!(
|
||||
(vi.vacuumed_max_file_key, vi.vacuumed_compaction_revision),
|
||||
want,
|
||||
"{}: in memory",
|
||||
when
|
||||
);
|
||||
assert_eq!(vacuum_record_on_disk(v), want, "{}: in the .vif", when);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vacuum_records_largest_needle_id_it_could_have_erased() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
assert_eq!(v.volume_info().vacuumed_max_file_key, 0);
|
||||
|
||||
write_ids(&v, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
||||
delete_ids(&v, &[8, 9, 10]);
|
||||
vacuum(&v);
|
||||
for id in 8..=10u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
..Needle::default()
|
||||
};
|
||||
assert!(v.read_needle(&mut n).is_err(), "id {} survived", id);
|
||||
}
|
||||
assert_vacuum_record(&v, (10, 1), "after the first vacuum");
|
||||
|
||||
write_ids(&v, &[11, 12]);
|
||||
delete_ids(&v, &[12]);
|
||||
vacuum(&v);
|
||||
assert_vacuum_record(&v, (12, 2), "after the second vacuum");
|
||||
|
||||
delete_ids(&v, &[11]);
|
||||
vacuum(&v);
|
||||
assert_vacuum_record(&v, (12, 3), "after a vacuum of smaller ids");
|
||||
|
||||
v.close();
|
||||
drop(v);
|
||||
let v = make_test_volume(dir);
|
||||
assert_vacuum_record(&v, (12, 3), "after a reload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vacuum_after_unrecorded_vacuum_records_nothing() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
write_ids(&v, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
delete_ids(&v, &[9]);
|
||||
vacuum(&v);
|
||||
assert_vacuum_record(&v, (9, 1), "after the first vacuum");
|
||||
|
||||
// as a vacuum that kept no record leaves it: the revision moved on
|
||||
v.volume_info.write().unwrap().vacuumed_compaction_revision = 0;
|
||||
v.save_vif().unwrap();
|
||||
|
||||
delete_ids(&v, &[8]);
|
||||
vacuum(&v);
|
||||
assert_eq!(v.super_block().compaction_revision, 2);
|
||||
assert_vacuum_record(&v, (9, 0), "after a vacuum past an unrecorded one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vif_vacuum_record_round_trips_go_json() {
|
||||
let go = r#"{"files":[],"version":3,"replication":"000","bytesOffset":4,"datFileSize":"0","expireAtSec":"0","readOnly":false,"readOnlyCanDelete":false,"vacuumedMaxFileKey":"12","vacuumedCompactionRevision":3}"#;
|
||||
let pb = serde_json::from_str::<VifVolumeInfo>(go).unwrap().to_pb();
|
||||
assert_eq!(pb.vacuumed_max_file_key, 12);
|
||||
assert_eq!(pb.vacuumed_compaction_revision, 3);
|
||||
let back = serde_json::to_string(&VifVolumeInfo::from_pb(&pb)).unwrap();
|
||||
assert!(back.contains(r#""vacuumedMaxFileKey":"12""#), "{}", back);
|
||||
assert!(
|
||||
back.contains(r#""vacuumedCompactionRevision":3"#),
|
||||
"{}",
|
||||
back
|
||||
);
|
||||
}
|
||||
|
||||
/// Guards the copy-phase integrity check against regressing into
|
||||
/// double-subtracting skipped bytes: expected_live_bytes already excludes
|
||||
/// needles dropped as unreadable (they continue before the tally), so the
|
||||
@@ -13922,33 +13746,4 @@ mod tests {
|
||||
v.read_needle(&mut n1).unwrap();
|
||||
assert_eq!(n1.data, b"data-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_vif_reads_the_old_format_destroy_time() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
{
|
||||
let _v = make_test_volume(dir);
|
||||
std::fs::write(
|
||||
format!("{}/1.vif", dir),
|
||||
format!(
|
||||
r#"{{"files":[],"version":3,"replication":"000","BytesOffset":{},"datFileSize":"0","DestroyTime":"4102444800","readOnly":true}}"#,
|
||||
OFFSET_SIZE
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
&VolumeSpec::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(v.volume_info().expire_at_sec, 4102444800);
|
||||
assert!(v.volume_info().read_only);
|
||||
}
|
||||
}
|
||||
Generated
-3
@@ -6357,15 +6357,12 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"crc32c",
|
||||
"log",
|
||||
"prost",
|
||||
"protoc-bin-vendored",
|
||||
"reqwest 0.12.28",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile",
|
||||
"seaweed-common",
|
||||
"thiserror 2.0.20",
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
//! The digest a cluster writes ETags and chunk digests in.
|
||||
//!
|
||||
//! The filer decides it (`weed filer -digest`) and reports it in its
|
||||
//! configuration; every writer follows it, so a cluster holds one kind of
|
||||
//! digest (Go's `util.AdoptFilerDigest`). Under sha256 a digest keeps MD5's
|
||||
//! 16 bytes but is SHA-256 cut to that size.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use md5::{Digest as _, Md5};
|
||||
use seaweed_common::fips::FipsMode;
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ContentDigest {
|
||||
#[default]
|
||||
Md5,
|
||||
Sha256,
|
||||
}
|
||||
|
||||
impl ContentDigest {
|
||||
/// The digest to write into `filer`, which reports `reported`: the filer's
|
||||
/// own, or, from a filer that reports none, sha256 under strict mode and
|
||||
/// md5 otherwise. Under strict mode a filer using md5 is refused, as the Go
|
||||
/// clients refuse it under `GODEBUG=fips140=only`.
|
||||
pub fn for_filer(filer: &str, reported: &str, mode: FipsMode) -> Result<Self> {
|
||||
let strict = mode == FipsMode::Strict;
|
||||
match reported {
|
||||
"sha256" => Ok(Self::Sha256),
|
||||
"md5" if strict => {
|
||||
bail!("filer {filer} uses digest md5, which needs MD5; fips.mode strict refuses it")
|
||||
}
|
||||
"md5" => Ok(Self::Md5),
|
||||
"" => {
|
||||
let own = if strict { Self::Sha256 } else { Self::Md5 };
|
||||
tracing::warn!(
|
||||
"filer {filer} does not report its digest; writing {own} digests as this process's fips.mode implies"
|
||||
);
|
||||
Ok(own)
|
||||
}
|
||||
other => bail!("filer {filer} reports digest {other:?}; want md5 or sha256"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The digest of `data`: its MD5, or its SHA-256 cut to MD5's 16 bytes.
|
||||
pub fn sum(self, data: &[u8]) -> [u8; 16] {
|
||||
match self {
|
||||
Self::Md5 => Md5::digest(data).into(),
|
||||
Self::Sha256 => {
|
||||
let full = Sha256::digest(data);
|
||||
let mut cut = [0u8; 16];
|
||||
cut.copy_from_slice(&full[..16]);
|
||||
cut
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ContentDigest {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Md5 => "md5",
|
||||
Self::Sha256 => "sha256",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn follows_the_filer_and_refuses_md5_under_strict_mode() {
|
||||
let pick = |reported, mode| ContentDigest::for_filer("f:18888", reported, mode);
|
||||
assert_eq!(
|
||||
pick("sha256", FipsMode::Off).unwrap(),
|
||||
ContentDigest::Sha256
|
||||
);
|
||||
assert_eq!(pick("md5", FipsMode::On).unwrap(), ContentDigest::Md5);
|
||||
assert_eq!(pick("", FipsMode::Off).unwrap(), ContentDigest::Md5);
|
||||
assert_eq!(pick("", FipsMode::Strict).unwrap(), ContentDigest::Sha256);
|
||||
assert_eq!(
|
||||
pick("sha256", FipsMode::Strict).unwrap(),
|
||||
ContentDigest::Sha256
|
||||
);
|
||||
assert!(
|
||||
pick("md5", FipsMode::Strict)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("fips.mode strict")
|
||||
);
|
||||
assert!(pick("sha512", FipsMode::Off).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha256_digests_keep_md5s_length() {
|
||||
assert_eq!(
|
||||
hex::encode(ContentDigest::Md5.sum(b"bar")),
|
||||
"37b51d194a7513e45b56f6524f2d51f2"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(ContentDigest::Sha256.sum(b"bar")),
|
||||
"fcde2b2edba56bf408601fb721fe9b5c"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::digest::ContentDigest;
|
||||
use anyhow::{Context, bail};
|
||||
use base64::prelude::{BASE64_STANDARD, Engine};
|
||||
use bytes::Bytes;
|
||||
@@ -22,6 +21,7 @@ use futures::StreamExt;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::stream::BoxStream;
|
||||
use lance::io::WrappingObjectStore;
|
||||
use md5::{Digest, Md5};
|
||||
use object_store::path::Path;
|
||||
use object_store::{Attribute, Attributes, PutMode, UploadPart};
|
||||
use object_store::{
|
||||
@@ -349,9 +349,13 @@ impl Source for Filers {
|
||||
data: Bytes,
|
||||
) -> anyhow::Result<FileChunk> {
|
||||
let name = path.rsplit('/').next().unwrap_or(path).to_string();
|
||||
self.writer
|
||||
let digest = BASE64_STANDARD.encode(Md5::digest(&data));
|
||||
let mut chunk = self
|
||||
.writer
|
||||
.upload_assigned_chunk_bytes(assignment, &name, offset as i64, data)
|
||||
.await
|
||||
.await?;
|
||||
chunk.e_tag = digest;
|
||||
Ok(chunk)
|
||||
}
|
||||
|
||||
async fn create(&self, dir: &str, entry: Entry, exclusive: bool) -> anyhow::Result<()> {
|
||||
@@ -432,9 +436,6 @@ struct Shared {
|
||||
chunk_size: usize,
|
||||
/// Chunks are encrypted for the volume servers, as the cluster asks.
|
||||
cipher: bool,
|
||||
/// The digest ETags and chunk digests are written in, as the filer reports
|
||||
/// it.
|
||||
digest: ContentDigest,
|
||||
/// The filer group, which prefixes a bucket's collection as the gateway
|
||||
/// names it.
|
||||
filer_group: String,
|
||||
@@ -529,11 +530,6 @@ impl DirectReads {
|
||||
Box::pin(async move { c.get_configuration().await })
|
||||
})
|
||||
.await?;
|
||||
let digest = ContentDigest::for_filer(
|
||||
&conn.filers.join(","),
|
||||
&config.digest,
|
||||
seaweed_common::fips::process_mode(),
|
||||
)?;
|
||||
let kek_file = filers
|
||||
.lookup(KEK_PATH.0, KEK_PATH.1)
|
||||
.await
|
||||
@@ -550,7 +546,6 @@ impl DirectReads {
|
||||
let shared = Arc::get_mut(&mut reads.shared).expect("just created");
|
||||
shared.chunk_size = chunk_size;
|
||||
shared.cipher = config.cipher;
|
||||
shared.digest = digest;
|
||||
shared.filer_group = if conn.filer_group.is_empty() {
|
||||
config.filer_group.clone()
|
||||
} else {
|
||||
@@ -573,7 +568,6 @@ impl DirectReads {
|
||||
keys,
|
||||
chunk_size: DEFAULT_CHUNK_SIZE,
|
||||
cipher: false,
|
||||
digest: ContentDigest::default(),
|
||||
filer_group: String::new(),
|
||||
objects: moka::sync::Cache::builder()
|
||||
.max_capacity(OBJECT_CACHE_ENTRIES)
|
||||
@@ -785,8 +779,8 @@ fn bare_directory(entry: &Entry) -> bool {
|
||||
|
||||
/// The object's ETag as the gateway reports it: its stored S3 ETag, else the
|
||||
/// remote ETag while the entry holds the remote bytes, else the entry's md5,
|
||||
/// else derived from the chunks' in the cluster's `digest`, quoted.
|
||||
fn etag(entry: &Entry, digest: ContentDigest) -> Option<String> {
|
||||
/// else derived from the chunks', quoted.
|
||||
fn etag(entry: &Entry) -> Option<String> {
|
||||
let quoted = |etag: String| {
|
||||
if etag.starts_with('"') {
|
||||
etag
|
||||
@@ -834,7 +828,7 @@ fn etag(entry: &Entry, digest: ContentDigest) -> Option<String> {
|
||||
[] => None,
|
||||
[one] => Some(quoted(hex::encode(one))),
|
||||
many => {
|
||||
let joined = digest.sum(&many.concat());
|
||||
let joined = Md5::digest(many.concat());
|
||||
Some(quoted(format!("{}-{}", hex::encode(joined), many.len())))
|
||||
}
|
||||
}
|
||||
@@ -974,7 +968,7 @@ impl DirectStore {
|
||||
.map_err(generic)?;
|
||||
Ok(Arc::new(Object {
|
||||
size: file_size(&entry, &chunks),
|
||||
etag: etag(&entry, self.reads.digest),
|
||||
etag: etag(&entry),
|
||||
entry,
|
||||
chunks,
|
||||
decoder,
|
||||
@@ -1015,7 +1009,7 @@ impl DirectStore {
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
size: entry_size(entry),
|
||||
e_tag: etag(entry, self.reads.digest),
|
||||
e_tag: etag(entry),
|
||||
version: None,
|
||||
}
|
||||
}
|
||||
@@ -1113,7 +1107,7 @@ impl ObjectStore for DirectStore {
|
||||
};
|
||||
let upload = Upload::start(self.clone(), location.clone(), &opts.attributes)?;
|
||||
let data: Bytes = payload.into();
|
||||
let md5 = self.reads.digest.sum(&data);
|
||||
let md5 = Md5::digest(&data);
|
||||
if let Err(err) = upload.put(data).await {
|
||||
if let Err(discard) = upload.discard_all().await {
|
||||
tracing::warn!("{location}: discarding after a failed upload: {discard:#}");
|
||||
@@ -1281,14 +1275,9 @@ impl fmt::Debug for Upload {
|
||||
impl Upload {
|
||||
fn start(store: DirectStore, location: Path, attributes: &Attributes) -> Result<Self> {
|
||||
let path = store.filer_path(&location);
|
||||
let encoder = EntryEncoder::new(
|
||||
store.reads.keys.clone(),
|
||||
store.sse_s3,
|
||||
store.reads.cipher,
|
||||
store.reads.digest,
|
||||
)
|
||||
.with_context(|| format!("encoding {path}"))
|
||||
.map_err(generic)?;
|
||||
let encoder = EntryEncoder::new(store.reads.keys.clone(), store.sse_s3, store.reads.cipher)
|
||||
.with_context(|| format!("encoding {path}"))
|
||||
.map_err(generic)?;
|
||||
let collection = match store.reads.filer_group.as_str() {
|
||||
"" => String::new(),
|
||||
group => format!("{group}_{}", store.bucket),
|
||||
@@ -1356,7 +1345,6 @@ impl Upload {
|
||||
}
|
||||
};
|
||||
chunk.size = size;
|
||||
chunk.e_tag = encoded.e_tag;
|
||||
chunk.cipher_key = encoded.cipher_key;
|
||||
chunk.sse_type = encoded.sse_type;
|
||||
chunk.sse_metadata = encoded.sse_metadata;
|
||||
@@ -1417,7 +1405,7 @@ impl Upload {
|
||||
}
|
||||
let attributes = self.encoder.attributes().map_err(generic)?;
|
||||
entry.extended.extend(attributes);
|
||||
let e_tag = etag(&entry, self.store.reads.digest);
|
||||
let e_tag = etag(&entry);
|
||||
let created = self.store.reads.source.create(dir, entry, exclusive).await;
|
||||
if let Err(err) = created {
|
||||
// A create the filer took and never answered may still be applied,
|
||||
@@ -1684,7 +1672,6 @@ impl VolumeTransport for JwtTransport {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::TryStreamExt;
|
||||
use md5::{Digest, Md5};
|
||||
use object_store::ObjectStoreExt;
|
||||
use object_store::memory::InMemory;
|
||||
use std::collections::HashMap;
|
||||
@@ -2680,64 +2667,6 @@ mod tests {
|
||||
assert_eq!(got, Bytes::from_static(b"again"));
|
||||
}
|
||||
|
||||
/// A store writing through `fake` into a cluster whose digest is `digest`,
|
||||
/// with 4096-byte chunks.
|
||||
fn writing_store_in(fake: Arc<Fake>, digest: ContentDigest) -> Arc<dyn ObjectStore> {
|
||||
let mut reads = DirectReads::new(fake, "", no_keys());
|
||||
{
|
||||
let shared = Arc::get_mut(&mut reads.shared).unwrap();
|
||||
shared.chunk_size = 4096;
|
||||
shared.digest = digest;
|
||||
}
|
||||
reads
|
||||
.encrypting(false)
|
||||
.wrap("s3$vb", Arc::new(InMemory::new()))
|
||||
}
|
||||
|
||||
/// In a sha256 cluster the entry's digest, its chunks' ETags and a
|
||||
/// multipart ETag are SHA-256 cut to 16 bytes, as Go's writers write them.
|
||||
#[tokio::test]
|
||||
async fn writes_follow_a_sha256_digest() {
|
||||
let fake = Arc::new(Fake::default());
|
||||
let store = writing_store_in(fake.clone(), ContentDigest::Sha256);
|
||||
let sum = |data: &[u8]| ContentDigest::Sha256.sum(data);
|
||||
let body = Bytes::from(vec![9u8; 5000]);
|
||||
let path = Path::from("vector/idx/_versions/1.manifest");
|
||||
let result = store
|
||||
.put_opts(&path, body.clone().into(), PutMode::Create.into())
|
||||
.await
|
||||
.unwrap();
|
||||
let whole = hex::encode(sum(&body));
|
||||
assert_eq!(
|
||||
result.e_tag.as_deref(),
|
||||
Some(format!("\"{whole}\"").as_str())
|
||||
);
|
||||
let entry = entry_of(&fake, "vector/idx/_versions/1.manifest");
|
||||
assert_eq!(hex::encode(&entry.attributes.as_ref().unwrap().md5), whole);
|
||||
let tags: Vec<String> = entry.chunks.iter().map(|c| c.e_tag.clone()).collect();
|
||||
let want: Vec<String> = [&body[..4096], &body[4096..]]
|
||||
.iter()
|
||||
.map(|piece| BASE64_STANDARD.encode(sum(piece)))
|
||||
.collect();
|
||||
assert_eq!(tags, want);
|
||||
|
||||
let mut upload = store
|
||||
.put_multipart(&Path::from("vector/idx/data/ef.lance"))
|
||||
.await
|
||||
.unwrap();
|
||||
let parts = [vec![1u8; 3000], vec![2u8; 1000]];
|
||||
for part in &parts {
|
||||
upload
|
||||
.put_part(Bytes::from(part.clone()).into())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let result = upload.complete().await.unwrap();
|
||||
let digests: Vec<u8> = parts.iter().flat_map(|p| sum(p)).collect();
|
||||
let want = format!("\"{}-2\"", hex::encode(sum(&digests)));
|
||||
assert_eq!(result.e_tag.as_deref(), Some(want.as_str()));
|
||||
}
|
||||
|
||||
/// A multipart upload's parts become chunks in order, its ETag derives
|
||||
/// from them as the gateway's does, and an abort leaves no needle behind.
|
||||
#[tokio::test]
|
||||
@@ -2814,12 +2743,6 @@ mod tests {
|
||||
let plain =
|
||||
&body[chunk.offset as usize..chunk.offset as usize + chunk.size as usize];
|
||||
assert_ne!(needle, plain, "cipher {cipher} sse {sse_s3}");
|
||||
// The ETag digests the bytes before the volume encryption.
|
||||
if !cipher {
|
||||
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(needle)));
|
||||
} else if !sse_s3 {
|
||||
assert_eq!(chunk.e_tag, BASE64_STANDARD.encode(Md5::digest(plain)));
|
||||
}
|
||||
assert_eq!(!chunk.cipher_key.is_empty(), cipher);
|
||||
assert_eq!(chunk.sse_type == SSE_S3_TYPE, sse_s3);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ pub mod admin_cluster;
|
||||
pub mod catalog;
|
||||
pub mod cluster;
|
||||
pub mod dataset;
|
||||
pub mod digest;
|
||||
pub mod direct_read;
|
||||
pub mod drop_guard;
|
||||
pub mod grpc_tls;
|
||||
|
||||
@@ -130,12 +130,7 @@ async fn main() -> Result<()> {
|
||||
// One security.toml for everything: the admin stream's and the catalog's
|
||||
// signing key, and the cluster connection.
|
||||
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
|
||||
let mode = weed_lance_worker::tls::install_for_fips_mode(&security)?;
|
||||
weed_lance_worker::security::check_signing_key_flag(
|
||||
mode,
|
||||
"--filer-signing-key (WEED_FILER_SIGNING_KEY)",
|
||||
args.filer_signing_key.as_deref(),
|
||||
)?;
|
||||
weed_lance_worker::tls::install_for_fips_mode(&security)?;
|
||||
let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) {
|
||||
Some(key) => Some((key, 0)),
|
||||
None => security
|
||||
|
||||
@@ -6,8 +6,6 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::sse::SseConfig;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use seaweed_common::fips::FipsMode;
|
||||
use seaweed_common::jwt_keys;
|
||||
use sw_client::HttpsTls;
|
||||
|
||||
const FILE_NAME: &str = "security.toml";
|
||||
@@ -151,32 +149,6 @@ impl Security {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
/// Checks the JWT HMAC signing keys from this security.toml and their
|
||||
/// WEED_ variables for a length of at least 14 characters, as FIPS 140
|
||||
/// requires. Under `fips.mode = strict`, if any of them is shorter, it
|
||||
/// returns an error naming each such setting and its length. In any other
|
||||
/// mode each such key except a `previous_key` gets a warning that strict
|
||||
/// mode would refuse it.
|
||||
pub fn check_jwt_keys(&self, mode: FipsMode) -> Result<()> {
|
||||
let file = self
|
||||
.path()
|
||||
.map_or_else(|| FILE_NAME.to_string(), |p| p.display().to_string());
|
||||
let keys: Vec<(&str, Vec<u8>)> = jwt_keys::JWT_KEY_SETTINGS
|
||||
.iter()
|
||||
.map(|&setting| (setting, self.get(setting).unwrap_or_default().into_bytes()))
|
||||
.collect();
|
||||
for (setting, key) in &keys {
|
||||
if let Some(warning) = jwt_keys::short_key_warning(mode, &file, setting, key) {
|
||||
tracing::warn!("{warning}");
|
||||
}
|
||||
}
|
||||
let keys: Vec<(&str, &[u8])> = keys.iter().map(|(s, k)| (*s, k.as_slice())).collect();
|
||||
if let Some(short) = jwt_keys::short_keys(mode, &keys) {
|
||||
bail!("{}", jwt_keys::startup_refusal(&file, &short));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn raw(&self, key: &str) -> Option<String> {
|
||||
let env_name = format!("WEED_{}", key.to_uppercase().replace('.', "_"));
|
||||
// viper treats an empty variable as unset
|
||||
@@ -357,70 +329,11 @@ impl Security {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks a signing key given on the command line as `flag`, as
|
||||
/// [`Security::check_jwt_keys`] checks the file's: under `fips.mode = strict`
|
||||
/// a key shorter than 14 characters is an error naming the flag and the
|
||||
/// key's length; in any other mode it gets a warning that strict mode would
|
||||
/// refuse it.
|
||||
pub fn check_signing_key_flag(mode: FipsMode, flag: &str, key: Option<&str>) -> Result<()> {
|
||||
let key = key.unwrap_or_default().as_bytes();
|
||||
if let Some(warning) = jwt_keys::short_key_warning(mode, "command line", flag, key) {
|
||||
tracing::warn!("{warning}");
|
||||
}
|
||||
if let Some(short) = jwt_keys::short_keys(mode, &[(flag, key)]) {
|
||||
bail!("this process runs with fips.mode strict, and stops because {short}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn strict_mode_refuses_a_short_jwt_key_from_the_file_or_the_environment() {
|
||||
let file = "[jwt.signing.read]\nkey = \"0123456789\"\n[jwt.filer_signing]\nkey = \"long-enough-filer-key\"\n";
|
||||
let err = security(file, &[])
|
||||
.check_jwt_keys(FipsMode::Strict)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
|
||||
"{err}"
|
||||
);
|
||||
assert!(security(file, &[]).check_jwt_keys(FipsMode::On).is_ok());
|
||||
|
||||
let env = [("WEED_JWT_FILER_SIGNING_KEY", "short")];
|
||||
let err = security("", &env)
|
||||
.check_jwt_keys(FipsMode::Strict)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("jwt.filer_signing.key (5 characters)"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let long = "[jwt.signing]\nkey = \"a-key-long-enough\"\n";
|
||||
assert!(security(long, &[]).check_jwt_keys(FipsMode::Strict).is_ok());
|
||||
assert!(security("", &[]).check_jwt_keys(FipsMode::Strict).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_mode_refuses_a_short_signing_key_flag() {
|
||||
let err = check_signing_key_flag(FipsMode::Strict, "--filer-signing-key", Some("short"))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("--filer-signing-key (5 characters)"),
|
||||
"{err}"
|
||||
);
|
||||
assert!(
|
||||
check_signing_key_flag(FipsMode::Off, "--filer-signing-key", Some("short")).is_ok()
|
||||
);
|
||||
assert!(check_signing_key_flag(FipsMode::Strict, "--filer-signing-key", None).is_ok());
|
||||
}
|
||||
|
||||
fn security(toml: &str, env: &[(&str, &str)]) -> Security {
|
||||
let env: HashMap<String, String> = env
|
||||
.iter()
|
||||
|
||||
@@ -20,8 +20,6 @@ use hkdf::Hkdf;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use sw_client::ChunkDecoder;
|
||||
|
||||
use crate::digest::ContentDigest;
|
||||
use sw_client::filer_pb::{Entry, FileChunk};
|
||||
|
||||
type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>;
|
||||
@@ -334,9 +332,6 @@ impl ObjectKey {
|
||||
/// records about them.
|
||||
pub struct EncodedChunk {
|
||||
pub data: Vec<u8>,
|
||||
/// The chunk's ETag: the digest of its bytes before the volume encryption,
|
||||
/// as Go's uploader records it under cipher.
|
||||
pub e_tag: String,
|
||||
pub cipher_key: Vec<u8>,
|
||||
pub sse_type: i32,
|
||||
pub sse_metadata: Vec<u8>,
|
||||
@@ -353,7 +348,6 @@ pub struct EntryEncoder {
|
||||
keys: Arc<SseS3Keys>,
|
||||
object: Option<(ObjectKey, String)>,
|
||||
cipher: bool,
|
||||
digest: ContentDigest,
|
||||
}
|
||||
|
||||
fn key_id() -> String {
|
||||
@@ -361,12 +355,7 @@ fn key_id() -> String {
|
||||
}
|
||||
|
||||
impl EntryEncoder {
|
||||
pub fn new(
|
||||
keys: Arc<SseS3Keys>,
|
||||
sse_s3: bool,
|
||||
cipher: bool,
|
||||
digest: ContentDigest,
|
||||
) -> Result<Self> {
|
||||
pub fn new(keys: Arc<SseS3Keys>, sse_s3: bool, cipher: bool) -> Result<Self> {
|
||||
let object = if sse_s3 {
|
||||
if !keys.configured() {
|
||||
bail!(
|
||||
@@ -381,7 +370,6 @@ impl EntryEncoder {
|
||||
keys,
|
||||
object,
|
||||
cipher,
|
||||
digest,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -402,7 +390,6 @@ impl EntryEncoder {
|
||||
}
|
||||
None => (0, Vec::new()),
|
||||
};
|
||||
let e_tag = BASE64_STANDARD.encode(self.digest.sum(&data));
|
||||
let (data, cipher_key) = if self.cipher {
|
||||
encrypt_chunk(&data)
|
||||
} else {
|
||||
@@ -410,7 +397,6 @@ impl EntryEncoder {
|
||||
};
|
||||
Ok(EncodedChunk {
|
||||
data,
|
||||
e_tag,
|
||||
cipher_key,
|
||||
sse_type,
|
||||
sse_metadata,
|
||||
|
||||
@@ -10,9 +10,8 @@ pub use seaweed_common::tls::{crypto_provider, install_default_crypto_provider,
|
||||
/// Resolves the FIPS mode of a process that reads `security`
|
||||
/// (`WEED_FIPS_MODE`, else its `fips.mode`, read from the same parsed file
|
||||
/// as the JWT keys), installs the matching rustls provider as the process
|
||||
/// default, logs the mode and checks the file's JWT keys for it
|
||||
/// ([`crate::security::Security::check_jwt_keys`]). Call it once at
|
||||
/// startup, before anything configures TLS or signs a token.
|
||||
/// default and logs the mode. Call it once at startup, before anything
|
||||
/// configures TLS.
|
||||
pub fn install_for_fips_mode(
|
||||
security: &crate::security::Security,
|
||||
) -> anyhow::Result<seaweed_common::fips::FipsMode> {
|
||||
@@ -31,7 +30,6 @@ pub fn install_for_fips_mode(
|
||||
} else {
|
||||
tracing::info!("{setting}");
|
||||
}
|
||||
security.check_jwt_keys(setting.mode)?;
|
||||
Ok(setting.mode)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
//! weed-worker under `fips.mode = strict` exits at startup when a JWT key is
|
||||
//! too short for FIPS 140, before it dials the admin server.
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Runs weed-worker with `args` under `WEED_FIPS_MODE=strict` and a
|
||||
/// security.toml holding `security`, without the caller's other WEED_
|
||||
/// variables, and returns its exit status and stderr. Fails when it is still
|
||||
/// running after 30 s, which means it accepted the keys.
|
||||
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("security.toml");
|
||||
std::fs::write(&file, security).unwrap();
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-worker"));
|
||||
for (name, _) in std::env::vars_os() {
|
||||
if name.to_string_lossy().starts_with("WEED_") {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
let mut child = command
|
||||
.arg("--security-toml")
|
||||
.arg(&file)
|
||||
.args(args)
|
||||
.env("WEED_FIPS_MODE", "strict")
|
||||
.current_dir(dir.path())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
let mut stderr = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut stderr)
|
||||
.unwrap();
|
||||
return (status, stderr);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
panic!("weed-worker still running after 30 s: it accepted the short key");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_key_in_security_toml_stops_the_worker() {
|
||||
let (status, stderr) = run_strict("[jwt.signing.read]\nkey = \"0123456789\"\n", &[]);
|
||||
assert!(!status.success(), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("fips.mode strict")
|
||||
&& stderr
|
||||
.contains("jwt.signing.read.key (10 characters) is shorter than the 14 characters"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_signing_key_flag_stops_the_worker() {
|
||||
let (status, stderr) = run_strict("", &["--filer-signing-key", "short"]);
|
||||
assert!(!status.success(), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("--filer-signing-key (WEED_FILER_SIGNING_KEY) (5 characters)"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
@@ -11,18 +11,12 @@ name = "sw_client"
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
base64 = "0.22"
|
||||
bytes = "1"
|
||||
# The checksum each upload carries for the volume server to check.
|
||||
crc32c = "0.6"
|
||||
log = "0.4"
|
||||
prost.workspace = true
|
||||
# System roots for volume servers behind public CAs, as Go's http client.
|
||||
reqwest = { version = "0.12", default-features = false, features = ["multipart", "rustls-tls-native-roots"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
# The system roots for the FIPS-mode client configuration sw-client builds
|
||||
# itself; the version reqwest's rustls-tls-native-roots uses.
|
||||
rustls-native-certs = "0.8"
|
||||
# The process-wide rustls provider every SeaweedFS Rust binary installs.
|
||||
seaweed-common = { path = "../../../seaweed-common" }
|
||||
thiserror = "2"
|
||||
|
||||
@@ -323,9 +323,6 @@ pub struct FilerConfig {
|
||||
pub version: String,
|
||||
pub cluster_id: String,
|
||||
pub filer_group: String,
|
||||
/// The digest the cluster writes ETags and chunk digests in, "md5" or
|
||||
/// "sha256"; empty from a filer that predates the setting.
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
impl From<GetFilerConfigurationResponse> for FilerConfig {
|
||||
@@ -340,7 +337,6 @@ impl From<GetFilerConfigurationResponse> for FilerConfig {
|
||||
version: r.version,
|
||||
cluster_id: r.cluster_id,
|
||||
filer_group: r.filer_group,
|
||||
digest: r.digest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,8 +238,9 @@ impl HttpTransport {
|
||||
pub fn with_tls(tls: &HttpsTls) -> Result<Self> {
|
||||
install_crypto_provider();
|
||||
let builder = reqwest::Client::builder().connect_timeout(VOLUME_CONNECT_TIMEOUT);
|
||||
let builder = if seaweed_common::fips::process_mode().is_fips() {
|
||||
builder.use_preconfigured_tls(fips_tls_config(
|
||||
let builder = if tls.insecure_skip_verify && seaweed_common::fips::process_mode().is_fips()
|
||||
{
|
||||
builder.use_preconfigured_tls(unverified_tls_config(
|
||||
tls,
|
||||
Arc::new(seaweed_common::tls::crypto_provider()),
|
||||
)?)
|
||||
@@ -282,31 +283,24 @@ fn reqwest_tls(builder: reqwest::ClientBuilder, tls: &HttpsTls) -> Result<reqwes
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
/// The client configuration for `tls` in FIPS mode, on `provider`. It is
|
||||
/// built here rather than by reqwest for two reasons: reqwest leaves
|
||||
/// `require_ems` at rustls's default, which is off for a provider that is not
|
||||
/// FIPS-validated, while Go requires the Extended Master Secret for TLS 1.2
|
||||
/// in FIPS mode; and reqwest's verifier for `insecure_skip_verify` advertises
|
||||
/// its own signature schemes (SHA-1, Ed448) whatever the provider allows.
|
||||
/// Server certificates are checked against `ca` (the system roots without
|
||||
/// one); with `insecure_skip_verify` they are not, but handshake signatures
|
||||
/// still are, with the provider's algorithms, and only its schemes are
|
||||
/// offered, and a malformed `ca` is still refused, as reqwest refuses it on
|
||||
/// every path. HTTP/1.1 only, as the volume servers speak it.
|
||||
fn fips_tls_config(tls: &HttpsTls, provider: Arc<CryptoProvider>) -> Result<rustls::ClientConfig> {
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
|
||||
/// The client configuration for `https.client.insecure_skip_verify` in FIPS
|
||||
/// mode, on `provider`. reqwest's verifier for that setting advertises its own
|
||||
/// signature schemes (SHA-1, Ed448) whatever the provider allows, so this one
|
||||
/// is built here: the server certificate is not checked, but handshake
|
||||
/// signatures are, with the provider's algorithms, and only its schemes are
|
||||
/// offered. HTTP/1.1 only, as the volume servers speak it.
|
||||
fn unverified_tls_config(
|
||||
tls: &HttpsTls,
|
||||
provider: Arc<CryptoProvider>,
|
||||
) -> Result<rustls::ClientConfig> {
|
||||
let verifier = Arc::new(UnverifiedServer {
|
||||
provider: provider.clone(),
|
||||
});
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.context("TLS versions")?;
|
||||
let builder = if tls.insecure_skip_verify {
|
||||
if let Some(ca) = &tls.ca_pem {
|
||||
ca_roots(ca)?;
|
||||
}
|
||||
builder
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(UnverifiedServer { provider }))
|
||||
} else {
|
||||
builder.with_root_certificates(root_certificates(tls)?)
|
||||
};
|
||||
.context("TLS versions")?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier);
|
||||
let mut config = match (&tls.cert_pem, &tls.key_pem) {
|
||||
(Some(cert), Some(key)) => {
|
||||
let chain = CertificateDer::pem_slice_iter(cert)
|
||||
@@ -321,47 +315,10 @@ fn fips_tls_config(tls: &HttpsTls, provider: Arc<CryptoProvider>) -> Result<rust
|
||||
_ => bail!("https.client needs both cert and key, or neither"),
|
||||
};
|
||||
config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
config.require_ems = true;
|
||||
config.require_ems = config.require_ems || seaweed_common::tls::require_ems();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The roots server certificates are checked against: the certificates in
|
||||
/// `https.client.ca`, else the system's.
|
||||
fn root_certificates(tls: &HttpsTls) -> Result<rustls::RootCertStore> {
|
||||
match &tls.ca_pem {
|
||||
Some(ca) => ca_roots(ca),
|
||||
None => native_roots(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The certificates in an `https.client.ca` PEM, refused when one does not
|
||||
/// parse, as reqwest refuses them.
|
||||
fn ca_roots(ca: &[u8]) -> Result<rustls::RootCertStore> {
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
for cert in CertificateDer::pem_slice_iter(ca) {
|
||||
roots
|
||||
.add(cert.context("https.client.ca")?)
|
||||
.context("https.client.ca")?;
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
/// The system's root certificates as reqwest loads them: ones rustls cannot
|
||||
/// parse are skipped, and it is an error only when none parses and some did
|
||||
/// not.
|
||||
fn native_roots() -> Result<rustls::RootCertStore> {
|
||||
let loaded = rustls_native_certs::load_native_certs();
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
let (added, ignored) = roots.add_parsable_certificates(loaded.certs);
|
||||
if added == 0 && ignored > 0 {
|
||||
bail!(
|
||||
"no valid certificate in the system root store: {:?}",
|
||||
loaded.errors
|
||||
);
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
/// Accepts any server certificate and host name, as `insecure_skip_verify`
|
||||
/// asks, while verifying the handshake signatures with the provider's
|
||||
/// algorithms and offering only their schemes.
|
||||
@@ -524,17 +481,6 @@ impl VolumeTransport for HttpTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// The header in which an upload carries the CRC32C of its bytes, which the
|
||||
/// volume server checks before storing them (Go's needle.ContentCrc32cHeader).
|
||||
pub const CONTENT_CRC32C_HEADER: &str = "X-Seaweed-Content-Crc32c";
|
||||
|
||||
/// The [`CONTENT_CRC32C_HEADER`] value for `data`: the base64 of its CRC32C,
|
||||
/// big-endian, as Go's needle.ContentCrc32c writes it.
|
||||
pub fn content_crc32c(data: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
base64::engine::general_purpose::STANDARD.encode(crc32c::crc32c(data).to_be_bytes())
|
||||
}
|
||||
|
||||
impl HttpTransport {
|
||||
async fn upload(
|
||||
&self,
|
||||
@@ -550,7 +496,6 @@ impl HttpTransport {
|
||||
url.push_str("?fsync=true");
|
||||
}
|
||||
let size = data.len() as u64;
|
||||
let crc32c = content_crc32c(&data);
|
||||
let part = reqwest::multipart::Part::stream_with_length(data, size)
|
||||
.file_name(filename.to_string());
|
||||
let form = reqwest::multipart::Form::new().part("file", part);
|
||||
@@ -558,7 +503,6 @@ impl HttpTransport {
|
||||
.http
|
||||
.post(&url)
|
||||
.timeout(self.write_timeout)
|
||||
.header(CONTENT_CRC32C_HEADER, crc32c)
|
||||
.multipart(form);
|
||||
if !auth.is_empty() {
|
||||
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
|
||||
@@ -629,148 +573,31 @@ mod tests {
|
||||
recorder.0.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
/// The provider FIPS mode installs.
|
||||
fn fips_provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(seaweed_common::tls::provider_for(
|
||||
#[test]
|
||||
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
|
||||
let provider = Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
))
|
||||
}
|
||||
|
||||
/// `https.client` with certificate checks off, as FIPS mode builds it.
|
||||
fn unverified() -> HttpsTls {
|
||||
HttpsTls {
|
||||
insecure_skip_verify: true,
|
||||
..HttpsTls::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `https.client` with `ca` set to the lance test CA.
|
||||
fn with_test_ca() -> HttpsTls {
|
||||
HttpsTls {
|
||||
ca_pem: Some(TEST_CA.to_vec()),
|
||||
..HttpsTls::default()
|
||||
}
|
||||
}
|
||||
|
||||
const TEST_CA: &[u8] = include_bytes!("../../lance/tests/tls/ca.pem");
|
||||
const TEST_LEAF: &[u8] = include_bytes!("../../lance/tests/tls/a.pem");
|
||||
const TEST_LEAF_KEY: &[u8] = include_bytes!("../../lance/tests/tls/a.key");
|
||||
|
||||
/// Runs a full handshake between `config` and a server presenting the
|
||||
/// lance test leaf for `localhost`, in memory.
|
||||
fn handshake(config: rustls::ClientConfig) -> std::result::Result<(), rustls::Error> {
|
||||
let chain = CertificateDer::pem_slice_iter(TEST_LEAF)
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
let key = PrivateKeyDer::from_pem_slice(TEST_LEAF_KEY).unwrap();
|
||||
let server_config = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::aws_lc_rs::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(chain, key)
|
||||
.unwrap();
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
let mut client = rustls::ClientConnection::new(Arc::new(config), name).unwrap();
|
||||
let mut server = rustls::ServerConnection::new(Arc::new(server_config)).unwrap();
|
||||
while client.is_handshaking() || server.is_handshaking() {
|
||||
let mut flight = Vec::new();
|
||||
client.write_tls(&mut flight).unwrap();
|
||||
if !flight.is_empty() {
|
||||
server.read_tls(&mut flight.as_slice()).unwrap();
|
||||
server.process_new_packets()?;
|
||||
}
|
||||
let mut flight = Vec::new();
|
||||
server.write_tls(&mut flight).unwrap();
|
||||
if !flight.is_empty() {
|
||||
client.read_tls(&mut flight.as_slice()).unwrap();
|
||||
client.process_new_packets()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `offered` and the FIPS signature schemes, each sorted.
|
||||
fn sorted_against_fips(
|
||||
mut offered: Vec<SignatureScheme>,
|
||||
) -> (Vec<SignatureScheme>, Vec<SignatureScheme>) {
|
||||
));
|
||||
let config = unverified_tls_config(&HttpsTls::default(), provider).unwrap();
|
||||
let mut offered = offered_schemes(config);
|
||||
let mut want = seaweed_common::tls::FIPS_SIGNATURE_SCHEMES.to_vec();
|
||||
offered.sort_by_key(|s| u16::from(*s));
|
||||
want.sort_by_key(|s| u16::from(*s));
|
||||
(offered, want)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
|
||||
let config = fips_tls_config(&unverified(), fips_provider()).unwrap();
|
||||
assert!(config.require_ems);
|
||||
let (offered, want) = sorted_against_fips(offered_schemes(config));
|
||||
assert_eq!(offered, want);
|
||||
assert!(!offered.contains(&SignatureScheme::ED448));
|
||||
assert!(!offered.contains(&SignatureScheme::RSA_PKCS1_SHA1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_tls_in_fips_mode_requires_ems_and_checks_the_server() {
|
||||
let config = fips_tls_config(&with_test_ca(), fips_provider()).unwrap();
|
||||
assert!(config.require_ems);
|
||||
let (offered, want) = sorted_against_fips(offered_schemes(config.clone()));
|
||||
assert_eq!(offered, want);
|
||||
handshake(config).unwrap();
|
||||
|
||||
let wrong_ca = HttpsTls {
|
||||
ca_pem: Some(TEST_LEAF.to_vec()),
|
||||
fn unverified_tls_needs_both_halves_of_the_identity() {
|
||||
let provider = Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
));
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
..HttpsTls::default()
|
||||
};
|
||||
let config = fips_tls_config(&wrong_ca, fips_provider()).unwrap();
|
||||
let err = handshake(config).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, rustls::Error::InvalidCertificate(_)),
|
||||
"{err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A PEM certificate block whose DER is not a certificate.
|
||||
const MALFORMED_CA: &[u8] = b"-----BEGIN CERTIFICATE-----
|
||||
AAAA
|
||||
-----END CERTIFICATE-----
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_malformed_ca_is_refused_with_and_without_certificate_checks() {
|
||||
for insecure_skip_verify in [false, true] {
|
||||
let tls = HttpsTls {
|
||||
ca_pem: Some(MALFORMED_CA.to_vec()),
|
||||
insecure_skip_verify,
|
||||
..HttpsTls::default()
|
||||
};
|
||||
let err = fips_tls_config(&tls, fips_provider()).unwrap_err();
|
||||
assert!(format!("{err:#}").contains("https.client.ca"), "{err:#}");
|
||||
assert!(
|
||||
HttpTransport::with_tls(&tls).is_err(),
|
||||
"off mode, insecure_skip_verify = {insecure_skip_verify}"
|
||||
);
|
||||
}
|
||||
let tls = HttpsTls {
|
||||
ca_pem: Some(TEST_CA.to_vec()),
|
||||
..unverified()
|
||||
};
|
||||
assert!(fips_tls_config(&tls, fips_provider()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fips_tls_needs_both_halves_of_the_identity() {
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
..unverified()
|
||||
};
|
||||
assert!(fips_tls_config(&half, fips_provider()).is_err());
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
..with_test_ca()
|
||||
};
|
||||
assert!(fips_tls_config(&half, fips_provider()).is_err());
|
||||
assert!(unverified_tls_config(&half, provider).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -980,68 +807,6 @@ AAAA
|
||||
);
|
||||
}
|
||||
|
||||
/// Reads one HTTP request from `socket`, however TCP splits it: the head up
|
||||
/// to its blank line, then as many body bytes as its Content-Length says.
|
||||
/// Returns the head.
|
||||
async fn read_request_head_and_body(socket: &mut tokio::net::TcpStream) -> String {
|
||||
let mut request = Vec::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
let head_end = loop {
|
||||
if let Some(at) = request.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
break at + 4;
|
||||
}
|
||||
let n = socket.read(&mut buf).await.unwrap();
|
||||
assert!(n > 0, "connection closed inside the request head");
|
||||
request.extend_from_slice(&buf[..n]);
|
||||
};
|
||||
let head = String::from_utf8_lossy(&request[..head_end]).to_string();
|
||||
let body_len: usize = head
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse().ok())?
|
||||
})
|
||||
.unwrap_or(0);
|
||||
while request.len() < head_end + body_len {
|
||||
let n = socket.read(&mut buf).await.unwrap();
|
||||
assert!(n > 0, "connection closed inside the request body");
|
||||
request.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
/// An upload carries the CRC32C of its bytes for the volume server to
|
||||
/// check, in the form Go writes it.
|
||||
#[tokio::test]
|
||||
async fn upload_carries_the_crc32c_of_its_bytes() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let head = read_request_head_and_body(&mut socket).await;
|
||||
socket
|
||||
.write_all(
|
||||
b"HTTP/1.1 201 Created\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
head.lines()
|
||||
.find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case(CONTENT_CRC32C_HEADER)
|
||||
.then(|| value.trim().to_string())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
HttpTransport::new()
|
||||
.write(&address, "7,abc", "", "k", Bytes::from_static(b"hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(server.await.unwrap(), content_crc32c(b"hello"));
|
||||
assert_eq!(content_crc32c(b"hello"), "mnG7TA==");
|
||||
}
|
||||
|
||||
/// A write that never reached the server (connection refused) is a plain
|
||||
/// error, not an ambiguous commit.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -187,10 +187,6 @@ func (store *MockFoundationDBStore) KvGet(ctx context.Context, key []byte) ([]by
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (store *MockFoundationDBStore) KvBatchGet(ctx context.Context, keys [][]byte) (map[string][]byte, error) {
|
||||
return filer.KvGetEach(ctx, store.KvGet, keys, 1)
|
||||
}
|
||||
|
||||
func (store *MockFoundationDBStore) KvDelete(ctx context.Context, key []byte) error {
|
||||
delete(store.kvStore, string(key))
|
||||
return nil
|
||||
|
||||
@@ -379,7 +379,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
|
||||
}
|
||||
|
||||
// Create publisher
|
||||
publisher, err := pub_client.NewTopicPublisher(context.Background(), config)
|
||||
publisher, err := pub_client.NewTopicPublisher(config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create publisher: %v", err)
|
||||
}
|
||||
@@ -397,7 +397,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
|
||||
}
|
||||
|
||||
// Publish structured record
|
||||
_, err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
|
||||
err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
|
||||
if err != nil {
|
||||
log.Printf("Error publishing message %d: %v", i+1, err)
|
||||
continue
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
package postgres_flat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"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/seaweedfs/seaweedfs/test/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/store_test"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
accessKey = "pgflat_access_key"
|
||||
secretKey = "pgflat_secret_key"
|
||||
)
|
||||
|
||||
// cluster is a "weed mini" whose filer keeps its metadata in a postgres_flat
|
||||
// store, in a schema of its own.
|
||||
type cluster struct {
|
||||
t *testing.T
|
||||
baseDir string
|
||||
weedBinary string
|
||||
filerAddr string
|
||||
s3Endpoint string
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func startCluster(t *testing.T) *cluster {
|
||||
pg := store_test.NewPostgresTestDatabase(t)
|
||||
weedBinary, err := framework.FindOrBuildWeedBinary()
|
||||
require.NoError(t, err)
|
||||
|
||||
c := &cluster{t: t, baseDir: t.TempDir(), weedBinary: weedBinary}
|
||||
configDir := filepath.Join(c.baseDir, "config")
|
||||
dataDir := filepath.Join(c.baseDir, "data")
|
||||
for _, d := range []string{configDir, dataDir} {
|
||||
require.NoError(t, os.MkdirAll(d, 0o755))
|
||||
}
|
||||
require.NoError(t, os.WriteFile(filepath.Join(configDir, "filer.toml"), []byte(filerToml(pg)), 0o644))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(configDir, "security.toml"), nil, 0o644))
|
||||
s3Config, err := testutil.WriteIAMConfig(configDir, accessKey, secretKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
dsn, _ := pgxutil.BuildDSN(pg)
|
||||
c.db, err = sql.Open("pgx", dsn)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { c.db.Close() })
|
||||
|
||||
ports := testutil.MustFreeMiniPorts(t, []string{"master", "volume", "filer", "s3", "admin"})
|
||||
c.filerAddr = fmt.Sprintf("127.0.0.1:%d", ports[2])
|
||||
c.s3Endpoint = fmt.Sprintf("http://127.0.0.1:%d", ports[3])
|
||||
args := append([]string{
|
||||
"-config_dir=" + configDir,
|
||||
"mini",
|
||||
"-dir=" + dataDir,
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-master.port=" + strconv.Itoa(ports[0]),
|
||||
"-master.peers=none",
|
||||
"-master.volumeSizeLimitMB=32",
|
||||
"-master.telemetry=false",
|
||||
"-volume.port=" + strconv.Itoa(ports[1]),
|
||||
"-volume.max=8",
|
||||
"-filer.port=" + strconv.Itoa(ports[2]),
|
||||
"-s3.port=" + strconv.Itoa(ports[3]),
|
||||
"-s3.config=" + s3Config,
|
||||
"-s3.port.iceberg=0",
|
||||
"-s3.port.lance=0",
|
||||
"-webdav=false",
|
||||
"-admin.ui=false",
|
||||
}, testutil.MiniAdminArgs(ports[4])...)
|
||||
mini := c.start(t, "mini", args...)
|
||||
|
||||
client := c.s3Client()
|
||||
deadline := time.Now().Add(testutil.SeaweedMiniStartupTimeout)
|
||||
for {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
_, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
|
||||
cancel()
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if exited(mini) || time.Now().After(deadline) {
|
||||
t.Fatalf("s3 not ready: %v\n%s", err, c.logTail("mini"))
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func filerToml(pg pgxutil.DSNOptions) string {
|
||||
return fmt.Sprintf(`[postgres_flat]
|
||||
enabled = true
|
||||
hostname = %q
|
||||
port = %d
|
||||
username = %q
|
||||
password = %q
|
||||
database = %q
|
||||
schema = %q
|
||||
sslmode = "disable"
|
||||
`, pg.Hostname, pg.Port, pg.User, pg.Password, pg.Database, pg.Schema)
|
||||
}
|
||||
|
||||
// start runs a weed command until the test ends, logging to <baseDir>/<name>.log.
|
||||
// The returned channel is closed once the command exits.
|
||||
func (c *cluster) start(t *testing.T, name string, args ...string) <-chan struct{} {
|
||||
log, err := os.Create(filepath.Join(c.baseDir, name+".log"))
|
||||
require.NoError(t, err)
|
||||
cmd := exec.Command(c.weedBinary, args...)
|
||||
cmd.Dir = c.baseDir
|
||||
cmd.Stdout = log
|
||||
cmd.Stderr = log
|
||||
require.NoError(t, cmd.Start())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_ = cmd.Wait()
|
||||
close(done)
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
stop(cmd, done)
|
||||
log.Close()
|
||||
if t.Failed() {
|
||||
t.Logf("%s log tail:\n%s", name, c.logTail(name))
|
||||
}
|
||||
})
|
||||
return done
|
||||
}
|
||||
|
||||
func stop(cmd *exec.Cmd, done <-chan struct{}) {
|
||||
if exited(done) {
|
||||
return
|
||||
}
|
||||
_ = cmd.Process.Signal(os.Interrupt)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
func exited(done <-chan struct{}) bool {
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *cluster) logTail(name string) string {
|
||||
data, _ := os.ReadFile(filepath.Join(c.baseDir, name+".log"))
|
||||
if len(data) > 8192 {
|
||||
data = data[len(data)-8192:]
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func (c *cluster) s3Client() *s3.Client {
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion("us-east-1"),
|
||||
config.WithRetryMaxAttempts(1),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
|
||||
)
|
||||
require.NoError(c.t, err)
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(c.s3Endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
// paths returns the path column of a table, in order, under a prefix.
|
||||
func (c *cluster) paths(t *testing.T, table, prefix string) []string {
|
||||
t.Helper()
|
||||
rows, err := c.db.Query(fmt.Sprintf(`SELECT path FROM "%s" WHERE starts_with(path, $1) ORDER BY path`, table), prefix)
|
||||
require.NoError(t, err)
|
||||
defer rows.Close()
|
||||
var paths []string
|
||||
for rows.Next() {
|
||||
var p string
|
||||
require.NoError(t, rows.Scan(&p))
|
||||
paths = append(paths, p)
|
||||
}
|
||||
require.NoError(t, rows.Err())
|
||||
return paths
|
||||
}
|
||||
|
||||
func (c *cluster) tableExists(t *testing.T, table string) bool {
|
||||
t.Helper()
|
||||
var exists bool
|
||||
require.NoError(t, c.db.QueryRow(`SELECT to_regclass(quote_ident($1)) IS NOT NULL`, table).Scan(&exists))
|
||||
return exists
|
||||
}
|
||||
|
||||
func (c *cluster) count(t *testing.T, query string, args ...interface{}) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
require.NoError(t, c.db.QueryRow(query, args...).Scan(&n))
|
||||
return n
|
||||
}
|
||||
|
||||
// eventually retries check until it passes or the timeout ends; the filer
|
||||
// creates and drops bucket tables from its metadata events.
|
||||
func eventually(t *testing.T, what string, check func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for !check() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting until %s", what)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// filerList pages through a directory listing of the filer's HTTP API.
|
||||
func (c *cluster) filerList(t *testing.T, dir string, pageSize int) []string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
last := ""
|
||||
for {
|
||||
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s%s/?limit=%d&lastFileName=%s", c.filerAddr, dir, pageSize, url.QueryEscape(last)), nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
var page struct {
|
||||
Entries []struct{ FullPath string }
|
||||
LastFileName string
|
||||
ShouldDisplayLoadMore bool
|
||||
}
|
||||
err = json.NewDecoder(resp.Body).Decode(&page)
|
||||
resp.Body.Close()
|
||||
require.NoError(t, err)
|
||||
for _, e := range page.Entries {
|
||||
names = append(names, e.FullPath[strings.LastIndex(e.FullPath, "/")+1:])
|
||||
}
|
||||
if !page.ShouldDisplayLoadMore {
|
||||
return names
|
||||
}
|
||||
last = page.LastFileName
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
//go:build linux
|
||||
|
||||
package postgres_flat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// mount mounts the filer root with a metadata cache of its own, so a new
|
||||
// mount reads everything back from the store.
|
||||
func (c *cluster) mount(t *testing.T, name string) string {
|
||||
t.Helper()
|
||||
if _, err := os.Stat("/dev/fuse"); err != nil {
|
||||
t.Skip("no /dev/fuse")
|
||||
}
|
||||
dir := filepath.Join(c.baseDir, name)
|
||||
cacheDir := filepath.Join(c.baseDir, name+"-cache")
|
||||
require.NoError(t, os.MkdirAll(dir, 0o755))
|
||||
require.NoError(t, os.MkdirAll(cacheDir, 0o755))
|
||||
done := c.start(t, name, "mount", "-filer="+c.filerAddr, "-dir="+dir, "-filer.path=/", "-cacheDir="+cacheDir, "-allowOthers=false")
|
||||
t.Cleanup(func() {
|
||||
_ = exec.Command("fusermount3", "-u", dir).Run()
|
||||
_ = exec.Command("fusermount", "-u", dir).Run()
|
||||
})
|
||||
|
||||
var parent syscall.Stat_t
|
||||
require.NoError(t, syscall.Stat(c.baseDir, &parent))
|
||||
probe := filepath.Join(dir, ".probe-"+name)
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for {
|
||||
var st syscall.Stat_t
|
||||
if syscall.Stat(dir, &st) == nil && st.Dev != parent.Dev {
|
||||
if err := os.WriteFile(probe, []byte("probe"), 0o644); err == nil {
|
||||
require.NoError(t, os.Remove(probe))
|
||||
return dir
|
||||
}
|
||||
}
|
||||
if exited(done) || time.Now().After(deadline) {
|
||||
t.Fatalf("mount %s not ready:\n%s", name, c.logTail(name))
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func unmount(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
out, err := exec.Command("fusermount3", "-u", dir).CombinedOutput()
|
||||
if err != nil {
|
||||
out, err = exec.Command("fusermount", "-u", dir).CombinedOutput()
|
||||
}
|
||||
require.NoError(t, err, "unmount %s: %s", dir, out)
|
||||
}
|
||||
|
||||
// tree lists every file under root with its content, and every directory
|
||||
// with a trailing slash.
|
||||
func tree(t *testing.T, root string) map[string]string {
|
||||
t.Helper()
|
||||
got := map[string]string{}
|
||||
require.NoError(t, filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || p == root {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(root, p)
|
||||
switch {
|
||||
case d.IsDir():
|
||||
got[rel+"/"] = ""
|
||||
case d.Type()&fs.ModeSymlink != 0:
|
||||
target, err := os.Readlink(p)
|
||||
got[rel+" -> "+target] = ""
|
||||
return err
|
||||
default:
|
||||
data, err := os.ReadFile(p)
|
||||
got[rel] = string(data)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
return got
|
||||
}
|
||||
|
||||
func TestPosix(t *testing.T) {
|
||||
c := startCluster(t)
|
||||
mnt := c.mount(t, "mount")
|
||||
client := c.s3Client()
|
||||
root := filepath.Join(mnt, "posix")
|
||||
require.NoError(t, os.MkdirAll(root, 0o755))
|
||||
write := func(t *testing.T, rel, body string) {
|
||||
t.Helper()
|
||||
p := filepath.Join(root, rel)
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755))
|
||||
require.NoError(t, os.WriteFile(p, []byte(body), 0o644))
|
||||
}
|
||||
read := func(t *testing.T, rel string) string {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(filepath.Join(root, rel))
|
||||
require.NoError(t, err)
|
||||
return string(data)
|
||||
}
|
||||
kvRows := func(t *testing.T) int { return c.count(t, `SELECT count(*) FROM filemeta_kv`) }
|
||||
|
||||
t.Run("files and directories are rows keyed by their path", func(t *testing.T) {
|
||||
write(t, "a/b/f.txt", "f")
|
||||
write(t, "a/g.txt", "g")
|
||||
require.Equal(t, []string{"/posix", "/posix/a", "/posix/a/b", "/posix/a/b/f.txt", "/posix/a/g.txt"}, c.paths(t, "filemeta", "/posix"))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "a/g.txt"), []byte("g2"), 0o644))
|
||||
require.Equal(t, "g2", read(t, "a/g.txt"))
|
||||
require.NoError(t, os.Chmod(filepath.Join(root, "a/g.txt"), 0o600))
|
||||
st, err := os.Stat(filepath.Join(root, "a/g.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0o600), st.Mode().Perm())
|
||||
})
|
||||
|
||||
t.Run("a directory longer than a listing page", func(t *testing.T) {
|
||||
require.NoError(t, os.Mkdir(filepath.Join(root, "many"), 0o755))
|
||||
var want []string
|
||||
for i := 0; i < filer.PaginationSize+100; i++ {
|
||||
name := fmt.Sprintf("f%05d", i)
|
||||
want = append(want, name)
|
||||
f, err := os.Create(filepath.Join(root, "many", name))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(root, "many"))
|
||||
require.NoError(t, err)
|
||||
var got []string
|
||||
for _, e := range entries {
|
||||
got = append(got, e.Name())
|
||||
}
|
||||
require.Equal(t, want, got)
|
||||
require.Equal(t, want, c.filerList(t, "/posix/many", 100))
|
||||
require.Equal(t, len(want), c.count(t, `SELECT count(*) FROM filemeta WHERE directory = '/posix/many'`))
|
||||
})
|
||||
|
||||
t.Run("rename moves rows", func(t *testing.T) {
|
||||
write(t, "mv/src/one.txt", "one")
|
||||
write(t, "mv/src/sub/two.txt", "two")
|
||||
require.NoError(t, os.Rename(filepath.Join(root, "mv/src/one.txt"), filepath.Join(root, "mv/uno.txt")))
|
||||
require.Equal(t, "one", read(t, "mv/uno.txt"))
|
||||
require.NoError(t, os.Rename(filepath.Join(root, "mv/src"), filepath.Join(root, "mv/dst")))
|
||||
require.Equal(t, "two", read(t, "mv/dst/sub/two.txt"))
|
||||
require.Equal(t, []string{"/posix/mv", "/posix/mv/dst", "/posix/mv/dst/sub", "/posix/mv/dst/sub/two.txt", "/posix/mv/uno.txt"}, c.paths(t, "filemeta", "/posix/mv"))
|
||||
})
|
||||
|
||||
t.Run("hard links keep their record in the key-value table", func(t *testing.T) {
|
||||
before := kvRows(t)
|
||||
write(t, "links/orig.txt", "linked")
|
||||
require.NoError(t, os.Link(filepath.Join(root, "links/orig.txt"), filepath.Join(root, "links/hard.txt")))
|
||||
require.Greater(t, kvRows(t), before)
|
||||
require.Equal(t, "linked", read(t, "links/hard.txt"))
|
||||
st, err := os.Stat(filepath.Join(root, "links/hard.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(2), uint64(st.Sys().(*syscall.Stat_t).Nlink))
|
||||
require.NoError(t, os.Remove(filepath.Join(root, "links/orig.txt")))
|
||||
require.Equal(t, "linked", read(t, "links/hard.txt"))
|
||||
|
||||
require.NoError(t, os.Symlink("hard.txt", filepath.Join(root, "links/soft")))
|
||||
target, err := os.Readlink(filepath.Join(root, "links/soft"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "hard.txt", target)
|
||||
require.Equal(t, "linked", read(t, "links/soft"))
|
||||
})
|
||||
|
||||
t.Run("remove a tree", func(t *testing.T) {
|
||||
write(t, "gone/x/y/z.txt", "z")
|
||||
write(t, "gone/w.txt", "w")
|
||||
write(t, "gone2/kept.txt", "kept")
|
||||
require.NoError(t, os.RemoveAll(filepath.Join(root, "gone")))
|
||||
require.Empty(t, c.paths(t, "filemeta", "/posix/gone/"))
|
||||
require.Equal(t, []string{"/posix/gone2", "/posix/gone2/kept.txt"}, c.paths(t, "filemeta", "/posix/gone"))
|
||||
})
|
||||
|
||||
t.Run("bucket made through the mount", func(t *testing.T) {
|
||||
bucket := "pgflat-posix"
|
||||
bucketDir := filepath.Join(mnt, "buckets", bucket)
|
||||
require.NoError(t, os.Mkdir(bucketDir, 0o755))
|
||||
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(bucketDir, "k"), 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(bucketDir, "k/v.txt"), []byte("from mount"), 0o644))
|
||||
require.Equal(t, []string{"/k", "/k/v.txt"}, c.paths(t, bucket, "/"))
|
||||
|
||||
ctx := context.Background()
|
||||
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String("k/v.txt")})
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(out.Body)
|
||||
out.Body.Close()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "from mount", string(data))
|
||||
|
||||
_, err = client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("k/s3.txt"), Body: strings.NewReader("from s3")})
|
||||
require.NoError(t, err)
|
||||
eventually(t, "the mount sees the S3 object", func() bool {
|
||||
data, err := os.ReadFile(filepath.Join(bucketDir, "k/s3.txt"))
|
||||
return err == nil && string(data) == "from s3"
|
||||
})
|
||||
|
||||
require.NoError(t, os.RemoveAll(bucketDir))
|
||||
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
|
||||
})
|
||||
|
||||
t.Run("a new mount reads the same tree from the store", func(t *testing.T) {
|
||||
write(t, "remount/sub/deep.txt", "deep")
|
||||
require.NoError(t, os.Symlink("sub/deep.txt", filepath.Join(root, "remount/link")))
|
||||
want := tree(t, root)
|
||||
require.Contains(t, want, "remount/sub/deep.txt")
|
||||
require.Contains(t, want, "remount/link -> sub/deep.txt")
|
||||
unmount(t, mnt)
|
||||
fresh := c.mount(t, "remount")
|
||||
got := tree(t, filepath.Join(fresh, "posix"))
|
||||
require.Equal(t, keys(want), keys(got))
|
||||
require.Equal(t, want, got)
|
||||
})
|
||||
}
|
||||
|
||||
func keys(m map[string]string) []string {
|
||||
var ks []string
|
||||
for k := range m {
|
||||
ks = append(ks, k)
|
||||
}
|
||||
sort.Strings(ks)
|
||||
return ks
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package postgres_flat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestS3RecursiveListing lists through a gateway that reads one path range of
|
||||
// the bucket's table per page, and expects the pages S3 returns: the keys under
|
||||
// the prefix and past the marker, in byte order.
|
||||
func TestS3RecursiveListing(t *testing.T) {
|
||||
c := startCluster(t)
|
||||
fast := c.s3Client()
|
||||
ctx := context.Background()
|
||||
bucket := "pgflat-recursive"
|
||||
b := aws.String(bucket)
|
||||
_, err := fast.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: b})
|
||||
require.NoError(t, err)
|
||||
|
||||
keys := []string{"a+b", "a-b/x", "a/x", "a/y/z", "a0", "日本/x", "sp ace/%_!", "z", "m/", "m/c", "m+/c", "mk/", "p", "p/q"}
|
||||
for i := 0; i < 60; i++ {
|
||||
keys = append(keys, fmt.Sprintf("deep/acct-%03d/Contract/rec-%03d/2026/10/doc.pdf", i, i))
|
||||
}
|
||||
for _, k := range keys {
|
||||
_, err := fast.PutObject(ctx, &s3.PutObjectInput{Bucket: b, Key: aws.String(k), Body: strings.NewReader("body of " + k)})
|
||||
require.NoError(t, err, "put %s", k)
|
||||
}
|
||||
_, err = fast.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{Bucket: b, Key: aws.String("up/unfinished")})
|
||||
require.NoError(t, err)
|
||||
|
||||
sorted := append([]string(nil), keys...)
|
||||
sort.Strings(sorted)
|
||||
want := func(prefix, startAfter string, maxKeys int) (pages [][]string) {
|
||||
var page []string
|
||||
for _, k := range sorted {
|
||||
if !strings.HasPrefix(k, prefix) || k <= startAfter {
|
||||
continue
|
||||
}
|
||||
if len(page) == maxKeys {
|
||||
pages, page = append(pages, page), nil
|
||||
}
|
||||
page = append(page, k)
|
||||
}
|
||||
return append(pages, page)
|
||||
}
|
||||
listV2 := func(t *testing.T, client *s3.Client, prefix, startAfter string, maxKeys int32) (pages [][]string) {
|
||||
t.Helper()
|
||||
in := &s3.ListObjectsV2Input{Bucket: b, Prefix: aws.String(prefix), StartAfter: aws.String(startAfter), MaxKeys: aws.Int32(maxKeys)}
|
||||
for {
|
||||
require.Less(t, len(pages), 500, "listing did not terminate")
|
||||
out, err := client.ListObjectsV2(ctx, in)
|
||||
require.NoError(t, err)
|
||||
var page []string
|
||||
for _, o := range out.Contents {
|
||||
page = append(page, aws.ToString(o.Key))
|
||||
}
|
||||
pages = append(pages, page)
|
||||
if !aws.ToBool(out.IsTruncated) {
|
||||
return pages
|
||||
}
|
||||
in.ContinuationToken = out.NextContinuationToken
|
||||
}
|
||||
}
|
||||
listV1 := func(t *testing.T, client *s3.Client, prefix, marker string, maxKeys int32) (keys []string, truncated bool) {
|
||||
t.Helper()
|
||||
out, err := client.ListObjects(ctx, &s3.ListObjectsInput{Bucket: b, Prefix: aws.String(prefix), Marker: aws.String(marker), MaxKeys: aws.Int32(maxKeys)})
|
||||
require.NoError(t, err)
|
||||
for _, o := range out.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
return keys, aws.ToBool(out.IsTruncated)
|
||||
}
|
||||
|
||||
all := listV2(t, fast, "", "", 1000)
|
||||
require.Len(t, all, 1)
|
||||
require.Len(t, all[0], len(keys), "every key once, no upload parts: %v", all[0])
|
||||
|
||||
for _, prefix := range []string{"", "a", "a/", "deep/", "deep/acct-01", "m", "m/", "p", "p/", "日", "sp ace/%_", "up/", "zz"} {
|
||||
for _, maxKeys := range []int32{1, 7, 1000} {
|
||||
require.Equal(t, want(prefix, "", int(maxKeys)), listV2(t, fast, prefix, "", maxKeys), "prefix %q max %d", prefix, maxKeys)
|
||||
}
|
||||
}
|
||||
for _, marker := range []string{"a", "a+", "a+b", "a/", "a/y", "m", "m+", "m/", "mk", "p", "p/", "deep/acct-010", "日本"} {
|
||||
for _, prefix := range []string{"", "m", "deep/"} {
|
||||
wantPages := want(prefix, marker, 3)
|
||||
require.Equal(t, wantPages, listV2(t, fast, prefix, marker, 3), "prefix %q start-after %q", prefix, marker)
|
||||
gotKeys, gotTruncated := listV1(t, fast, prefix, marker, 3)
|
||||
require.Equal(t, wantPages[0], gotKeys, "prefix %q marker %q", prefix, marker)
|
||||
require.Equal(t, len(wantPages) > 1, gotTruncated, "prefix %q marker %q", prefix, marker)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a page reads the bucket table a few times, not once per directory", func(t *testing.T) {
|
||||
// A backend reports its table statistics when idle, at least every 10s.
|
||||
scans := func() int {
|
||||
time.Sleep(11 * time.Second)
|
||||
_, err := c.db.Exec(`SELECT pg_stat_clear_snapshot()`)
|
||||
require.NoError(t, err)
|
||||
return c.count(t, `SELECT coalesce(idx_scan, 0) + coalesce(seq_scan, 0) FROM pg_stat_user_tables WHERE schemaname = current_schema() AND relname = $1`, bucket)
|
||||
}
|
||||
before := scans()
|
||||
require.Len(t, listV2(t, fast, "deep/", "", 1000)[0], 60)
|
||||
after := scans()
|
||||
t.Logf("60 keys in 300 directories under deep/: %d scans", after-before)
|
||||
require.LessOrEqual(t, after-before, 5)
|
||||
})
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
package postgres_flat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestS3(t *testing.T) {
|
||||
c := startCluster(t)
|
||||
client := c.s3Client()
|
||||
ctx := context.Background()
|
||||
bucket := "pgflat-s3"
|
||||
|
||||
put := func(t *testing.T, bkt, key, body string) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bkt), Key: aws.String(key), Body: strings.NewReader(body)})
|
||||
require.NoError(t, err, "put %s", key)
|
||||
}
|
||||
get := func(t *testing.T, bkt, key string) string {
|
||||
t.Helper()
|
||||
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bkt), Key: aws.String(key)})
|
||||
require.NoError(t, err, "get %s", key)
|
||||
defer out.Body.Close()
|
||||
data, err := io.ReadAll(out.Body)
|
||||
require.NoError(t, err)
|
||||
return string(data)
|
||||
}
|
||||
listAll := func(t *testing.T, in s3.ListObjectsV2Input) (keys, prefixes []string) {
|
||||
t.Helper()
|
||||
in.Bucket = aws.String(bucket)
|
||||
p := s3.NewListObjectsV2Paginator(client, &in)
|
||||
for p.HasMorePages() {
|
||||
page, err := p.NextPage(ctx)
|
||||
require.NoError(t, err)
|
||||
for _, o := range page.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
for _, cp := range page.CommonPrefixes {
|
||||
prefixes = append(prefixes, aws.ToString(cp.Prefix))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)})
|
||||
require.NoError(t, err)
|
||||
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
|
||||
|
||||
deep := strings.Repeat(strings.Repeat("k", 200)+"/", 5) + "deep.txt"
|
||||
keys := []string{
|
||||
"top.txt",
|
||||
"a/x.txt",
|
||||
"a/b/c.txt",
|
||||
"a/b/d.txt",
|
||||
"a+b=c.txt",
|
||||
"dir with space/f %_!.txt",
|
||||
"日本/語.txt",
|
||||
deep,
|
||||
}
|
||||
sorted := append([]string(nil), keys...)
|
||||
sort.Strings(sorted)
|
||||
for _, k := range keys {
|
||||
put(t, bucket, k, "body of "+k)
|
||||
}
|
||||
|
||||
vb := "pgflat-versioned"
|
||||
_, err = client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(vb)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(vb),
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("objects are rows keyed by their key", func(t *testing.T) {
|
||||
for _, k := range keys {
|
||||
require.Equal(t, "body of "+k, get(t, bucket, k))
|
||||
}
|
||||
rows := c.paths(t, bucket, "/")
|
||||
for _, k := range keys {
|
||||
require.Contains(t, rows, "/"+k)
|
||||
}
|
||||
require.Contains(t, rows, "/a/b", "parent directories are rows too")
|
||||
require.Empty(t, c.paths(t, "filemeta", "/buckets/"+bucket+"/"), "bucket entries stay out of the default table")
|
||||
})
|
||||
|
||||
t.Run("list", func(t *testing.T) {
|
||||
got, _ := listAll(t, s3.ListObjectsV2Input{})
|
||||
require.Equal(t, sorted, got, "recursive listing in key order")
|
||||
got, _ = listAll(t, s3.ListObjectsV2Input{MaxKeys: aws.Int32(2)})
|
||||
require.Equal(t, sorted, got, "recursive listing in pages of two")
|
||||
|
||||
require.Equal(t, []string{"a", "a+b=c.txt", "dir with space", deep[:200], "top.txt", "日本"}, c.filerList(t, "/buckets/"+bucket, 2))
|
||||
|
||||
got, prefixes := listAll(t, s3.ListObjectsV2Input{Delimiter: aws.String("/")})
|
||||
require.Equal(t, []string{"a+b=c.txt", "top.txt"}, got)
|
||||
require.Equal(t, []string{"a/", "dir with space/", deep[:201], "日本/"}, prefixes)
|
||||
|
||||
got, prefixes = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/"), Delimiter: aws.String("/"), MaxKeys: aws.Int32(1)})
|
||||
require.Equal(t, []string{"a/x.txt"}, got)
|
||||
require.Equal(t, []string{"a/b/"}, prefixes)
|
||||
|
||||
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/b/")})
|
||||
require.Equal(t, []string{"a/b/c.txt", "a/b/d.txt"}, got)
|
||||
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/b/d")})
|
||||
require.Equal(t, []string{"a/b/d.txt"}, got)
|
||||
got, _ = listAll(t, s3.ListObjectsV2Input{StartAfter: aws.String("a/b/c.txt")})
|
||||
require.Equal(t, sorted[sort.SearchStrings(sorted, "a/b/c.txt")+1:], got)
|
||||
got, _ = listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("dir with space/f %_")})
|
||||
require.Equal(t, []string{"dir with space/f %_!.txt"}, got)
|
||||
})
|
||||
|
||||
t.Run("overwrite, copy and delete", func(t *testing.T) {
|
||||
put(t, bucket, "a/x.txt", "replaced")
|
||||
require.Equal(t, "replaced", get(t, bucket, "a/x.txt"))
|
||||
require.Equal(t, 1, c.count(t, `SELECT count(*) FROM "`+bucket+`" WHERE path = '/a/x.txt'`))
|
||||
|
||||
_, err := client.CopyObject(ctx, &s3.CopyObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt"), CopySource: aws.String(bucket + "/a/x.txt")})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "replaced", get(t, bucket, "copied/x.txt"))
|
||||
require.Contains(t, c.paths(t, bucket, "/copied/"), "/copied/x.txt")
|
||||
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt")})
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, c.paths(t, bucket, "/copied/"), "/copied/x.txt")
|
||||
_, err = client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String("copied/x.txt")})
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = client.DeleteObjects(ctx, &s3.DeleteObjectsInput{Bucket: aws.String(bucket), Delete: &types.Delete{Objects: []types.ObjectIdentifier{
|
||||
{Key: aws.String("a/b/c.txt")}, {Key: aws.String("a/b/d.txt")},
|
||||
}}})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, c.paths(t, bucket, "/a/b/"))
|
||||
got, _ := listAll(t, s3.ListObjectsV2Input{Prefix: aws.String("a/")})
|
||||
require.Equal(t, []string{"a/x.txt"}, got)
|
||||
})
|
||||
|
||||
t.Run("multipart upload", func(t *testing.T) {
|
||||
key := "multi/part.bin"
|
||||
created, err := client.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, c.paths(t, bucket, "/.uploads/"), "the upload lives in the bucket table")
|
||||
parts := [][]byte{bytes.Repeat([]byte{'1'}, 5<<20), []byte("tail")}
|
||||
var completed []types.CompletedPart
|
||||
for i, p := range parts {
|
||||
out, err := client.UploadPart(ctx, &s3.UploadPartInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int32(int32(i + 1)), Body: bytes.NewReader(p)})
|
||||
require.NoError(t, err)
|
||||
completed = append(completed, types.CompletedPart{ETag: out.ETag, PartNumber: aws.Int32(int32(i + 1))})
|
||||
}
|
||||
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &types.CompletedMultipartUpload{Parts: completed}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(parts[0])+string(parts[1]), get(t, bucket, key))
|
||||
require.Contains(t, c.paths(t, bucket, "/multi/"), "/multi/part.bin")
|
||||
eventually(t, "the upload folder is gone", func() bool {
|
||||
return len(c.paths(t, bucket, "/.uploads/"+aws.ToString(created.UploadId))) == 0
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("versioning", func(t *testing.T) {
|
||||
first, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(vb), Key: aws.String("doc/v.txt"), Body: strings.NewReader("one")})
|
||||
require.NoError(t, err)
|
||||
put(t, vb, "doc/v.txt", "two")
|
||||
require.Equal(t, "two", get(t, vb, "doc/v.txt"))
|
||||
|
||||
out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(vb), Key: aws.String("doc/v.txt"), VersionId: first.VersionId})
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(out.Body)
|
||||
out.Body.Close()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "one", string(data))
|
||||
|
||||
versions, err := client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(vb)})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions.Versions, 2)
|
||||
require.True(t, c.tableExists(t, vb))
|
||||
})
|
||||
|
||||
t.Run("delete bucket drops its table", func(t *testing.T) {
|
||||
keys, _ := listAll(t, s3.ListObjectsV2Input{})
|
||||
for _, k := range keys {
|
||||
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(k)})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
_, err := client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
|
||||
require.NoError(t, err)
|
||||
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
|
||||
require.True(t, c.tableExists(t, vb), "other buckets keep their tables")
|
||||
})
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
package postgres_flat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestS3Versioning(t *testing.T) {
|
||||
c := startCluster(t)
|
||||
client := c.s3Client()
|
||||
ctx := context.Background()
|
||||
bucket := "pgflat-versioned"
|
||||
b := aws.String(bucket)
|
||||
|
||||
put := func(t *testing.T, key, body string) string {
|
||||
t.Helper()
|
||||
out, err := client.PutObject(ctx, &s3.PutObjectInput{Bucket: b, Key: aws.String(key), Body: strings.NewReader(body)})
|
||||
require.NoError(t, err, "put %s", key)
|
||||
return aws.ToString(out.VersionId)
|
||||
}
|
||||
get := func(t *testing.T, key, versionId string) (string, error) {
|
||||
t.Helper()
|
||||
in := &s3.GetObjectInput{Bucket: b, Key: aws.String(key)}
|
||||
if versionId != "" {
|
||||
in.VersionId = aws.String(versionId)
|
||||
}
|
||||
out, err := client.GetObject(ctx, in)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer out.Body.Close()
|
||||
data, err := io.ReadAll(out.Body)
|
||||
require.NoError(t, err)
|
||||
return string(data), nil
|
||||
}
|
||||
mustGet := func(t *testing.T, key, versionId string) string {
|
||||
t.Helper()
|
||||
body, err := get(t, key, versionId)
|
||||
require.NoError(t, err, "get %s %s", key, versionId)
|
||||
return body
|
||||
}
|
||||
type version struct {
|
||||
key, id string
|
||||
latest bool
|
||||
marker bool
|
||||
}
|
||||
listVersions := func(t *testing.T, prefix string, maxKeys int32) []version {
|
||||
t.Helper()
|
||||
in := &s3.ListObjectVersionsInput{Bucket: b, Prefix: aws.String(prefix)}
|
||||
if maxKeys > 0 {
|
||||
in.MaxKeys = aws.Int32(maxKeys)
|
||||
}
|
||||
var all []version
|
||||
for {
|
||||
out, err := client.ListObjectVersions(ctx, in)
|
||||
require.NoError(t, err)
|
||||
for _, v := range out.Versions {
|
||||
all = append(all, version{aws.ToString(v.Key), aws.ToString(v.VersionId), aws.ToBool(v.IsLatest), false})
|
||||
}
|
||||
for _, m := range out.DeleteMarkers {
|
||||
all = append(all, version{aws.ToString(m.Key), aws.ToString(m.VersionId), aws.ToBool(m.IsLatest), true})
|
||||
}
|
||||
if !aws.ToBool(out.IsTruncated) {
|
||||
return all
|
||||
}
|
||||
in.KeyMarker, in.VersionIdMarker = out.NextKeyMarker, out.NextVersionIdMarker
|
||||
}
|
||||
}
|
||||
listKeys := func(t *testing.T, delimiter string) (keys, prefixes []string) {
|
||||
t.Helper()
|
||||
in := &s3.ListObjectsV2Input{Bucket: b}
|
||||
if delimiter != "" {
|
||||
in.Delimiter = aws.String(delimiter)
|
||||
}
|
||||
out, err := client.ListObjectsV2(ctx, in)
|
||||
require.NoError(t, err)
|
||||
for _, o := range out.Contents {
|
||||
keys = append(keys, aws.ToString(o.Key))
|
||||
}
|
||||
for _, p := range out.CommonPrefixes {
|
||||
prefixes = append(prefixes, aws.ToString(p.Prefix))
|
||||
}
|
||||
return
|
||||
}
|
||||
notFound := func(t *testing.T, key, versionId string) {
|
||||
t.Helper()
|
||||
_, err := get(t, key, versionId)
|
||||
var re *awshttp.ResponseError
|
||||
require.ErrorAs(t, err, &re, "get %s %s", key, versionId)
|
||||
require.Equal(t, http.StatusNotFound, re.HTTPStatusCode(), "get %s %s", key, versionId)
|
||||
}
|
||||
|
||||
_, err := client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: b})
|
||||
require.NoError(t, err)
|
||||
eventually(t, "the bucket has a table", func() bool { return c.tableExists(t, bucket) })
|
||||
_, err = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: b,
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}})
|
||||
require.NoError(t, err)
|
||||
|
||||
var docIds, topIds []string
|
||||
for i := 1; i <= 3; i++ {
|
||||
docIds = append(docIds, put(t, "doc/v.txt", "doc "+string(rune('0'+i))))
|
||||
}
|
||||
for i := 1; i <= 2; i++ {
|
||||
topIds = append(topIds, put(t, "top.txt", "top "+string(rune('0'+i))))
|
||||
}
|
||||
|
||||
t.Run("each version is a row under the key's .versions folder", func(t *testing.T) {
|
||||
rows := c.paths(t, bucket, "/")
|
||||
for _, id := range docIds {
|
||||
require.NotEmpty(t, id)
|
||||
require.Contains(t, rows, "/doc/v.txt.versions/v_"+id)
|
||||
}
|
||||
for _, id := range topIds {
|
||||
require.Contains(t, rows, "/top.txt.versions/v_"+id)
|
||||
}
|
||||
require.Equal(t, "doc 3", mustGet(t, "doc/v.txt", ""))
|
||||
for i, id := range docIds {
|
||||
require.Equal(t, "doc "+string(rune('1'+i)), mustGet(t, "doc/v.txt", id))
|
||||
}
|
||||
require.Empty(t, c.paths(t, "filemeta", "/buckets/"+bucket+"/"), "versions stay out of the default table")
|
||||
})
|
||||
|
||||
t.Run("listings", func(t *testing.T) {
|
||||
all := listVersions(t, "", 0)
|
||||
require.Equal(t, []version{
|
||||
{"doc/v.txt", docIds[2], true, false}, {"doc/v.txt", docIds[1], false, false}, {"doc/v.txt", docIds[0], false, false},
|
||||
{"top.txt", topIds[1], true, false}, {"top.txt", topIds[0], false, false},
|
||||
}, all)
|
||||
require.Equal(t, all, listVersions(t, "", 1), "one version a page")
|
||||
require.Equal(t, all[:3], listVersions(t, "doc/", 0))
|
||||
|
||||
keys, _ := listKeys(t, "")
|
||||
require.Equal(t, []string{"doc/v.txt", "top.txt"}, keys, ".versions folders are not keys")
|
||||
keys, prefixes := listKeys(t, "/")
|
||||
require.Equal(t, []string{"top.txt"}, keys)
|
||||
require.Equal(t, []string{"doc/"}, prefixes)
|
||||
})
|
||||
|
||||
t.Run("a delete marker hides the key until it is deleted", func(t *testing.T) {
|
||||
out, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt")})
|
||||
require.NoError(t, err)
|
||||
require.True(t, aws.ToBool(out.DeleteMarker))
|
||||
markerId := aws.ToString(out.VersionId)
|
||||
require.Contains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+markerId)
|
||||
|
||||
notFound(t, "doc/v.txt", "")
|
||||
require.Equal(t, "doc 2", mustGet(t, "doc/v.txt", docIds[1]))
|
||||
keys, _ := listKeys(t, "")
|
||||
require.Equal(t, []string{"top.txt"}, keys)
|
||||
require.Equal(t, version{"doc/v.txt", markerId, true, true}, listVersions(t, "doc/", 0)[3])
|
||||
|
||||
_, err = client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt"), VersionId: aws.String(markerId)})
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+markerId)
|
||||
require.Equal(t, "doc 3", mustGet(t, "doc/v.txt", ""))
|
||||
})
|
||||
|
||||
t.Run("deleting the latest version promotes the one before", func(t *testing.T) {
|
||||
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String("doc/v.txt"), VersionId: aws.String(docIds[2])})
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, c.paths(t, bucket, "/doc/v.txt.versions/"), "/doc/v.txt.versions/v_"+docIds[2])
|
||||
notFound(t, "doc/v.txt", docIds[2])
|
||||
require.Equal(t, "doc 2", mustGet(t, "doc/v.txt", ""))
|
||||
require.Equal(t, []version{{"doc/v.txt", docIds[1], true, false}, {"doc/v.txt", docIds[0], false, false}}, listVersions(t, "doc/", 0))
|
||||
})
|
||||
|
||||
t.Run("suspended versioning writes the null version", func(t *testing.T) {
|
||||
_, err := client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: b,
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusSuspended}})
|
||||
require.NoError(t, err)
|
||||
put(t, "top.txt", "top null")
|
||||
put(t, "top.txt", "top null again")
|
||||
require.Equal(t, "top null again", mustGet(t, "top.txt", ""))
|
||||
require.Equal(t, "top null again", mustGet(t, "top.txt", "null"))
|
||||
require.Equal(t, "top 1", mustGet(t, "top.txt", topIds[0]))
|
||||
require.ElementsMatch(t, []version{{"top.txt", "null", true, false}, {"top.txt", topIds[1], false, false}, {"top.txt", topIds[0], false, false}},
|
||||
listVersions(t, "top", 0))
|
||||
})
|
||||
|
||||
t.Run("deleting every version and the bucket drops its table", func(t *testing.T) {
|
||||
for _, v := range listVersions(t, "", 0) {
|
||||
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: b, Key: aws.String(v.key), VersionId: aws.String(v.id)})
|
||||
require.NoError(t, err, "delete %s %s", v.key, v.id)
|
||||
}
|
||||
require.Empty(t, listVersions(t, "", 0))
|
||||
_, err := client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: b})
|
||||
require.NoError(t, err)
|
||||
eventually(t, "the bucket table is dropped", func() bool { return !c.tableExists(t, bucket) })
|
||||
})
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Checks what strict FIPS mode refuses, in the Go components
|
||||
# (GODEBUG=fips140=only) and the Rust volume server (WEED_FIPS_MODE=strict).
|
||||
# Go's crypto/hmac refuses keys shorter than 112 bits (14 bytes) in that mode,
|
||||
# so a component must refuse such a key at startup instead of failing (or
|
||||
# panicking) on the first request that needs it.
|
||||
#
|
||||
# master, filer, volume (Go), volume (Rust): started alone with a 10-byte
|
||||
# jwt.signing.key; each must exit non-zero within 20 s naming the mode.
|
||||
# s3: a fips140=only cluster with valid JWT keys and an identity whose
|
||||
# 8-character secret makes a SigV4 signing key under 14 bytes; a request
|
||||
# signed with it must get an S3 error answer, not a dropped connection.
|
||||
#
|
||||
# Prints one line per component and exits non-zero if any check fails.
|
||||
# WEED, WEED_VOLUME, WORK_DIR binaries and scratch dir
|
||||
set -uo pipefail
|
||||
|
||||
WEED=${WEED:-weed}
|
||||
WEED_VOLUME=${WEED_VOLUME:-weed-volume}
|
||||
WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-negative-config}
|
||||
export GODEBUG=fips140=only WEED_FIPS_MODE=strict
|
||||
|
||||
rm -rf "$WORK_DIR"
|
||||
mkdir -p "$WORK_DIR/short" "$WORK_DIR/valid"
|
||||
printf '[jwt.signing]\nkey = "0123456789"\n' > "$WORK_DIR/short/security.toml"
|
||||
printf '[jwt.signing]\nkey = "%s"\n' "$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')" \
|
||||
> "$WORK_DIR/valid/security.toml"
|
||||
failures=0
|
||||
|
||||
# expect_refusal starts a component with the short key and reports whether it
|
||||
# exited non-zero within 20 s naming the mode in its log: fips140=only for Go,
|
||||
# fips.mode strict for Rust.
|
||||
expect_refusal() {
|
||||
local name=$1; shift
|
||||
local log="$WORK_DIR/$name.log"
|
||||
(cd "$WORK_DIR/short" && exec "$@") > "$log" 2>&1 &
|
||||
local pid=$! status=
|
||||
for _ in $(seq 1 20); do
|
||||
if ! kill -0 "$pid" 2>/dev/null; then wait "$pid"; status=$?; break; fi
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$status" ]; then
|
||||
kill -KILL "$pid" 2>/dev/null; wait "$pid" 2>/dev/null
|
||||
echo "FAIL $name: still running after 20 s with a 10-byte jwt.signing.key"
|
||||
failures=$((failures + 1))
|
||||
elif [ "$status" -ne 0 ] && grep -q -E 'fips140=only|fips\.mode strict' "$log"; then
|
||||
echo "ok $name: refused at startup (exit $status)"
|
||||
else
|
||||
echo "FAIL $name: exited $status without naming the FIPS mode; log tail:"
|
||||
tail -5 "$log" | sed 's/^/ /'
|
||||
failures=$((failures + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
mkdir -p "$WORK_DIR/m" "$WORK_DIR/f" "$WORK_DIR/vg" "$WORK_DIR/vr"
|
||||
expect_refusal master "$WEED" master -port=19333 -mdir="$WORK_DIR/m" -peers=none
|
||||
expect_refusal filer "$WEED" filer -master=127.0.0.1:19333 -port=18888 -defaultStoreDir="$WORK_DIR/f"
|
||||
expect_refusal volume-go "$WEED" volume -master=127.0.0.1:19333 -port=18080 -dir="$WORK_DIR/vg"
|
||||
expect_refusal volume-rust "$WEED_VOLUME" --master 127.0.0.1:19333 --port 18081 --port.grpc 28081 \
|
||||
--dir "$WORK_DIR/vr" --securityFile "$WORK_DIR/short/security.toml"
|
||||
|
||||
cat > "$WORK_DIR/valid/s3.json" <<'EOF'
|
||||
{"identities":[{"name":"short","credentials":[{"accessKey":"shortsecretkey01","secretKey":"abcd1234"}],"actions":["Admin"]}]}
|
||||
EOF
|
||||
mkdir -p "$WORK_DIR/s"
|
||||
(cd "$WORK_DIR/valid" && exec "$WEED" server -filer -s3 -ip=127.0.0.1 -dir="$WORK_DIR/s" \
|
||||
-master.port=29333 -volume.port=28080 -filer.port=28888 -s3.port=28000 -master.peers=none \
|
||||
-s3.config="$WORK_DIR/valid/s3.json") > "$WORK_DIR/s3.log" 2>&1 &
|
||||
server_pid=$!
|
||||
for _ in $(seq 1 60); do curl -s -o /dev/null http://127.0.0.1:28000/ && break; sleep 1; done
|
||||
code=$(curl -s -o "$WORK_DIR/s3.body" -w '%{http_code}' --aws-sigv4 "aws:amz:us-east-1:s3" \
|
||||
--user shortsecretkey01:abcd1234 http://127.0.0.1:28000/)
|
||||
curl_status=$?
|
||||
if [ "$curl_status" -eq 0 ] && [ "${code:0:1}" = 4 ]; then
|
||||
echo "ok s3: an 8-character secret gets HTTP $code ($(grep -o '<Code>[^<]*' "$WORK_DIR/s3.body" | cut -c7-))"
|
||||
else
|
||||
echo "FAIL s3: an 8-character secret got curl exit $curl_status, HTTP $code (a dropped connection is a panic in the request)"
|
||||
failures=$((failures + 1))
|
||||
fi
|
||||
kill -TERM "$server_pid" 2>/dev/null; wait "$server_pid" 2>/dev/null
|
||||
|
||||
exit $((failures > 0))
|
||||
@@ -4,9 +4,7 @@
|
||||
# $WORK_DIR/pids, so `xargs kill < "$WORK_DIR/pids"` stops the cell.
|
||||
#
|
||||
# DIGEST_MODE md5 (GODEBUG=fips140=off), sha256 (fips140=on with the
|
||||
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only
|
||||
# and WEED_FIPS_MODE=strict, which the Rust volume server
|
||||
# takes its mode from and the Go processes check)
|
||||
# filer's -digest=sha256) or fips140only (GODEBUG=fips140=only)
|
||||
# VOLUME_SERVER go (weed server's own volume server) or rust (weed-volume)
|
||||
# WEED, WEED_VOLUME, WORK_DIR, S3_CONFIG binaries, scratch dir, identities
|
||||
#
|
||||
@@ -24,7 +22,7 @@ WORK_DIR=${WORK_DIR:-/tmp/seaweedfs-digest-matrix}
|
||||
case "$DIGEST_MODE" in
|
||||
md5) export GODEBUG=fips140=off; digest_flag=() ;;
|
||||
sha256) export GODEBUG=fips140=on; digest_flag=(-filer.digest=sha256) ;;
|
||||
fips140only) export GODEBUG=fips140=only WEED_FIPS_MODE=strict; digest_flag=() ;;
|
||||
fips140only) export GODEBUG=fips140=only; digest_flag=() ;;
|
||||
*) echo "unknown DIGEST_MODE $DIGEST_MODE" >&2; exit 2 ;;
|
||||
esac
|
||||
case "$VOLUME_SERVER" in
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
v2aws "github.com/aws/aws-sdk-go-v2/aws"
|
||||
v2credentials "github.com/aws/aws-sdk-go-v2/credentials"
|
||||
v2s3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"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/aws/smithy-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func s3ErrorCode(err error) string {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.ErrorCode()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestS3BucketDefaultStorageClass(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
ctx := context.Background()
|
||||
client := newS3V2Client(cluster)
|
||||
bucket := createTestBucket(t, cluster, "test-default-class-")
|
||||
otherBucket := createTestBucket(t, cluster, "test-default-class-src-")
|
||||
|
||||
getDefault := func(t *testing.T) types.BucketDefaultStorageClass {
|
||||
t.Helper()
|
||||
out, err := client.GetBucketDefaultStorageClass(ctx, &v2s3.GetBucketDefaultStorageClassInput{Bucket: v2aws.String(bucket)})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.DefaultStorageClassConfiguration)
|
||||
return out.DefaultStorageClassConfiguration.DefaultStorageClass
|
||||
}
|
||||
putDefault := func(sc types.BucketDefaultStorageClass) error {
|
||||
_, err := client.PutBucketDefaultStorageClass(ctx, &v2s3.PutBucketDefaultStorageClassInput{
|
||||
Bucket: v2aws.String(bucket),
|
||||
DefaultStorageClassConfiguration: &types.DefaultStorageClassConfiguration{DefaultStorageClass: sc},
|
||||
})
|
||||
return err
|
||||
}
|
||||
put := func(t *testing.T, b, key string, sc types.StorageClass) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &v2s3.PutObjectInput{Bucket: v2aws.String(b), Key: v2aws.String(key), Body: strings.NewReader("data"), StorageClass: sc})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
classOf := func(t *testing.T, key string) types.StorageClass {
|
||||
t.Helper()
|
||||
out, err := client.HeadObject(ctx, &v2s3.HeadObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
return out.StorageClass
|
||||
}
|
||||
|
||||
t.Run("unset default reads STANDARD", func(t *testing.T) {
|
||||
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
|
||||
})
|
||||
|
||||
put(t, bucket, "before.txt", "")
|
||||
|
||||
t.Run("unsupported class is rejected", func(t *testing.T) {
|
||||
err := putDefault("GLACIER")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, "InvalidStorageClass", s3ErrorCode(err))
|
||||
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
|
||||
})
|
||||
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
|
||||
|
||||
t.Run("default is stored in the bucket entry", func(t *testing.T) {
|
||||
assert.Equal(t, types.BucketDefaultStorageClassIntelligentTiering, getDefault(t))
|
||||
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/buckets/%s?metadata=true", cluster.filerPort, bucket))
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
var entry struct{ Extended map[string][]byte }
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&entry))
|
||||
assert.Equal(t, "INTELLIGENT_TIERING", string(entry.Extended["Seaweed-X-Amz-Default-Storage-Class"]))
|
||||
})
|
||||
|
||||
t.Run("put without a class takes the default", func(t *testing.T) {
|
||||
put(t, bucket, "plain.txt", "")
|
||||
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "plain.txt"))
|
||||
})
|
||||
|
||||
t.Run("explicit class wins", func(t *testing.T) {
|
||||
put(t, bucket, "ia.txt", types.StorageClassStandardIa)
|
||||
assert.Equal(t, types.StorageClassStandardIa, classOf(t, "ia.txt"))
|
||||
put(t, bucket, "standard.txt", types.StorageClassStandard)
|
||||
assert.Equal(t, types.StorageClassStandard, classOf(t, "standard.txt"))
|
||||
})
|
||||
|
||||
t.Run("multipart upload keeps the class from initiation", func(t *testing.T) {
|
||||
created, err := client.CreateMultipartUpload(ctx, &v2s3.CreateMultipartUploadInput{Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin")})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
|
||||
part, err := client.UploadPart(ctx, &v2s3.UploadPartInput{
|
||||
Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin"), UploadId: created.UploadId,
|
||||
PartNumber: v2aws.Int32(1), Body: strings.NewReader("only part"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = client.CompleteMultipartUpload(ctx, &v2s3.CompleteMultipartUploadInput{
|
||||
Bucket: v2aws.String(bucket), Key: v2aws.String("mpu.bin"), UploadId: created.UploadId,
|
||||
MultipartUpload: &types.CompletedMultipartUpload{Parts: []types.CompletedPart{{PartNumber: v2aws.Int32(1), ETag: part.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
|
||||
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "mpu.bin"))
|
||||
})
|
||||
|
||||
t.Run("copy takes the destination default unless it names a class", func(t *testing.T) {
|
||||
put(t, otherBucket, "src.txt", types.StorageClassStandardIa)
|
||||
source := v2aws.String(otherBucket + "/src.txt")
|
||||
_, err := client.CopyObject(ctx, &v2s3.CopyObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String("copied.txt"), CopySource: source})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "copied.txt"))
|
||||
_, err = client.CopyObject(ctx, &v2s3.CopyObjectInput{Bucket: v2aws.String(bucket), Key: v2aws.String("copied-ia.txt"), CopySource: source, StorageClass: types.StorageClassStandardIa})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, types.StorageClassStandardIa, classOf(t, "copied-ia.txt"))
|
||||
})
|
||||
|
||||
t.Run("changing the default leaves existing objects alone", func(t *testing.T) {
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassIntelligentTiering))
|
||||
put(t, bucket, "tiered.txt", "")
|
||||
assert.Empty(t, classOf(t, "before.txt"))
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
|
||||
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
|
||||
assert.Equal(t, types.StorageClassIntelligentTiering, classOf(t, "tiered.txt"))
|
||||
put(t, bucket, "after.txt", "")
|
||||
assert.Empty(t, classOf(t, "after.txt"))
|
||||
})
|
||||
|
||||
t.Run("each API needs its own grant", func(t *testing.T) {
|
||||
require.NoError(t, putDefault(types.BucketDefaultStorageClassStandard))
|
||||
sess, err := session.NewSession(cluster.s3Client.Config.Copy())
|
||||
require.NoError(t, err)
|
||||
iamClient := iam.New(sess)
|
||||
userName := "default-class-user"
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
userClient := v2s3.New(client.Options(), func(o *v2s3.Options) {
|
||||
o.Credentials = v2credentials.NewStaticCredentialsProvider(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
|
||||
})
|
||||
attach := func(name, action string) {
|
||||
doc := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s","Resource":"arn:aws:s3:::%s"}]}`, action, bucket)
|
||||
created, err := iamClient.CreatePolicy(&iam.CreatePolicyInput{PolicyName: aws.String(name), PolicyDocument: aws.String(doc)})
|
||||
require.NoError(t, err)
|
||||
_, err = iamClient.AttachUserPolicy(&iam.AttachUserPolicyInput{UserName: aws.String(userName), PolicyArn: created.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
userPut := func() error {
|
||||
_, err := userClient.PutBucketDefaultStorageClass(ctx, &v2s3.PutBucketDefaultStorageClassInput{
|
||||
Bucket: v2aws.String(bucket),
|
||||
DefaultStorageClassConfiguration: &types.DefaultStorageClassConfiguration{DefaultStorageClass: types.BucketDefaultStorageClassIntelligentTiering},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
attach("default-class-get", "s3:GetBucketDefaultStorageClass")
|
||||
require.Eventually(t, func() bool {
|
||||
_, err := userClient.GetBucketDefaultStorageClass(ctx, &v2s3.GetBucketDefaultStorageClassInput{Bucket: v2aws.String(bucket)})
|
||||
return err == nil
|
||||
}, 10*time.Second, 200*time.Millisecond)
|
||||
err = userPut()
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, "AccessDenied", s3ErrorCode(err))
|
||||
assert.Equal(t, types.BucketDefaultStorageClassStandard, getDefault(t))
|
||||
|
||||
attach("default-class-put", "s3:PutBucketDefaultStorageClass")
|
||||
require.Eventually(t, func() bool { return userPut() == nil }, 10*time.Second, 200*time.Millisecond)
|
||||
assert.Equal(t, types.BucketDefaultStorageClassIntelligentTiering, getDefault(t))
|
||||
})
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
"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"
|
||||
)
|
||||
|
||||
// getPart issues GetPart, which the SDK this suite pins predates, as a signed
|
||||
// raw request.
|
||||
func getPart(t *testing.T, cluster *TestCluster, creds *credentials.Credentials, bucket, key, uploadID string, partNumber int, header http.Header) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
query := url.Values{}
|
||||
query.Set("part", "")
|
||||
query.Set("partNumber", fmt.Sprint(partNumber))
|
||||
query.Set("uploadId", uploadID)
|
||||
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s?%s", cluster.s3Endpoint, bucket, key, query.Encode()), nil)
|
||||
require.NoError(t, err)
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
_, err = v4.NewSigner(creds).Sign(req, nil, "s3", testRegion, time.Now())
|
||||
require.NoError(t, err)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp, body
|
||||
}
|
||||
|
||||
func errorCode(t *testing.T, body []byte) string {
|
||||
t.Helper()
|
||||
var e struct{ Code string }
|
||||
require.NoError(t, xml.Unmarshal(body, &e), string(body))
|
||||
return e.Code
|
||||
}
|
||||
|
||||
func TestS3GetPart(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-")
|
||||
key := "media/clip.bin"
|
||||
|
||||
part1 := bytes.Repeat([]byte("a"), 5*1024*1024)
|
||||
part1Retry := bytes.Repeat([]byte("c"), 5*1024*1024)
|
||||
part2 := []byte("the last part, short")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
upload := func(n int64, data []byte) *s3.UploadPartOutput {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(n), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
}
|
||||
upload(1, part1)
|
||||
retried := upload(1, part1Retry)
|
||||
uploaded2 := upload(2, part2)
|
||||
|
||||
t.Run("open upload serves the latest attempt", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "IN_PROGRESS", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(retried.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.True(t, bytes.Equal(part1Retry, body), "part 1 body is not the retried attempt")
|
||||
})
|
||||
|
||||
t.Run("open upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=4-7"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 4-7/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[4:8]), string(body))
|
||||
})
|
||||
|
||||
t.Run("missing part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("sse request header is rejected", func(t *testing.T) {
|
||||
resp, _ := getPart(t, cluster, admin, bucket, key, uploadID, 1, http.Header{"X-Amz-Server-Side-Encryption": {"AES256"}})
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("open part returns its checksum when asked", func(t *testing.T) {
|
||||
data := []byte("checksummed part")
|
||||
sum := crc32.ChecksumIEEE(data)
|
||||
want := base64.StdEncoding.EncodeToString([]byte{byte(sum >> 24), byte(sum >> 16), byte(sum >> 8), byte(sum)})
|
||||
_, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(5), Body: bytes.NewReader(data), ChecksumCRC32: aws.String(want),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 5, http.Header{"X-Amz-Checksum-Mode": {"ENABLED"}})
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, want, resp.Header.Get("x-amz-checksum-crc32"))
|
||||
})
|
||||
|
||||
t.Run("ListParts still answers without ?part", func(t *testing.T) {
|
||||
parts, err := client.ListParts(&s3.ListPartsInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID)})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, parts.Parts, 3)
|
||||
})
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{
|
||||
{PartNumber: aws.Int64(1), ETag: retried.ETag},
|
||||
{PartNumber: aws.Int64(2), ETag: uploaded2.ETag},
|
||||
}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("completed upload serves the part from the object", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(uploaded2.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=-4"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
n := len(part2)
|
||||
assert.Equal(t, fmt.Sprintf("bytes %d-%d/%d", n-4, n-1, n), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[n-4:]), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload has no such part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("completed upload in a version that is no longer latest", func(t *testing.T) {
|
||||
vbucket := createTestBucket(t, cluster, "test-get-part-versioned-")
|
||||
_, err := client.PutBucketVersioning(&s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(vbucket), VersioningConfiguration: &s3.VersioningConfiguration{Status: aws.String("Enabled")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(vbucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: bytes.NewReader(part2),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
done, err := client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: out.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = client.PutObject(&s3.PutObjectInput{Bucket: aws.String(vbucket), Key: aws.String(key), Body: strings.NewReader("newer")})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, vbucket, key, aws.StringValue(created.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, aws.StringValue(done.VersionId), resp.Header.Get("x-amz-version-id"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed empty part", func(t *testing.T) {
|
||||
emptyKey := "media/empty-tail.bin"
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(emptyKey)})
|
||||
require.NoError(t, err)
|
||||
var parts []*s3.CompletedPart
|
||||
for n, data := range [][]byte{part1, nil} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(n + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
parts = append(parts, &s3.CompletedPart{PartNumber: aws.Int64(int64(n + 1)), ETag: out.ETag})
|
||||
}
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, bucket, emptyKey, aws.StringValue(created.UploadId), 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(parts[1].ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, body)
|
||||
})
|
||||
|
||||
t.Run("aborted upload", func(t *testing.T) {
|
||||
other, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: other.UploadId})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, aws.StringValue(other.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchUpload", errorCode(t, body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartIncompleteUploadGrant checks that reading a part of an open
|
||||
// upload needs s3:GetIncompleteUpload on top of s3:GetObject, while a
|
||||
// completed upload's part needs only the read grant.
|
||||
func TestS3GetPartIncompleteUploadGrant(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-grant-")
|
||||
openKey, doneKey := "open.bin", "done.bin"
|
||||
|
||||
start := func(key string) (string, *s3.UploadPartOutput) {
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
part, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: strings.NewReader("only part"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return aws.StringValue(created.UploadId), part
|
||||
}
|
||||
openID, _ := start(openKey)
|
||||
doneID, donePart := start(doneKey)
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(doneKey), UploadId: aws.String(doneID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: donePart.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sess, err := session.NewSession(client.Config.Copy())
|
||||
require.NoError(t, err)
|
||||
iamClient := iam.New(sess)
|
||||
userName := "getpart-reader"
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
reader := credentials.NewStaticCredentials(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
|
||||
|
||||
grant := func(actions ...string) {
|
||||
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":["arn:aws:s3:::%s/*"]}]}`, strings.Join(actions, `","`), bucket)
|
||||
_, err := iamClient.PutUserPolicy(&iam.PutUserPolicyInput{UserName: aws.String(userName), PolicyName: aws.String("reader"), PolicyDocument: aws.String(policy)})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
expectStatus := func(t *testing.T, key, uploadID string, want int) {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool {
|
||||
resp, _ := getPart(t, cluster, reader, bucket, key, uploadID, 1, nil)
|
||||
return resp.StatusCode == want
|
||||
}, 10*time.Second, 200*time.Millisecond)
|
||||
}
|
||||
|
||||
grant("s3:GetObject")
|
||||
t.Run("read grant alone reads a completed part", func(t *testing.T) {
|
||||
expectStatus(t, doneKey, doneID, http.StatusOK)
|
||||
})
|
||||
t.Run("read grant alone cannot read an open part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusForbidden)
|
||||
})
|
||||
|
||||
grant("s3:GetObject", "s3:GetIncompleteUpload")
|
||||
t.Run("GetIncompleteUpload opens the part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusOK)
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartSSES3 reads SSE-S3 parts back decrypted, before and after the
|
||||
// upload completes.
|
||||
func TestS3GetPartSSES3(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-sse-")
|
||||
key := "secret.bin"
|
||||
part1 := bytes.Repeat([]byte("0123456789"), 600*1024)
|
||||
part2 := []byte("encrypted tail")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), ServerSideEncryption: aws.String("AES256"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var completed []*s3.CompletedPart
|
||||
for i, data := range [][]byte{part1, part2} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(i + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
completed = append(completed, &s3.CompletedPart{PartNumber: aws.Int64(int64(i + 1)), ETag: out.ETag})
|
||||
}
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
|
||||
check := func(t *testing.T, status string) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, status, resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.True(t, bytes.Equal(part1, body), "part 1 does not decrypt to what was uploaded")
|
||||
|
||||
resp, body = getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=0-8"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 0-8/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[:9]), string(body))
|
||||
}
|
||||
t.Run("open", func(t *testing.T) { check(t, "IN_PROGRESS") })
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: completed},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Run("completed", func(t *testing.T) { check(t, "COMPLETED") })
|
||||
}
|
||||
@@ -26,3 +26,8 @@ TestIntegration/FsMkdir/FsEncoding/trailing_VT # name with a vertical tab liste
|
||||
# BucketAlreadyOwnedByYou, which rclone expects only with use_already_exists set;
|
||||
# the SeaweedFS provider defaults it to false and rclone.conf keeps that (see there).
|
||||
TestIntegration/FsMkdir/FsPutFiles/Internal/Versions/Mkdir # rclone provider quirk use_already_exists=false
|
||||
|
||||
# The test itself, not its subtests: FsMkdir ends by removing the test bucket,
|
||||
# and DeleteBucket answers 409 BucketNotEmpty although no keys are left -
|
||||
# leftover empty directories or FsEncoding objects that were not deleted.
|
||||
TestIntegration/FsMkdir # DeleteBucket returns BucketNotEmpty at the end of the run
|
||||
@@ -254,7 +254,6 @@ spark = (SparkSession.builder
|
||||
.config("spark.hadoop.hive.metastore.schema.verification.record.version", "false")
|
||||
.config("spark.jars.ivy", ivy_dir)
|
||||
.config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:3.3.2,com.amazonaws:aws-java-sdk-bundle:1.12.262")
|
||||
.config("spark.jars.repositories", "https://maven-central.storage-download.googleapis.com/maven2/")
|
||||
.config("spark.hadoop.fs.s3a.access.key", "test")
|
||||
.config("spark.hadoop.fs.s3a.secret.key", "test")
|
||||
.config("spark.hadoop.fs.s3a.endpoint", "host.docker.internal:%d")
|
||||
|
||||
@@ -40,55 +40,6 @@ func TestVacuumVolumeCheckSuccessAndMissingVolume(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// can_delete_mark reports a readonlyCanDelete mark, the read-only cause a
|
||||
// sweep compacts through; a plain read-only mark refuses deletes and is not one.
|
||||
func TestVacuumVolumeCheckReportsCanDeleteMark(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
const volumeID = uint32(32)
|
||||
framework.AllocateVolume(t, grpcClient, volumeID, "")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
check := func(stage string, want bool) {
|
||||
t.Helper()
|
||||
resp, err := grpcClient.VacuumVolumeCheck(ctx, &volume_server_pb.VacuumVolumeCheckRequest{VolumeId: volumeID})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: VacuumVolumeCheck failed: %v", stage, err)
|
||||
}
|
||||
if resp.GetCanDeleteMark() != want {
|
||||
t.Fatalf("%s: can_delete_mark = %v, want %v", stage, resp.GetCanDeleteMark(), want)
|
||||
}
|
||||
}
|
||||
|
||||
check("writable", false)
|
||||
|
||||
_, err := grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: volumeID, CanDelete: true})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeMarkReadonly canDelete failed: %v", err)
|
||||
}
|
||||
check("readonlyCanDelete", true)
|
||||
|
||||
_, err = grpcClient.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{VolumeId: volumeID})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeMarkReadonly failed: %v", err)
|
||||
}
|
||||
check("readonly", false)
|
||||
|
||||
_, err = grpcClient.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{VolumeId: volumeID})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeMarkWritable failed: %v", err)
|
||||
}
|
||||
check("writable again", false)
|
||||
}
|
||||
|
||||
func TestVacuumMaintenanceModeRejections(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
|
||||
@@ -79,53 +79,6 @@ func TestWriteMalformedMultipartAndMD5Mismatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS checks that in strict FIPS
|
||||
// mode (GODEBUG=fips140=only for Go, fips.mode strict for Rust), where no MD5
|
||||
// may be computed, an upload whose Content-MD5 does not match its body is
|
||||
// stored with the client's value instead of refused. The master and volume
|
||||
// server inherit the environment set here; this test process keeps the mode it
|
||||
// started with.
|
||||
func TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
t.Setenv("GODEBUG", "fips140=only")
|
||||
t.Setenv("WEED_FIPS_MODE", "strict")
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
const volumeID = uint32(97)
|
||||
framework.AllocateVolume(t, grpcClient, volumeID, "")
|
||||
|
||||
client := framework.NewHTTPClient()
|
||||
url := clusterHarness.VolumeAdminURL() + "/" + framework.NewFileID(volumeID, 772101, 0x1A2B3C4D)
|
||||
payload := []byte("content-md5-unchecked-body")
|
||||
const wrongMD5 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
||||
|
||||
uploadReq := newUploadRequest(t, url, payload)
|
||||
uploadReq.Header.Set("Content-MD5", wrongMD5)
|
||||
uploadResp := framework.DoRequest(t, client, uploadReq)
|
||||
uploadBody := framework.ReadAllAndClose(t, uploadResp)
|
||||
if uploadResp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("content-md5 mismatch write under strict FIPS mode expected 201, got %d: %s", uploadResp.StatusCode, uploadBody)
|
||||
}
|
||||
if !strings.Contains(string(uploadBody), `"contentMd5":"`+wrongMD5+`"`) {
|
||||
t.Fatalf("upload result should carry the client's Content-MD5 %s, got %s", wrongMD5, uploadBody)
|
||||
}
|
||||
|
||||
readReq, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("create read request: %v", err)
|
||||
}
|
||||
readResp := framework.DoRequest(t, client, readReq)
|
||||
readBody := framework.ReadAllAndClose(t, readResp)
|
||||
if readResp.StatusCode != http.StatusOK || !bytes.Equal(readBody, payload) {
|
||||
t.Fatalf("read back expected 200 with the payload, got %d: %q", readResp.StatusCode, readBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteReadOnlyReportsConflictAndSafeRefusal(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
|
||||
@@ -48,7 +48,7 @@ func main() {
|
||||
|
||||
assignResult, targetUrl := genFile(grpcDialOption, i)
|
||||
|
||||
util_http.Delete(context.Background(), targetUrl, string(assignResult.Auth))
|
||||
util_http.Delete(targetUrl, string(assignResult.Auth))
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -56,9 +56,6 @@ type AdminData struct {
|
||||
// VersionSummary reports whether all cluster nodes run the same binary
|
||||
// version, so the dashboard can warn about partially upgraded clusters.
|
||||
VersionSummary ClusterVersionSummary `json:"version_summary"`
|
||||
|
||||
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
|
||||
MisplacedVolumes int `json:"misplaced_volumes"`
|
||||
}
|
||||
|
||||
// Object Store Users management structures
|
||||
@@ -264,9 +261,6 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
Trends: s.GetDashboardTrends(),
|
||||
TierStats: topology.TierStats,
|
||||
VersionSummary: buildClusterVersionSummary(volumeServersData.VolumeServers, filerNodes, s3Nodes, messageBrokers),
|
||||
|
||||
UnderReplicatedVolumes: topology.UnderReplicatedVolumes,
|
||||
MisplacedVolumes: topology.MisplacedVolumes,
|
||||
}
|
||||
|
||||
return adminData, nil
|
||||
|
||||
@@ -251,7 +251,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
|
||||
|
||||
topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb)
|
||||
topology.UnderReplicatedVolumes, topology.MisplacedVolumes = countReplicaIssues(resp.TopologyInfo)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/topology/balancer"
|
||||
)
|
||||
|
||||
// countReplicaIssues counts the volumes volume.fix.replication would repair:
|
||||
// under-replicated ones, missing a copy or not spread as their placement
|
||||
// asks, and misplaced ones.
|
||||
func countReplicaIssues(topologyInfo *master_pb.TopologyInfo) (underReplicated, misplaced int) {
|
||||
replicas := make(map[uint32][]balancer.Replica)
|
||||
placements := make(map[uint32]uint32)
|
||||
for _, dc := range topologyInfo.GetDataCenterInfos() {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, dn := range rack.DataNodeInfos {
|
||||
loc := balancer.Location{
|
||||
DataCenter: dc.Id,
|
||||
Rack: rack.Id,
|
||||
NodeID: dn.Id,
|
||||
Host: pb.NewServerAddressFromDataNode(dn).ToHost(),
|
||||
}
|
||||
for _, disk := range dn.DiskInfos {
|
||||
for _, v := range disk.VolumeInfos {
|
||||
if _, found := placements[v.Id]; !found {
|
||||
placements[v.Id] = v.ReplicaPlacement
|
||||
}
|
||||
replicas[v.Id] = append(replicas[v.Id], balancer.Replica{Location: loc})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for vid, rs := range replicas {
|
||||
rp, _ := super_block.NewReplicaPlacementFromByte(byte(placements[vid]))
|
||||
locs := make([]balancer.Location, len(rs))
|
||||
for i, r := range rs {
|
||||
locs[i] = r.Location
|
||||
}
|
||||
switch {
|
||||
case rp.GetCopyCount() > len(rs) || !balancer.SatisfyReplicaCurrentLocation(rp, locs):
|
||||
underReplicated++
|
||||
case balancer.IsMisplaced(rs, rp):
|
||||
misplaced++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestCountReplicaIssues(t *testing.T) {
|
||||
node := func(id string, volumes ...*master_pb.VolumeInformationMessage) *master_pb.DataNodeInfo {
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: id,
|
||||
Address: id,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{"": {VolumeInfos: volumes}},
|
||||
}
|
||||
}
|
||||
volume := func(id uint32, placement uint32) *master_pb.VolumeInformationMessage {
|
||||
return &master_pb.VolumeInformationMessage{Id: id, ReplicaPlacement: placement}
|
||||
}
|
||||
dc := func(id string, nodes ...*master_pb.DataNodeInfo) *master_pb.DataCenterInfo {
|
||||
return &master_pb.DataCenterInfo{Id: id, RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}}}
|
||||
}
|
||||
// placements are stored as their decimal digits: 200, 100, 001 as 1.
|
||||
topo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
dc("dc1",
|
||||
node("10.0.0.11:8080", volume(1, 200), volume(2, 200), volume(3, 100), volume(4, 1), volume(5, 0)),
|
||||
node("10.0.0.12:8080", volume(4, 1))),
|
||||
dc("dc2", node("10.0.0.21:8080", volume(1, 200), volume(2, 200), volume(3, 100))),
|
||||
dc("dc3", node("10.0.0.31:8080", volume(1, 200))),
|
||||
}}
|
||||
// volume 1 has its 3 copies; volume 2, grown degraded, misses its dc3 copy.
|
||||
under, misplaced := countReplicaIssues(topo)
|
||||
if under != 1 || misplaced != 0 {
|
||||
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 0", under, misplaced)
|
||||
}
|
||||
|
||||
// volume 6 (010) has its two racks, but in two data centers.
|
||||
dc1 := topo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
|
||||
dc2 := topo.DataCenterInfos[1].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
|
||||
dc1.VolumeInfos = append(dc1.VolumeInfos, volume(6, 10))
|
||||
dc2.VolumeInfos = append(dc2.VolumeInfos, volume(6, 10))
|
||||
under, misplaced = countReplicaIssues(topo)
|
||||
if under != 1 || misplaced != 1 {
|
||||
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 1", under, misplaced)
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,6 @@ type ClusterTopology struct {
|
||||
// TierStats breaks volumes and EC shards down by storage tier: local
|
||||
// disk types plus one entry per remote storage holding tiered volumes.
|
||||
TierStats []TierStats `json:"tier_stats"`
|
||||
// UnderReplicatedVolumes and MisplacedVolumes count the volumes
|
||||
// volume.fix.replication would repair.
|
||||
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
|
||||
MisplacedVolumes int `json:"misplaced_volumes"`
|
||||
}
|
||||
|
||||
type MasterNode struct {
|
||||
|
||||
@@ -86,15 +86,12 @@ var jobTypeLaneMap = map[string]SchedulerLane{
|
||||
"erasure_coding": LaneDefault,
|
||||
"admin_script": LaneDefault,
|
||||
|
||||
// Iceberg table maintenance and MQ topic table appends
|
||||
// Iceberg table maintenance
|
||||
"iceberg_maintenance": LaneIceberg,
|
||||
"mq_topic_table": LaneIceberg,
|
||||
|
||||
// S3 lifecycle management
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
"filer_ttl": LaneLifecycle,
|
||||
"meta_log_purge": LaneLifecycle,
|
||||
"dir_usage": LaneLifecycle,
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
"filer_ttl": LaneLifecycle,
|
||||
|
||||
// Lance table maintenance. Without these the job types fall back to the
|
||||
// default lane, which serialises everything under the cluster admin lock
|
||||
|
||||
@@ -63,7 +63,6 @@ func TestKnownJobTypesInMap(t *testing.T) {
|
||||
"erasure_coding": LaneDefault,
|
||||
"admin_script": LaneDefault,
|
||||
"iceberg_maintenance": LaneIceberg,
|
||||
"mq_topic_table": LaneIceberg,
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
}
|
||||
for jobType, wantLane := range expected {
|
||||
|
||||
@@ -78,7 +78,7 @@ func (at *ActiveTopology) GetEffectiveAvailableEcShardSlots(nodeID string, diskI
|
||||
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeID, diskID)
|
||||
disk, exists := at.disks[diskKey]
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ func (at *ActiveTopology) CanAccommodateTask(nodeID string, diskID uint32, taskT
|
||||
|
||||
// getPlanningCapacityUnsafe considers both pending and active tasks for planning
|
||||
func (at *ActiveTopology) getPlanningCapacityUnsafe(disk *activeDisk) StorageSlotChange {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
return StorageSlotChange{}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ func (at *ActiveTopology) getEffectiveCapacityUnsafe(disk *activeDisk) StorageSl
|
||||
|
||||
// getEffectiveAvailableCapacityUnsafe returns detailed available capacity as StorageSlotChange
|
||||
func (at *ActiveTopology) getEffectiveAvailableCapacityUnsafe(disk *activeDisk) StorageSlotChange {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
return StorageSlotChange{}
|
||||
}
|
||||
|
||||
|
||||
@@ -64,13 +64,6 @@ func (at *ActiveTopology) assignTaskToDisk(task *taskState) {
|
||||
}
|
||||
}
|
||||
|
||||
// inMaintenanceUnsafe reports whether the disk's volume server is in
|
||||
// maintenance mode. Such a server refuses new data, so it is a source only.
|
||||
func (at *ActiveTopology) inMaintenanceUnsafe(disk *activeDisk) bool {
|
||||
node := at.nodes[disk.NodeID]
|
||||
return node != nil && node.nodeInfo.GetMaintenance()
|
||||
}
|
||||
|
||||
// isDiskAvailable checks if a disk can accept new tasks. Per-volume safety is
|
||||
// enforced by HasAnyTask at detection time, so cross-type tasks on the same
|
||||
// disk are intentionally not considered conflicting (see #9147).
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestMaintenanceNodeHasNoCapacity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
topo := singleDiskTopologyInfoForCapacityTest()
|
||||
rack := topo.DataCenterInfos[0].RackInfos[0]
|
||||
rack.DataNodeInfos = append(rack.DataNodeInfos, &master_pb.DataNodeInfo{
|
||||
Id: "node-b",
|
||||
Maintenance: true,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {DiskId: 0, Type: "hdd", MaxVolumeCount: 1000},
|
||||
},
|
||||
})
|
||||
|
||||
at := NewActiveTopology(0)
|
||||
if err := at.UpdateTopology(topo); err != nil {
|
||||
t.Fatalf("UpdateTopology: %v", err)
|
||||
}
|
||||
|
||||
if got := at.GetEffectiveAvailableCapacity("node-b", 0); got != 0 {
|
||||
t.Errorf("GetEffectiveAvailableCapacity(node-b) = %d, want 0", got)
|
||||
}
|
||||
if got := at.GetEffectiveAvailableEcShardSlots("node-b", 0, 0); got != 0 {
|
||||
t.Errorf("GetEffectiveAvailableEcShardSlots(node-b) = %d, want 0", got)
|
||||
}
|
||||
if got := at.GetEffectiveAvailableCapacity("node-a", 0); got != 1000 {
|
||||
t.Errorf("GetEffectiveAvailableCapacity(node-a) = %d, want 1000", got)
|
||||
}
|
||||
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 1) {
|
||||
if d.NodeID == "node-b" {
|
||||
t.Errorf("GetDisksWithEffectiveCapacity returned maintenance node-b")
|
||||
}
|
||||
}
|
||||
for _, d := range at.GetAvailableDisks(TaskTypeBalance, "") {
|
||||
if d.NodeID == "node-b" {
|
||||
t.Errorf("GetAvailableDisks returned maintenance node-b")
|
||||
}
|
||||
}
|
||||
sources := 0
|
||||
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 0) {
|
||||
if d.NodeID == "node-b" {
|
||||
sources++
|
||||
}
|
||||
}
|
||||
if sources != 1 {
|
||||
t.Errorf("maintenance node-b should stay listed with zero capacity, got %d entries", sources)
|
||||
}
|
||||
}
|
||||
@@ -165,8 +165,8 @@ func (at *ActiveTopology) GetAvailableDisks(taskType TaskType, excludeNodeID str
|
||||
var available []*DiskInfo
|
||||
|
||||
for _, disk := range at.disks {
|
||||
if disk.NodeID == excludeNodeID || at.inMaintenanceUnsafe(disk) {
|
||||
continue
|
||||
if disk.NodeID == excludeNodeID {
|
||||
continue // Skip excluded node
|
||||
}
|
||||
|
||||
if at.isDiskAvailable(disk, taskType) {
|
||||
|
||||
@@ -75,9 +75,7 @@ func TestClusterHealthSummary(t *testing.T) {
|
||||
degraded := healthy
|
||||
degraded.MasterNodes = []dash.MasterNode{{Address: "m1:9333"}}
|
||||
degraded.DiskUsage = 95
|
||||
degraded.UnderReplicatedVolumes = 3
|
||||
degraded.MisplacedVolumes = 1
|
||||
want := "Needs attention: no master leader, disks 95% full, 3 volumes under-replicated, 1 volume misplaced. 2 volume servers and 1 filer reporting, 1 master configured."
|
||||
want := "Needs attention: no master leader, disks 95% full. 2 volume servers and 1 filer reporting, 1 master configured."
|
||||
if got := clusterHealthSummary(degraded); got != want {
|
||||
t.Errorf("degraded summary = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
@@ -24,12 +24,6 @@ func clusterHealthIssues(data dash.AdminData) []string {
|
||||
issues = append(issues, fmt.Sprintf("disks %d%% full", p))
|
||||
}
|
||||
}
|
||||
if data.UnderReplicatedVolumes > 0 {
|
||||
issues = append(issues, countNoun(data.UnderReplicatedVolumes, "volume")+" under-replicated")
|
||||
}
|
||||
if data.MisplacedVolumes > 0 {
|
||||
issues = append(issues, countNoun(data.MisplacedVolumes, "volume")+" misplaced")
|
||||
}
|
||||
if data.VersionSummary.Mixed() {
|
||||
issues = append(issues, "mixed server versions")
|
||||
}
|
||||
|
||||
@@ -56,7 +56,6 @@ func buildPolicyActionSuggestions() []string {
|
||||
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
|
||||
s3_constants.S3_ACTION_LIST_PARTS,
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
|
||||
s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
s3_constants.S3_ACTION_CREATE_BUCKET,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET,
|
||||
s3_constants.S3_ACTION_LIST_BUCKET,
|
||||
|
||||
@@ -172,7 +172,7 @@ type LiveLock struct {
|
||||
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
|
||||
self string
|
||||
lc *LockClient
|
||||
owner atomic.Pointer[string] // read by other goroutines through LockOwner
|
||||
owner string
|
||||
lockTTL time.Duration
|
||||
consecutiveFailures int // Track connection failures to trigger fallback
|
||||
}
|
||||
@@ -497,7 +497,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
lock.key, lock.hostFiler, lock.self)
|
||||
|
||||
previousHostFiler := lock.hostFiler
|
||||
previousOwner := lock.LockOwner()
|
||||
previousOwner := lock.owner
|
||||
|
||||
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Bound each attempt: a ring member that is reachable from the masters
|
||||
@@ -549,12 +549,12 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
if resp.LockOwner != "" && resp.LockOwner != previousOwner {
|
||||
// Only log if the owner actually changed
|
||||
glog.V(2).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
lock.owner = resp.LockOwner
|
||||
} else if resp.LockOwner != "" {
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
lock.owner = resp.LockOwner
|
||||
} else if previousOwner != "" {
|
||||
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
|
||||
lock.owner.Store(nil)
|
||||
lock.owner = ""
|
||||
}
|
||||
}
|
||||
return err
|
||||
@@ -575,10 +575,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
}
|
||||
|
||||
func (lock *LiveLock) LockOwner() string {
|
||||
if owner := lock.owner.Load(); owner != nil {
|
||||
return *owner
|
||||
}
|
||||
return ""
|
||||
return lock.owner
|
||||
}
|
||||
|
||||
// Generation returns the fencing token for this lock.
|
||||
|
||||
@@ -327,7 +327,7 @@ type grantingLockFiler struct {
|
||||
}
|
||||
|
||||
func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{RenewToken: "tok", LockOwner: req.Owner}, nil
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
}
|
||||
|
||||
type rotatingAuthLockFiler struct {
|
||||
@@ -819,29 +819,3 @@ func TestLiveLockIsLockedOnlyWithinLease(t *testing.T) {
|
||||
t.Fatal("a lock whose lease ran out must not read as locked")
|
||||
}
|
||||
}
|
||||
|
||||
// Other goroutines read the owner while renewals rewrite it.
|
||||
func TestLiveLockOwnerReadDuringRenewal(t *testing.T) {
|
||||
lock := newGrantingLockClient(t).NewShortLivedLock("test-key", "test-owner")
|
||||
if lock == nil {
|
||||
t.Fatal("lock not granted")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < 20; i++ {
|
||||
lock.AttemptToLock(5 * time.Second)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
if got := lock.LockOwner(); got != "test-owner" {
|
||||
t.Fatalf("owner = %q, want test-owner", got)
|
||||
}
|
||||
return
|
||||
default:
|
||||
_ = lock.LockOwner()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ const DefaultMasterMaintenanceScripts = `
|
||||
ec.encode -fullPercent=95 -quietFor=1h
|
||||
ec.rebuild -apply
|
||||
ec.balance -apply
|
||||
fs.log.purge -daysAgo=7
|
||||
volume.deleteEmpty -quietFor=24h -apply
|
||||
volume.balance -apply
|
||||
volume.fix.replication -apply
|
||||
|
||||
@@ -240,7 +240,7 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
if isSecure {
|
||||
jwtAuthorization = operation.LookupJwt(context.Background(), b.masterClient.GetMaster(context.Background()), b.grpcDialOption, df.fp.Fid)
|
||||
}
|
||||
if e := util_http.Delete(context.Background(), fmt.Sprintf("http://%s/%s", df.fp.Server, df.fp.Fid), string(jwtAuthorization)); e == nil {
|
||||
if e := util_http.Delete(fmt.Sprintf("http://%s/%s", df.fp.Server, df.fp.Fid), string(jwtAuthorization)); e == nil {
|
||||
s.completed++
|
||||
} else {
|
||||
s.failed++
|
||||
|
||||
+10
-60
@@ -36,47 +36,17 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
f FilerOptions
|
||||
filerStartS3 *bool
|
||||
filerS3Options S3Options
|
||||
filerStartS3MqBroker *bool
|
||||
filerS3MqBrokerOptions MessageQueueBrokerOptions
|
||||
filerStartWebDav *bool
|
||||
filerWebDavOptions WebDavOption
|
||||
filerStartIam *bool
|
||||
filerIamOptions IamOptions
|
||||
filerStartSftp *bool
|
||||
filerSftpOptions SftpOptions
|
||||
f FilerOptions
|
||||
filerStartS3 *bool
|
||||
filerS3Options S3Options
|
||||
filerStartWebDav *bool
|
||||
filerWebDavOptions WebDavOption
|
||||
filerStartIam *bool
|
||||
filerIamOptions IamOptions
|
||||
filerStartSftp *bool
|
||||
filerSftpOptions SftpOptions
|
||||
)
|
||||
|
||||
// filerRunsMqBrokerBesideS3 reports whether weed filer starts a broker with
|
||||
// its S3 gateway; the filer has no other broker to collide with.
|
||||
func filerRunsMqBrokerBesideS3(brokerFlagPassed bool) bool {
|
||||
return *filerStartS3 && wantsMqBrokerBesideS3("s3.mq.broker", *filerStartS3MqBroker, brokerFlagPassed)
|
||||
}
|
||||
|
||||
// filerPortsBesideS3 lists the ports of the filer and the other servers weed
|
||||
// filer starts with its gateway, derived gRPC ports included.
|
||||
func filerPortsBesideS3() []int {
|
||||
ports := append([]int{*f.metricsHttpPort}, withGrpc(f.port, f.portGrpc)...)
|
||||
if *f.debug {
|
||||
ports = append(ports, *f.debugPort)
|
||||
}
|
||||
if *f.publicPort != 0 {
|
||||
ports = append(ports, *f.publicPort)
|
||||
}
|
||||
if *filerStartWebDav {
|
||||
ports = append(ports, *filerWebDavOptions.port)
|
||||
}
|
||||
if *filerStartIam {
|
||||
ports = append(ports, *filerIamOptions.port)
|
||||
}
|
||||
if *filerStartSftp {
|
||||
ports = append(ports, *filerSftpOptions.port)
|
||||
}
|
||||
return ports
|
||||
}
|
||||
|
||||
// allowUntrustedRemoteEndpointsUsage documents the flag shared by the filer and
|
||||
// S3 gateway, whose remote-mount read paths dial the mounted endpoint directly.
|
||||
const allowUntrustedRemoteEndpointsUsage = "if true, a read of a remote-only entry accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints."
|
||||
@@ -255,8 +225,6 @@ func init() {
|
||||
filerS3Options.unreachableOwnerTTL = cmdFiler.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage)
|
||||
filerS3Options.volumeLookupTimeout = cmdFiler.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage)
|
||||
filerS3Options.preStopSeconds = cmdFiler.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage)
|
||||
filerStartS3MqBroker = cmdFiler.Flag.Bool("s3.mq.broker", false, mqBrokerBesideS3Usage)
|
||||
filerS3MqBrokerOptions.port = cmdFiler.Flag.Int("s3.mq.broker.port", defaultMqBrokerPort, "message queue broker gRPC listen port")
|
||||
|
||||
// start webdav on filer
|
||||
filerStartWebDav = cmdFiler.Flag.Bool("webdav", false, "whether to start webdav gateway")
|
||||
@@ -314,10 +282,6 @@ func filerLongDesc() string {
|
||||
|
||||
The example filer.toml configuration file can be generated by "weed scaffold -config=filer"
|
||||
|
||||
With -s3, and grpc.msg_broker cert and key in security.toml, a message queue broker
|
||||
runs beside the S3 gateway on -s3.mq.broker.port; use -s3.mq.broker=false to leave it
|
||||
out, or -s3.mq.broker=true to run it without TLS.
|
||||
|
||||
Supported Filer Stores:
|
||||
`
|
||||
|
||||
@@ -382,21 +346,8 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
if *filerS3Options.metricsHttpIp == "" {
|
||||
*filerS3Options.metricsHttpIp = *filerS3Options.bindIp
|
||||
}
|
||||
filerS3Options.mqBroker = nil
|
||||
if filerRunsMqBrokerBesideS3(isFlagExplicitlySet(cmdFiler, "s3.mq.broker")) {
|
||||
filerS3Options.mqBroker = &filerS3MqBrokerOptions
|
||||
if err := filerS3Options.checkMqBrokerPort("s3.mq.broker.port", isFlagExplicitlySet(cmdFiler, "s3.mq.broker.port"), filerPortsBesideS3()...); err != nil {
|
||||
glog.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
go func(delay time.Duration) {
|
||||
time.Sleep(delay * time.Second)
|
||||
// By now startFiler has filled an empty -ip.bind, which the gateway
|
||||
// and its broker both bind.
|
||||
if b := filerS3Options.mqBroker; b != nil {
|
||||
filerS3Options.brokerBeside(b)
|
||||
b.dataCenter, b.rack = f.dataCenter, f.rack
|
||||
}
|
||||
filerS3Options.startS3Server()
|
||||
}(startDelay)
|
||||
startDelay++
|
||||
@@ -586,8 +537,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
grpcTLSOption, grpcTLSReloadOption := security.LoadServerTLS(util.GetViper(), "grpc.filer")
|
||||
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, weed_server.FilerGrpcMetricsServerOptions()...)
|
||||
grpcOptions = append(grpcOptions, fs.GrpcScopeServerOptions()...)
|
||||
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, fs.GrpcScopeServerOptions()...)
|
||||
grpcS := pb.NewGrpcServer(grpcOptions...)
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcS, fs)
|
||||
|
||||
|
||||
@@ -572,8 +572,7 @@ func runInitialSnapshot(
|
||||
// still gets seeded (only its children would be skipped by the parent
|
||||
// check).
|
||||
if parent == filer.SystemLogDir || strings.HasPrefix(parent, filer.SystemLogDir+"/") ||
|
||||
source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") ||
|
||||
isSyncCursor(sourceKey) {
|
||||
source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") {
|
||||
return nil
|
||||
}
|
||||
if matchesExcludePath(parent, excludePaths) || matchesExcludePath(source, excludePaths) {
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type snapshotListFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
dirs map[string][]*filer_pb.Entry
|
||||
}
|
||||
|
||||
func (f *snapshotListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
||||
for _, entry := range f.dirs[req.Directory] {
|
||||
if req.StartFromFileName != "" && (entry.Name < req.StartFromFileName || entry.Name == req.StartFromFileName && !req.InclusiveStartFrom) {
|
||||
continue
|
||||
}
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestInitialSnapshotSkipsSyncCursors(t *testing.T) {
|
||||
dir := func(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
|
||||
}
|
||||
file := func(name string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}}
|
||||
}
|
||||
fake := &snapshotListFiler{dirs: map[string][]*filer_pb.Entry{
|
||||
"/": {dir("data"), dir("etc")},
|
||||
"/data": {file("a.txt")},
|
||||
"/etc": {dir("seaweedfs")},
|
||||
"/etc/seaweedfs": {file("filer.conf"), dir("filer_sync")},
|
||||
filer.SyncCursorDir: {file("0000000a-0000000000000001.json")},
|
||||
}}
|
||||
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(server, fake)
|
||||
go server.Serve(lis)
|
||||
defer server.Stop()
|
||||
|
||||
filerSource := &source.FilerSource{}
|
||||
if err := filerSource.DoInitialize("localhost:1", lis.Addr().String(), "/", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sink := &recordSink{created: map[string]*filer_pb.Entry{}}
|
||||
if _, err := runInitialSnapshot(lis.Addr().String(), filerSource, "/", "/", nil, nil, nil, nil, sink, false, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var created []string
|
||||
for key := range sink.created {
|
||||
created = append(created, key)
|
||||
}
|
||||
sort.Strings(created)
|
||||
want := []string{"/data", "/data/a.txt", "/etc", "/etc/seaweedfs", "/etc/seaweedfs/filer.conf"}
|
||||
if strings.Join(created, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("seeded %v, want %v", created, want)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
@@ -70,7 +69,6 @@ func (c *lookupEntrySeaweedClient) ListEntries(_ context.Context, in *filer_pb.L
|
||||
}
|
||||
|
||||
type recordSink struct {
|
||||
mu sync.Mutex
|
||||
created map[string]*filer_pb.Entry
|
||||
deleted []string
|
||||
}
|
||||
@@ -80,14 +78,10 @@ func (s *recordSink) Initialize(configuration util.Configuration, prefix string)
|
||||
return nil
|
||||
}
|
||||
func (s *recordSink) DeleteEntry(key string, isDirectory, deleteIncludeChunks bool, signatures []int32) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.deleted = append(s.deleted, key)
|
||||
return nil
|
||||
}
|
||||
func (s *recordSink) CreateEntry(key string, entry *filer_pb.Entry, signatures []int32) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.created[key] = entry
|
||||
return nil
|
||||
}
|
||||
|
||||
Loaded 100 of 985 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user