mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73ddb004ab | ||
|
|
6bdd775963 | ||
|
|
d2e64e85ce | ||
|
|
61c1735cdd | ||
|
|
49ce2b7326 | ||
|
|
a890300eaf | ||
|
|
6642a64d2b | ||
|
|
93d604d799 | ||
|
|
dec09d1484 | ||
|
|
25d7f2c569 | ||
|
|
86c5e815d2 | ||
|
|
f4ce2be875 | ||
|
|
f1d5f31a93 | ||
|
|
8857dbfb74 | ||
|
|
9a6b566fb1 | ||
|
|
3ff92f797d | ||
|
|
a8ba9d106e | ||
|
|
73f10fa528 | ||
|
|
fe9ca35bbd | ||
|
|
8a6348d3e9 | ||
|
|
af1e571297 | ||
|
|
e24a443b17 | ||
|
|
d7d834b8f9 | ||
|
|
6787a4b4e8 | ||
|
|
6832b9945b | ||
|
|
1c130c2d47 | ||
|
|
c1ccbe97dd | ||
|
|
d57fc67022 | ||
|
|
96af27a131 | ||
|
|
6bcacedda9 | ||
|
|
0315da9022 | ||
|
|
bfea14320a | ||
|
|
0bddc2652e | ||
|
|
2da24cc230 | ||
|
|
32cbed9658 | ||
|
|
cce98fcecf | ||
|
|
88ac2d0431 | ||
|
|
e8767f42b6 | ||
|
|
f720f559cb | ||
|
|
45578a42e9 | ||
|
|
664ae64646 | ||
|
|
018e648d00 | ||
|
|
66ce0c29cf | ||
|
|
108e6b0d5f | ||
|
|
9d15705c16 | ||
|
|
9554e259dd | ||
|
|
00a2e22478 | ||
|
|
7916e61c08 | ||
|
|
ecc0390795 | ||
|
|
40ffc73aa8 | ||
|
|
ff4f96c71f | ||
|
|
9896eade51 | ||
|
|
ceae01d05b | ||
|
|
216b52c13a | ||
|
|
886d50a6a5 | ||
|
|
e1fa4ec756 | ||
|
|
213b6c3107 |
No files matched your search
@@ -1 +0,0 @@
|
||||
{"sessionId":"81536282-6277-4e32-9922-37c6e3a01b1f","pid":84648,"acquiredAt":1776208413235}
|
||||
@@ -4,6 +4,10 @@ on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
concurrency:
|
||||
group: binaries-dev-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ jobs:
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Build
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
|
||||
@@ -150,7 +150,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Build and push image
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
|
||||
@@ -232,7 +232,7 @@ jobs:
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
- name: Build ${{ matrix.platform }} ${{ matrix.variant }}
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
@@ -322,7 +322,7 @@ jobs:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Build local scan image tarball
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
fi
|
||||
-
|
||||
name: Build
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ./docker
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
|
||||
@@ -251,7 +251,7 @@ jobs:
|
||||
|
||||
- name: Build and push ${{ matrix.variant }}
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/build-push-action@v7.1.0
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
name: "FUSE P2P Peer Chunk Sharing Integration Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/command/mount*.go'
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/mount_peer_registry*.go'
|
||||
- 'weed/server/filer_grpc_server_mount_peer.go'
|
||||
- 'weed/pb/mount_peer.proto'
|
||||
- 'weed/pb/filer.proto'
|
||||
- 'test/fuse_p2p/**'
|
||||
- '.github/workflows/fuse-p2p-integration.yml'
|
||||
push:
|
||||
branches: [master]
|
||||
paths:
|
||||
- 'weed/command/mount*.go'
|
||||
- 'weed/mount/**'
|
||||
- 'weed/filer/mount_peer_registry*.go'
|
||||
- 'weed/server/filer_grpc_server_mount_peer.go'
|
||||
- 'weed/pb/mount_peer.proto'
|
||||
- 'weed/pb/filer.proto'
|
||||
- 'test/fuse_p2p/**'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref || github.ref }}/fuse-p2p-integration
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
fuse-p2p-integration:
|
||||
name: FUSE P2P Peer Chunk Sharing
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Install FUSE dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libfuse3-dev
|
||||
echo 'user_allow_other' | sudo tee -a /etc/fuse.conf
|
||||
sudo chmod 644 /etc/fuse.conf
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: go build -o weed/weed -buildvcs=false ./weed
|
||||
|
||||
- name: Run P2P integration tests
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
WEED_BINARY: ${{ github.workspace }}/weed/weed
|
||||
run: go test -v -count=1 -timeout=12m ./test/fuse_p2p/...
|
||||
|
||||
- name: Upload logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: fuse-p2p-test-logs
|
||||
path: /tmp/seaweedfs-fuse-p2p-logs/
|
||||
retention-days: 3
|
||||
@@ -445,7 +445,7 @@ jobs:
|
||||
# Test consumer group functionality with explicit timeout
|
||||
ulimit -n 512 || echo "Warning: Could not set file descriptor limit"
|
||||
ulimit -u 100 || echo "Warning: Could not set process limit"
|
||||
timeout 240s go test -v -run "^TestConsumerGroups" -timeout 180s ./integration/... || echo "Test execution timed out or failed"
|
||||
timeout 240s go test -v -run "^TestConsumerGroups" -timeout 180s ./integration/...
|
||||
env:
|
||||
GOMAXPROCS: 1
|
||||
SEAWEEDFS_MASTERS: 127.0.0.1:9333
|
||||
|
||||
@@ -39,18 +39,49 @@ jobs:
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build SeaweedFS e2e image
|
||||
- name: Start local Docker registry
|
||||
run: docker run -d --restart=always -p 5000:5000 --name registry registry:2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
driver-opts: network=host
|
||||
|
||||
- name: Build weed race binary
|
||||
run: |
|
||||
cd docker
|
||||
make build_e2e || {
|
||||
echo "Retrying without buildx cache..."
|
||||
make binary_race
|
||||
docker build --no-cache -t chrislusf/seaweedfs:e2e -f Dockerfile.e2e .
|
||||
}
|
||||
make binary_race
|
||||
|
||||
- name: Build SeaweedFS e2e image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: docker
|
||||
file: docker/Dockerfile.e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:e2e
|
||||
push: true
|
||||
cache-from: type=gha,scope=pjdfstest-e2e
|
||||
cache-to: type=gha,mode=max,scope=pjdfstest-e2e
|
||||
|
||||
- name: Tag e2e image for docker compose
|
||||
run: |
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:e2e
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:e2e chrislusf/seaweedfs:e2e
|
||||
|
||||
- name: Build pjdfstest image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: test/pjdfstest
|
||||
build-contexts: |
|
||||
chrislusf/seaweedfs:e2e=docker-image://localhost:5000/chrislusf/seaweedfs:e2e
|
||||
tags: localhost:5000/chrislusf/seaweedfs:pjdfstest
|
||||
push: true
|
||||
cache-from: type=gha,scope=pjdfstest-harness
|
||||
cache-to: type=gha,mode=max,scope=pjdfstest-harness
|
||||
|
||||
- name: Tag pjdfstest image for docker compose
|
||||
run: |
|
||||
docker build -t chrislusf/seaweedfs:pjdfstest test/pjdfstest/
|
||||
docker pull localhost:5000/chrislusf/seaweedfs:pjdfstest
|
||||
docker tag localhost:5000/chrislusf/seaweedfs:pjdfstest chrislusf/seaweedfs:pjdfstest
|
||||
|
||||
- name: Start SeaweedFS cluster
|
||||
run: |
|
||||
|
||||
@@ -37,6 +37,8 @@ jobs:
|
||||
run: |
|
||||
git clone https://github.com/ceph/s3-tests.git
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
@@ -339,6 +341,8 @@ jobs:
|
||||
run: |
|
||||
git clone https://github.com/ceph/s3-tests.git
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
@@ -507,6 +511,8 @@ jobs:
|
||||
run: |
|
||||
git clone https://github.com/ceph/s3-tests.git
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
@@ -730,6 +736,8 @@ jobs:
|
||||
run: |
|
||||
git clone https://github.com/ceph/s3-tests.git
|
||||
cd s3-tests
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
|
||||
pip install -r requirements.txt
|
||||
pip install tox
|
||||
pip install -e .
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you find a security issue in SeaweedFS, please report it privately:
|
||||
|
||||
- Email: support@seaweedfs.com
|
||||
- Do not open a public GitHub issue
|
||||
|
||||
Please include:
|
||||
- A clear description of the issue
|
||||
- Steps to reproduce (if possible)
|
||||
- Affected versions
|
||||
|
||||
## Response
|
||||
|
||||
- We will respond as soon as possible (usually within 1 business day)
|
||||
- We will investigate and work on a fix
|
||||
- We may coordinate disclosure with you
|
||||
|
||||
## Notes
|
||||
|
||||
- Please allow time for a fix before public disclosure
|
||||
- If you’re unsure whether something is a security issue, feel free to reach out
|
||||
@@ -7,8 +7,8 @@ LABEL author="Chris Lu"
|
||||
# Production images (Dockerfile.go_build) use proper user isolation with su-exec.
|
||||
# For testing purposes, running as root avoids permission complexities and dependency
|
||||
# on Alpine-specific tools like su-exec (not available in Ubuntu repos).
|
||||
RUN apt-get update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
|
||||
--no-install-recommends \
|
||||
--no-install-suggests \
|
||||
curl \
|
||||
|
||||
@@ -4,7 +4,7 @@ go 1.25.0
|
||||
|
||||
require (
|
||||
cloud.google.com/go v0.123.0 // indirect
|
||||
cloud.google.com/go/pubsub v1.50.1
|
||||
cloud.google.com/go/pubsub v1.50.2
|
||||
cloud.google.com/go/storage v1.60.0
|
||||
github.com/Shopify/sarama v1.38.1
|
||||
github.com/aws/aws-sdk-go v1.55.8
|
||||
@@ -39,7 +39,7 @@ require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/jackc/pgx/v5 v5.8.0
|
||||
github.com/jackc/pgx/v5 v5.9.0
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
@@ -109,7 +109,7 @@ require (
|
||||
modernc.org/b v1.0.0 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.46.1
|
||||
modernc.org/sqlite v1.49.1
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -123,13 +123,14 @@ require (
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0
|
||||
github.com/cognusion/imaging v1.0.2
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.44.1
|
||||
github.com/go-git/go-billy/v5 v5.8.0
|
||||
github.com/go-ldap/ldap/v3 v3.4.13
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
|
||||
@@ -143,7 +144,7 @@ require (
|
||||
github.com/parquet-go/parquet-go v0.28.0
|
||||
github.com/pkg/sftp v1.13.10
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/rclone/rclone v1.73.1
|
||||
github.com/rclone/rclone v1.73.5
|
||||
github.com/rdleal/intervalst v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/schollz/progressbar/v3 v3.19.0
|
||||
@@ -153,6 +154,7 @@ require (
|
||||
github.com/testcontainers/testcontainers-go v0.40.0
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/willscott/go-nfs v0.0.3
|
||||
github.com/willscott/go-nfs-client v0.0.0-20251022144359-801f10d98886
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.134.0
|
||||
@@ -170,11 +172,11 @@ require (
|
||||
atomicgo.dev/keyboard v0.2.9 // indirect
|
||||
atomicgo.dev/schedule v0.1.0 // indirect
|
||||
cloud.google.com/go/longrunning v0.8.0 // indirect
|
||||
cloud.google.com/go/pubsub/v2 v2.3.0 // indirect
|
||||
cloud.google.com/go/pubsub/v2 v2.4.0 // indirect
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 // indirect
|
||||
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 // indirect
|
||||
github.com/anchore/go-lzo v0.1.0 // indirect
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
@@ -210,7 +212,6 @@ require (
|
||||
github.com/dromara/dongle v1.0.1 // indirect
|
||||
github.com/gin-gonic/gin v1.11.0 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
@@ -223,7 +224,7 @@ require (
|
||||
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
|
||||
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd // 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.2 // indirect
|
||||
@@ -272,7 +273,6 @@ require (
|
||||
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
|
||||
github.com/willscott/go-nfs-client v0.0.0-20251022144359-801f10d98886 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
@@ -326,7 +326,7 @@ require (
|
||||
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
|
||||
@@ -340,7 +340,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10
|
||||
github.com/aws/smithy-go v1.24.2
|
||||
github.com/aws/smithy-go v1.25.0
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
@@ -507,7 +507,7 @@ require (
|
||||
gopkg.in/validator.v2 v2.0.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.68.0 // indirect
|
||||
modernc.org/libc v1.72.0 // indirect
|
||||
moul.io/http2curl/v2 v2.3.0 // indirect
|
||||
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||
storj.io/common v0.0.0-20251107171817-6221ae45072c // indirect
|
||||
|
||||
@@ -391,10 +391,10 @@ cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjp
|
||||
cloud.google.com/go/pubsub v1.26.0/go.mod h1:QgBH3U/jdJy/ftjPhTkyXNj543Tin1pRYcdcPRnFIRI=
|
||||
cloud.google.com/go/pubsub v1.27.1/go.mod h1:hQN39ymbV9geqBnfQq6Xf63yNhUAhv9CZhzp5O6qsW0=
|
||||
cloud.google.com/go/pubsub v1.28.0/go.mod h1:vuXFpwaVoIPQMGXqRyUQigu/AX1S3IWugR9xznmcXX8=
|
||||
cloud.google.com/go/pubsub v1.50.1 h1:fzbXpPyJnSGvWXF1jabhQeXyxdbCIkXTpjXHy7xviBM=
|
||||
cloud.google.com/go/pubsub v1.50.1/go.mod h1:6YVJv3MzWJUVdvQXG081sFvS0dWQOdnV+oTo++q/xFk=
|
||||
cloud.google.com/go/pubsub/v2 v2.3.0 h1:DgAN907x+sP0nScYfBzneRiIhWoXcpCD8ZAut8WX9vs=
|
||||
cloud.google.com/go/pubsub/v2 v2.3.0/go.mod h1:O5f0KHG9zDheZAd3z5rlCRhxt2JQtB+t/IYLKK3Bpvw=
|
||||
cloud.google.com/go/pubsub v1.50.2 h1:54Up97HnThdP4H8jjWJSSQ/mnYG2EKon7ZSNETRq0tM=
|
||||
cloud.google.com/go/pubsub v1.50.2/go.mod h1:jyCWeZdGFqd4mitSsBERnJcpqaHBsxQoPkNvjj4sp0w=
|
||||
cloud.google.com/go/pubsub/v2 v2.4.0 h1:oMKNiBQpXImRWnHYla9uSU66ZzByZwBSCJOEs/pTKVg=
|
||||
cloud.google.com/go/pubsub/v2 v2.4.0/go.mod h1:2lS/XQKq5qtOMs6kHBK+WX1ytUC36kLl2ig3zqsGUx8=
|
||||
cloud.google.com/go/pubsublite v1.5.0/go.mod h1:xapqNQ1CuLfGi23Yda/9l4bBCKz/wC3KIJ5gKcxveZg=
|
||||
cloud.google.com/go/pubsublite v1.6.0/go.mod h1:1eFCS0U11xlOuMFV/0iBqw3zP12kddMeCbj/F3FSj9k=
|
||||
cloud.google.com/go/recaptchaenterprise v1.3.1/go.mod h1:OdD+q+y4XGeAlxRaMn1Y7/GveP6zmq76byL6tjPE7d4=
|
||||
@@ -593,8 +593,8 @@ github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3
|
||||
github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw=
|
||||
github.com/DefangLabs/secret-detector v0.0.0-20250403165618-22662109213e h1:rd4bOvKmDIx0WeTv9Qz+hghsgyjikFiPrseXHlKepO0=
|
||||
github.com/DefangLabs/secret-detector v0.0.0-20250403165618-22662109213e/go.mod h1:blbwPQh4DTlCZEfk1BLU4oMIhLda2U+A840Uag9DsZw=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 h1:W8S9TrAyZ4//3PXsU6+Bi+fe/6uIL986GyS7PVzIDL4=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 h1:YCyHs3wUXEe2BEWn40vcoyaQ2ruHNmNwkasfo3Th16A=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 h1:lMHTplAYI9FtmCo/QOcpRxmPA5REVAct1r2riQmDQKw=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264/go.mod h1:wGqkOzRu/ClJibvDgcfuJNAqI2nLhe8g91tPlDKRCdE=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c=
|
||||
@@ -714,8 +714,8 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
|
||||
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 h1:1AX0AthnBQzMx1vbmir3Y4WsnJgiydmnJjiLu+LvXOg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6/go.mod h1:dy0UzBIfwSeot4grGvY1AqFWN5zgziMmWGzysDnHFcQ=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
|
||||
@@ -724,8 +724,8 @@ github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8TH
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21/go.mod h1:YWNWJQNjKigKY1RHVJCuupeWDrrHjRqHm0N9rdrWzYI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 h1:Zy6Tme1AA13kX8x3CnkHx5cqdGWGaj/anwOiWGnA0Xo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12/go.mod h1:ql4uXYKoTM9WUAUSmthY4AtPVrlTBZOvnBJTiCUdPxI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 h1:IbWiN670htmBioc+Zj32vSpJgQ2+OYSlvTvfQ1nCORQ=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1/go.mod h1:tw/B596EUhBWDFGdDGuLC21fVU4A3s4/5Efy8S39W18=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
|
||||
@@ -756,8 +756,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 h1:dzztQ1YmfPrxdrOiuZRMF6f
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19/go.mod h1:YO8TrYtFdl5w/4vmjL8zaBSsiNp3w0L1FfKVKenZT7w=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUdErbMnAFFp12Lm/U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=
|
||||
github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
|
||||
github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.25.0 h1:Sz/XJ64rwuiKtB6j98nDIPyYrV1nVNJ4YU74gttcl5U=
|
||||
github.com/aws/smithy-go v1.25.0/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=
|
||||
@@ -1071,8 +1071,8 @@ github.com/go-fonts/latin-modern v0.2.0/go.mod h1:rQVLdDMK+mK1xscDwsqM5J8U2jrRa3
|
||||
github.com/go-fonts/liberation v0.1.1/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY=
|
||||
github.com/go-fonts/liberation v0.2.0/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY=
|
||||
github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY=
|
||||
github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
|
||||
github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
|
||||
github.com/go-git/go-billy/v5 v5.8.0 h1:I8hjc3LbBlXTtVuFNJuwYuMiHvQJDq1AT6u4DwDzZG0=
|
||||
github.com/go-git/go-billy/v5 v5.8.0/go.mod h1:RpvI/rw4Vr5QA+Z60c6d6LXH0rYJo0uD5SqfmrrheCY=
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
@@ -1397,14 +1397,14 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/inhies/go-bytesize v0.0.0-20220417184213-4913239db9cf h1:FtEj8sfIcaaBfAKrE1Cwb61YDtYq9JxChK1c7AKce7s=
|
||||
github.com/inhies/go-bytesize v0.0.0-20220417184213-4913239db9cf/go.mod h1:yrqSXGoD/4EKfF26AOGzscPOgTTJcyAwM2rpixWT+t4=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c h1:r+KtxPyrhsYeNbsfeqTfEM8xRdwgV6LuNhLZxpXecb4=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd h1:dSIuz2mpJAPQfhHYtG57D0qwSkgC/vQ69gHfeyQ4kxA=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
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.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
|
||||
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
|
||||
github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE=
|
||||
github.com/jackc/pgx/v5 v5.9.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=
|
||||
@@ -1789,8 +1789,8 @@ github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11 h1:4MI2
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11/go.mod h1:3HLX7dwZgvB7nt+Yl/xdzVPcargQ1yBmJEUg3n+jMKM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18 h1:Lc+d3ISfQaMJKWZOE7z4ZSY4RVmdzbn1B0IM8xN18qM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/rclone v1.73.1 h1:FCGZUd7sXO8+nIpbuXGPkd+f23o/ZACefrHtRGDAiDM=
|
||||
github.com/rclone/rclone v1.73.1/go.mod h1:T9HeSXv/SI9qJFkYLqsjY/5ljIFWJTVmTrG7H/4JrPY=
|
||||
github.com/rclone/rclone v1.73.5 h1:r8a9JHYIWUqk7hNRJuMJ3cROkKfB2zmfkADg8ZLYh6I=
|
||||
github.com/rclone/rclone v1.73.5/go.mod h1:WVv8gvA/lEl/Y37e8I8yosm7ZY+Szq7ujXbJS8Ol63o=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
@@ -2103,8 +2103,8 @@ github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.einride.tech/aip v0.73.0 h1:bPo4oqBo2ZQeBKo4ZzLb1kxYXTY1ysJhpvQyfuGzvps=
|
||||
go.einride.tech/aip v0.73.0/go.mod h1:Mj7rFbmXEgw0dq1dqJ7JGMvYCZZVxmGOR3S4ZcV5LvQ=
|
||||
go.einride.tech/aip v0.83.0 h1:TI21IdeOnLTwZEJ3BxtImIZk6bsN2Q+sd0x99SLiQ+M=
|
||||
go.einride.tech/aip v0.83.0/go.mod h1:E8+wdTApA70odnpFzJgsGogHozC2JCIhFJBKPr8bVig=
|
||||
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
|
||||
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
|
||||
go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY=
|
||||
@@ -2981,19 +2981,19 @@ modernc.org/b v1.0.0/go.mod h1:uZWcZfRj1BpYzfN9JTerzlNUnnPsV9O2ZA8JsRcubNg=
|
||||
modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v3 v3.36.3/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
|
||||
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/cc/v4 v4.27.3 h1:uNCgn37E5U09mTv1XgskEVUJ8ADKpmFMPxzGJ0TSo+U=
|
||||
modernc.org/cc/v4 v4.27.3/go.mod h1:3YjcbCqhoTTHPycJDRl2WZKKFj0nwcOIPBfEZK0Hdk8=
|
||||
modernc.org/ccgo/v3 v3.0.0-20220428102840-41399a37e894/go.mod h1:eI31LL8EwEBKPpNpA4bU1/i+sKOwOrQy8D87zWUcRZc=
|
||||
modernc.org/ccgo/v3 v3.0.0-20220430103911-bc99d88307be/go.mod h1:bwdAnOoaIt8Ax9YdWGjxWsdkPcZyRPHqrOvJxaKAKGw=
|
||||
modernc.org/ccgo/v3 v3.16.4/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
|
||||
modernc.org/ccgo/v3 v3.16.6/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ=
|
||||
modernc.org/ccgo/v3 v3.16.8/go.mod h1:zNjwkizS+fIFDrDjIAgBSCLkWbJuHF+ar3QRn+Z9aws=
|
||||
modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo=
|
||||
modernc.org/ccgo/v4 v4.30.2 h1:4yPaaq9dXYXZ2V8s1UgrC3KIj580l2N4ClrLwnbv2so=
|
||||
modernc.org/ccgo/v4 v4.30.2/go.mod h1:yZMnhWEdW0qw3EtCndG1+ldRrVGS+bIwyWmAWzS0XEw=
|
||||
modernc.org/ccgo/v4 v4.32.4 h1:L5OB8rpEX4ZsXEQwGozRfJyJSFHbbNVOoQ59DU9/KuU=
|
||||
modernc.org/ccgo/v4 v4.32.4/go.mod h1:lY7f+fiTDHfcv6YlRgSkxYfhs+UvOEEzj49jAn2TOx0=
|
||||
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
|
||||
@@ -3008,8 +3008,8 @@ modernc.org/libc v1.16.17/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU=
|
||||
modernc.org/libc v1.16.19/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA=
|
||||
modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0=
|
||||
modernc.org/libc v1.17.1/go.mod h1:FZ23b+8LjxZs7XtFMbSzL/EhPxNbfZbErxEHc7cbD9s=
|
||||
modernc.org/libc v1.68.0 h1:PJ5ikFOV5pwpW+VqCK1hKJuEWsonkIJhhIXyuF/91pQ=
|
||||
modernc.org/libc v1.68.0/go.mod h1:NnKCYeoYgsEqnY3PgvNgAeaJnso968ygU8Z0DxjoEc0=
|
||||
modernc.org/libc v1.72.0 h1:IEu559v9a0XWjw0DPoVKtXpO2qt5NVLAnFaBbjq+n8c=
|
||||
modernc.org/libc v1.72.0/go.mod h1:tTU8DL8A+XLVkEY3x5E/tO7s2Q/q42EtnNWda/L5QhQ=
|
||||
modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
@@ -3028,8 +3028,8 @@ modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4=
|
||||
modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
|
||||
modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
|
||||
modernc.org/sqlite v1.49.1 h1:dYGHTKcX1sJ+EQDnUzvz4TJ5GbuvhNJa8Fg6ElGx73U=
|
||||
modernc.org/sqlite v1.49.1/go.mod h1:m0w8xhwYUVY3H6pSDwc3gkJ/irZT/0YEXwBlhaxQEew=
|
||||
modernc.org/strutil v1.1.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs=
|
||||
modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw=
|
||||
modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.20"
|
||||
appVersion: "4.21"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.20.0
|
||||
version: 4.21.0
|
||||
@@ -86,6 +86,13 @@ service SeaweedFiler {
|
||||
}
|
||||
rpc ReplicateLock(ReplicateLockRequest) returns (ReplicateLockResponse) {
|
||||
}
|
||||
|
||||
// Peer chunk sharing — tier 1: mount-server registry.
|
||||
// See design-weed-mount-peer-chunk-sharing.md for details.
|
||||
rpc MountRegister (MountRegisterRequest) returns (MountRegisterResponse) {
|
||||
}
|
||||
rpc MountList (MountListRequest) returns (MountListResponse) {
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
@@ -197,6 +204,10 @@ message FuseAttributes {
|
||||
bytes md5 = 14;
|
||||
uint32 rdev = 16;
|
||||
uint64 inode = 17;
|
||||
int64 ctime = 18; // unix time in seconds, inode change time
|
||||
int32 mtime_ns = 19; // nanosecond component of mtime (0-999999999)
|
||||
int32 ctime_ns = 20; // nanosecond component of ctime (0-999999999)
|
||||
int32 crtime_ns = 21; // nanosecond component of crtime (0-999999999)
|
||||
}
|
||||
|
||||
message CreateEntryRequest {
|
||||
@@ -597,3 +608,31 @@ message StreamMutateEntryResponse {
|
||||
string error = 7; // human-readable error message when the operation failed
|
||||
int32 errno = 8; // POSIX errno (e.g. ENOENT=2, ENOTEMPTY=66) for direct FUSE status mapping
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
// Peer chunk sharing — mount-server registry
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
message MountRegisterRequest {
|
||||
string peer_addr = 1; // host:port where this mount serves peer chunk requests
|
||||
string rack = 2; // locality label (rack); used for peer ranking
|
||||
int32 ttl_seconds = 3; // how long the filer should keep this entry without a heartbeat
|
||||
string data_center = 4; // locality label (data center); coarser than rack
|
||||
}
|
||||
|
||||
message MountRegisterResponse {
|
||||
}
|
||||
|
||||
message MountListRequest {
|
||||
}
|
||||
|
||||
message MountListResponse {
|
||||
repeated MountInfo mounts = 1;
|
||||
}
|
||||
|
||||
message MountInfo {
|
||||
string peer_addr = 1;
|
||||
string rack = 2;
|
||||
int64 last_seen_ns = 3;
|
||||
string data_center = 4;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ use compact_map::CompactMap;
|
||||
use redb::{Database, Durability, ReadableDatabase, ReadableTable, TableDefinition};
|
||||
|
||||
use crate::storage::idx;
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::types::*;
|
||||
|
||||
// ============================================================================
|
||||
@@ -63,6 +64,11 @@ pub struct NeedleMapMetric {
|
||||
pub deletion_count: AtomicI64,
|
||||
pub deletion_byte_count: AtomicU64,
|
||||
pub max_file_key: AtomicU64,
|
||||
/// Largest (offset.to_actual_offset() + get_actual_size(size, version))
|
||||
/// observed during the load walk. Used at volume load to verify that no
|
||||
/// .idx entry references bytes past the end of .dat (issue #8928)
|
||||
/// without paying for a second linear scan.
|
||||
pub max_needle_end: AtomicI64,
|
||||
}
|
||||
|
||||
impl NeedleMapMetric {
|
||||
@@ -108,6 +114,29 @@ impl NeedleMapMetric {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Update `max_needle_end` if this entry's (offset + actual size) exceeds
|
||||
/// the running maximum. Skips deleted/zero-offset entries because they
|
||||
/// don't reserve space in .dat.
|
||||
fn maybe_set_max_needle_end(&self, offset: Offset, size: Size, version: Version) {
|
||||
if offset.is_zero() || !size.is_valid() {
|
||||
return;
|
||||
}
|
||||
let end = offset.to_actual_offset() + get_actual_size(size, version);
|
||||
loop {
|
||||
let current = self.max_needle_end.load(Ordering::Relaxed);
|
||||
if end <= current {
|
||||
break;
|
||||
}
|
||||
if self
|
||||
.max_needle_end
|
||||
.compare_exchange(current, end, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -163,9 +192,10 @@ impl CompactNeedleMap {
|
||||
}
|
||||
|
||||
/// Load from an .idx file, building the in-memory map.
|
||||
pub fn load_from_idx<R: Read + Seek>(reader: &mut R) -> io::Result<Self> {
|
||||
pub fn load_from_idx<R: Read + Seek>(reader: &mut R, version: Version) -> io::Result<Self> {
|
||||
let mut nm = CompactNeedleMap::new();
|
||||
idx::walk_index_file(reader, 0, |key, offset, size| {
|
||||
nm.metric.maybe_set_max_needle_end(offset, size, version);
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
nm.delete_from_map(key);
|
||||
} else {
|
||||
@@ -284,6 +314,12 @@ impl CompactNeedleMap {
|
||||
NeedleId(self.metric.max_file_key.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Largest (offset + actual size) seen during the load walk; 0 if the
|
||||
/// map is empty. See `NeedleMapMetric::maybe_set_max_needle_end`.
|
||||
pub fn max_needle_end(&self) -> i64 {
|
||||
self.metric.max_needle_end.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn index_file_size(&self) -> u64 {
|
||||
self.idx_file_offset
|
||||
}
|
||||
@@ -431,7 +467,7 @@ impl RedbNeedleMap {
|
||||
|
||||
/// Rebuild metrics by scanning all entries in the redb table.
|
||||
/// Called when reusing an existing .rdb without a full rebuild.
|
||||
fn rebuild_metrics_from_db(&self) -> io::Result<()> {
|
||||
fn rebuild_metrics_from_db(&self, version: Version) -> io::Result<()> {
|
||||
let txn = self
|
||||
.db
|
||||
.begin_read()
|
||||
@@ -453,6 +489,8 @@ impl RedbNeedleMap {
|
||||
arr.copy_from_slice(bytes);
|
||||
let nv = unpack_needle_value(&arr);
|
||||
self.metric.maybe_set_max_file_key(key);
|
||||
self.metric
|
||||
.maybe_set_max_needle_end(nv.offset, nv.size, version);
|
||||
if nv.size.is_valid() {
|
||||
self.metric.file_count.fetch_add(1, Ordering::Relaxed);
|
||||
self.metric
|
||||
@@ -477,20 +515,24 @@ impl RedbNeedleMap {
|
||||
/// 2. If .idx size matches → reuse .rdb, rebuild metrics from scan
|
||||
/// 3. If .idx is larger → replay new entries incrementally
|
||||
/// 4. Otherwise (missing, corrupted, .idx smaller) → full rebuild
|
||||
pub fn load_from_idx<R: Read + Seek>(db_path: &str, reader: &mut R) -> io::Result<Self> {
|
||||
pub fn load_from_idx<R: Read + Seek>(
|
||||
db_path: &str,
|
||||
reader: &mut R,
|
||||
version: Version,
|
||||
) -> io::Result<Self> {
|
||||
let idx_size = reader.seek(io::SeekFrom::End(0))?;
|
||||
reader.seek(io::SeekFrom::Start(0))?;
|
||||
|
||||
// Try to reuse existing .rdb
|
||||
if Path::new(db_path).exists() {
|
||||
if let Ok(nm) = Self::try_reuse_rdb(db_path, reader, idx_size) {
|
||||
if let Ok(nm) = Self::try_reuse_rdb(db_path, reader, idx_size, version) {
|
||||
return Ok(nm);
|
||||
}
|
||||
// Reuse failed — fall through to full rebuild
|
||||
reader.seek(io::SeekFrom::Start(0))?;
|
||||
}
|
||||
|
||||
Self::full_rebuild(db_path, reader, idx_size)
|
||||
Self::full_rebuild(db_path, reader, idx_size, version)
|
||||
}
|
||||
|
||||
/// Try to reuse an existing .rdb file. Returns Ok if successful,
|
||||
@@ -499,6 +541,7 @@ impl RedbNeedleMap {
|
||||
db_path: &str,
|
||||
reader: &mut R,
|
||||
idx_size: u64,
|
||||
version: Version,
|
||||
) -> io::Result<Self> {
|
||||
let db = Database::open(db_path)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("redb open: {}", e)))?;
|
||||
@@ -523,7 +566,7 @@ impl RedbNeedleMap {
|
||||
}
|
||||
|
||||
// Rebuild metrics from existing data
|
||||
nm.rebuild_metrics_from_db()?;
|
||||
nm.rebuild_metrics_from_db(version)?;
|
||||
|
||||
if stored_idx_size < idx_size {
|
||||
// .idx grew — replay new entries incrementally
|
||||
@@ -534,6 +577,7 @@ impl RedbNeedleMap {
|
||||
io::Error::new(io::ErrorKind::Other, format!("redb open_table: {}", e))
|
||||
})?;
|
||||
idx::walk_index_file(reader, start_entry, |key, offset, size| {
|
||||
nm.metric.maybe_set_max_needle_end(offset, size, version);
|
||||
let key_u64: u64 = key.into();
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
// Delete: look up old value for metric update, then
|
||||
@@ -607,6 +651,7 @@ impl RedbNeedleMap {
|
||||
db_path: &str,
|
||||
reader: &mut R,
|
||||
idx_size: u64,
|
||||
version: Version,
|
||||
) -> io::Result<Self> {
|
||||
let _ = std::fs::remove_file(db_path);
|
||||
let nm = RedbNeedleMap::new(db_path)?;
|
||||
@@ -614,6 +659,7 @@ impl RedbNeedleMap {
|
||||
// Collect entries from idx file, resolving duplicates/deletions
|
||||
let mut entries: HashMap<NeedleId, Option<NeedleValue>> = HashMap::new();
|
||||
idx::walk_index_file(reader, 0, |key, offset, size| {
|
||||
nm.metric.maybe_set_max_needle_end(offset, size, version);
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
entries.insert(key, None);
|
||||
} else {
|
||||
@@ -788,6 +834,12 @@ impl RedbNeedleMap {
|
||||
NeedleId(self.metric.max_file_key.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Largest (offset + actual size) seen during the load walk; 0 if the
|
||||
/// map is empty. See `NeedleMapMetric::maybe_set_max_needle_end`.
|
||||
pub fn max_needle_end(&self) -> i64 {
|
||||
self.metric.max_needle_end.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn index_file_size(&self) -> u64 {
|
||||
self.idx_file_offset
|
||||
}
|
||||
@@ -988,6 +1040,16 @@ impl NeedleMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest (offset + actual size) seen during the load walk; 0 if the
|
||||
/// map is empty. Used at volume load to detect .idx entries that
|
||||
/// reference past the end of .dat (issue #8928) without a second scan.
|
||||
pub fn max_needle_end(&self) -> i64 {
|
||||
match self {
|
||||
NeedleMap::InMemory(nm) => nm.max_needle_end(),
|
||||
NeedleMap::Redb(nm) => nm.max_needle_end(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Index file size in bytes.
|
||||
pub fn index_file_size(&self) -> u64 {
|
||||
match self {
|
||||
@@ -1157,7 +1219,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let mut cursor = Cursor::new(idx_data);
|
||||
let nm = CompactNeedleMap::load_from_idx(&mut cursor).unwrap();
|
||||
let nm = CompactNeedleMap::load_from_idx(&mut cursor, Version::current()).unwrap();
|
||||
|
||||
assert!(nm.get(NeedleId(1)).is_some());
|
||||
assert!(nm.get(NeedleId(2)).is_none()); // deleted
|
||||
@@ -1300,7 +1362,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let mut cursor = Cursor::new(idx_data);
|
||||
let nm = RedbNeedleMap::load_from_idx(db_path.to_str().unwrap(), &mut cursor).unwrap();
|
||||
let nm = RedbNeedleMap::load_from_idx(db_path.to_str().unwrap(), &mut cursor, Version::current()).unwrap();
|
||||
|
||||
assert!(nm.get(NeedleId(1)).is_some());
|
||||
assert!(nm.get(NeedleId(2)).is_none()); // deleted and removed
|
||||
@@ -1377,7 +1439,7 @@ mod tests {
|
||||
|
||||
// Load back with CompactNeedleMap to verify
|
||||
let mut idx_file = std::fs::File::open(&idx_path).unwrap();
|
||||
let loaded = CompactNeedleMap::load_from_idx(&mut idx_file).unwrap();
|
||||
let loaded = CompactNeedleMap::load_from_idx(&mut idx_file, Version::current()).unwrap();
|
||||
assert_eq!(loaded.file_count(), 2); // only live entries
|
||||
assert!(loaded.get(NeedleId(1)).is_some());
|
||||
assert!(loaded.get(NeedleId(2)).is_none()); // deleted, not saved
|
||||
|
||||
@@ -19,6 +19,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tracing::warn;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::storage::idx;
|
||||
use crate::storage::needle::needle::{self, get_actual_size, Needle, NeedleError};
|
||||
use crate::storage::needle_map::{CompactNeedleMap, NeedleMap, NeedleMapKind, RedbNeedleMap};
|
||||
use crate::storage::super_block::{ReplicaPlacement, SuperBlock, SUPER_BLOCK_SIZE};
|
||||
@@ -73,6 +75,24 @@ pub enum VolumeError {
|
||||
StreamingUnsupported,
|
||||
}
|
||||
|
||||
/// Returns true when a needle read failed because the on-disk bytes are
|
||||
/// unreadable in a permanent way (offset past EOF, header corruption, CRC
|
||||
/// mismatch, malformed v2/v3/v4 fields). Vacuum can safely drop such entries
|
||||
/// during compaction. Anything else (real disk EIO, ERROR_CRC on Windows,
|
||||
/// network timeouts, EROFS, etc.) is transient or environmental and must
|
||||
/// abort the compaction so an operator notices.
|
||||
fn is_skippable_needle_read_error(e: &VolumeError) -> bool {
|
||||
match e {
|
||||
VolumeError::Io(io_err) => io_err.kind() == io::ErrorKind::UnexpectedEof,
|
||||
VolumeError::Needle(NeedleError::SizeMismatch { .. }) => true,
|
||||
VolumeError::Needle(NeedleError::CrcMismatch { .. }) => true,
|
||||
VolumeError::Needle(NeedleError::IndexOutOfRange(_)) => true,
|
||||
VolumeError::Needle(NeedleError::TailTooShort) => true,
|
||||
VolumeError::SizeMismatch => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VolumeInfo (.vif persistence)
|
||||
// ============================================================================
|
||||
@@ -712,6 +732,28 @@ impl Volume {
|
||||
"volumeDataIntegrityChecking failed"
|
||||
);
|
||||
}
|
||||
|
||||
// Structural check: no .idx entry may reference bytes past the
|
||||
// end of .dat. The needle map's load walk above already
|
||||
// populated max_needle_end, so this is a numeric comparison
|
||||
// — no extra disk I/O. A violation marks the volume read-only
|
||||
// so vacuum doesn't silently drop reachable data based on a
|
||||
// corrupt .idx left over from a crashed batched write.
|
||||
// See issue #8928.
|
||||
if let Some(ref nm) = self.nm {
|
||||
if let Ok(dat_size) = self.current_dat_file_size() {
|
||||
let max_end = nm.max_needle_end();
|
||||
if dat_size > 0 && max_end > dat_size as i64 {
|
||||
self.no_write_or_delete = true;
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
max_needle_end = max_end,
|
||||
dat_size,
|
||||
"idx references bytes past end of .dat; marking volume read-only"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -759,7 +801,7 @@ impl Volume {
|
||||
// Open read-only
|
||||
if Path::new(&idx_path).exists() {
|
||||
let mut idx_file = File::open(&idx_path)?;
|
||||
let nm = CompactNeedleMap::load_from_idx(&mut idx_file)?;
|
||||
let nm = CompactNeedleMap::load_from_idx(&mut idx_file, self.version())?;
|
||||
self.nm = Some(NeedleMap::InMemory(nm));
|
||||
} else {
|
||||
// Missing .idx with existing .dat could orphan needles
|
||||
@@ -785,7 +827,7 @@ impl Volume {
|
||||
|
||||
let idx_size = idx_file.metadata()?.len();
|
||||
let mut idx_reader = io::BufReader::new(&idx_file);
|
||||
let mut nm = CompactNeedleMap::load_from_idx(&mut idx_reader)?;
|
||||
let mut nm = CompactNeedleMap::load_from_idx(&mut idx_reader, self.version())?;
|
||||
|
||||
// Re-open for append-only writes
|
||||
let write_file = OpenOptions::new()
|
||||
@@ -808,7 +850,7 @@ impl Volume {
|
||||
// Open read-only
|
||||
if Path::new(&idx_path).exists() {
|
||||
let mut idx_file = File::open(&idx_path)?;
|
||||
let nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_file)?;
|
||||
let nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_file, self.version())?;
|
||||
self.nm = Some(NeedleMap::Redb(nm));
|
||||
} else {
|
||||
// Missing .idx with existing .dat could orphan needles
|
||||
@@ -834,7 +876,7 @@ impl Volume {
|
||||
|
||||
let idx_size = idx_file.metadata()?.len();
|
||||
let mut idx_reader = io::BufReader::new(&idx_file);
|
||||
let mut nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_reader)?;
|
||||
let mut nm = RedbNeedleMap::load_from_idx(&rdb_path, &mut idx_reader, self.version())?;
|
||||
|
||||
// Re-open for append-only writes
|
||||
let write_file = OpenOptions::new()
|
||||
@@ -1752,6 +1794,11 @@ impl Volume {
|
||||
|
||||
let version = self.version();
|
||||
|
||||
// The deeper-than-tail structural check (every (offset + actual size)
|
||||
// fits inside .dat — issue #8928) is now handled in load() via the
|
||||
// needle map's max_needle_end accumulator, so we don't pay for a
|
||||
// second linear scan of the .idx here.
|
||||
|
||||
// Check last 10 index entries (matching Go's CheckVolumeDataIntegrity).
|
||||
// Go starts healthyIndexSize = indexSize and reduces on EOF.
|
||||
// On success: break (err != ErrorSizeMismatch when err == nil).
|
||||
@@ -2683,6 +2730,8 @@ impl Volume {
|
||||
}
|
||||
entries.sort_by_key(|(_, offset, _)| *offset);
|
||||
|
||||
let mut skipped_needles: u64 = 0;
|
||||
let mut skipped_data_bytes: u64 = 0;
|
||||
for (id, offset, size) in entries {
|
||||
// Progress callback
|
||||
if !progress_fn(offset.to_actual_offset()) {
|
||||
@@ -2699,7 +2748,41 @@ impl Volume {
|
||||
id,
|
||||
..Needle::default()
|
||||
};
|
||||
self.read_needle_data_at(&mut n, offset.to_actual_offset(), size)?;
|
||||
match self.read_needle_data_at(&mut n, offset.to_actual_offset(), size) {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
// Record EIO for health monitoring (parity with Go's checkReadWriteError).
|
||||
if let VolumeError::Io(ref io_err) = e {
|
||||
self.check_read_write_error(Some(io_err));
|
||||
}
|
||||
// Only drop the entry when the failure is one of the well-
|
||||
// known permanent-corruption shapes. A transient disk fault,
|
||||
// a tiered-read timeout, or a Windows hardware error (which
|
||||
// surfaces as a generic Io rather than UnexpectedEof) must
|
||||
// abort so an operator notices, rather than silently
|
||||
// compacting away data that might come back on retry.
|
||||
// See issue #8928.
|
||||
if !is_skippable_needle_read_error(&e) {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("cannot hydrate needle from file: {}", e),
|
||||
)));
|
||||
}
|
||||
skipped_needles += 1;
|
||||
if size.is_valid() {
|
||||
skipped_data_bytes += size.0 as u64;
|
||||
}
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
key = id.0,
|
||||
offset = offset.to_actual_offset(),
|
||||
size = size.0,
|
||||
error = %e,
|
||||
"vacuum: dropping unreadable needle"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip TTL-expired needles using the volume's TTL (matches Go's volume_vacuum.go)
|
||||
if n.has_ttl() {
|
||||
@@ -2721,6 +2804,15 @@ impl Volume {
|
||||
new_offset += bytes.len() as i64;
|
||||
}
|
||||
|
||||
if skipped_needles > 0 {
|
||||
warn!(
|
||||
volume_id = self.id.0,
|
||||
skipped_needles,
|
||||
skipped_data_bytes,
|
||||
"vacuum: dropped unreadable index entries during compaction"
|
||||
);
|
||||
}
|
||||
|
||||
dst.sync_all()?;
|
||||
|
||||
// Save new index
|
||||
@@ -3710,6 +3802,138 @@ mod tests {
|
||||
v.cleanup_compact().unwrap();
|
||||
}
|
||||
|
||||
/// Vacuum compaction must tolerate an .idx entry whose offset points past
|
||||
/// the end of the .dat file (the failure mode in issue #8928). The bad
|
||||
/// entry is silently dropped from the resulting .cpx; healthy needles
|
||||
/// survive untouched.
|
||||
#[test]
|
||||
fn test_compact_by_index_drops_dangling_needle() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
// Write a handful of healthy needles to establish a baseline .dat/.idx.
|
||||
for i in 1..=5u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: format!("payload-{}", i).into_bytes(),
|
||||
data_size: format!("payload-{}", i).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let dat_size = v.dat_file_size().unwrap();
|
||||
let bad_key = NeedleId(9999);
|
||||
let bad_offset = Offset::from_actual_offset((dat_size + 1024 * 1024) as i64);
|
||||
let bad_size = Size(2048);
|
||||
v.nm
|
||||
.as_mut()
|
||||
.expect("needle map present")
|
||||
.put(bad_key, bad_offset, bad_size)
|
||||
.unwrap();
|
||||
v.nm.as_ref().unwrap().sync().unwrap();
|
||||
|
||||
// Vacuum must succeed in spite of the dangling entry.
|
||||
v.compact_by_index(0, 0, |_| true)
|
||||
.expect("compact_by_index should tolerate dangling entries");
|
||||
|
||||
// Walk the resulting .cpx and confirm the bad key was dropped while
|
||||
// every healthy key made it through.
|
||||
let cpx_path = v.file_name(".cpx");
|
||||
let mut cpx = File::open(&cpx_path).unwrap();
|
||||
let mut kept: Vec<u64> = Vec::new();
|
||||
idx::walk_index_file(&mut cpx, 0, |key, _, size| {
|
||||
if !size.is_deleted() {
|
||||
kept.push(key.0);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
!kept.contains(&bad_key.0),
|
||||
"dangling key {} should have been dropped from .cpx, got {:?}",
|
||||
bad_key.0,
|
||||
kept
|
||||
);
|
||||
for i in 1..=5u64 {
|
||||
assert!(
|
||||
kept.contains(&i),
|
||||
"healthy key {} missing from compacted .cpx, got {:?}",
|
||||
i,
|
||||
kept
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The needle map's max_needle_end accumulator must let volume.load
|
||||
/// detect an .idx whose entries point past the end of the .dat — the
|
||||
/// deeper-than-tail corruption shape from issue #8928 that the existing
|
||||
/// last-10-entries scan cannot see. The check is populated by the load
|
||||
/// walk and read in volume.load() to flip the volume read-only.
|
||||
#[test]
|
||||
fn test_max_needle_end_detects_dangling_entry() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for i in 1..=4u64 {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: format!("data-{}", i).into_bytes(),
|
||||
data_size: format!("data-{}", i).len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let dat_size = v.dat_file_size().unwrap() as i64;
|
||||
let idx_path = v.file_name(".idx");
|
||||
let version = v.version();
|
||||
|
||||
// Sanity: a fresh load walk over the healthy .idx puts max_needle_end
|
||||
// somewhere inside the .dat.
|
||||
let mut idx_reader = File::open(&idx_path).unwrap();
|
||||
let healthy_nm =
|
||||
CompactNeedleMap::load_from_idx(&mut idx_reader, version).unwrap();
|
||||
let healthy_end = healthy_nm.max_needle_end();
|
||||
assert!(
|
||||
healthy_end > 0 && healthy_end <= dat_size,
|
||||
"healthy volume should have max_needle_end ({}) in [1, dat_size={}]",
|
||||
healthy_end,
|
||||
dat_size
|
||||
);
|
||||
|
||||
// Inject a dangling entry by appending a bogus 16/17-byte record
|
||||
// directly to the .idx, then reload. The load walk should observe
|
||||
// max_needle_end past dat_size — which is exactly the signal
|
||||
// volume.load uses to mark the volume read-only.
|
||||
let bad_offset = Offset::from_actual_offset(dat_size + 4 * 1024 * 1024);
|
||||
let mut idx_append = OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.open(&idx_path)
|
||||
.unwrap();
|
||||
idx::write_index_entry(&mut idx_append, NeedleId(9999), bad_offset, Size(1024))
|
||||
.unwrap();
|
||||
idx_append.sync_all().unwrap();
|
||||
|
||||
let mut idx_reread = File::open(&idx_path).unwrap();
|
||||
let bad_nm = CompactNeedleMap::load_from_idx(&mut idx_reread, version).unwrap();
|
||||
let bad_end = bad_nm.max_needle_end();
|
||||
assert!(
|
||||
bad_end > dat_size,
|
||||
"after dangling-entry inject max_needle_end ({}) should exceed dat_size ({})",
|
||||
bad_end,
|
||||
dat_size
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compaction_revision_relookup() {
|
||||
// Verifies that re_lookup_needle_data_offset returns the correct data offset
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# V3 Phase 14 S8 Assignment
|
||||
|
||||
Date: 2026-04-19
|
||||
Status: draft
|
||||
Owner: sw, with architect and tester review
|
||||
Purpose: execute the final bounded P14 close by producing evidence, scenario classification, and a clean P15 handoff
|
||||
|
||||
## 1. One-Line Goal
|
||||
|
||||
Close P14 as a bounded internal single-active-master topology/control-plane loop, backed by L0/L1/L2 evidence and honest L3/P15 carry-forward.
|
||||
|
||||
## 2. Scope
|
||||
|
||||
Included:
|
||||
|
||||
1. S4-S7 route evidence consolidation
|
||||
2. acceptance matrix for all P14 internal claims
|
||||
3. final supported topology statement
|
||||
4. unsupported/deferred list
|
||||
5. V2 testrunner/scenario port classification
|
||||
6. process smoke gaps review
|
||||
7. 14A final targeted review packet
|
||||
8. P15 handoff mapping
|
||||
|
||||
Excluded:
|
||||
|
||||
1. CSI implementation
|
||||
2. external API implementation
|
||||
3. user data-path production readiness
|
||||
4. migration implementation
|
||||
5. security implementation
|
||||
6. multi-master / HA
|
||||
7. performance or soak claims
|
||||
|
||||
## 3. Required Work
|
||||
|
||||
### A. Evidence Inventory
|
||||
|
||||
Create an evidence table that maps S4-S7 claims to concrete tests and commands.
|
||||
|
||||
Must include:
|
||||
|
||||
1. observation institution
|
||||
2. durable authority institution
|
||||
3. convergence institution
|
||||
4. real-route restart closure
|
||||
5. placement/rebalance/failover policy for accepted topology
|
||||
6. unsupported topology evidence
|
||||
7. old-slot/stale observation rejection
|
||||
8. per-volume isolation
|
||||
|
||||
### B. Gap Classification
|
||||
|
||||
Classify every missing proof as one of:
|
||||
|
||||
1. P14 internal blocker
|
||||
2. P14 S8 test/harness gap
|
||||
3. P15 product-surface gap
|
||||
4. 14A verification follow-up
|
||||
5. explicit non-goal
|
||||
|
||||
Any P14 internal blocker must be fixed before S8 close. A P15 product-surface gap must be carried forward, not disguised as P14 closure.
|
||||
|
||||
### C. V2 Scenario Port Classification
|
||||
|
||||
Inspect V2 scenario/test assets and produce a table:
|
||||
|
||||
| V2 asset | P14 use | P15 use | Port shape | Blocker |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Start with:
|
||||
|
||||
1. `weed/storage/blockvol/testrunner/`
|
||||
2. `weed/storage/blockvol/testrunner/scenarios/public/ha-restart-recovery.yaml`
|
||||
3. `weed/storage/blockvol/testrunner/scenarios/public/ha-failover.yaml`
|
||||
4. `weed/storage/blockvol/testrunner/scenarios/public/fault-partition.yaml`
|
||||
5. `weed/storage/blockvol/test/component/`
|
||||
6. `weed/server/qa_block_*`
|
||||
7. `learn/test` evidence layout
|
||||
|
||||
### D. L2 Process Smoke Decision
|
||||
|
||||
Answer whether current `sparrow` hidden smoke surfaces are sufficient for S8 L2 internal close.
|
||||
|
||||
If not sufficient, add the minimum internal S8 smoke surface needed to prove the S4-S7 route without inventing P15 external product APIs.
|
||||
|
||||
The smoke must check:
|
||||
|
||||
1. real process starts
|
||||
2. durable authority reloads
|
||||
3. observation or fixture input drives controller
|
||||
4. assignment reaches adapter through `VolumeBridge`
|
||||
5. restart does not mint backward
|
||||
6. structured output can be consumed by tester
|
||||
|
||||
### E. 14A Final Targeted Pass
|
||||
|
||||
Prepare a 14A checklist for:
|
||||
|
||||
1. stale authority after restart
|
||||
2. stale observation after reassignment
|
||||
3. old-slot delivery after authority move
|
||||
4. unsupported topology no-op/evidence
|
||||
5. convergence stuck/supersede clearing
|
||||
6. publication honesty during transition
|
||||
7. per-volume isolation
|
||||
|
||||
14A should review findings first. It should not expand P14 scope.
|
||||
|
||||
### F. P15 Handoff
|
||||
|
||||
Produce a P15 handoff table:
|
||||
|
||||
| Gap | Why not P14 | P15 owner track | Required first proof |
|
||||
|---|---|---|---|
|
||||
|
||||
Must include:
|
||||
|
||||
1. CSI lifecycle
|
||||
2. frontend data path
|
||||
3. external volume API
|
||||
4. security/auth
|
||||
5. diagnostics/operator workflow
|
||||
6. migration/coexistence
|
||||
7. deployment/hardening
|
||||
8. final cluster validation agent
|
||||
|
||||
## 4. Required Commands
|
||||
|
||||
At minimum run or document blockers for:
|
||||
|
||||
```text
|
||||
go test ./core/engine ./core/adapter ./core/authority -count=1
|
||||
go test ./cmd/sparrow ./core/authority -count=1
|
||||
go test ./... -count=1
|
||||
```
|
||||
|
||||
If sandbox or Windows filesystem behavior blocks durable-store tests, rerun outside the sandbox and record the reason.
|
||||
|
||||
If L3 hardware scenarios are not runnable, do not fake them. Record the scenario names and blockers.
|
||||
|
||||
## 5. Expected Files
|
||||
|
||||
Expected docs:
|
||||
|
||||
1. `sw-block/design/v3-phase-14-s8-final-bounded-close.md` — this scope document
|
||||
2. `sw-block/design/v3-phase-14-s8-assignment.md` — this assignment
|
||||
3. `sw-block/design/v3-phase-14-s8-closure.md` — final closure statement, created after implementation/evidence
|
||||
4. updates to `v3-phase-14-checklist.md`
|
||||
5. updates to `v3-phase-14-log.md`
|
||||
6. updates to `v3-phase-14a-checklist.md` if 14A final pass finds coverage gaps
|
||||
|
||||
Expected code/tests only if needed:
|
||||
|
||||
1. internal process smoke helper in `cmd/sparrow`
|
||||
2. component evidence consolidation tests in `core/authority` or a shared component package
|
||||
3. scenario classification artifacts under the chosen test/runner directory
|
||||
|
||||
## 6. Acceptance
|
||||
|
||||
S8 can be accepted only when:
|
||||
|
||||
1. the evidence matrix exists and is honest
|
||||
2. all P14 internal blockers are either fixed or explicitly rejected from the P14 claim
|
||||
3. L0 and L1 tests pass
|
||||
4. L2 process smoke is present or its absence is classified as a P15 product-surface blocker
|
||||
5. L3 scenarios are classified with runnable/deferred/blocker status
|
||||
6. 14A final targeted pass has no open P14 safety blocker
|
||||
7. P15 handoff maps every product gap to a P15 track
|
||||
8. final closure statement does not claim production readiness
|
||||
|
||||
## 7. Review Focus
|
||||
|
||||
Architect should review:
|
||||
|
||||
1. whether S8 closure is product-honest
|
||||
2. whether any P15 work was pulled backward into P14
|
||||
3. whether any P14 internal truth gap was pushed forward into P15
|
||||
4. whether test evidence matches the claimed layer
|
||||
5. whether V2 porting stays mechanism-only
|
||||
|
||||
Tester should review:
|
||||
|
||||
1. whether evidence is reproducible
|
||||
2. whether commands and scenario blockers are specific
|
||||
3. whether L2/L3 gaps are visible
|
||||
4. whether final artifacts are enough to start P15 without re-litigating P14
|
||||
@@ -0,0 +1,114 @@
|
||||
# V3 Phase 14 S8 Closure
|
||||
|
||||
Date: 2026-04-20
|
||||
Status: draft — pending 14A final pass + architect + tester sign-off
|
||||
Purpose: the final P14 closure statement per `v3-phase-14-s8-final-bounded-close.md` §10
|
||||
|
||||
## 1. What P14 Now Owns
|
||||
|
||||
After S4-S7, P14 closes **one bounded single-active-master internal topology/control-plane truth loop** for the accepted topology:
|
||||
|
||||
1. **Observation institution (S4)**: heartbeats and inventory flow through `ObservationHost` into a synthesized `ClusterSnapshot` + `SupportabilityReport`. Observation never mints authority. Partial / conflicting / duplicate / unknown / expired inventory becomes explicit `VolumeUnsupportedEvidence`; pending state is distinct from unsupported; per-volume isolation holds.
|
||||
|
||||
2. **Durable authority institution (S5)**: current authority line is durable, single-owner, atomically written, and reloaded synchronously at publisher boot. One record per volume. Corrupt records per-volume-fail-closed and surface as structured `ReloadSkips`. Process lock is exclusive and idempotent. Store never mints authority (boundary-guard test).
|
||||
|
||||
3. **Convergence institution (S6)**: desired assignments have bounded fate — confirmed (cleared), publish-not-observed (stuck-evidence, no re-mint, no churn), or superseded (by newer publisher line or different decision). Passive retry only; no active re-drive. Normal observation lag does NOT supersede. Per-volume retry clock; no global state.
|
||||
|
||||
4. **Real-route restart closure (S7)**: the full `ObservationHost → TopologyController → Publisher(reloaded) → VolumeBridge → VolumeReplicaAdapter` composes correctly at restart. Restart recomputes desired from durable authority + fresh observation (no durable desired store). Old-slot per-replica state is NOT revived from the store (S5 one-record-per-volume rule); live-route old-slot delivery via bridge is rejected by the adapter's monotonic guard. Stale observation cannot move authority backward (4 simulation shapes). Unsupported topology after restart records evidence, not silent idle. L2 process smoke proves real-binary restart × 2 preserves durable truth with no backward mint, via pinned structured JSON.
|
||||
|
||||
5. **Accepted topology** (S8 §4): single active master; multiple volumes; three replica slots per volume on distinct servers; one primary + two candidates; publisher-owned `Epoch` / `EndpointVersion`; durable current line; passive convergence; real `VolumeBridge` into adapter.
|
||||
|
||||
## 2. What P14 Explicitly Does NOT Own
|
||||
|
||||
1. CSI lifecycle (Create/Delete/Publish/Node*).
|
||||
2. iSCSI / NVMe-oF frontend data path.
|
||||
3. External volume management API (REST / gRPC).
|
||||
4. Security / auth (authn, CHAP, encryption).
|
||||
5. Operator diagnostics surface (dashboards, alerts, `/metrics`).
|
||||
6. Operator workflow (drain, planned failover, manual reassign, supervised rebuild).
|
||||
7. V2 ↔ V3 migration and coexistence.
|
||||
8. Deployment / packaging / hardening (systemd, container, backup of durable store).
|
||||
9. Performance / soak / release-hardening claims.
|
||||
10. Multi-master / leader election / distributed authority (explicit non-goal, not just deferred).
|
||||
11. V2 `HandleAssignment` / `promote` / `demote` semantics (explicit non-goal).
|
||||
12. Heartbeat-as-authority (explicit non-goal).
|
||||
|
||||
Every item 1–9 is mapped to a P15 track in `v3-phase-14-s8-p15-handoff.md` §2. Items 10–12 are permanent non-goals.
|
||||
|
||||
## 3. Evidence At L0 / L1 / L2 / L3
|
||||
|
||||
Full matrix: `v3-phase-14-s8-evidence-matrix.md` §3. Summary of coverage:
|
||||
|
||||
| Claim | L0 | L1 | L2 | L3 |
|
||||
|---|---|---|---|---|
|
||||
| 1. Observation system-fed | ✓ | ✓ | — (via L1) | L3 shape only |
|
||||
| 2. Supportability explicit | ✓ | ✓ | — | L3 shape only |
|
||||
| 3. Durable authority / reload | ✓ (13 tests) | ✓ | ✓ (subprocess) | L3 shape only |
|
||||
| 4. No old-slot durable revival | ✓ | ✓ | ✓ | L3 shape only |
|
||||
| 5. Live-route old-slot rejected | ✓ | ✓ | N/A (live-route) | N/A |
|
||||
| 6. Controller-driven bind/reassign/refresh | ✓ (7 tests) | ✓ | ✓ (Bind only — Reassign / RefreshEndpoint are L1-only; subprocess does not ingest heartbeats) | L3 shape only |
|
||||
| 7. Confirmation clears desired | ✓ | ✓ | N/A | L3 shape only |
|
||||
| 8. Stuck evidence bounded / no churn | ✓ (5 tests) | ✓ | N/A | L3 shape only |
|
||||
| 9. Supersede (2 modes) | ✓ (3 tests) | ✓ | N/A | L3 shape only |
|
||||
| 10. Restart re-anchors via VolumeBridge | ✓ | ✓ | **subclaim only** — L2 proves durable `Publisher` reload (Claim 3); the bridge/adapter re-anchor is NOT at L2 because `sparrow` subprocess does not construct `ObservationHost` / controller / bridge / adapter | L3 shape only |
|
||||
| 11. Stale observation cannot go backward | ✓ | ✓ (4 sub-cases) | — | L3 shape only |
|
||||
| 12. Unsupported → evidence | ✓ | ✓ | **not at L2** — `ReloadSkips` is S5 durable-corruption evidence, not observation-layer unsupported-topology. Controller `LastUnsupported` is L1 | L3 shape only |
|
||||
| 13. Per-volume isolation | ✓ (4 tests) | ✓ | N/A | L3 shape only |
|
||||
| 14. Placement / rebalance | ✓ (5 tests) | ✓ | N/A | L3 shape only |
|
||||
| 15. Fence route bounded | ✓ (adapter) | PARTIAL | N/A | L3 shape only |
|
||||
| 16. Boundary guards | ✓ | N/A (structural) | N/A | N/A |
|
||||
|
||||
Sixteen claims; fifteen PROVEN at their target level; one (Claim 15) PARTIAL — adapter-package follow-up per §5 below. L3 is classification-only at P14 (`v3-phase-14-s8-v2-scenario-classification.md`) — L3 entries are scenario SHAPES, not executed evidence. Runnable L3 is P15 Final Gate (Cluster Validation Agent). Claims 6, 10, and 12 have NARROWED L2 cells where the subprocess binary cannot carry the full claim surface; each is handed off to the correct canonical P15 track.
|
||||
|
||||
## 4. Test Baseline (2026-04-20)
|
||||
|
||||
```
|
||||
$ go test ./core/engine ./core/adapter ./core/authority ./cmd/sparrow -count=1
|
||||
ok github.com/seaweedfs/seaweed-block/core/engine 0.016s
|
||||
ok github.com/seaweedfs/seaweed-block/core/adapter 2.344s
|
||||
ok github.com/seaweedfs/seaweed-block/core/authority 4.569s
|
||||
ok github.com/seaweedfs/seaweed-block/cmd/sparrow 2.264s
|
||||
|
||||
$ go test ./... -count=1
|
||||
(14 packages, all PASS)
|
||||
```
|
||||
|
||||
193 Go tests across the P14 scope. L2 subprocess smoke (`TestS7Process_RealSubprocessRestartSmoke`) spawns a real `sparrow` binary twice on the same store directory and asserts the pinned JSON pass-line schema.
|
||||
|
||||
## 5. Residual Risks
|
||||
|
||||
| # | Risk | Scope / carry-forward |
|
||||
|---|---|---|
|
||||
| 1 | Windows `os.RemoveAll` on `t.TempDir()` can race with lock-file release during teardown. No correctness impact. | S7 sketch §8.5 — logged as `t.Logf`, not a failure. |
|
||||
| 2 | Claim 15 PARTIAL: fence quantitative timeout-bound is adapter-package-owned, depends on the uncommitted fence-watchdog branch committing. | `v3-phase-14-s8-p15-handoff.md` item 11 — P14 internal follow-up, NOT P15. Single adapter test replaces PARTIAL status. |
|
||||
| 3 | L2 subprocess drives mint via `StaticDirective`; it does NOT construct `ObservationHost` / controller / bridge / adapter. Full heartbeat-ingress and real-binary adapter route are L1-only in S8. | **P15 T1** Frontend + Data Path (handoff items #1 and #2). |
|
||||
|
||||
**No S8-blocking correctness residuals.** One adapter-owned quantitative fence proof (Claim 15) remains as P14-internal follow-up per row 11 of the handoff table — not a P15 track, not an S8 gate. Zero backward-authority-mint residuals. Zero silent-idle residuals.
|
||||
|
||||
## 6. P15 Track Owners
|
||||
|
||||
Handoff complete per `v3-phase-14-s8-p15-handoff.md`, aligned to canonical `v3-phase-15-product-plan.md` §4. Every P14 residual product gap has a named P15 track and a concrete first-proof gate:
|
||||
|
||||
- T1 Frontend + Data Path Contract (includes subprocess heartbeat ingress)
|
||||
- T2 CSI / External Lifecycle Surface
|
||||
- T3 External Control API
|
||||
- T4 Security And Auth Posture
|
||||
- T5 Diagnostics And Explainability
|
||||
- T6 Operator Workflow
|
||||
- T7 V2/V3 Coexistence And Migration
|
||||
- T8 Deployment / Upgrade / Release Hardening
|
||||
- Final Gate — Cluster Validation Agent
|
||||
|
||||
## 7. Final P14 Claim
|
||||
|
||||
> **P14 has closed one bounded single-active-master internal topology/control-plane truth loop for the accepted topology set.** Observation is system-fed; authority is durable, single-owner, and restart-recovered; convergence has bounded fate; the real `VolumeBridge → adapter` route re-anchors across restart without backward mint or old-slot revival.
|
||||
>
|
||||
> **P14 has NOT closed CSI, external API, frontend data path, migration, security, deployment, performance, or production readiness.** Those nine tracks are handed off to P15 with concrete first-proof gates. Multi-master, V2 `HandleAssignment/promote/demote` semantics, and heartbeat-as-authority are explicit non-goals — not deferrals.
|
||||
|
||||
## 8. Sign-off State
|
||||
|
||||
- **Architect** — pending review of this matrix + handoff.
|
||||
- **Tester** — pending reproducibility check (commands in §4).
|
||||
- **14A final targeted pass** — pending (scope in `v3-phase-14a-checklist.md`).
|
||||
|
||||
S8 cannot be accepted until all three sign off. After that, P14 is closed and the next active work is P15 T1 Frontend.
|
||||
@@ -0,0 +1,241 @@
|
||||
# V3 Phase 14 S8 Evidence Matrix
|
||||
|
||||
Date: 2026-04-20
|
||||
Status: draft (S8 evidence consolidation)
|
||||
Purpose: map every internal P14 claim from `v3-phase-14-s8-final-bounded-close.md` §5 to concrete tests and commands, classify L0/L1/L2/L3 coverage, and surface residual gaps for 14A / P15 handoff
|
||||
|
||||
## 1. How To Read This Matrix
|
||||
|
||||
Each row is one internal P14 claim. Columns:
|
||||
|
||||
- **L0 Unit** — package-local invariant / policy test that proves the claim inside one package.
|
||||
- **L1 Component** — in-process multi-package route test (real `ObservationHost` + `TopologyController` + `Publisher` + `VolumeBridge` + `VolumeReplicaAdapter`, no shell, no kernel).
|
||||
- **L2 Process** — real `sparrow` binary or in-process `Bootstrap()` against a real filesystem store.
|
||||
- **L3 Scenario** — hardware / YAML-driven scenario. For P14 S8, L3 is **classification-only**: the rows below say "L3 shape only, not executed" where a V2 YAML scenario describes the same claim shape. L3 entries are NOT executed evidence; they are the scenario shapes that P15 Cluster Validation (Final Gate) will run. A claim with an L3 shape listed is NOT proven at L3 by S8.
|
||||
- **Status** — `PROVEN` (explicit test); `PARTIAL` (route covered but some sub-claim deferred); `DEFERRED` (intentionally pushed to later slice / P15); `N/A` (not applicable at that level).
|
||||
- **Residual** — what is NOT proven and where it is carried.
|
||||
|
||||
All cited L0/L1/L2 tests live in the committed tree; re-run with:
|
||||
|
||||
```
|
||||
go test ./core/engine ./core/adapter ./core/authority ./cmd/sparrow -count=1
|
||||
```
|
||||
|
||||
Baseline on 2026-04-20: engine 0.02s / adapter 2.3s / authority 4.6s / sparrow 2.3s — all green, 193 Go tests total across the S4-S7 scope.
|
||||
|
||||
## 2. Accepted Topology Claim Recap
|
||||
|
||||
Pinned by the S8 close doc §4. Reproduced here so every row in the matrix below is read against the correct bounded shape:
|
||||
|
||||
1. single active master
|
||||
2. multiple volumes
|
||||
3. three bounded replica slots per volume, distinct servers
|
||||
4. one current authoritative primary, two failover/rebalance candidates
|
||||
5. publisher-owned `Epoch` / `EndpointVersion`
|
||||
6. durable current authority line, one record per volume
|
||||
7. passive convergence (publish → observe → confirm / stuck / supersede)
|
||||
8. real `VolumeBridge` delivery into adapter/engine
|
||||
|
||||
Anything outside this set is P15 or explicit non-goal.
|
||||
|
||||
## 3. Evidence Matrix
|
||||
|
||||
### Claim 1 — Observation is system-fed, not test-authored
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestObservation_BuilderStampsAuthorityFromReader` / `TestObservation_SupportabilityDoesNotReadClusterSnapshotOutput` / `TestObservation_NeverMintsAuthority_BoundaryGuard` | `TestObservation_EndToEnd_SystemFedSnapshotReachesController` / `TestConvergenceRoute_ObservationFedFailover_ConfirmsAndClearsDesired` / `TestS7_ReloadedAuthority_ReanchorsAdapterViaVolumeBridge` | (covered at L1; `sparrow` run-path uses the same `ObservationHost` construction) | L3 shape only, not executed — `ha-restart-recovery.yaml` / `ha-failover.yaml` carry the L3 shape | PROVEN | none at L0/L1 |
|
||||
|
||||
### Claim 2 — Topology supportability is explicit and fail-closed (partial inventory / missing-server / conflict / duplicate / unknown-volume / expired)
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestObservation_PartialInventory_PendingThenUnsupported` / `TestObservation_MissingServerObservation_NeverOrdinaryIneligible` / `TestObservation_ConflictingPrimaryClaim_Unsupported` / `..._NoWinnerEverChosen` / `TestObservation_DuplicateServerTopology_UnsupportedAndEvidenceRecorded` / `TestObservation_UnknownObservedVolume_ProducesUnsupportedEvidence` / `TestObservation_ExpiredFact_SemanticallyIneligible` / `TestObservation_ExpiredDoesNotReachController` / `TestObservation_FreshnessWindowHonored_NotTickMultiples` | `TestObservation_SupportabilityCollapsePropagatesToController` / `TestObservation_SupportabilityCollapseClearsControllerDesired` / `TestS7_Restart_UnsupportedTopologyRecordsEvidence` | N/A (covered by L0/L1) | L3 shape only, not executed — `fault-partition.yaml` is the L3 shape | PROVEN | none |
|
||||
|
||||
### Claim 3 — Durable authority is single-owner, atomic, and restart-recovered
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestFileAuthorityStore_RoundTrip` / `TestFileAuthorityStore_LatestWinsPerVolumeID` / `TestFileAuthorityStore_EnvelopeShape` / `TestDurableAuthority_AtomicWrite_NoTornRecord` / `TestDurableAuthority_CorruptRecord_PerVolumeFailClosed` / `TestDurableAuthority_ProcessLock_ExclusiveOwner` / `TestDurableAuthority_ProcessLock_IdempotentRelease` / `TestDurableAuthority_ProcessLock_SurvivesStaleFileOnDisk` / `TestDurableAuthority_UnreadableIndex_BootFailsClosed` / `TestDurableAuthority_StoreNeverMintsAuthority_BoundaryGuard` / `TestDurableAuthority_StoreWriteCallerAllowlist_BoundaryGuard` / `TestEncodeVolumeIDForFilename_Injective` / `TestEncodeVolumeIDForFilename_NoFilesystemUnsafeOutput` | `TestDurableAuthority_ReloadReproducesCurrentLine` / `TestDurableAuthority_ControllerSeesReloadedLineAtBoot` / `TestDurableAuthority_StoreBackedPublisherRunsNormalRoute` / `TestDurableAuthority_PutFailureRollsBackInMemoryState` / `TestS7_ReloadedAuthority_ReanchorsAdapterViaVolumeBridge` | `TestBootstrap_FreshDir_AcquiresLockAndReloads` / `TestBootstrap_WithExistingRecord_ReloadsPublisherState` / `TestBootstrap_CorruptRecord_LoggedAtStartup` / `TestBootstrap_LockContention_RefusesSecondBootstrap` / `TestS7Process_BootstrapReloadRouteSmoke` / **subprocess**: `TestS7Process_RealSubprocessRestartSmoke` | L3 shape only, not executed — `ha-restart-recovery.yaml` / `diag-restart-recovery.yaml` | PROVEN | Windows `os.RemoveAll` may race with lock release at teardown — logged as residual per S7 sketch §8.5; does NOT affect correctness |
|
||||
|
||||
### Claim 4 — No old-slot durable revival after restart
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestDurableAuthority_StalePreFailoverRecordRejectedOnReload` | `TestS7_Restart_OldSlotNotRevivedFromDurable` (explicitly asserts `LastAuthorityBasis("vr","r1")==false` and `("vr","r2")==Epoch=2` post-restart) | covered by S7 subprocess smoke plus in-process two-run `TestS7Process_RestartDoesNotRegressAuthorityLine` | L3 shape only, not executed | PROVEN | none — row 4a/4b split in S7 closes the original ambiguity |
|
||||
|
||||
### Claim 5 — Live-route monotonic guard rejects stale old-slot delivery (pre-restart)
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| adapter-internal: engine monotonic guards covered in `core/adapter/adapter_test.go` and `core/engine/*_test.go` | `TestS7_LiveRoute_OldSlotDeliveryRejectedByAdapter` (real `VolumeBridge`, in-memory publisher holds both per-replica keys, lower-epoch catch-up rejected) | N/A (live-route, pre-restart) | N/A | PROVEN | none |
|
||||
|
||||
### Claim 6 — Controller-driven bind / reassign / refresh over accepted topology (system-driven, not test-driven)
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestTopologyController_InitialPlacementBalancesAcrossVolumes` / `..._InitialPlacementUsesEvidenceTieBreakOnEqualLoad` / `..._FailoverUsesHighestEvidenceCandidate` / `..._RebalanceMovesToLighterServer` / `..._RebalanceSkipsWhenLoadAlreadyWithinBound` / `..._ObservedAuthorityClearsPending` / `..._StalePreConfirmSnapshotDoesNotDuplicateQueuedMove` | Placement / failover: `TestTopologyControllerToPublisher_E2E_MultiVolumePlacementAndFailover` / `TestObservationHost_IdenticalSupportedSnapshots_NoDuplicateAsks` / `TestObservationHost_VolumeRecovers_ClearsStaleDesired`. Rebalance: `TestTopologyControllerToPublisher_E2E_Rebalance`. **Refresh: `TestConvergenceRoute_RefreshEndpoint_ConfirmsAndClearsDesired`** (host heartbeat changes slot DataAddr/CtrlAddr while publisher holds old addrs → controller emits `IntentRefreshEndpoint` → publisher bumps `EndpointVersion` on same `Epoch` → bridge delivers refreshed `AssignmentInfo` → confirmation clears desired). | `TestS7Process_RealSubprocessRestartSmoke` covers the Bind mint via the real binary (Reassign/Refresh are L1-only in `sparrow` today; real binary does not ingest heartbeats — see §5 L2 scope note). | L3 shape only, not executed | PROVEN | none |
|
||||
|
||||
### Claim 7 — Convergence: confirmation clears desired
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestConvergence_Confirmation_ClearsDesired` / `TestConvergence_Confirmation_RequiresBothSources` / `TestConvergence_StaleObservation_NoConfirmation` / `TestConvergence_StuckThenConfirm_ClearsStuckEvidence` | `TestConvergenceRoute_ObservationFedFailover_ConfirmsAndClearsDesired` | N/A | L3 shape only, not executed | PROVEN | none |
|
||||
|
||||
### Claim 8 — Publish-not-observed stuck evidence is bounded and non-churning
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestConvergence_PublishNotObserved_StuckAfterWindow` / `TestConvergence_Stuck_DoesNotReMintReassign` / `TestConvergence_Reassign_CalledAtMostOncePerDesired` / `TestConvergence_RetryStateIsPerVolume` / `TestConvergence_SupportedRecovery_ClearsPriorUnsupportedEvidence` | `TestConvergenceRoute_PublishNotObserved_StuckWithoutChurn` | N/A | L3 shape only, not executed | PROVEN | none |
|
||||
|
||||
### Claim 9 — Supersede by newer authority or different decision
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestConvergence_Supersede_PublisherAdvancedToOtherReplica` / `TestConvergence_NormalLag_OldObservationDoesNotSupersede` / `TestConvergence_Supersede_DecisionTableProducesDifferentAsk` | `TestConvergenceRoute_Supersede_PublisherMovedElsewhere_DropsStaleDesired` | N/A | L3 shape only, not executed | PROVEN | Case 2 of the supersede rule was intentionally dropped (see S6 sketch §9) — that decision is tested indirectly by `TestConvergence_NormalLag_OldObservationDoesNotSupersede` which would otherwise fail |
|
||||
|
||||
### Claim 10 — Restart re-anchors authority via real `VolumeBridge` into the adapter/engine route
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestDurableAuthority_PublisherAdvancesFromReloaded` | `TestS7_ReloadedAuthority_ReanchorsAdapterViaVolumeBridge` / `TestS7_Restart_RecomputesDesiredNotTransientState` (hard precondition prevents vacuous pass) | **Not at L2.** The `sparrow` subprocess smoke (`TestS7Process_RealSubprocessRestartSmoke`) reloads durable `Publisher` state only; it does NOT construct `ObservationHost`, `TopologyController`, `VolumeBridge`, or `VolumeReplicaAdapter`, so the bridge/adapter re-anchor cannot be counted at L2. L2 proves a strictly narrower subclaim (durable `Publisher` reload — Claim 3). | L3 shape only, not executed — `ha-restart-recovery.yaml` is the L3 shape | PROVEN at L1 (full route); L2 COVERS a subclaim only (durable reload, see Claim 3) | Subprocess heartbeat ingress + real-binary adapter route → **P15 T1** (handoff item #2) |
|
||||
|
||||
### Claim 11 — Stale observation cannot move authority backward
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestConvergence_StaleObservation_NoConfirmation` | `TestS7_Restart_StaleObservationCannotMoveBackward` (4 sub-cases: stale-epoch / stale-replica / stale-endpointVersion / unassigned via `snapshottingReader` host-reader freeze) / `TestConvergenceRoute_PublishNotObserved_StuckWithoutChurn` (proves host-reader lag scenario) | covered at L1 | L3 shape only, not executed — `fault-partition.yaml` | PROVEN | stale-basis simulation is via host-reader freeze; heartbeat wire does not carry authority (documented in S7 sketch §9.1) |
|
||||
|
||||
### Claim 12 — Unsupported topology after restart records evidence, not silent idle
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestConvergence_UnsupportedClearsDesiredWithEvidence` / `TestConvergence_PendingClearsDesired` | `TestS7_Restart_UnsupportedTopologyRecordsEvidence` | **Not at L2.** This claim is about the controller's `LastUnsupported(vid)` surface being populated from conflicting / incomplete observation; that requires `ObservationHost` + controller composition, which the subprocess does not construct. `Bootstrap.ReloadSkips` is a DIFFERENT surface (S5 durable-record corruption, see Claim 3 residual path) and is NOT observation-layer unsupported-topology evidence. | L3 shape only, not executed — `fault-partition.yaml` + `diag-restart-recovery.yaml` are the L3 shapes | PROVEN at L1 | Operator-visible surface over `LastUnsupported` / `LastConvergenceStuck` → **P15 T5** Diagnostics (handoff item #6) |
|
||||
|
||||
### Claim 13 — Per-volume isolation (one volume's failure does not block others)
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestObservation_BadVolumeDoesNotBlockHealthyVolume_Isolation` / `TestObservation_VolumeUnsupportedEvidence_IsolatedPerVolume` / `TestConvergence_OneStuckVolumeDoesNotBlockOthers` / `TestTopologyController_UnsupportedVolumeDoesNotBlockOtherVolumes` | `TestS7_Restart_PerVolumeIsolation` | N/A | L3 shape only, not executed | PROVEN | none |
|
||||
|
||||
### Claim 14 — Placement / rebalance / failover within the accepted topology
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestTopologyController_InitialPlacementBalancesAcrossVolumes` / `..._FailoverUsesHighestEvidenceCandidate` / `..._RebalanceMovesToLighterServer` / `..._RebalanceSkipsWhenLoadAlreadyWithinBound` / `..._OutOfTopologyAuthority_NoAskPlusEvidence` | `TestTopologyControllerToPublisher_E2E_MultiVolumePlacementAndFailover` / `TestTopologyControllerToPublisher_E2E_Rebalance` | N/A | L3 shape only, not executed — `ha-failover.yaml` carries the L3 shape | PROVEN | none |
|
||||
|
||||
### Claim 15 — Fence path routes through bridge + adapter without spurious Healthy
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| adapter fence-slot / monotonic-guard tests in `core/adapter/adapter_test.go` | `TestS7_Restart_FenceRouteBoundedWithoutCallback` (Fence command reaches executor via real bridge; withheld callback does not produce Healthy) | N/A | L3 shape only, not executed | PARTIAL | Full timeout-expiry quantitative bound (watchdog fires at exact deadline + structured event) is adapter-owned proof (sketch §10.1 Path B — S7 may not reconfigure the fence path). Carried to the adapter package's own tests; not an L1 S7 proof |
|
||||
|
||||
### Claim 16 — Boundary guards (no unauthorized `AssignmentInfo` minting, no observation-side asks, no store minting, no hidden adapter ingress)
|
||||
|
||||
| L0 | L1 | L2 | L3 | Status | Residual |
|
||||
|---|---|---|---|---|---|
|
||||
| `TestObservation_NeverMintsAuthority_BoundaryGuard` / `TestDurableAuthority_StoreNeverMintsAuthority_BoundaryGuard` / `TestDurableAuthority_StoreWriteCallerAllowlist_BoundaryGuard` / `TestNonForgeability_*` (AST-level guards in `authority_test.go`) | N/A (structural, not route) | N/A | N/A | PROVEN | none |
|
||||
|
||||
## 4. Gap Classification
|
||||
|
||||
Per S8 assignment §3.B, every missing proof must be classified. Scanning the matrix above:
|
||||
|
||||
### 4.1 P14 internal blockers
|
||||
**None.** Every P14 internal claim has at least one PROVEN row.
|
||||
|
||||
### 4.2 P14 S8 test/harness gap
|
||||
**Claim 15 (fence quantitative bound).** S7 deliberately capped at L1 route coverage. The full `fence timeout fires at exact deadline` proof lives in the adapter package and depends on the uncommitted fence-watchdog branch landing committed. After that commits, a single-file adapter test replaces the current PARTIAL status. Not an S8 gate.
|
||||
|
||||
### 4.3 P15 product-surface gaps (carried forward)
|
||||
See `v3-phase-14-s8-p15-handoff.md` for the full mapping (aligned to canonical `v3-phase-15-product-plan.md` §4 track numbering). Cross-reference summary:
|
||||
|
||||
- Frontend data path + subprocess heartbeat ingress → **P15 T1** Frontend + Data Path
|
||||
- CSI lifecycle → **P15 T2** CSI / External Lifecycle Surface
|
||||
- External control API → **P15 T3** External Control API
|
||||
- Security / auth → **P15 T4** Security And Auth Posture
|
||||
- Operator diagnostics for `LastUnsupported` / `LastConvergenceStuck` / `ReloadSkips` → **P15 T5** Diagnostics
|
||||
- Operator workflow (drain / supervised reassign / rebuild) → **P15 T6** Operator Workflow
|
||||
- V2/V3 migration → **P15 T7** Migration
|
||||
- Deployment / hardening → **P15 T8** Deployment / Release Hardening
|
||||
- End-to-end cluster validation → **P15 Final Gate**
|
||||
|
||||
### 4.4 14A verification follow-ups
|
||||
See `v3-phase-14a-checklist.md` for the sidecar list. The S8 matrix above is the input to 14A's final targeted review.
|
||||
|
||||
### 4.5 Explicit non-goals (do NOT carry)
|
||||
- multi-master / leader election
|
||||
- performance / soak claims at P14 close
|
||||
- long-running stability under production load
|
||||
|
||||
## 5. L2 Process Smoke Decision
|
||||
|
||||
Per S8 assignment §3.D, S8 must answer: are current `sparrow` smoke surfaces sufficient?
|
||||
|
||||
**Answer: scoped YES — L2 proves durable-restart only; the full S4-S7 route remains L1-proven.** (Round-2 architect correction.)
|
||||
|
||||
### 5.1 What L2 proves today
|
||||
|
||||
| Required check | Covered by |
|
||||
|---|---|
|
||||
| real process starts | `TestS7Process_RealSubprocessRestartSmoke` spawns the real `sparrow` binary. |
|
||||
| durable authority reloads | same test + component `TestS7Process_BootstrapReloadRouteSmoke`. |
|
||||
| restart does not mint backward | subprocess asserts `backwardMint: false` in the pinned JSON pass-line; component `TestS7Process_RestartDoesNotRegressAuthorityLine` asserts reloaded `Epoch` equals pre-restart `Epoch`. |
|
||||
| structured output can be consumed by tester | subprocess pass-line schema pinned in S7 sketch §8.4. |
|
||||
|
||||
### 5.2 What L2 deliberately does NOT prove
|
||||
|
||||
| Not covered at L2 | Where it IS proven | Carry-forward |
|
||||
|---|---|---|
|
||||
| "heartbeat wire → `ObservationHost` → `TopologyController`" in a real process. Subprocess drives mints via `StaticDirective`; there is no heartbeat ingress in `sparrow` today. | L1: `TestObservation_EndToEnd_SystemFedSnapshotReachesController`, `TestConvergenceRoute_ObservationFedFailover_ConfirmsAndClearsDesired`, `TestConvergenceRoute_RefreshEndpoint_ConfirmsAndClearsDesired`, `TestS7_ReloadedAuthority_ReanchorsAdapterViaVolumeBridge` (all run real `ObservationHost` → controller → publisher → bridge → adapter, in-process). | **P15 T1 Frontend + Data Path** (subprocess heartbeat ingress is part of the frontend/transport contract). Handoff item #2 in `v3-phase-14-s8-p15-handoff.md`. |
|
||||
| "assignment reaches adapter via bridge IN THE REAL BINARY". The subprocess binary does not construct a VolumeReplicaAdapter — only the in-process component test does. | L1: `TestS7_ReloadedAuthority_ReanchorsAdapterViaVolumeBridge` composes the full stack in-process and waits for adapter `ModeHealthy`. | **P15 T1 Frontend + Data Path** — the first real-binary adapter ↔ frontend route is a T1 deliverable. |
|
||||
| Multi-process mixed-route scenarios (separate authority + observing processes). | N/A at P14 | **P15 Final Gate** (Cluster Validation). |
|
||||
|
||||
### 5.3 Decision
|
||||
|
||||
**No new S8 smoke is added.** The scope split above is honest:
|
||||
|
||||
- L2 subprocess smoke correctly proves durable restart truth.
|
||||
- The full S4-S7 composed route is proven at L1 — including the `RefreshEndpoint` path added in this pass.
|
||||
- Subprocess heartbeat ingress and full real-binary adapter route are genuinely P15 T1 surfaces; inventing a hidden `--s8-route-smoke` heartbeat fixture would be a P15 surface in P14 clothing.
|
||||
|
||||
This is a downgrade from the round-1 matrix claim ("L2 covers the S4-S7 internal route"), which was an overclaim.
|
||||
|
||||
## 6. Baseline Command Result (2026-04-20)
|
||||
|
||||
```
|
||||
$ go test ./core/engine ./core/adapter ./core/authority ./cmd/sparrow -count=1
|
||||
ok github.com/seaweedfs/seaweed-block/core/engine 0.016s
|
||||
ok github.com/seaweedfs/seaweed-block/core/adapter 2.344s
|
||||
ok github.com/seaweedfs/seaweed-block/core/authority 4.569s
|
||||
ok github.com/seaweedfs/seaweed-block/cmd/sparrow 2.264s
|
||||
|
||||
$ go test ./... -count=1
|
||||
(14 packages, all PASS; runtime/schema have no tests)
|
||||
```
|
||||
|
||||
Evidence is reproducible by any reviewer on Windows / Linux from the committed tree on `phase-14` at commit `a6421f9` or later.
|
||||
|
||||
## 7. Residual Risks
|
||||
|
||||
| # | Risk | Scope |
|
||||
|---|------|-------|
|
||||
| 1 | Windows `os.RemoveAll` on the lock file during `t.TempDir()` teardown races with lock release. Does NOT affect correctness — only teardown. | S7 sketch §8.5 residual; logged as `t.Logf` in `restart_route_test.go`. |
|
||||
| 2 | Claim 15 partial: L1 covers "fence command dispatched via real bridge + withheld callback does not produce Healthy"; full timeout-expiry bound is adapter-package-owned. | Closes when adapter fence-watchdog branch commits. Not an S8 blocker. |
|
||||
| 3 | L2 subprocess smoke drives the directive via `StaticDirective`, not real heartbeat ingress to `ObservationHost`. The full heartbeat-path is L1-proven; subprocess widening requires a P15 external surface. | P15 Frontend / Cluster Validation. |
|
||||
|
||||
**No S8-blocking correctness residuals.** One adapter-owned quantitative fence proof (Claim 15) remains as a P14-internal follow-up, landing when the fence-watchdog branch commits. No backward-authority-mint risk on restart. No unsupported-topology silent-idle path.
|
||||
|
||||
## 8. Closure Readiness
|
||||
|
||||
Against S8 acceptance gate (`v3-phase-14-s8-assignment.md` §6):
|
||||
|
||||
1. evidence matrix exists and is honest — **yes** (this document)
|
||||
2. P14 internal blockers fixed or explicitly non-P14 — **yes** (§4.1 empty)
|
||||
3. L0 + L1 tests pass — **yes** (baseline §6)
|
||||
4. L2 process smoke present or absence classified — **yes** (§5; present)
|
||||
5. L3 classified — **yes** (L3 shape only, not executed this slice; see `v3-phase-14-s8-v2-scenario-classification.md`)
|
||||
6. 14A final pass has no open P14 safety blocker — **pending** (14A review on this matrix)
|
||||
7. P15 handoff maps every product gap — **yes** (see `v3-phase-14-s8-p15-handoff.md`)
|
||||
8. final closure statement does not claim production readiness — **yes** (see `v3-phase-14-s8-closure.md`, draft)
|
||||
|
||||
**S8 is evidence-complete pending 14A sign-off.** Awaiting architect + tester review.
|
||||
@@ -0,0 +1,212 @@
|
||||
# V3 Phase 14 S8 Final Bounded Close
|
||||
|
||||
Date: 2026-04-19
|
||||
Status: draft
|
||||
Purpose: close the bounded P14 internal topology/control-plane claim and hand off product surfaces to P15 without pretending P14 is production-ready block storage
|
||||
|
||||
## 1. Target
|
||||
|
||||
`P14 S8` closes one bounded internal control-plane product shape:
|
||||
|
||||
`heartbeat/observation -> ClusterSnapshot -> TopologyController -> Publisher durable authority -> VolumeBridge -> adapter/engine -> observed convergence/restart evidence`.
|
||||
|
||||
S8 is not another protocol slice and not a broad product surface slice. It is the final acceptance and evidence package for the internal single-active-master topology/control-plane loop built by S4-S7.
|
||||
|
||||
## 2. What S8 Must Prove
|
||||
|
||||
S8 must prove, at the appropriate test layer, that:
|
||||
|
||||
1. observation is system-fed, not test-authored
|
||||
2. topology supportability is explicit and fail-closed
|
||||
3. authority is durable, single-owner, and restart-recovered
|
||||
4. controller decisions are system-driven for the accepted topology set
|
||||
5. convergence has bounded fate: confirmed, stuck, or superseded
|
||||
6. restart re-anchors current authority through the real bridge/adapter route
|
||||
7. stale observation, stale old-slot delivery, and unsupported topology do not silently move the system backward
|
||||
8. per-volume isolation holds under mixed supported/unsupported states
|
||||
9. the accepted topology set and unsupported list are explicit
|
||||
10. every product-facing gap is handed to P15, not hidden inside P14 closure
|
||||
|
||||
## 3. What S8 Does Not Prove
|
||||
|
||||
S8 does not prove:
|
||||
|
||||
1. CSI completion
|
||||
2. iSCSI/NVMe product frontend completion
|
||||
3. external volume lifecycle API completion
|
||||
4. real user data-path production readiness
|
||||
5. V2/V3 migration readiness
|
||||
6. multi-master HA / leader election / distributed authority
|
||||
7. final performance or soak readiness
|
||||
|
||||
Those are P15 tracks and the P15 final cluster validation gate.
|
||||
|
||||
S8 may prepare scenario shapes and port test runner muscle for those later gates, but it must not claim them as P14 closure.
|
||||
|
||||
## 4. Accepted Topology Claim
|
||||
|
||||
The S8 supported topology claim is bounded to:
|
||||
|
||||
1. single active master
|
||||
2. multiple volumes
|
||||
3. three bounded replica slots per volume
|
||||
4. distinct server per slot
|
||||
5. one current authoritative primary
|
||||
6. two bounded failover/rebalance candidates
|
||||
7. publisher-owned `Epoch` / `EndpointVersion`
|
||||
8. durable current authority line, one record per volume
|
||||
9. passive convergence: publish, observe, confirm / stuck / supersede
|
||||
10. real `VolumeBridge` delivery into the adapter/engine path
|
||||
|
||||
Anything outside this set is unsupported or deferred.
|
||||
|
||||
## 5. Required Evidence Matrix
|
||||
|
||||
S8 must produce a closure table with these columns:
|
||||
|
||||
| Claim | L0 Unit | L1 Component | L2 Process | L3 Scenario | Status | Residual |
|
||||
|---|---|---|---|---|---|---|
|
||||
|
||||
Minimum claims:
|
||||
|
||||
1. observation supportability
|
||||
2. duplicate/missing/conflicting inventory handling
|
||||
3. durable authority reload
|
||||
4. no old-slot durable revival
|
||||
5. controller-driven bind/reassign/refresh
|
||||
6. convergence confirm/clear
|
||||
7. publish-not-observed stuck evidence
|
||||
8. supersede by newer authority
|
||||
9. restart re-anchor via `VolumeBridge`
|
||||
10. stale observation cannot move backward
|
||||
11. unsupported topology records evidence
|
||||
12. per-volume isolation
|
||||
13. placement/rebalance within accepted topology
|
||||
14. P15 handoff gaps identified
|
||||
|
||||
## 6. Required Test Levels
|
||||
|
||||
### L0 Unit / Invariant
|
||||
|
||||
Required command baseline:
|
||||
|
||||
```text
|
||||
go test ./core/engine ./core/adapter ./core/authority -count=1
|
||||
```
|
||||
|
||||
Must include boundary guards for:
|
||||
|
||||
1. no non-authority `AssignmentInfo` minting
|
||||
2. no observation code constructing assignment asks
|
||||
3. no store minting authority
|
||||
4. no hidden adapter ingress
|
||||
|
||||
### L1 Component
|
||||
|
||||
Required routes:
|
||||
|
||||
1. `ObservationHost -> TopologyController -> Publisher -> VolumeBridge -> VolumeReplicaAdapter`
|
||||
2. observation-fed failover confirms and clears desired
|
||||
3. stuck evidence appears without ask churn
|
||||
4. supersede drops stale desired
|
||||
5. restart route reloads and re-anchors authority
|
||||
6. old-slot live delivery is rejected by adapter monotonicity
|
||||
7. unsupported topology records evidence
|
||||
|
||||
### L2 Local Process
|
||||
|
||||
Required shapes:
|
||||
|
||||
1. real `sparrow` durable authority restart smoke
|
||||
2. process-level S4-S7 route smoke if the current binary surface can expose it cleanly
|
||||
3. if process route smoke cannot be added without inventing P15 surfaces, S8 must record the blocker and carry it to P15 T1/T2/T3
|
||||
|
||||
L2 tests must check exit code, artifact/log output, lock release, reload count, and no backward mint.
|
||||
|
||||
### L3 Hardware / Scenario
|
||||
|
||||
S8 should port scenario shapes from V2 and classify each as:
|
||||
|
||||
1. runnable in P14 internal mode
|
||||
2. blocked by missing P15 frontend/API/data-path surface
|
||||
3. deferred to P15 final cluster validation
|
||||
|
||||
Initial scenario candidates:
|
||||
|
||||
1. restart recovery
|
||||
2. failover
|
||||
3. partition / delayed heartbeat
|
||||
4. unsupported topology
|
||||
5. IO continuity only if frontend/data path exists
|
||||
|
||||
S8 can close P14 with L3 blockers only if the blockers are genuinely P15 product-surface gaps, not internal truth gaps.
|
||||
|
||||
## 7. V2 Port Plan
|
||||
|
||||
### Classify now (S8 scope), port deferred to P15
|
||||
|
||||
S8 **does not port testrunner machinery into the V3 tree** (round-2 doc-consistency fix, aligned with `v3-phase-14-s8-v2-scenario-classification.md` §2). The items below are the V2 muscles S8 inventories and classifies; actual porting is a P15 Final Gate (Cluster Validation Agent) deliverable, not an S8 one.
|
||||
|
||||
1. `weed/storage/blockvol/testrunner/`
|
||||
- **classify now**: runner architecture, scenario YAML shape, action vocabulary, artifact collection, report generation — recorded as PORT-MECHANISM in the classification table. **Port in P15 Final Gate.**
|
||||
|
||||
2. `weed/storage/blockvol/testrunner/scenarios/public` and selected internal scenarios
|
||||
- **classify now**: map each scenario shape to RUNNABLE-P14 / BLOCKED-FRONTEND / BLOCKED-OPS / BLOCKED-HA / BLOCKED-PERF. **Port in P15 Final Gate.**
|
||||
|
||||
3. `weed/storage/blockvol/test/component/`
|
||||
- **classify now**: component harness structure and failure-injection style. **Port in P15 T1 Frontend + Data Path** as that track's real-route harness.
|
||||
|
||||
4. `weed/server/qa_block_*`
|
||||
- **classify now**: coverage taxonomy and route scenario ideas as reference for the evidence matrix (§5). **Port only as applicable per P15 track needs.**
|
||||
|
||||
5. `learn/test` evidence convention
|
||||
- **classify now**: manifest / result / report / run-notes convention referenced as the target shape for future P15 evidence bundles. **Adopt when P15 ships real L3/L4 runs.**
|
||||
|
||||
### Do not port
|
||||
|
||||
1. `promotion.go`
|
||||
2. `HandleAssignment` / `promote` / `demote`
|
||||
3. local runtime self-promotion
|
||||
4. heartbeat timing directly becoming authority
|
||||
5. V2 authority ownership or HA assumptions
|
||||
6. CSI/iSCSI/NVMe product integration as P14 close criteria
|
||||
|
||||
## 8. Deliverables
|
||||
|
||||
S8 must deliver:
|
||||
|
||||
1. final P14 supported-topology statement
|
||||
2. final P14 unsupported/deferred list
|
||||
3. acceptance evidence matrix
|
||||
4. scenario-port classification table
|
||||
5. tester sign-off packet template
|
||||
6. 14A final targeted review checklist
|
||||
7. P15 handoff statement mapping every remaining gap to a P15 track
|
||||
8. code/tests only where needed to make the evidence route real
|
||||
|
||||
## 9. Reject Conditions
|
||||
|
||||
Reject S8 if:
|
||||
|
||||
1. closure is based only on local unit tests
|
||||
2. a claimed route still uses manual assignment choreography
|
||||
3. S8 invents CSI/API/operator surfaces to make tests look complete
|
||||
4. unsupported topology becomes silent idle
|
||||
5. stale observation can emit a newer decision from an old basis
|
||||
6. durable restart can revive stale old-slot truth
|
||||
7. convergence can churn epochs without observation confirmation
|
||||
8. S8 claims production readiness without P15 frontend/data-path/security/cluster validation
|
||||
|
||||
## 10. Closure Statement Shape
|
||||
|
||||
The final S8 closure statement must say exactly:
|
||||
|
||||
1. what P14 now owns
|
||||
2. what P14 explicitly does not own
|
||||
3. what evidence exists at L0/L1/L2/L3
|
||||
4. what risks remain
|
||||
5. which P15 track owns each product gap
|
||||
|
||||
The expected final claim is:
|
||||
|
||||
`P14 has closed one bounded single-active-master internal topology/control-plane truth loop for the accepted topology set. P14 has not closed CSI, external API, frontend data path, migration, security, deployment, performance, or production readiness.`
|
||||
@@ -0,0 +1,86 @@
|
||||
# V3 Phase 14 S8 — P15 Handoff
|
||||
|
||||
Date: 2026-04-20
|
||||
Status: draft (S8 P15 handoff, round-2 aligned to canonical P15 plan)
|
||||
Purpose: map every P14-residual product gap to the canonical P15 track in `v3-phase-15-product-plan.md`, so P15 execution starts from the correct ownership map
|
||||
|
||||
## 1. Handoff Contract
|
||||
|
||||
Per `v3-phase-14-s8-assignment.md` §3.F: every gap that P14 does NOT close must appear here with four columns — the gap, why it is not P14, which canonical P15 track owns it, and the minimum first proof gate.
|
||||
|
||||
**Canonical P15 track numbering** (from `v3-phase-15-product-plan.md` §4):
|
||||
|
||||
1. `T1` Frontend + Data Path Contract
|
||||
2. `T2` CSI / External Lifecycle Surface
|
||||
3. `T3` External Control API
|
||||
4. `T4` Security And Auth Posture
|
||||
5. `T5` Diagnostics And Explainability
|
||||
6. `T6` Operator Workflow
|
||||
7. `T7` V2/V3 Coexistence And Migration
|
||||
8. `T8` Deployment / Upgrade / Release Hardening
|
||||
9. `Final Gate` Cluster Validation Agent
|
||||
|
||||
S8 does NOT invent new tracks, renumber existing ones, or prescribe P15 implementation — only the acceptance gate each P15 track must pass for the handed-off gap.
|
||||
|
||||
## 2. Handoff Table
|
||||
|
||||
| # | Gap | Why not P14 | P15 owner track | Required first proof |
|
||||
|---|---|---|---|---|
|
||||
| 1 | **Frontend data path** (attach → real read → real write → stale-primary fence at frontend boundary) | P14 stops at adapter/engine projection; there is no user-data I/O path in P14, and `adapter.PublishHealthy` is a control-plane signal, not a data-path handshake. | **P15 T1** Frontend + Data Path | L2: V3 frontend backend attaches to an internal volume, writes data, reads it back, triggers P14 reassignment/failover, and verifies the stale primary can no longer serve writes. Covered by T1 §5 Acceptance. |
|
||||
| 2 | **Subprocess heartbeat ingress** — the L2 subprocess smoke (`TestS7Process_RealSubprocessRestartSmoke`) drives mint via `StaticDirective`, not a real heartbeat wire. The full `heartbeat → observation → controller` path is L1-only in the subprocess. | Real heartbeat ingress is a frontend/transport surface. P14 has no intention of adding one. | **P15 T1** Frontend + Data Path (observation ingress is part of the frontend/transport contract) | L2: subprocess accepts heartbeats over a real transport; observation store mutates; controller sees the change; adapter advances — end-to-end in a real process. |
|
||||
| 3 | **CSI driver lifecycle** (CreateVolume / DeleteVolume / ControllerPublish / NodeStage / NodePublish / NodeUnpublish / ControllerUnpublish) | P14 has no orchestrator-facing lifecycle surface; CSI sits above the P14 authority/adapter route. | **P15 T2** CSI / External Lifecycle Surface | L2: CSI sidecar ↔ sparrow process, full Create → Publish → use → Unpublish → Delete cycle via real CSI gRPC against V3 authority (T2 §5 Acceptance). |
|
||||
| 4 | **External control API** (REST / gRPC verbs for list / inspect / create / delete / resize / pause / resume) | P14 exposes hidden test flags on `sparrow` only. An external API is a net-new surface. | **P15 T3** External Control API | L2: OpenAPI / gRPC verbs backed by V3 authority state, exercised by an external client that does NOT construct `AssignmentInfo` directly. |
|
||||
| 5 | **Security / auth posture** (API authn/authz, CHAP for iSCSI, TLS/mTLS where applicable, audit trail) | P14 has no external authn surface. | **P15 T4** Security And Auth | L1+L2: CHAP positive+negative for any iSCSI target shipped; API authn positive+negative; tenant-scoped listing; audit log for mutating verbs. |
|
||||
| 6 | **Operator diagnostics surface** (health dashboard, structured readout of `LastUnsupported` / `LastConvergenceStuck` / `ReloadSkips`, alerts) | P14 records internal evidence (per-volume maps + structured JSON pass-line in S7 subprocess smoke) but does NOT expose it to operators. | **P15 T5** Diagnostics And Explainability | L2: structured `/healthz` + `/metrics` surfacing P14 internal states; L3 `cp85-metrics-verify.yaml` scenario class reshaped for V3. |
|
||||
| 7 | **Operator workflow** (planned failover, graceful drain, supervised reassign, supervised rebuild) | P14 rejects V2 `promote/demote/HandleAssignment`. Operator-initiated actions MUST route through the publisher mint path as ordinary `AssignmentAsk`s. A new workflow surface is required. | **P15 T6** Operator Workflow | L2: operator-triggered reassign lands in `TopologyController` as an `AssignmentAsk`; publisher mints new epoch; adapter converges. Manual promote is explicitly reshaped from V2 semantics. |
|
||||
| 8 | **V2 ↔ V3 migration / coexistence** (online migrate a V2 volume to V3 authority; rollback; mixed V2+V3 cluster) | Migration is a product-level transition requiring both T1 and T6. P14 is V3-only. | **P15 T7** V2/V3 Coexistence And Migration | L3 + L4: `op-upgrade-rollback.yaml` scenario class on a mixed cluster; explicit no-split-brain check under migration. |
|
||||
| 9 | **Deployment / hardening** (systemd / container packaging, lockfile+storedir pathing, crash policy, log rotation, store backup) | `sparrow` is currently a test binary with hidden smoke flags; no deployment story. | **P15 T8** Deployment / Upgrade / Release Hardening | L2: deployable package starts `sparrow` with the durable store correctly mounted; crash-restart cycle preserves the P14 restart truth. L4: release-hardening soak (`cp84-soak-4h.yaml`, `cp85-soak-24h.yaml`). |
|
||||
| 10 | **Final cluster validation** (end-to-end: operator creates volume → data written → primary killed → failover → operator reads data back → no loss, on real hardware) | P14 covers the control plane only; full cluster validation needs T1 + T2 + T3 + T4 + T5 + T6 all landed. | **P15 Final Gate** Cluster Validation Agent | Composite L3/L4 pack: `smoke-block-api` + `ha-restart-recovery` + `ha-failover` + `ha-io-continuity` + `fault-partition` in one run on real hardware, with evidence artifacts in `learn/test/`. |
|
||||
| 11 | **Adapter fence-watchdog quantitative timeout bound** (watchdog fires at exact fence deadline + structured watchdog event for fence lineage) | S7 L1 covers "Fence command reaches executor via bridge + withheld callback does not produce Healthy"; the quantitative bound is adapter-package-owned and depends on the currently-uncommitted fence-watchdog branch. S7 sketch §10.1 Path B forbids S7 from reconfiguring the fence path. | **P14 internal follow-up** (NOT a P15 track) | Single adapter-package test replacing the PARTIAL row for evidence-matrix Claim 15. Lands when the fence-watchdog branch commits. Not an S8 gate. |
|
||||
|
||||
## 3. Out-Of-Scope (NOT Handed Off)
|
||||
|
||||
These are explicit non-goals for both P14 and current P15 bounds — not failures, not deferrals, permanent exclusions.
|
||||
|
||||
| Non-goal | Reason |
|
||||
|---|---|
|
||||
| Multi-master / leader election / distributed authority store | `v3-phase-14-s8-final-bounded-close.md` §3.6 and `v3-phase-15-product-plan.md` §2 both reject. Single-active-master is the accepted topology. Any multi-master claim would require a separate phase with a distributed-authority institution. |
|
||||
| V2 `HandleAssignment` / `promote` / `demote` authority-owning semantic | Rejected at S2, reaffirmed S3-S8. Not ported under any P15 track. Operator promote surface in T6 is reshaped, not ported. |
|
||||
| V2 heartbeat-as-authority | Rejected at S4. Heartbeats are observation inputs only under any P14 or P15 surface. |
|
||||
|
||||
## 4. Handoff Integrity Check
|
||||
|
||||
The table splits into two distinct row classes, each with its own integrity rule:
|
||||
|
||||
**Rows 1-10 — P15 product-surface gaps.** Each of these must satisfy all four checks as of 2026-04-20:
|
||||
|
||||
1. **Gap is not proven at any P14 level.** Cross-reference `v3-phase-14-s8-evidence-matrix.md` §3 — none of rows 1-10 appear as PROVEN or PARTIAL rows of the internal matrix. These are genuinely product-surface gaps P14 never attempted.
|
||||
2. **Gap is assigned to a canonical P15 track.** Numbering matches `v3-phase-15-product-plan.md` §4.
|
||||
3. **First-proof gate is concrete**, not a hand-wave. Every row names a specific test layer and a specific scenario or surface shape.
|
||||
4. **Gap does not silently depend on a P14 claim being wider than is actually proven.** Example: P15 T1 is allowed to depend on P14 Claim 10 (restart re-anchors via VolumeBridge, PROVEN at L1) but NOT on any data-path claim — P14 makes none.
|
||||
|
||||
**Row 11 — P14 internal follow-up (exception to rule #1).** Row 11 is NOT a P15 gap; it is a targeted P14 internal completion that lands when the fence-watchdog branch commits. Its integrity rules are narrower:
|
||||
|
||||
1. **Row 11 MUST correspond to an existing PARTIAL or subclaim-only row of the internal matrix** — the whole point of the row is to name the follow-up that closes that partial. In this case row 11 corresponds to evidence-matrix **Claim 15 PARTIAL** (fence quantitative timeout bound). This is the inverse of rule #1 above: row 11 is listed here precisely BECAUSE it appears as PARTIAL in the matrix.
|
||||
2. **Row 11 MUST NOT be assigned to any P15 track** — it is explicitly labeled "P14 internal follow-up (NOT a P15 track)" in the gap table.
|
||||
3. **Row 11's first-proof gate MUST be a single-package test that closes the matrix PARTIAL row** — not a multi-track composite.
|
||||
|
||||
Splitting the integrity check this way keeps rule #1 for P15 gaps strict (any cross-reference to PROVEN/PARTIAL in the matrix is a bug there) while making row 11's purpose explicit and auditable (every P14 internal follow-up row should have a matrix PARTIAL anchor).
|
||||
|
||||
## 5. Per-Track Dependency Summary
|
||||
|
||||
| P15 Track | Depends on P14 claims | Notes |
|
||||
|---|---|---|
|
||||
| T1 Frontend + Data Path | Claims 3, 6, 10, 14 (durable reload, controller-driven, restart re-anchor, placement/rebalance) | Core product dependency. |
|
||||
| T2 CSI / Lifecycle | T1 + Claims 6, 10 | CSI needs a working data path. |
|
||||
| T3 External API | Claims 6, 14 | API translates external verbs to `AssignmentAsk`s. |
|
||||
| T4 Security | T1 + T3 | Authn/authz sits above the surfaces T1 and T3 expose. |
|
||||
| T5 Diagnostics | Claims 2, 8, 11, 12 (supportability / stuck / unsupported evidence) | Surfaces what P14 already records internally. |
|
||||
| T6 Operator Workflow | Claims 6, 9, 14 (controller-driven, supersede, placement) | Operator actions are `AssignmentAsk`s through the controller. |
|
||||
| T7 Migration | T1 + T6 | Needs both frontend and operator surfaces. |
|
||||
| T8 Deployment | Claim 3 (durable reload) + T1 | Depends on durable store shape and frontend. |
|
||||
| Final Gate | All P14 claims + all P15 tracks | Composite. |
|
||||
|
||||
## 6. Closure
|
||||
|
||||
Every product gap that S8 identifies is listed here with a canonical P15 track or explicit P14 follow-up. Track numbering matches `v3-phase-15-product-plan.md`. P15 execution starts from this table without needing to re-derive the ownership map.
|
||||
@@ -0,0 +1,107 @@
|
||||
# V3 Phase 14 S8 — V2 Scenario Port Classification
|
||||
|
||||
Date: 2026-04-20
|
||||
Status: draft (S8 scenario classification)
|
||||
Purpose: classify every V2 testrunner scenario (`weed/storage/blockvol/testrunner/scenarios/`) as P14-runnable / P15-blocked / deferred, producing the table required by `v3-phase-14-s8-assignment.md` §3.C
|
||||
|
||||
## 1. Classification Vocabulary
|
||||
|
||||
| Class | Meaning | P14 S8 action |
|
||||
|---|---|---|
|
||||
| **RUNNABLE-P14** | Shape maps onto S4-S7 internal surfaces. Runnable with V3 binary + no external frontend. | Keep scenario YAML shape; adapt actions to V3 route; run as L3 classification only (S8 does not need to execute L3 itself). |
|
||||
| **BLOCKED-FRONTEND** | Requires iSCSI / NVMe / CSI / real data path. P15 Frontend track gate. | Preserve scenario reference; hand off to P15 with required precondition. |
|
||||
| **BLOCKED-OPS** | Requires operator CLI / HTTP / admin workflow. P15 Ops track gate. | Hand off to P15 Ops. |
|
||||
| **BLOCKED-HA** | Requires multi-master / leader election / distributed authority. Outside P14/P15 bounded claim. | Mark as out-of-scope for both P14 and current P15 bounds. Document only. |
|
||||
| **BLOCKED-PERF** | Benchmark / soak / perf-baseline; not a correctness gate. | Defer to release-hardening track; document only. |
|
||||
| **PORT-MECHANISM** | Testrunner machinery itself (not a scenario): action vocabulary, artifact collection, scenario YAML shape. | Port machinery without V2 authority semantics (see `v3-phase-14-s6-s8-v2-port-plan.md` §5). |
|
||||
|
||||
## 2. Testrunner Machinery (port decision)
|
||||
|
||||
`weed/storage/blockvol/testrunner/` — YAML-driven runner with action vocabulary, artifact collection, report generation. V3 acceptance pack (P14 S8 carries scenario SHAPES forward; actual V3 testrunner integration is a P15 Cluster Validation track deliverable).
|
||||
|
||||
| Component | Classification | S8 action |
|
||||
|---|---|---|
|
||||
| `testrunner/*.go` (engine / parser / registry / reporter / metrics) | PORT-MECHANISM | Port to V3 when V3 has a stable CLI surface. S8 does not run the runner directly. |
|
||||
| `testrunner/actions/*.go` (37 registered actions) | PORT-MECHANISM | Port per-action as V3 surfaces appear. S8 ports NONE directly (no V3 CLI surface exists yet outside `sparrow` hidden smoke flags). |
|
||||
| `testrunner/scenarios/*.yaml` | scenario-by-scenario below | — |
|
||||
|
||||
**S8 decision:** do not port testrunner machinery into the V3 tree as part of S8. The scenario SHAPES below are what S8 classifies; the runner itself is a P15 Cluster Validation deliverable.
|
||||
|
||||
## 3. Public Scenarios Table
|
||||
|
||||
Path: `weed/storage/blockvol/testrunner/scenarios/public/`.
|
||||
|
||||
| # | Scenario | P14 route it touches | Class | Notes |
|
||||
|---|---|---|---|---|
|
||||
| 1 | `smoke-block-api.yaml` | block create / write / read / verify | **BLOCKED-FRONTEND** | Requires V3 block API surface + real data path. No V3 equivalent exists. P15 Frontend track. |
|
||||
| 2 | `smoke-iscsi.yaml` | kernel iSCSI sanity | **BLOCKED-FRONTEND** | Requires iSCSI target + kernel initiator. P15 Frontend. |
|
||||
| 3 | `smoke-kv.yaml` | KV layer smoke | **BLOCKED-FRONTEND** | KV path is out of P14 scope. P15 Frontend. |
|
||||
| 4 | `e2e-block.yaml` / `e2e-block-auto.yaml` | end-to-end block I/O with V3 backend | **BLOCKED-FRONTEND** | Same preconditions as #1. |
|
||||
| 5 | `e2e-kv.yaml` / `e2e-kv-auto.yaml` / `e2e-combined-auto.yaml` | KV + block combined | **BLOCKED-FRONTEND** | Same as #3. |
|
||||
| 6 | `ha-restart-recovery.yaml` | restart-and-reload closed loop | **RUNNABLE-P14** | Shape maps directly onto S7 restart route. L1 / L2 subprocess smoke already proves the route in-process; scenario YAML would just drive the same route under scenario harness. Keep shape; port when V3 testrunner lands. Covered by Claim 3 / Claim 10 of the evidence matrix at L0/L1/L2. |
|
||||
| 7 | `ha-failover.yaml` | failover under live I/O | **BLOCKED-FRONTEND** | Shape touches S4-S7 (observation → controller → reassign → adapter), but "under live I/O" requires the data path. Classification: control-plane portions are RUNNABLE-P14 (covered by Claim 14 at L1); I/O-continuity portions are BLOCKED-FRONTEND. Split at P15 port time. |
|
||||
| 8 | `ha-full-lifecycle.yaml` | bind → heal → failover → rebuild → restart full cycle | **BLOCKED-FRONTEND** | Contains rebuild + I/O. Rebuild is P14-internal but has no V3 equivalent outside V2 bridge; I/O is frontend. Defer whole scenario to P15. |
|
||||
| 9 | `ha-io-continuity.yaml` | zero data loss across failover | **BLOCKED-FRONTEND** | Entirely data-path. P15 Frontend. |
|
||||
| 10 | `ha-rebuild.yaml` | full-extent rebuild via transport | **BLOCKED-FRONTEND** | Rebuild transport is V2-side; V3 adapter has no rebuild surface in current slice. Deferred. |
|
||||
| 11 | `crash-recovery.yaml` | process kill + restart + verify | **RUNNABLE-P14** | Control-plane portion identical to #6. Data-verify portion is BLOCKED-FRONTEND. Split at port time. |
|
||||
| 12 | `diag-restart-recovery.yaml` | diagnostics on restart | **RUNNABLE-P14** (control-plane subset) | S7 subprocess smoke emits structured JSON (`Bootstrap.ReloadedRecords`, `ReloadSkips`, no-backward-mint); maps onto this shape. Operator dashboards / full diag bundle is P15 Diagnostics. |
|
||||
| 13 | `fault-partition.yaml` | network partition + recovery | **RUNNABLE-P14** (control-plane) | Control-plane partition → stale observation / convergence stuck is covered by Claims 8, 11 at L1. Real netem + data-path partition is BLOCKED-FRONTEND. |
|
||||
| 14 | `fault-netem.yaml` | generic network fault injection | **BLOCKED-FRONTEND** | Needs data path under load. P15. |
|
||||
| 15 | `fault-disk-full.yaml` | ENOSPC on primary | **BLOCKED-FRONTEND** | Needs write path. P15. |
|
||||
| 16 | `consistency-epoch.yaml` | epoch monotonicity across failover | **RUNNABLE-P14** | Pure control-plane claim — already covered at L0 by `TestDurableAuthority_PublisherAdvancesFromReloaded` and at L1 by `TestS7_*` restart tests. L3 version would add cross-process multi-primary validation. |
|
||||
| 17 | `consistency-lease.yaml` | lease-based guard | **BLOCKED-OPS** | Lease semantics are V2-specific; V3 uses publisher-owned Epoch. Would need a reshaped V3 scenario. Defer. |
|
||||
| 18 | `lease-expiry-write-gate.yaml` | write blocked on lease expiry | **BLOCKED-FRONTEND** | Write path + lease. P15. |
|
||||
| 19 | `lease-renewal-under-io.yaml` | lease renewal during I/O | **BLOCKED-FRONTEND** | Same. |
|
||||
| 20 | `cp11b3-auto-failover.yaml` | automatic failover trigger | **RUNNABLE-P14** (control-plane) | Control-plane covered at L1 by `TestTopologyControllerToPublisher_E2E_MultiVolumePlacementAndFailover`. |
|
||||
| 21 | `cp11b3-manual-promote.yaml` | operator-initiated promote | **BLOCKED-OPS** | Requires operator CLI + admin API. P15 Ops. Also — manual promote is V2 semantics; V3 does not have a direct equivalent by design (S6-S8 V2 port plan §2 rejects V2 `promote` ownership). |
|
||||
| 22 | `cp11b3-fast-reconnect.yaml` | reconnect skips unnecessary failover | **RUNNABLE-P14** (control-plane) | S6 normal-lag handling covers this — `TestConvergence_NormalLag_OldObservationDoesNotSupersede`. Full scenario requires real reconnect transport = BLOCKED-FRONTEND for the transport layer, RUNNABLE-P14 for the control-plane. |
|
||||
|
||||
**Public scenarios summary:**
|
||||
- RUNNABLE-P14: 6 scenarios (ha-restart-recovery, crash-recovery control plane, diag-restart-recovery, fault-partition control plane, consistency-epoch, cp11b3-auto-failover control plane) — all covered by Claims 3/10/11/12/14 at L0/L1/L2.
|
||||
- BLOCKED-FRONTEND: 13 scenarios
|
||||
- BLOCKED-OPS: 2 scenarios (lease-consistency, manual-promote)
|
||||
- Mixed (split required at port time): ha-failover, cp11b3-fast-reconnect
|
||||
|
||||
## 4. Internal Scenarios Table (selected, by category)
|
||||
|
||||
Path: `weed/storage/blockvol/testrunner/scenarios/internal/`. 50+ files; classifying by category rather than per-file.
|
||||
|
||||
| Category | Example files | Class | Notes |
|
||||
|---|---|---|---|
|
||||
| Recovery baselines | `recovery-baseline-restart.yaml` / `recovery-baseline-failover.yaml` / `recovery-baseline-partition.yaml` / `recovery-baseline-rebuild.yaml` | RUNNABLE-P14 (control-plane) | Restart/failover/partition portions map onto S4-S7; rebuild portions need V3 rebuild surface (not in S8). |
|
||||
| Coordination dev-cycle | `coord-dev-cycle.yaml` / `coord-ha-failover.yaml` / `coord-smoke-iscsi.yaml` | BLOCKED-FRONTEND | iSCSI / end-to-end workflows. |
|
||||
| CP103 performance matrix | `cp103-*.yaml` | BLOCKED-PERF | Performance, not correctness. Defer to release hardening. |
|
||||
| CP85 chaos | `cp85-chaos-partition.yaml` / `cp85-chaos-primary-kill-loop.yaml` / `cp85-chaos-replica-kill-loop.yaml` / `cp85-role-flap.yaml` / `cp85-session-storm.yaml` | Mixed | Control-plane portions RUNNABLE-P14 as property tests (kill-loop restart, role-flap convergence). I/O portions BLOCKED-FRONTEND. |
|
||||
| CP85 metrics / observability | `cp85-metrics-verify.yaml` | BLOCKED-OPS | Operator metrics pipeline. P15 Diagnostics. |
|
||||
| CP85 soak | `cp85-soak-24h.yaml` / `cp84-soak-4h.yaml` | BLOCKED-PERF | Long-running stability. Release hardening. |
|
||||
| CP85 database / filesystem | `cp85-db-ext4-fsck.yaml` / `cp85-db-sqlite-crash.yaml` / `cp85-expand-failover.yaml` | BLOCKED-FRONTEND | Real filesystem + DB workload. |
|
||||
| Snapshot | `cp11a4-snapshot-export-import.yaml` / `cp83-snapshot-expand.yaml` / `cp85-snapshot-stress.yaml` | BLOCKED-FRONTEND | Snapshot API is P15 Frontend / Ops. |
|
||||
| EC / Erasure | `ec3-*.yaml` / `ec5-*.yaml` | BLOCKED-FRONTEND | Data path erasure. |
|
||||
| HA extensions | `ha-failover-during-rebuild.yaml` / `ha-multi-client-failover.yaml` | BLOCKED-FRONTEND | Multi-client data path. |
|
||||
| Benchmark | `benchmark-*.yaml` / `bench-validated.yaml` / `baseline-full-roce.yaml` / `fsync-only-test.yaml` | BLOCKED-PERF | Performance. |
|
||||
| DM / stripe | `dm-stripe-two-server.yaml` | BLOCKED-FRONTEND | Device mapper. |
|
||||
| Operator lifecycle | `op-upgrade-rollback.yaml` / `op-csi-lifecycle.yaml` / `op-failure-injection.yaml` | BLOCKED-OPS | P15 Ops + Migration. |
|
||||
| Real-workload validation | `cp13-8-real-workload-validation.yaml` | BLOCKED-FRONTEND + BLOCKED-PERF | Full stack. |
|
||||
|
||||
**Internal scenarios summary:**
|
||||
- Directly useful now as P14-internal control-plane L3 shape: ~8 scenarios (recovery-baseline × 3, cp85 chaos × 3, consistency-epoch at public, diag-restart-recovery at public). All already covered at L0/L1/L2 by the evidence matrix; L3 runnable is P15 Cluster Validation.
|
||||
- BLOCKED-FRONTEND majority: ~30 scenarios tied to I/O / iSCSI / NVMe / snapshot / DB workloads.
|
||||
- BLOCKED-OPS: ~8 scenarios tied to operator workflows.
|
||||
- BLOCKED-PERF: ~10 scenarios tied to perf / soak.
|
||||
- BLOCKED-HA: none of the current set explicitly requires multi-master, but `cp85-role-flap` and any future "multi-master" test would be BLOCKED-HA.
|
||||
|
||||
## 5. Port Shape (V3)
|
||||
|
||||
When V3 eventually ships a testrunner integration (P15 Cluster Validation), the port order should be:
|
||||
|
||||
1. **RUNNABLE-P14 scenarios first** — port scenario YAML shape (not V2 actions) against V3 `sparrow` binary + testrunner-wrapped smoke flags. Keep the structured-JSON stdout shape from S7 smoke; wrap it in testrunner action vocabulary.
|
||||
2. **Mixed scenarios second** — split each into (control-plane sub-scenario, data-path sub-scenario). Port the control-plane half first.
|
||||
3. **BLOCKED-FRONTEND last** — arrives when P15 Frontend ships iSCSI / NVMe / CSI.
|
||||
4. **BLOCKED-OPS as needed** — arrives with P15 Ops admin surface.
|
||||
5. **BLOCKED-PERF and BLOCKED-HA** — release-hardening and explicit non-goals respectively.
|
||||
|
||||
## 6. Closure
|
||||
|
||||
Per S8 assignment §3.C, this table is sufficient for S8. Actual scenario PORTING is P15 Cluster Validation work and is not an S8 deliverable. S8 produces the classification + the residual map; P15 executes.
|
||||
|
||||
Evidence that the RUNNABLE-P14 scenarios' underlying claims are proven today is in `v3-phase-14-s8-evidence-matrix.md` §3 — each RUNNABLE-P14 scenario above has at least one PROVEN row backing it at L0/L1/L2.
|
||||
@@ -84,11 +84,14 @@ func NewFuseTestFramework(t *testing.T, config *TestConfig) *FuseTestFramework {
|
||||
|
||||
// freePort asks the OS for a free TCP port in a range where the gRPC
|
||||
// offset (port + 10000) won't collide with well-known ports.
|
||||
// Stay below the Linux ephemeral floor (32768) so the kernel does not
|
||||
// reuse the chosen port for an outbound connection between close() here
|
||||
// and re-bind in the child "weed mini" process.
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
const (
|
||||
minServicePort = 20000
|
||||
maxServicePort = 55535
|
||||
maxServicePort = 32000
|
||||
)
|
||||
|
||||
portCount := maxServicePort - minServicePort + 1
|
||||
@@ -247,6 +250,7 @@ func (f *FuseTestFramework) startMini(config *TestConfig) error {
|
||||
"mini",
|
||||
"-dir=" + f.dataDir,
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-filer.port=" + strconv.Itoa(f.filerPort),
|
||||
"-s3=false",
|
||||
"-webdav=false",
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package fuse_p2p
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// p2pTestCluster manages a minimal SeaweedFS cluster exercising the peer
|
||||
// chunk-sharing (p2p) read path: 1 master, 1 volume, 1 filer, and N FUSE
|
||||
// mounts that all have -peer.enable set. Three mounts is the sweet spot
|
||||
// for integration testing — with 2 mounts the HRW owner of a chunk is
|
||||
// ~50% the reader itself (which short-circuits the peer path); with 3+
|
||||
// mounts it's ≤ 1/3, so a multi-chunk file almost certainly exercises
|
||||
// the remote-owner fan-out.
|
||||
type p2pTestCluster struct {
|
||||
t testing.TB
|
||||
baseDir string
|
||||
weedBinary string
|
||||
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
volumePort int
|
||||
volumeGrpcPort int
|
||||
filerPort int
|
||||
filerGrpcPort int
|
||||
mountPeerPorts []int
|
||||
mountPoints []string
|
||||
|
||||
masterCmd *exec.Cmd
|
||||
volumeCmd *exec.Cmd
|
||||
filerCmd *exec.Cmd
|
||||
mountCmds []*exec.Cmd
|
||||
logFiles []*os.File
|
||||
|
||||
cleanupOnce sync.Once
|
||||
}
|
||||
|
||||
// startP2PTestCluster brings up a cluster with numMounts FUSE mounts,
|
||||
// every one advertising on its own -peer.listen port. All mounts register
|
||||
// with the same filer. Verbose logging (-v=4) is enabled on each mount so
|
||||
// peer-read success/failure messages land in the log file and the test
|
||||
// can grep them to verify the p2p path fired.
|
||||
func startP2PTestCluster(t testing.TB, numMounts int) *p2pTestCluster {
|
||||
require.GreaterOrEqual(t, numMounts, 2, "need at least 2 mounts to exercise p2p")
|
||||
binary := findWeedBinary()
|
||||
if binary == "" {
|
||||
t.Skip("weed binary not found; set WEED_BINARY or ensure it is on PATH")
|
||||
}
|
||||
baseDir, err := os.MkdirTemp("", "seaweedfs_fuse_p2p_test_")
|
||||
require.NoError(t, err)
|
||||
|
||||
c := &p2pTestCluster{
|
||||
t: t,
|
||||
baseDir: baseDir,
|
||||
weedBinary: binary,
|
||||
mountPeerPorts: make([]int, numMounts),
|
||||
mountPoints: make([]string, numMounts),
|
||||
mountCmds: make([]*exec.Cmd, numMounts),
|
||||
}
|
||||
t.Cleanup(c.Stop)
|
||||
|
||||
// master(2) + volume(2) + filer(2) + one peer port per mount.
|
||||
// testutil.AllocatePorts holds all listeners open until every port
|
||||
// is reserved, avoiding the brief close→bind race that would
|
||||
// happen with a per-listener close loop.
|
||||
ports, err := testutil.AllocatePorts(6 + numMounts)
|
||||
require.NoError(t, err)
|
||||
c.masterPort = ports[0]
|
||||
c.masterGrpcPort = ports[1]
|
||||
c.volumePort = ports[2]
|
||||
c.volumeGrpcPort = ports[3]
|
||||
c.filerPort = ports[4]
|
||||
c.filerGrpcPort = ports[5]
|
||||
for i := 0; i < numMounts; i++ {
|
||||
c.mountPeerPorts[i] = ports[6+i]
|
||||
}
|
||||
|
||||
configDir := filepath.Join(baseDir, "config")
|
||||
require.NoError(t, os.MkdirAll(configDir, 0755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(configDir, "security.toml"), []byte(""), 0644))
|
||||
|
||||
require.NoError(t, c.startMaster(configDir))
|
||||
require.NoError(t, c.waitForTCP(c.masterCmd, "master",
|
||||
fmt.Sprintf("127.0.0.1:%d", c.masterPort), 30*time.Second))
|
||||
|
||||
require.NoError(t, c.startVolume(configDir))
|
||||
require.NoError(t, c.waitForTCP(c.volumeCmd, "volume",
|
||||
fmt.Sprintf("127.0.0.1:%d", c.volumePort), 30*time.Second))
|
||||
|
||||
require.NoError(t, c.startFiler(configDir))
|
||||
require.NoError(t, c.waitForTCP(c.filerCmd, "filer",
|
||||
fmt.Sprintf("127.0.0.1:%d", c.filerGrpcPort), 30*time.Second))
|
||||
|
||||
for i := 0; i < numMounts; i++ {
|
||||
mp := filepath.Join(baseDir, fmt.Sprintf("mount%d", i))
|
||||
require.NoError(t, os.MkdirAll(mp, 0755))
|
||||
c.mountPoints[i] = mp
|
||||
require.NoError(t, c.startMount(i, configDir))
|
||||
require.NoError(t, c.waitForMount(mp, 30*time.Second),
|
||||
"mount %d not ready\n%s", i, c.tailLog(fmt.Sprintf("mount%d", i)))
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) Stop() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.cleanupOnce.Do(func() {
|
||||
for i := len(c.mountCmds) - 1; i >= 0; i-- {
|
||||
stopCmd(c.mountCmds[i])
|
||||
// Backup unmount in case the FUSE teardown didn't clean up.
|
||||
exec.Command("fusermount3", "-u", c.mountPoints[i]).Run()
|
||||
exec.Command("fusermount", "-u", c.mountPoints[i]).Run()
|
||||
}
|
||||
stopCmd(c.filerCmd)
|
||||
stopCmd(c.volumeCmd)
|
||||
stopCmd(c.masterCmd)
|
||||
|
||||
for _, f := range c.logFiles {
|
||||
f.Close()
|
||||
}
|
||||
c.copyLogsForCI()
|
||||
if !c.t.Failed() {
|
||||
os.RemoveAll(c.baseDir)
|
||||
}
|
||||
time.Sleep(2 * time.Second) // let ports drain
|
||||
})
|
||||
}
|
||||
|
||||
// MountDir returns the filesystem path of the i-th mount.
|
||||
func (c *p2pTestCluster) MountDir(i int) string { return c.mountPoints[i] }
|
||||
|
||||
// masterAddress / filerAddress return SeaweedFS-style addresses encoding
|
||||
// both ports as "host:httpPort.grpcPort". Without this, downstream
|
||||
// components fall back to the grpcPort = httpPort + 10000 default,
|
||||
// which doesn't match the random port we allocate.
|
||||
func (c *p2pTestCluster) masterAddress() string {
|
||||
return string(pb.NewServerAddress("127.0.0.1", c.masterPort, c.masterGrpcPort))
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) filerAddress() string {
|
||||
return string(pb.NewServerAddress("127.0.0.1", c.filerPort, c.filerGrpcPort))
|
||||
}
|
||||
|
||||
// MountLog returns the contents of mount i's log file.
|
||||
func (c *p2pTestCluster) MountLog(i int) string {
|
||||
return c.tailLogFull(fmt.Sprintf("mount%d", i))
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) startMaster(configDir string) error {
|
||||
c.masterCmd = exec.Command(c.weedBinary,
|
||||
"-logdir="+filepath.Join(c.baseDir, "logs"),
|
||||
"master",
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port="+strconv.Itoa(c.masterPort),
|
||||
"-port.grpc="+strconv.Itoa(c.masterGrpcPort),
|
||||
"-mdir="+filepath.Join(c.baseDir, "master"),
|
||||
)
|
||||
return c.startCmd(c.masterCmd, "master")
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) startVolume(configDir string) error {
|
||||
volDir := filepath.Join(c.baseDir, "volume")
|
||||
if err := os.MkdirAll(volDir, 0755); err != nil {
|
||||
return fmt.Errorf("create volume dir: %w", err)
|
||||
}
|
||||
c.volumeCmd = exec.Command(c.weedBinary,
|
||||
"-logdir="+filepath.Join(c.baseDir, "logs"),
|
||||
"volume",
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port="+strconv.Itoa(c.volumePort),
|
||||
"-port.grpc="+strconv.Itoa(c.volumeGrpcPort),
|
||||
"-master="+c.masterAddress(),
|
||||
"-dir="+volDir,
|
||||
"-max=10",
|
||||
)
|
||||
return c.startCmd(c.volumeCmd, "volume")
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) startFiler(configDir string) error {
|
||||
filerDir := filepath.Join(c.baseDir, "filer")
|
||||
if err := os.MkdirAll(filerDir, 0755); err != nil {
|
||||
return fmt.Errorf("create filer dir: %w", err)
|
||||
}
|
||||
c.filerCmd = exec.Command(c.weedBinary,
|
||||
"-logdir="+filepath.Join(c.baseDir, "logs"),
|
||||
"filer",
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-port="+strconv.Itoa(c.filerPort),
|
||||
"-port.grpc="+strconv.Itoa(c.filerGrpcPort),
|
||||
"-master="+c.masterAddress(),
|
||||
"-defaultStoreDir="+filerDir,
|
||||
// default is -mount.p2p=true; be explicit so the intent is grep-able.
|
||||
"-mount.p2p=true",
|
||||
)
|
||||
return c.startCmd(c.filerCmd, "filer")
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) startMount(idx int, configDir string) error {
|
||||
cacheDir := filepath.Join(c.baseDir, fmt.Sprintf("cache%d", idx))
|
||||
if err := os.MkdirAll(cacheDir, 0755); err != nil {
|
||||
return fmt.Errorf("create cache dir: %w", err)
|
||||
}
|
||||
c.mountCmds[idx] = exec.Command(c.weedBinary,
|
||||
"-logdir="+filepath.Join(c.baseDir, "logs"),
|
||||
"-v=4",
|
||||
"mount",
|
||||
"-filer="+c.filerAddress(),
|
||||
"-dir="+c.mountPoints[idx],
|
||||
"-filer.path=/",
|
||||
"-dirAutoCreate",
|
||||
"-allowOthers=false",
|
||||
"-cacheDir="+cacheDir,
|
||||
"-peer.enable=true",
|
||||
fmt.Sprintf("-peer.listen=127.0.0.1:%d", c.mountPeerPorts[idx]),
|
||||
fmt.Sprintf("-peer.advertise=127.0.0.1:%d", c.mountPeerPorts[idx]),
|
||||
"-peer.dataCenter=dc1",
|
||||
fmt.Sprintf("-peer.rack=rack%d", idx),
|
||||
)
|
||||
return c.startCmd(c.mountCmds[idx], fmt.Sprintf("mount%d", idx))
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) startCmd(cmd *exec.Cmd, name string) error {
|
||||
logPath := filepath.Join(c.baseDir, "logs")
|
||||
if err := os.MkdirAll(logPath, 0755); err != nil {
|
||||
return fmt.Errorf("create log dir: %w", err)
|
||||
}
|
||||
logFile, err := os.Create(filepath.Join(logPath, name+".log"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.logFiles = append(c.logFiles, logFile)
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
return cmd.Start()
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) tailLog(name string) string {
|
||||
data, err := os.ReadFile(filepath.Join(c.baseDir, "logs", name+".log"))
|
||||
if err != nil {
|
||||
return fmt.Sprintf("(log %s not available: %v)", name, err)
|
||||
}
|
||||
const maxTail = 8192
|
||||
if len(data) > maxTail {
|
||||
data = data[len(data)-maxTail:]
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) tailLogFull(name string) string {
|
||||
data, err := os.ReadFile(filepath.Join(c.baseDir, "logs", name+".log"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func (c *p2pTestCluster) copyLogsForCI() {
|
||||
ciLogDir := "/tmp/seaweedfs-fuse-p2p-logs"
|
||||
os.MkdirAll(ciLogDir, 0755)
|
||||
logsDir := filepath.Join(c.baseDir, "logs")
|
||||
entries, err := os.ReadDir(logsDir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
data, err := os.ReadFile(filepath.Join(logsDir, e.Name()))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
os.WriteFile(filepath.Join(ciLogDir, e.Name()), data, 0644)
|
||||
}
|
||||
}
|
||||
|
||||
// waitForTCP polls addr until it accepts a connection, OR the supplied
|
||||
// subprocess exits — whichever comes first. Short-circuiting on child
|
||||
// exit turns a 30 s-spin-on-dead-process into an immediate failure with
|
||||
// the tail of its log. cmd may be nil for callers that don't track a
|
||||
// process; in that case we fall back to pure polling.
|
||||
//
|
||||
// Liveness is checked with signal 0 (POSIX "is this process alive").
|
||||
// We deliberately do NOT call cmd.Wait() in a goroutine here because
|
||||
// stopCmd() later calls Wait() at shutdown, and only one Wait per
|
||||
// process is allowed.
|
||||
func (c *p2pTestCluster) waitForTCP(cmd *exec.Cmd, name, addr string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := net.DialTimeout("tcp", addr, time.Second)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
return nil
|
||||
}
|
||||
if cmd != nil && cmd.Process != nil {
|
||||
// signal 0 doesn't actually send anything; it just asks
|
||||
// the kernel whether the process exists. An error here
|
||||
// (typically "process already finished" or ESRCH) means
|
||||
// the child died before coming up.
|
||||
if sigErr := cmd.Process.Signal(syscall.Signal(0)); sigErr != nil {
|
||||
return fmt.Errorf("%s exited before listening on %s: %v\n%s",
|
||||
name, addr, sigErr, c.tailLog(name))
|
||||
}
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("service at %s not ready within timeout\n%s", addr, c.tailLog(name))
|
||||
}
|
||||
|
||||
// waitForMount waits for a FUSE filesystem to actually be mounted by
|
||||
// watching the device id flip (FUSE mounts have a different Dev than
|
||||
// their parent dir).
|
||||
func (c *p2pTestCluster) waitForMount(mountPoint string, timeout time.Duration) error {
|
||||
parentDir := filepath.Dir(mountPoint)
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
parentStat, err := os.Stat(parentDir)
|
||||
if err != nil {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
mountStat, err := os.Stat(mountPoint)
|
||||
if err != nil {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
parentSys := parentStat.Sys().(*syscall.Stat_t)
|
||||
mountSys := mountStat.Sys().(*syscall.Stat_t)
|
||||
if parentSys.Dev != mountSys.Dev {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("mount point %s not ready within timeout (FUSE not detected)", mountPoint)
|
||||
}
|
||||
|
||||
// --- utilities (binary discovery, process shutdown) ---
|
||||
//
|
||||
// Port allocation is delegated to testutil.MustAllocatePorts, which
|
||||
// holds all listeners open until every port is reserved before
|
||||
// returning them in a batch — safer than the per-listener
|
||||
// close-then-reserve pattern fuse_dlm originally used.
|
||||
|
||||
func findWeedBinary() string {
|
||||
if env := os.Getenv("WEED_BINARY"); env != "" {
|
||||
if _, err := os.Stat(env); err == nil {
|
||||
return env
|
||||
}
|
||||
}
|
||||
if p, err := exec.LookPath("weed"); err == nil {
|
||||
return p
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// stopCmd kills a child process with SIGTERM and waits up to 5 s, then
|
||||
// escalates to SIGKILL. Tolerates nil and already-exited processes.
|
||||
func stopCmd(cmd *exec.Cmd) {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return
|
||||
}
|
||||
cmd.Process.Signal(syscall.SIGTERM)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
cmd.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
cmd.Process.Signal(syscall.SIGKILL)
|
||||
<-done
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package fuse_p2p
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// peerReadSuccessMarker is the log line tryPeerRead emits when a peer
|
||||
// fetch succeeded. The test greps non-writer mount logs for it to
|
||||
// prove the p2p path fired. At glog verbosity 4 (framework sets -v=4).
|
||||
const peerReadSuccessMarker = "peer read successful"
|
||||
|
||||
// seedConvergenceTimeout bounds how long the test waits for:
|
||||
// - the filer registry to list all mounts,
|
||||
// - every mount's seed view (via MountList poll) to include all peers,
|
||||
// - the first announcer flush cycle to publish chunk holders.
|
||||
//
|
||||
// With defaults the mount polls MountList every 30 s and flushes
|
||||
// ChunkAnnounce every 15 s. Allowing 45 s absorbs one MountList refresh
|
||||
// plus one announce cycle plus some slop for CI variance.
|
||||
const seedConvergenceTimeout = 90 * time.Second
|
||||
|
||||
// TestPeerChunkSharing_ReadersPullFromPeerCache is the headline p2p
|
||||
// integration test. It proves at least one non-writer mount can satisfy
|
||||
// a read from the writer's chunk cache instead of the volume tier.
|
||||
//
|
||||
// 1. Bring up 1 master/volume/filer + 3 mounts, all with -peer.enable.
|
||||
// 2. Mount 0 writes a ~8 MiB file and reads it back so chunks land in
|
||||
// its local cache and the announcer publishes them.
|
||||
// 3. Wait for seed convergence + at least one announcer flush cycle.
|
||||
// 4. BOTH mount 1 and mount 2 read the file.
|
||||
//
|
||||
// Why both readers: with 3 mounts, HRW picks one owner for the chunk.
|
||||
// If that owner is mount 1, only mount 2's read will hit the peer
|
||||
// path (mount 1's tryPeerRead bails on owner==self). If that owner is
|
||||
// mount 2, only mount 1's read will. If that owner is mount 0 (the
|
||||
// writer), both can. So by reading from both, we deterministically
|
||||
// guarantee at least one non-writer mount exercises the peer path.
|
||||
//
|
||||
// Once the peer fetch populates its local cache, subsequent reads
|
||||
// short-circuit on IsInCache — so we only get one real shot per mount
|
||||
// per chunk. That's fine: one success is all the test needs.
|
||||
func TestPeerChunkSharing_ReadersPullFromPeerCache(t *testing.T) {
|
||||
c := startP2PTestCluster(t, 3)
|
||||
|
||||
// ~8 MiB, pseudo-random so compression doesn't collapse it to one block.
|
||||
payload := make([]byte, 8*1024*1024)
|
||||
rng := rand.New(rand.NewPCG(1, 2))
|
||||
for i := range payload {
|
||||
payload[i] = byte(rng.Uint32())
|
||||
}
|
||||
|
||||
const relPath = "p2p-test.bin"
|
||||
writer := c.MountDir(0)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(writer, relPath), payload, 0644))
|
||||
|
||||
// Warm mount 0's chunk cache by reading back through its own FUSE.
|
||||
// Without this the chunks are on the volume server but not yet
|
||||
// in anyone's peer-servable cache.
|
||||
readBack, err := os.ReadFile(filepath.Join(writer, relPath))
|
||||
require.NoError(t, err)
|
||||
require.True(t, bytes.Equal(readBack, payload), "write-then-read on writer mount should match")
|
||||
|
||||
waitForSeedConvergence(t, c, seedConvergenceTimeout)
|
||||
|
||||
// Give the announcer several flush windows to push chunk-holder
|
||||
// entries to the HRW owners. First flush may see the writer's seed
|
||||
// view incomplete (only self) and defer all fids; subsequent
|
||||
// flushes re-check against a refreshed seed view. announce interval
|
||||
// is 15 s, so 45 s covers three attempts.
|
||||
time.Sleep(45 * time.Second)
|
||||
|
||||
// Read from both non-writer mounts. For any HRW outcome on any
|
||||
// chunk, at least one of these reads will NOT have the reader as
|
||||
// the HRW owner, so its tryPeerRead will proceed to ChunkLookup +
|
||||
// FetchChunk.
|
||||
for _, idx := range []int{1, 2} {
|
||||
got, err := os.ReadFile(filepath.Join(c.MountDir(idx), relPath))
|
||||
require.NoError(t, err, "read from mount %d must succeed\n--- mount%d ---\n%s",
|
||||
idx, idx, tailLines(c.MountLog(idx), 80))
|
||||
require.Equal(t, md5.Sum(payload), md5.Sum(got),
|
||||
"mount %d returned mismatched bytes (len got=%d want=%d)", idx, len(got), len(payload))
|
||||
}
|
||||
|
||||
// Content matches alone doesn't prove p2p — the volume fallback
|
||||
// would also satisfy the reads. Require at least one non-writer
|
||||
// mount's log to contain the peer-read success marker.
|
||||
var sawPeerRead bool
|
||||
for _, idx := range []int{1, 2} {
|
||||
if strings.Contains(c.MountLog(idx), peerReadSuccessMarker) {
|
||||
sawPeerRead = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !sawPeerRead {
|
||||
t.Fatalf("no non-writer mount logged %q — peer read path never fired.\n"+
|
||||
"--- mount0 (writer) tail ---\n%s\n--- mount1 tail ---\n%s\n--- mount2 tail ---\n%s",
|
||||
peerReadSuccessMarker,
|
||||
tailLines(c.MountLog(0), 60), tailLines(c.MountLog(1), 60), tailLines(c.MountLog(2), 60))
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSeedConvergence polls each mount's log looking for any sign
|
||||
// that MountList returned a peer list containing the other mounts.
|
||||
func waitForSeedConvergence(t *testing.T, c *p2pTestCluster, timeout time.Duration) {
|
||||
t.Helper()
|
||||
// The first MountRegister happens synchronously during mount startup,
|
||||
// and the first MountList is pulled right after. 30 s is the refresh
|
||||
// interval; waiting one full cycle here guarantees every mount has
|
||||
// at minimum observed the others in its seed view.
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
ready := true
|
||||
for i := range c.mountCmds {
|
||||
if !strings.Contains(c.MountLog(i), "peer-grpc listening on") {
|
||||
ready = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ready {
|
||||
time.Sleep(30 * time.Second)
|
||||
return
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("peer-grpc servers did not come up within %s", timeout)
|
||||
}
|
||||
|
||||
// tailLines returns the last n newline-delimited lines of s, or the
|
||||
// whole thing if shorter. Keeps test failures readable.
|
||||
func tailLines(s string, n int) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
if len(lines) <= n {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("... (%d earlier lines omitted) ...\n%s",
|
||||
len(lines)-n, strings.Join(lines[len(lines)-n:], "\n"))
|
||||
}
|
||||
+11
-10
@@ -45,7 +45,7 @@ require (
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
|
||||
@@ -57,7 +57,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
|
||||
@@ -70,6 +70,7 @@ require (
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
github.com/buengese/sgzip v0.1.1 // indirect
|
||||
github.com/buger/jsonparser v1.1.2 // indirect
|
||||
github.com/bwmarrin/snowflake v0.3.0 // indirect
|
||||
github.com/calebcase/tmpfile v1.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/chilts/sid v0.0.0-20190607042430-660e94789ec9 // indirect
|
||||
@@ -241,20 +242,20 @@ require (
|
||||
go.mongodb.org/mongo-driver v1.17.9 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect
|
||||
go.opentelemetry.io/otel v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.43.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.49.0 // indirect
|
||||
golang.org/x/crypto v0.50.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/image v0.38.0 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/term v0.41.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/term v0.42.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/api v0.274.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
|
||||
+28
-26
@@ -116,8 +116,8 @@ github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.13 h1:5KgbxMaS2coSWRrx9TX/QtWbqzgQkOdEa3sZPhBhCSg=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.13/go.mod h1:8zz7wedqtCbw5e9Mi2doEwDyEgHcEE9YOJp6a8jdSMY=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14/go.mod h1:U4/V0uKxh0Tl5sxmCBZ3AecYny4UNlVmObYjKuuaiOo=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8THYELoX6gVcUvgl6fI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
|
||||
@@ -140,8 +140,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3x
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0 h1:foqo/ocQ7WqKwy3FojGtZQJo0FR4vto9qnz9VaumbCo=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.98.0/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0 h1:hlSuz394kV0vhv9drL5lhuEFbEOEP1VyQpy15qWh1Pk=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.99.0/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 h1:QKZH0S178gCmFEgst8hN0mCX1KxLgHBKKY/CLqwP8lg=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9/go.mod h1:7yuQJoT+OoH8aqIxw9vwF+8KpvLZ8AWmvmUWHsGQZvI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 h1:lFd1+ZSEYJZYvv9d6kXzhkZu07si3f+GQ1AaYwa2LUM=
|
||||
@@ -170,6 +170,8 @@ github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU
|
||||
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
|
||||
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
|
||||
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
|
||||
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
|
||||
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
|
||||
github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
|
||||
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
|
||||
@@ -752,16 +754,16 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
|
||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
@@ -785,8 +787,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -867,8 +869,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -944,8 +946,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -957,8 +959,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -974,8 +976,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1028,8 +1030,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
|
||||
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -49,12 +49,20 @@ func testConsumerGroupBasicFunctionality(t *testing.T, addr string) {
|
||||
err = client.ProduceMessages(topicName, messages)
|
||||
testutil.AssertNoError(t, err, "Failed to produce messages")
|
||||
|
||||
// Test with multiple consumers in the same group
|
||||
// Test with multiple consumers in the same group. The messages channel is
|
||||
// shared so the assertion can verify total-consumed/no-duplicates across the
|
||||
// group. Each consumer gets its own handler (and its own ready channel) so
|
||||
// we can wait for each distinct consumer to reach Setup, rather than
|
||||
// relying on a single close() that only signals once.
|
||||
numConsumers := 3
|
||||
handler := &ConsumerGroupHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, len(messages)),
|
||||
ready: make(chan bool),
|
||||
t: t,
|
||||
handlers := make([]*ConsumerGroupHandler, numConsumers)
|
||||
sharedMessages := make(chan *sarama.ConsumerMessage, len(messages))
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
handlers[i] = &ConsumerGroupHandler{
|
||||
messages: sharedMessages,
|
||||
ready: make(chan bool),
|
||||
t: t,
|
||||
}
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
@@ -72,35 +80,32 @@ func testConsumerGroupBasicFunctionality(t *testing.T, addr string) {
|
||||
}
|
||||
defer consumerGroup.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err = consumerGroup.Consume(ctx, []string{topicName}, handler)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
consumerErrors <- fmt.Errorf("consumer %d: consumption error: %v", consumerID, err)
|
||||
return
|
||||
}
|
||||
runConsumeLoop(t, ctx, fmt.Sprintf("Consumer%d", consumerID),
|
||||
consumerGroup, []string{topicName}, handlers[consumerID])
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Wait for consumers to be ready
|
||||
readyCount := 0
|
||||
for readyCount < numConsumers {
|
||||
// Wait for each consumer to be ready. Multi-consumer rebalance can take
|
||||
// a few heartbeat intervals (default 3s) as the initial leader receives
|
||||
// REBALANCE_IN_PROGRESS from its heartbeat and re-joins, so allow headroom.
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
select {
|
||||
case <-handler.ready:
|
||||
readyCount++
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("Timeout waiting for consumers to be ready")
|
||||
case <-handlers[i].ready:
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatalf("Timeout waiting for consumer %d to be ready", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Collect consumed messages
|
||||
consumedMessages := make([]*sarama.ConsumerMessage, 0, len(messages))
|
||||
messageTimeout := time.After(10 * time.Second)
|
||||
messageTimeout := time.After(15 * time.Second)
|
||||
|
||||
for len(consumedMessages) < len(messages) {
|
||||
select {
|
||||
case msg := <-handler.messages:
|
||||
case msg := <-sharedMessages:
|
||||
consumedMessages = append(consumedMessages, msg)
|
||||
case err := <-consumerErrors:
|
||||
t.Fatalf("Consumer error: %v", err)
|
||||
|
||||
@@ -2,6 +2,7 @@ package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -11,6 +12,25 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/test/kafka/internal/testutil"
|
||||
)
|
||||
|
||||
// runConsumeLoop drives consumerGroup.Consume in a for-loop until ctx is cancelled
|
||||
// or the group is closed. This is the idiomatic Sarama pattern: Consume returns
|
||||
// when a rebalance cancels the session, and the caller is expected to re-enter.
|
||||
// Tests that observe rebalance behaviour MUST loop — otherwise the consumer goroutine
|
||||
// exits on the first rebalance and never sees the post-rebalance assignment.
|
||||
func runConsumeLoop(t *testing.T, ctx context.Context, name string, cg sarama.ConsumerGroup, topics []string, handler sarama.ConsumerGroupHandler) {
|
||||
for {
|
||||
if err := cg.Consume(ctx, topics, handler); err != nil {
|
||||
if ctx.Err() != nil || errors.Is(err, sarama.ErrClosedConsumerGroup) {
|
||||
return
|
||||
}
|
||||
t.Logf("%s Consume returned: %v (will retry)", name, err)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testSingleConsumerAllPartitions(t *testing.T, addr, topicName, groupID string) {
|
||||
config := sarama.NewConfig()
|
||||
config.Consumer.Group.Rebalance.Strategy = sarama.BalanceStrategyRange
|
||||
@@ -28,7 +48,7 @@ func testSingleConsumerAllPartitions(t *testing.T, addr, topicName, groupID stri
|
||||
handler := &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
}
|
||||
|
||||
@@ -93,7 +113,7 @@ func testTwoConsumersRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
handler1 := &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
name: "Consumer1",
|
||||
}
|
||||
@@ -101,12 +121,7 @@ func testTwoConsumersRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
ctx1, cancel1 := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel1()
|
||||
|
||||
go func() {
|
||||
err := consumerGroup1.Consume(ctx1, []string{topicName}, handler1)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
t.Logf("Consumer1 error: %v", err)
|
||||
}
|
||||
}()
|
||||
go runConsumeLoop(t, ctx1, "Consumer1", consumerGroup1, []string{topicName}, handler1)
|
||||
|
||||
// Wait for first consumer to be ready and get initial assignment
|
||||
<-handler1.ready
|
||||
@@ -132,7 +147,7 @@ func testTwoConsumersRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
handler2 := &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
name: "Consumer2",
|
||||
}
|
||||
@@ -140,12 +155,7 @@ func testTwoConsumersRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel2()
|
||||
|
||||
go func() {
|
||||
err := consumerGroup2.Consume(ctx2, []string{topicName}, handler2)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
t.Logf("Consumer2 error: %v", err)
|
||||
}
|
||||
}()
|
||||
go runConsumeLoop(t, ctx2, "Consumer2", consumerGroup2, []string{topicName}, handler2)
|
||||
|
||||
// Wait for second consumer to be ready
|
||||
<-handler2.ready
|
||||
@@ -228,7 +238,7 @@ func testConsumerLeaveRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
handler1 := &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
name: "Consumer1",
|
||||
}
|
||||
@@ -236,7 +246,7 @@ func testConsumerLeaveRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
handler2 := &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
name: "Consumer2",
|
||||
}
|
||||
@@ -246,20 +256,9 @@ func testConsumerLeaveRebalance(t *testing.T, addr, topicName, groupID string) {
|
||||
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
// Start both consumers
|
||||
go func() {
|
||||
err := consumerGroup1.Consume(ctx1, []string{topicName}, handler1)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
t.Logf("Consumer1 error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
err := consumerGroup2.Consume(ctx2, []string{topicName}, handler2)
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
t.Logf("Consumer2 error: %v", err)
|
||||
}
|
||||
}()
|
||||
// Start both consumers with loops so they survive rebalance session exits.
|
||||
go runConsumeLoop(t, ctx1, "Consumer1", consumerGroup1, []string{topicName}, handler1)
|
||||
go runConsumeLoop(t, ctx2, "Consumer2", consumerGroup2, []string{topicName}, handler2)
|
||||
|
||||
// Wait for both consumers to be ready
|
||||
<-handler1.ready
|
||||
@@ -315,7 +314,7 @@ func testMultipleConsumersJoin(t *testing.T, addr, topicName, groupID string) {
|
||||
handlers[i] = &RebalanceTestHandler{
|
||||
messages: make(chan *sarama.ConsumerMessage, 20),
|
||||
ready: make(chan bool),
|
||||
assignments: make(chan []int32, 5),
|
||||
assignments: make(chan []int32, 1),
|
||||
t: t,
|
||||
name: fmt.Sprintf("Consumer%d", i),
|
||||
}
|
||||
@@ -323,10 +322,8 @@ func testMultipleConsumersJoin(t *testing.T, addr, topicName, groupID string) {
|
||||
contexts[i], cancels[i] = context.WithTimeout(context.Background(), 45*time.Second)
|
||||
|
||||
go func(idx int) {
|
||||
err := consumers[idx].Consume(contexts[idx], []string{topicName}, handlers[idx])
|
||||
if err != nil && err != context.DeadlineExceeded {
|
||||
t.Logf("Consumer%d error: %v", idx, err)
|
||||
}
|
||||
runConsumeLoop(t, contexts[idx], fmt.Sprintf("Consumer%d", idx),
|
||||
consumers[idx], []string{topicName}, handlers[idx])
|
||||
}(i)
|
||||
}
|
||||
|
||||
@@ -339,26 +336,43 @@ func testMultipleConsumersJoin(t *testing.T, addr, topicName, groupID string) {
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for all consumers to be ready
|
||||
// Wait for all consumers to be ready. Four consumers racing in produces
|
||||
// several rebalance rounds; each round costs ~HeartbeatInterval (3s) before
|
||||
// the prior leader sees REBALANCE_IN_PROGRESS and rejoins. Give enough
|
||||
// headroom for the group to converge.
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
select {
|
||||
case <-handlers[i].ready:
|
||||
t.Logf("Consumer%d ready", i)
|
||||
case <-time.After(15 * time.Second):
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatalf("Timeout waiting for Consumer%d to be ready", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Collect final assignments from all consumers
|
||||
// Collect the settled assignment for each consumer. Because each consumer's
|
||||
// Consume() returns and re-enters on every rebalance, Setup fires multiple
|
||||
// times while the group converges and the handler's assignments channel
|
||||
// accumulates several snapshots. Drain it and keep the most recent value.
|
||||
assignments := make([][]int32, numConsumers)
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
select {
|
||||
case partitions := <-handlers[i].assignments:
|
||||
assignments[i] = partitions
|
||||
t.Logf("Consumer%d final assignment: %v", i, partitions)
|
||||
case <-time.After(20 * time.Second):
|
||||
case <-time.After(time.Until(deadline)):
|
||||
t.Errorf("Timeout waiting for Consumer%d assignment", i)
|
||||
continue
|
||||
}
|
||||
drain:
|
||||
for {
|
||||
select {
|
||||
case partitions := <-handlers[i].assignments:
|
||||
assignments[i] = partitions
|
||||
case <-time.After(3 * time.Second):
|
||||
break drain
|
||||
}
|
||||
}
|
||||
t.Logf("Consumer%d final assignment: %v", i, assignments[i])
|
||||
}
|
||||
|
||||
// Verify all partitions are assigned exactly once
|
||||
@@ -418,13 +432,20 @@ func (h *RebalanceTestHandler) Setup(session sarama.ConsumerGroupSession) error
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case h.assignments <- partitions:
|
||||
default:
|
||||
// Channel might be full, that's ok
|
||||
// Always publish the latest assignment. If the channel is full, drain one
|
||||
// stale value first so readers see the most recent rebalance outcome (not
|
||||
// whatever arrived first while the group was still converging).
|
||||
for {
|
||||
select {
|
||||
case h.assignments <- partitions:
|
||||
return nil
|
||||
default:
|
||||
select {
|
||||
case <-h.assignments:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *RebalanceTestHandler) Cleanup(sarama.ConsumerGroupSession) error {
|
||||
|
||||
@@ -10,6 +10,14 @@ import (
|
||||
"github.com/segmentio/kafka-go"
|
||||
)
|
||||
|
||||
const (
|
||||
consumerGroupHeartbeatInterval = 2 * time.Second
|
||||
consumerGroupSessionTimeout = 6 * time.Second
|
||||
consumerGroupRebalanceTimeout = 6 * time.Second
|
||||
consumerGroupJoinBackoff = 250 * time.Millisecond
|
||||
consumerGroupAttemptTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// KafkaGoClient wraps kafka-go client with test utilities
|
||||
type KafkaGoClient struct {
|
||||
brokerAddr string
|
||||
@@ -128,40 +136,81 @@ func (k *KafkaGoClient) ConsumeMessages(topicName string, expectedCount int) ([]
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ConsumeWithGroup consumes messages using consumer group
|
||||
// ConsumeWithGroup consumes messages using consumer group.
|
||||
// Retries the initial join+fetch with a fresh reader if it fails before any
|
||||
// message is received — re-joining an existing group races with the previous
|
||||
// member's LeaveGroup / session cleanup and can surface as an i/o timeout on
|
||||
// the first FetchMessage.
|
||||
func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCount int) ([]kafka.Message, error) {
|
||||
k.t.Helper()
|
||||
|
||||
const maxJoinAttempts = 5
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= maxJoinAttempts; attempt++ {
|
||||
messages, err, progressed := k.consumeWithGroupOnce(topicName, groupID, expectedCount)
|
||||
if err == nil {
|
||||
return messages, nil
|
||||
}
|
||||
lastErr = err
|
||||
// Only retry if we failed before any message was received. Once we've
|
||||
// fetched at least one message, a partial result is more useful than a
|
||||
// full retry (which would start over from the last committed offset).
|
||||
if progressed {
|
||||
return messages, err
|
||||
}
|
||||
if attempt == maxJoinAttempts {
|
||||
break
|
||||
}
|
||||
backoff := time.Duration(500*(1<<(attempt-1))) * time.Millisecond
|
||||
k.t.Logf("ConsumeWithGroup join attempt %d/%d failed (%v) — retrying after %v", attempt, maxJoinAttempts, err, backoff)
|
||||
time.Sleep(backoff)
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// consumeWithGroupOnce runs a single consume attempt. Returns the messages
|
||||
// fetched, any error, and whether any message was received (used to decide
|
||||
// whether a retry is safe).
|
||||
func (k *KafkaGoClient) consumeWithGroupOnce(topicName, groupID string, expectedCount int) ([]kafka.Message, error, bool) {
|
||||
// Give each reader its own ClientID so restarts do not get mistaken for the
|
||||
// still-shutting-down reader they are replacing.
|
||||
dialer := &kafka.Dialer{
|
||||
ClientID: fmt.Sprintf("seaweedfs-e2e-%s-%d", groupID, time.Now().UnixNano()),
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
reader := kafka.NewReader(kafka.ReaderConfig{
|
||||
Brokers: []string{k.brokerAddr},
|
||||
Topic: topicName,
|
||||
GroupID: groupID,
|
||||
MinBytes: 1,
|
||||
MaxBytes: 10e6,
|
||||
CommitInterval: 500 * time.Millisecond,
|
||||
Brokers: []string{k.brokerAddr},
|
||||
Dialer: dialer,
|
||||
Topic: topicName,
|
||||
GroupID: groupID,
|
||||
MinBytes: 1,
|
||||
MaxBytes: 10e6,
|
||||
CommitInterval: 500 * time.Millisecond,
|
||||
HeartbeatInterval: consumerGroupHeartbeatInterval,
|
||||
SessionTimeout: consumerGroupSessionTimeout,
|
||||
RebalanceTimeout: consumerGroupRebalanceTimeout,
|
||||
JoinGroupBackoff: consumerGroupJoinBackoff,
|
||||
})
|
||||
defer reader.Close()
|
||||
|
||||
// Log the initial offset position
|
||||
offset := reader.Offset()
|
||||
k.t.Logf("Consumer group reader created for group %s, initial offset: %d", groupID, offset)
|
||||
|
||||
// Increased timeout for consumer groups - they require coordinator discovery,
|
||||
// offset fetching, and offset commits which can be slow in CI environments
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
// Keep each attempt short enough that a retry can outlive a stale group
|
||||
// member instead of burning most of the overall test timeout on one try.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), consumerGroupAttemptTimeout)
|
||||
defer cancel()
|
||||
|
||||
var messages []kafka.Message
|
||||
for i := 0; i < expectedCount; i++ {
|
||||
// Fetch then explicitly commit to better control commit timing
|
||||
msg, err := reader.FetchMessage(ctx)
|
||||
if err != nil {
|
||||
return messages, fmt.Errorf("read message %d: %w", i, err)
|
||||
return messages, fmt.Errorf("read message %d: %w", i, err), len(messages) > 0
|
||||
}
|
||||
messages = append(messages, msg)
|
||||
k.t.Logf(" Fetched message %d: offset=%d, partition=%d", i, msg.Offset, msg.Partition)
|
||||
|
||||
// Commit with simple retry to handle transient connection churn
|
||||
var commitErr error
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
commitErr = reader.CommitMessages(ctx, msg)
|
||||
@@ -170,16 +219,15 @@ func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCoun
|
||||
break
|
||||
}
|
||||
k.t.Logf(" Commit attempt %d failed for offset %d: %v", attempt+1, msg.Offset, commitErr)
|
||||
// brief backoff
|
||||
time.Sleep(time.Duration(50*(1<<attempt)) * time.Millisecond)
|
||||
}
|
||||
if commitErr != nil {
|
||||
return messages, fmt.Errorf("committing message %d: %w", i, commitErr)
|
||||
return messages, fmt.Errorf("committing message %d: %w", i, commitErr), true
|
||||
}
|
||||
}
|
||||
|
||||
k.t.Logf("Consumed %d messages from topic %s with group %s", len(messages), topicName, groupID)
|
||||
return messages, nil
|
||||
return messages, nil, true
|
||||
}
|
||||
|
||||
// CreateTopic creates a topic using Sarama
|
||||
|
||||
@@ -17,16 +17,18 @@ COPY test/kafka/kafka-client-loadtest/ ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o /kafka-loadtest ./cmd/loadtest
|
||||
|
||||
# Stage 2: Runtime
|
||||
FROM ubuntu:22.04
|
||||
# Use alpine so we don't depend on Ubuntu apt mirrors, which intermittently
|
||||
# refuse connections from GitHub Actions runners and fail the CI build.
|
||||
# All runtime dependencies we need (ca-certificates, curl, jq, bash, nc)
|
||||
# are in the Alpine main repo.
|
||||
FROM alpine:3.20
|
||||
|
||||
# Install runtime dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
curl \
|
||||
jq \
|
||||
bash \
|
||||
netcat \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
netcat-openbsd
|
||||
|
||||
# Copy built binary from builder stage
|
||||
COPY --from=builder /kafka-loadtest /usr/local/bin/kafka-loadtest
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
FROM openjdk:11-jdk-slim
|
||||
|
||||
# Install Maven
|
||||
RUN apt-get update && apt-get install -y maven && rm -rf /var/lib/apt/lists/*
|
||||
# Use the official Eclipse Temurin + Maven image so we don't depend on
|
||||
# Debian apt mirrors, which intermittently refuse connections from
|
||||
# GitHub Actions runners and fail the CI build. This image already has
|
||||
# JDK 11 and Maven installed.
|
||||
FROM maven:3.9-eclipse-temurin-11
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
FROM chrislusf/seaweedfs:e2e
|
||||
|
||||
RUN apt-get update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
RUN apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 install -y \
|
||||
--no-install-recommends \
|
||||
--no-install-suggests \
|
||||
autoconf \
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
// Reproduction tests for https://github.com/seaweedfs/seaweedfs/issues/9103
|
||||
//
|
||||
// The issue reports two distinct failure modes when using DuckDB against the
|
||||
// SeaweedFS Iceberg REST catalog:
|
||||
//
|
||||
// 1. `ATTACH 's3://test/' AS cat (TYPE 'ICEBERG', ...); SELECT * FROM cat.ovirt.disk;`
|
||||
// fails with "Table with name 'ovirt.disk' does not exist because schema
|
||||
// 'ovirt' does not exist." The namespace "ovirt" does exist in the bucket.
|
||||
//
|
||||
// 2. `SELECT * FROM iceberg_scan('s3://test/ovirt/disk');` fails with HTTP 403
|
||||
// AccessDenied when DuckDB tries to glob `s3://test/ovirt/disk/metadata/v*`
|
||||
// because the LoadTable response does not vend S3 file-io credentials back
|
||||
// to the client.
|
||||
//
|
||||
// These tests reproduce the underlying catalog-level misbehavior at the REST
|
||||
// protocol layer so they run quickly and deterministically. A DuckDB-based
|
||||
// end-to-end reproduction is also included (gated on Docker availability).
|
||||
package catalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
// TestIssue9103_ConfigDoesNotVendWarehousePrefix reproduces failure mode #2.
|
||||
//
|
||||
// Per the Iceberg REST spec, a client attaching with warehouse=s3://<bucket>/
|
||||
// calls GET /v1/config?warehouse=s3://<bucket>/ and expects the server to
|
||||
// return an `overrides.prefix` that identifies the catalog namespace for
|
||||
// subsequent requests. Without it the client falls back to unprefixed paths
|
||||
// like /v1/namespaces, which on SeaweedFS resolve to the hard-coded default
|
||||
// bucket ("warehouse") and therefore do not list the user's namespaces.
|
||||
//
|
||||
// Currently the handler ignores the warehouse query parameter and returns
|
||||
// empty defaults/overrides. That is exactly what makes DuckDB's ATTACH flow
|
||||
// report `schema "ovirt" does not exist`.
|
||||
func TestIssue9103_ConfigDoesNotVendWarehousePrefix(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := sharedEnv
|
||||
bucketName := "warehouse-9103cfg-" + randomSuffix()
|
||||
createTableBucket(t, env, bucketName)
|
||||
|
||||
warehouse := fmt.Sprintf("s3://%s/", bucketName)
|
||||
u := fmt.Sprintf("%s/v1/config?warehouse=%s", env.IcebergURL(), url.QueryEscape(warehouse))
|
||||
|
||||
status, body, err := doIcebergJSONRequest(env, http.MethodGet, fmt.Sprintf("/v1/config?warehouse=%s", url.QueryEscape(warehouse)), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s failed: %v", u, err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("GET %s status = %d, want 200", u, status)
|
||||
}
|
||||
|
||||
overrides, _ := body["overrides"].(map[string]any)
|
||||
gotPrefix, _ := overrides["prefix"].(string)
|
||||
if gotPrefix != bucketName {
|
||||
t.Fatalf("GET /v1/config?warehouse=%s: overrides.prefix = %q, want %q (catalog must echo the warehouse's table bucket so clients like DuckDB know which /v1/{prefix}/namespaces to use)",
|
||||
warehouse, gotPrefix, bucketName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssue9103_BareNamespacesListMissesNamespaceInAttachedBucket
|
||||
// demonstrates the downstream effect of the /v1/config bug.
|
||||
//
|
||||
// The client created the namespace "ovirt" inside bucket "test" (via
|
||||
// /v1/{bucket}/namespaces), but when it later issues GET /v1/namespaces (no
|
||||
// prefix, because /v1/config didn't give it one), that request resolves to
|
||||
// the default bucket and returns no namespaces. DuckDB surfaces this as
|
||||
// `schema "ovirt" does not exist`.
|
||||
func TestIssue9103_BareNamespacesListMissesNamespaceInAttachedBucket(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
env := sharedEnv
|
||||
bucketName := "warehouse-9103ns-" + randomSuffix()
|
||||
createTableBucket(t, env, bucketName)
|
||||
|
||||
namespace := "ovirt"
|
||||
status, _, err := doIcebergJSONRequest(env, http.MethodPost,
|
||||
icebergPath(bucketName, "/v1/namespaces"),
|
||||
map[string]any{"namespace": []string{namespace}})
|
||||
if err != nil {
|
||||
t.Fatalf("create namespace: %v", err)
|
||||
}
|
||||
if status != http.StatusOK && status != http.StatusConflict {
|
||||
t.Fatalf("create namespace status = %d, want 200 or 409", status)
|
||||
}
|
||||
|
||||
// Sanity: prefixed listing finds the namespace.
|
||||
status, prefixedBody, err := doIcebergJSONRequest(env, http.MethodGet,
|
||||
icebergPath(bucketName, "/v1/namespaces"), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list namespaces with prefix: %v", err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("prefixed list status = %d, want 200", status)
|
||||
}
|
||||
if !containsNamespace(prefixedBody, namespace) {
|
||||
t.Fatalf("prefixed list missing namespace %q: %v", namespace, prefixedBody)
|
||||
}
|
||||
|
||||
// Simulate what a DuckDB-style client does when /v1/config did not vend a
|
||||
// prefix: it falls back to the unprefixed listing. It should still be
|
||||
// able to discover the namespace (e.g. via a warehouse query parameter),
|
||||
// but today it cannot, which is the user-visible bug.
|
||||
bareWarehouse := "s3://" + bucketName + "/"
|
||||
status, bareBody, err := doIcebergJSONRequest(env, http.MethodGet,
|
||||
fmt.Sprintf("/v1/namespaces?warehouse=%s", url.QueryEscape(bareWarehouse)), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("bare list namespaces: %v", err)
|
||||
}
|
||||
switch {
|
||||
case status != http.StatusOK:
|
||||
t.Fatalf("GET /v1/namespaces?warehouse=%s status = %d, want 200 (server ignores the warehouse query parameter and falls back to the default %q bucket, causing DuckDB to see no schemas)",
|
||||
bareWarehouse, status, "warehouse")
|
||||
case !containsNamespace(bareBody, namespace):
|
||||
t.Fatalf("GET /v1/namespaces?warehouse=%s did not return %q: %v (server must honor the warehouse query parameter here or vend overrides.prefix from /v1/config so the client can route to the right bucket)",
|
||||
bareWarehouse, namespace, bareBody)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssue9103_DuckDBAttachCannotResolveNamespace is the end-to-end
|
||||
// reproduction of the issue using DuckDB in Docker, mirroring the exact
|
||||
// sequence of commands from the bug report. It runs under its own weed
|
||||
// mini with IAM configured so the OAuth2 client_credentials flow that
|
||||
// DuckDB's iceberg extension requires actually works (the shared env has
|
||||
// no credentials registered). Gated on Docker availability.
|
||||
func TestIssue9103_DuckDBAttachCannotResolveNamespace(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
if !testutil.HasDocker() {
|
||||
t.Skip("Docker not available, skipping DuckDB integration reproduction")
|
||||
}
|
||||
|
||||
env := newOAuthTestEnv(t)
|
||||
defer env.cleanup(t)
|
||||
env.start(t)
|
||||
|
||||
bucketName := "test9103-" + randomSuffix()
|
||||
createTableBucketViaShell(t, env, bucketName)
|
||||
|
||||
namespace := "ovirt"
|
||||
tableName := "disk"
|
||||
|
||||
token := requestOAuthToken(t, env, env.accessKey, env.secretKey)
|
||||
createNamespaceWithToken(t, env, token, bucketName, namespace)
|
||||
createTableWithToken(t, env, token, bucketName, namespace, tableName)
|
||||
|
||||
sql := fmt.Sprintf(`
|
||||
INSTALL iceberg;
|
||||
LOAD iceberg;
|
||||
|
||||
CREATE SECRET test_berg (
|
||||
TYPE ICEBERG,
|
||||
ENDPOINT 'http://host.docker.internal:%d',
|
||||
SCOPE 's3://%s/',
|
||||
CLIENT_ID '%s',
|
||||
CLIENT_SECRET '%s'
|
||||
);
|
||||
|
||||
CREATE SECRET s3_berg (
|
||||
TYPE S3,
|
||||
KEY_ID '%s',
|
||||
SECRET '%s',
|
||||
ENDPOINT 'host.docker.internal:%d',
|
||||
URL_STYLE 'path',
|
||||
USE_SSL false,
|
||||
SCOPE 's3://%s/'
|
||||
);
|
||||
|
||||
ATTACH 's3://%s/' AS test_catalog (TYPE 'ICEBERG', secret test_berg);
|
||||
SELECT * FROM test_catalog.%s.%s LIMIT 0;
|
||||
`, env.icebergPort, bucketName,
|
||||
env.accessKey, env.secretKey,
|
||||
env.accessKey, env.secretKey, env.s3Port, bucketName,
|
||||
bucketName, namespace, tableName)
|
||||
|
||||
sqlFile := filepath.Join(env.dataDir, "issue_9103.sql")
|
||||
if err := os.WriteFile(sqlFile, []byte(sql), 0644); err != nil {
|
||||
t.Fatalf("write SQL: %v", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command("docker", "run", "--rm",
|
||||
"-v", fmt.Sprintf("%s:/test", env.dataDir),
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-e", "AWS_REGION=us-east-1",
|
||||
"--entrypoint", "duckdb",
|
||||
"duckdb/duckdb:latest",
|
||||
"-init", "/test/issue_9103.sql",
|
||||
"-c", "SELECT 1",
|
||||
)
|
||||
|
||||
out, runErr := cmd.CombinedOutput()
|
||||
outStr := string(out)
|
||||
t.Logf("DuckDB output:\n%s", outStr)
|
||||
|
||||
if strings.Contains(outStr, "iceberg extension is not available") ||
|
||||
strings.Contains(outStr, "Failed to load") ||
|
||||
strings.Contains(outStr, "could not fetch extension") ||
|
||||
strings.Contains(outStr, "failed to download") {
|
||||
t.Skip("Iceberg extension not available in DuckDB Docker image")
|
||||
}
|
||||
|
||||
if runErr != nil {
|
||||
if strings.Contains(outStr, "does not exist because schema") &&
|
||||
strings.Contains(outStr, namespace) {
|
||||
t.Fatalf("reproduced issue #9103: DuckDB cannot see namespace %q after ATTACH 's3://%s/'; see output above",
|
||||
namespace, bucketName)
|
||||
}
|
||||
t.Fatalf("DuckDB run failed for an unexpected reason: %v", runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// createTableWithToken creates an Iceberg table using an OAuth bearer token.
|
||||
func createTableWithToken(t *testing.T, env *oauthTestEnv, token, bucketName, namespace, tableName string) {
|
||||
t.Helper()
|
||||
|
||||
payload := map[string]any{
|
||||
"name": tableName,
|
||||
"schema": map[string]any{
|
||||
"type": "struct",
|
||||
"schema-id": 0,
|
||||
"fields": []map[string]any{
|
||||
{"id": 1, "name": "id", "required": true, "type": "long"},
|
||||
},
|
||||
},
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal create-table payload: %v", err)
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s/v1/%s/namespaces/%s/tables", env.icebergURL(), bucketName, namespace)
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("create table: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("create table failed: status=%d body=%s", resp.StatusCode, respBody)
|
||||
}
|
||||
t.Logf("Created table %s.%s in bucket %s", namespace, tableName, bucketName)
|
||||
}
|
||||
|
||||
// containsNamespace checks whether an Iceberg REST ListNamespaces response
|
||||
// contains the given single-level namespace.
|
||||
func containsNamespace(body map[string]any, name string) bool {
|
||||
arr, _ := body["namespaces"].([]any)
|
||||
for _, item := range arr {
|
||||
parts, _ := item.([]any)
|
||||
if len(parts) == 1 {
|
||||
if s, ok := parts[0].(string); ok && s == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -59,7 +59,6 @@ type TestEnvironment struct {
|
||||
filerPort int
|
||||
s3Port int
|
||||
icebergRestPort int
|
||||
risingwavePort int
|
||||
bindIP string
|
||||
accessKey string
|
||||
secretKey string
|
||||
@@ -114,12 +113,11 @@ func (env *TestEnvironment) StartSeaweedFS(t *testing.T) {
|
||||
t.Fatalf("failed to create temp directory: %v", err)
|
||||
}
|
||||
|
||||
ports := testutil.MustFreeMiniPorts(t, []string{"Master", "Filer", "S3", "Iceberg", "RisingWave"})
|
||||
ports := testutil.MustFreeMiniPorts(t, []string{"Master", "Filer", "S3", "Iceberg"})
|
||||
env.masterPort = ports[0]
|
||||
env.filerPort = ports[1]
|
||||
env.s3Port = ports[2]
|
||||
env.icebergRestPort = ports[3]
|
||||
env.risingwavePort = ports[4]
|
||||
|
||||
env.bindIP = testutil.FindBindIP()
|
||||
|
||||
@@ -183,7 +181,6 @@ func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
|
||||
cmd := exec.Command("docker", "run", "-d",
|
||||
"--name", containerName,
|
||||
"-p", fmt.Sprintf("%d:4566", env.risingwavePort),
|
||||
"--add-host", "host.docker.internal:host-gateway",
|
||||
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
|
||||
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
|
||||
@@ -210,12 +207,9 @@ func (env *TestEnvironment) StartRisingWave(t *testing.T) {
|
||||
t.Fatalf("failed to start postgres sidecar: %v\n%s", err, string(output))
|
||||
}
|
||||
|
||||
// Wait for RisingWave port to be open on host
|
||||
if !testutil.WaitForPort(env.risingwavePort, 120*time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave port %d to be open", env.risingwavePort)
|
||||
}
|
||||
|
||||
// Wait for RisingWave to be truly ready via psql in the sidecar.
|
||||
// The sidecar shares RisingWave's network namespace, so it reaches
|
||||
// 4566 directly without a host port mapping.
|
||||
if !env.waitForRisingWave(120 * time.Second) {
|
||||
t.Fatalf("timed out waiting for RisingWave to be ready via psql")
|
||||
}
|
||||
|
||||
@@ -256,10 +256,11 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
Fsync: *b.fsync,
|
||||
}
|
||||
ar := &operation.VolumeAssignRequest{
|
||||
Count: 1,
|
||||
Collection: *b.collection,
|
||||
Replication: *b.replication,
|
||||
DiskType: *b.diskType,
|
||||
Count: 1,
|
||||
Collection: *b.collection,
|
||||
Replication: *b.replication,
|
||||
DiskType: *b.diskType,
|
||||
ExpectedDataSize: uint64(fileSize),
|
||||
}
|
||||
if assignResult, err := operation.Assign(context.Background(), b.masterClient.GetMaster, b.grpcDialOption, ar); err == nil {
|
||||
fp.Server, fp.Fid, fp.Pref.Collection = assignResult.Url, assignResult.Fid, *b.collection
|
||||
|
||||
+35
-15
@@ -84,6 +84,14 @@ type FilerOptions struct {
|
||||
tusBasePath *string
|
||||
certProvider certprovider.Provider
|
||||
s3ConfigFile *string // optional path to static S3 identity config
|
||||
mountPeerRegistryEnable *bool // accept MountRegister/MountList RPCs (peer chunk sharing tier 1)
|
||||
// shutdownCtx, when non-nil, tells startFiler to gracefully shut down its
|
||||
// HTTP/gRPC servers once the ctx is cancelled. Used by integration tests
|
||||
// and by weed mini; nil for standalone weed filer.
|
||||
shutdownCtx context.Context
|
||||
// gracefulStopTimeout caps how long startFiler waits for gRPC graceful
|
||||
// stop before forcing the server to stop. Zero means the default of 10s.
|
||||
gracefulStopTimeout time.Duration
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -119,6 +127,7 @@ func init() {
|
||||
f.allowedOrigins = cmdFiler.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
f.exposeDirectoryData = cmdFiler.Flag.Bool("exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
f.tusBasePath = cmdFiler.Flag.String("tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
f.mountPeerRegistryEnable = cmdFiler.Flag.Bool("mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
// start s3 on filer
|
||||
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
|
||||
@@ -379,6 +388,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
|
||||
TusBasePath: *fo.tusBasePath,
|
||||
CredentialManager: credentialManager,
|
||||
MountPeerRegistryEnabled: fo.mountPeerRegistryEnable != nil && *fo.mountPeerRegistryEnable,
|
||||
})
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
@@ -446,8 +456,12 @@ func (fo *FilerOptions) startFiler() {
|
||||
go grpcS.Serve(grpcL)
|
||||
pb.ServeGrpcOnLocalSocket(grpcS, grpcPort)
|
||||
|
||||
// Register graceful shutdown for gRPC server to wait for active RPCs
|
||||
grace.OnInterrupt(func() {
|
||||
// Helper to gracefully stop the gRPC server, waiting for active RPCs.
|
||||
gracefulTimeout := fo.gracefulStopTimeout
|
||||
if gracefulTimeout <= 0 {
|
||||
gracefulTimeout = 10 * time.Second
|
||||
}
|
||||
stopGrpcServer := func() {
|
||||
glog.V(0).Infof("Gracefully stopping gRPC server")
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
@@ -457,11 +471,11 @@ func (fo *FilerOptions) startFiler() {
|
||||
select {
|
||||
case <-stopped:
|
||||
glog.V(0).Infof("gRPC server stopped gracefully")
|
||||
case <-time.After(10 * time.Second):
|
||||
glog.V(0).Infof("gRPC server graceful stop timed out, forcing stop")
|
||||
case <-time.After(gracefulTimeout):
|
||||
glog.V(0).Infof("gRPC server graceful stop timed out after %s, forcing stop", gracefulTimeout)
|
||||
grpcS.Stop()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var socketServer *http.Server
|
||||
if runtime.GOOS != "windows" {
|
||||
@@ -528,8 +542,12 @@ func (fo *FilerOptions) startFiler() {
|
||||
}
|
||||
httpS := newHttpServer(defaultMux, tlsConfig)
|
||||
|
||||
// Register shutdown hooks: stop all HTTP servers, then close filer database
|
||||
// Register a single shutdown hook that runs the steps in the correct order:
|
||||
// stop accepting new gRPC/HTTP requests, then close the filer database.
|
||||
// Combining them into one hook keeps ordering intact regardless of how
|
||||
// grace fires interrupt hooks (FIFO vs LIFO).
|
||||
grace.OnInterrupt(func() {
|
||||
stopGrpcServer()
|
||||
glog.V(0).Infof("Gracefully stopping all HTTP servers")
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
@@ -542,13 +560,12 @@ func (fo *FilerOptions) startFiler() {
|
||||
if err := httpS.Shutdown(shutdownCtx); err != nil {
|
||||
glog.Warningf("HTTPS server shutdown: %v", err)
|
||||
}
|
||||
shutdownFiler()
|
||||
})
|
||||
grace.OnInterrupt(shutdownFiler)
|
||||
|
||||
if MiniClusterCtx != nil {
|
||||
ctx := MiniClusterCtx
|
||||
if fo.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
<-fo.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
grpcS.Stop()
|
||||
}()
|
||||
@@ -570,8 +587,12 @@ func (fo *FilerOptions) startFiler() {
|
||||
}
|
||||
httpS := newHttpServer(defaultMux, nil)
|
||||
|
||||
// Register shutdown hooks: stop all HTTP servers, then close filer database
|
||||
// Register a single shutdown hook that runs the steps in the correct order:
|
||||
// stop accepting new gRPC/HTTP requests, then close the filer database.
|
||||
// Combining them into one hook keeps ordering intact regardless of how
|
||||
// grace fires interrupt hooks (FIFO vs LIFO).
|
||||
grace.OnInterrupt(func() {
|
||||
stopGrpcServer()
|
||||
glog.V(0).Infof("Gracefully stopping all HTTP servers")
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
@@ -584,13 +605,12 @@ func (fo *FilerOptions) startFiler() {
|
||||
if err := httpS.Shutdown(shutdownCtx); err != nil {
|
||||
glog.Warningf("HTTP server shutdown: %v", err)
|
||||
}
|
||||
shutdownFiler()
|
||||
})
|
||||
grace.OnInterrupt(shutdownFiler)
|
||||
|
||||
if MiniClusterCtx != nil {
|
||||
ctx := MiniClusterCtx
|
||||
if fo.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
<-fo.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
grpcS.Stop()
|
||||
}()
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
nethttp "net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/repl_util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -35,6 +40,7 @@ type FilerBackupOptions struct {
|
||||
ignore404Error *bool
|
||||
timeAgo *time.Duration
|
||||
retentionDays *int
|
||||
initialSnapshot *bool
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -57,6 +63,7 @@ func init() {
|
||||
filerBackupOptions.retentionDays = cmdFilerBackup.Flag.Int("retentionDays", 0, "incremental backup retention days")
|
||||
filerBackupOptions.disableErrorRetry = cmdFilerBackup.Flag.Bool("disableErrorRetry", false, "disables errors retry, only logs will print")
|
||||
filerBackupOptions.ignore404Error = cmdFilerBackup.Flag.Bool("ignore404Error", true, "ignore 404 errors from filer")
|
||||
filerBackupOptions.initialSnapshot = cmdFilerBackup.Flag.Bool("initialSnapshot", false, "before subscribing to metadata updates, walk the live filer tree under -filerPath and seed the destination. Only runs on a fresh sync (no prior checkpoint and -timeAgo is 0). After the walk, subscription starts from the walk-start timestamp so concurrent changes are still captured.")
|
||||
}
|
||||
|
||||
var cmdFilerBackup = &Command{
|
||||
@@ -70,6 +77,11 @@ var cmdFilerBackup = &Command{
|
||||
If restarted and "-timeAgo" is not set, the synchronization will resume from the previous checkpoints, persisted every minute.
|
||||
A fresh sync will start from the earliest metadata logs. To reset the checkpoints, just set "-timeAgo" to a high value.
|
||||
|
||||
On a fresh sync the metadata event log only re-materializes files that still exist on the source; entries that were
|
||||
created and later deleted are replayed as a create-then-delete pair and therefore never appear on the destination.
|
||||
Pass "-initialSnapshot" to walk the live filer tree first and seed the destination with the current tree, then
|
||||
subscribe from the walk-start timestamp. The walk only runs when there is no prior checkpoint.
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -123,17 +135,27 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
|
||||
// get start time for the data sink
|
||||
startFrom := time.Unix(0, 0)
|
||||
isFreshSync := true
|
||||
sinkId := util.HashStringToLong(dataSink.GetName() + dataSink.GetSinkToDirectory())
|
||||
if timeAgo.Milliseconds() == 0 {
|
||||
lastOffsetTsNs, err := getOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, int32(sinkId))
|
||||
if err != nil {
|
||||
glog.V(0).Infof("starting from %v", startFrom)
|
||||
} else {
|
||||
// A KV read failure is ambiguous — a checkpoint may well exist but the
|
||||
// source filer is temporarily unreachable. Don't treat that as a fresh
|
||||
// sync; otherwise runFilerBackup's retry loop would redo the full
|
||||
// -initialSnapshot walk on every transient error.
|
||||
isFreshSync = false
|
||||
glog.V(0).Infof("starting from %v (offset read failed: %v)", startFrom, err)
|
||||
} else if lastOffsetTsNs > 0 {
|
||||
startFrom = time.Unix(0, lastOffsetTsNs)
|
||||
isFreshSync = false
|
||||
glog.V(0).Infof("resuming from %v", startFrom)
|
||||
} else {
|
||||
glog.V(0).Infof("starting from %v (no prior checkpoint)", startFrom)
|
||||
}
|
||||
} else {
|
||||
startFrom = time.Now().Add(-timeAgo)
|
||||
isFreshSync = false
|
||||
glog.V(0).Infof("start time is set to %v", startFrom)
|
||||
}
|
||||
|
||||
@@ -150,6 +172,28 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
}
|
||||
dataSink.SetSourceFiler(filerSource)
|
||||
|
||||
// When the destination has no prior checkpoint and the user opted in to an
|
||||
// initial snapshot, walk the live filer tree first and seed the destination
|
||||
// with the current entries. This avoids the "only new files appear" pitfall
|
||||
// of replaying the metadata event log: entries created-then-deleted before
|
||||
// the walk leave no trace, so a re-backup after wiping the destination
|
||||
// reflects what is actually live on the source instead of an empty tree.
|
||||
if *backupOption.initialSnapshot && isFreshSync {
|
||||
snapshotTsNs, err := runInitialSnapshot(sourceFiler.ToGrpcAddress(), filerSource, sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.ignore404Error)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initial snapshot: %w", err)
|
||||
}
|
||||
// The walk can take hours on large trees; retry the tiny KV write a
|
||||
// handful of times before giving up so a flaky filer KV doesn't force
|
||||
// the whole walk to repeat on the next retry loop iteration.
|
||||
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, int32(sinkId), snapshotTsNs); err != nil {
|
||||
glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err)
|
||||
return fmt.Errorf("persist initial snapshot offset: %w", err)
|
||||
}
|
||||
startFrom = time.Unix(0, snapshotTsNs)
|
||||
glog.V(0).Infof("initialSnapshot done; subscribing from %v", startFrom)
|
||||
}
|
||||
|
||||
var processEventFn func(*filer_pb.SubscribeMetadataResponse) error
|
||||
if *backupOption.ignore404Error {
|
||||
processEventFnGenerated := genProcessFunction(sourcePath, targetPath, excludePaths, reExcludeFileName, excludeFileNames, excludePathPatterns, dataSink, *backupOption.doDeleteFiles, debug)
|
||||
@@ -241,3 +285,151 @@ func isIgnorable404(err error) bool {
|
||||
strings.Contains(errStr, "LookupFileId") ||
|
||||
(strings.Contains(errStr, "volume id") && strings.Contains(errStr, "not found"))
|
||||
}
|
||||
|
||||
// persistSnapshotOffset writes the snapshot high-water mark to the source
|
||||
// filer's KV, retrying a few times with exponential backoff on transient
|
||||
// errors. Losing this write forces a full re-walk on the next retry loop
|
||||
// iteration, so a small retry budget here is far cheaper than paying the
|
||||
// walk cost again on a large tree.
|
||||
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64) error {
|
||||
const attempts = 4
|
||||
backoff := 500 * time.Millisecond
|
||||
var lastErr error
|
||||
for i := 1; i <= attempts; i++ {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, tsNs); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
if i == attempts {
|
||||
break
|
||||
}
|
||||
glog.V(0).Infof("initialSnapshot: setOffset attempt %d/%d failed: %v (retrying in %v)", i, attempts, err, backoff)
|
||||
time.Sleep(backoff)
|
||||
backoff *= 2
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// runInitialSnapshot walks the live filer tree under sourcePath and seeds the
|
||||
// destination via the sink. The snapshot timestamp is captured before the walk
|
||||
// starts so any create/update/delete that races with the walk is still caught
|
||||
// by the subscription that runs afterward (sink CreateEntry is idempotent for
|
||||
// all builtin sinks, so replaying a concurrent create from the subscription
|
||||
// over an entry already written by the walk is safe).
|
||||
//
|
||||
// Note on excludes: TraverseBfs enumerates every directory and enqueues its
|
||||
// children unconditionally before the callback runs, so the exclude filters
|
||||
// below only prevent *processing* of excluded entries — they do not prune the
|
||||
// listing RPCs for excluded subtrees. For small system excludes (SystemLogDir)
|
||||
// that is fine; for large user-supplied excludes (say an archive directory
|
||||
// with millions of files), the listing cost can dominate the snapshot. A
|
||||
// proper prune signal through TraverseBfs is a separate change.
|
||||
func runInitialSnapshot(
|
||||
grpcAddress string,
|
||||
filerSource *source.FilerSource,
|
||||
sourcePath string,
|
||||
targetPath string,
|
||||
excludePaths []string,
|
||||
reExcludeFileName *regexp.Regexp,
|
||||
excludeFileNames []*wildcard.WildcardMatcher,
|
||||
excludePathPatterns []*wildcard.WildcardMatcher,
|
||||
dataSink sink.ReplicationSink,
|
||||
ignore404Error bool,
|
||||
) (int64, error) {
|
||||
// Metadata events are stamped server-side, so the backup host clock may be
|
||||
// ahead of the filer's. Take `now - 1min` as the subscription watermark so
|
||||
// a fast client clock can't skip events that fire during/right-after the
|
||||
// walk. meta_aggregator.go uses the same 1-minute margin on initial peer
|
||||
// traversal; see the note there on why duplicate replay is harmless.
|
||||
snapshotTsNs := time.Now().Add(-time.Minute).UnixNano()
|
||||
glog.V(0).Infof("initialSnapshot: walking %s on %s -> %s (snapshotTsNs=%d, -1m skew margin applied)", sourcePath, grpcAddress, targetPath, snapshotTsNs)
|
||||
|
||||
// TraverseBfs fans the callback out across 5 worker goroutines, so counter
|
||||
// updates and the progress-log gate need to be safe under concurrent access.
|
||||
var entryCount, byteCount atomic.Int64
|
||||
start := time.Now()
|
||||
var logMu sync.Mutex
|
||||
lastLog := start
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
err := filer_pb.TraverseBfs(ctx, filerSource, util.FullPath(sourcePath), func(parentPath util.FullPath, entry *filer_pb.Entry) error {
|
||||
parent := string(parentPath)
|
||||
sourceKey := parentPath.Child(entry.Name)
|
||||
source := string(sourceKey)
|
||||
// Check exclusion on the entry's own path too — otherwise a walked
|
||||
// directory whose full path is SystemLogDir or a user-excluded path
|
||||
// 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+"/") {
|
||||
return nil
|
||||
}
|
||||
if matchesExcludePath(parent, excludePaths) || matchesExcludePath(source, excludePaths) {
|
||||
return nil
|
||||
}
|
||||
if isEntryExcluded(parent, entry, reExcludeFileName, excludeFileNames, excludePathPatterns) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !util.IsEqualOrUnder(source, sourcePath) {
|
||||
return nil
|
||||
}
|
||||
|
||||
targetKey := initialSnapshotTargetKey(dataSink, targetPath, sourcePath, sourceKey, entry)
|
||||
if err := dataSink.CreateEntry(targetKey, entry, nil); err != nil {
|
||||
// A file can be listed by TraverseBfs and then deleted before
|
||||
// CreateEntry reads its chunks. The follow phase ignores 404s when
|
||||
// -ignore404Error is set; apply the same policy here so the walk
|
||||
// doesn't abort (and trigger a full re-walk on retry) just because
|
||||
// a single entry disappeared mid-snapshot.
|
||||
if ignore404Error && isIgnorable404(err) {
|
||||
glog.V(0).Infof("initialSnapshot: source entry %s disappeared, ignore it: %s", sourceKey, err.Error())
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("seed %s: %w", targetKey, err)
|
||||
}
|
||||
|
||||
curEntries := entryCount.Add(1)
|
||||
var curBytes int64
|
||||
if entry.Attributes != nil {
|
||||
curBytes = byteCount.Add(int64(entry.Attributes.FileSize))
|
||||
} else {
|
||||
curBytes = byteCount.Load()
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
logMu.Lock()
|
||||
shouldLog := now.Sub(lastLog) >= 5*time.Second
|
||||
if shouldLog {
|
||||
lastLog = now
|
||||
}
|
||||
logMu.Unlock()
|
||||
if shouldLog {
|
||||
elapsed := now.Sub(start).Seconds()
|
||||
if elapsed == 0 {
|
||||
elapsed = 1
|
||||
}
|
||||
glog.V(0).Infof("initialSnapshot: %d entries / %d bytes seeded (%.1f/sec)", curEntries, curBytes, float64(curEntries)/elapsed)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
glog.V(0).Infof("initialSnapshot: done — %d entries / %d bytes in %v", entryCount.Load(), byteCount.Load(), time.Since(start))
|
||||
return snapshotTsNs, nil
|
||||
}
|
||||
|
||||
// initialSnapshotTargetKey pulls the entry mtime and delegates to the shared
|
||||
// destKey helper in filer_sync.go so the walk and the event-log path produce
|
||||
// the same destination key for the same source entry.
|
||||
func initialSnapshotTargetKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourceKey util.FullPath, entry *filer_pb.Entry) string {
|
||||
var mTime int64
|
||||
if entry.Attributes != nil {
|
||||
mTime = entry.Attributes.Mtime
|
||||
}
|
||||
return destKey(dataSink, targetPath, sourcePath, sourceKey, mTime)
|
||||
}
|
||||
@@ -7,7 +7,12 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/sink"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
@@ -71,3 +76,66 @@ func TestIsIgnorable404_NonIgnorableError(t *testing.T) {
|
||||
t.Errorf("expected not ignorable, got ignorable: %v", genErr)
|
||||
}
|
||||
}
|
||||
|
||||
// stubSink is a minimal ReplicationSink used to exercise initialSnapshotTargetKey
|
||||
// without standing up a real sink. Only the two methods read by the key builder
|
||||
// (GetName, IsIncremental) need meaningful behavior; the rest satisfy the interface.
|
||||
type stubSink struct {
|
||||
name string
|
||||
isIncremental bool
|
||||
}
|
||||
|
||||
func (s *stubSink) GetName() string { return s.name }
|
||||
func (s *stubSink) Initialize(util.Configuration, string) error { return nil }
|
||||
func (s *stubSink) DeleteEntry(string, bool, bool, []int32) error {
|
||||
return nil
|
||||
}
|
||||
func (s *stubSink) CreateEntry(string, *filer_pb.Entry, []int32) error { return nil }
|
||||
func (s *stubSink) UpdateEntry(string, *filer_pb.Entry, string, *filer_pb.Entry, bool, []int32) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
func (s *stubSink) GetSinkToDirectory() string { return "" }
|
||||
func (s *stubSink) SetSourceFiler(*source.FilerSource) {}
|
||||
func (s *stubSink) IsIncremental() bool { return s.isIncremental }
|
||||
|
||||
var _ sink.ReplicationSink = (*stubSink)(nil)
|
||||
|
||||
func TestInitialSnapshotTargetKey(t *testing.T) {
|
||||
// Mirror the non-incremental path of buildKey so a refactor of one without
|
||||
// the other will fail this test.
|
||||
mirror := &stubSink{name: "mirror", isIncremental: false}
|
||||
got := initialSnapshotTargetKey(mirror, "/backup", "/data", util.FullPath("/data/sub/file.txt"), &filer_pb.Entry{})
|
||||
if got != "/backup/sub/file.txt" {
|
||||
t.Errorf("mirror sink: got %q, want %q", got, "/backup/sub/file.txt")
|
||||
}
|
||||
|
||||
// Incremental sinks partition by entry mtime, so the seed must use the same
|
||||
// YYYY-MM-DD prefix a replayed CreateEntry would produce. buildKey in
|
||||
// filer_sync.go formats the date in local time, so compute the expected
|
||||
// key the same way to keep the test timezone-independent.
|
||||
inc := &stubSink{name: "inc", isIncremental: true}
|
||||
mtime := int64(1704196800) // 2024-01-02T12:00:00 UTC — unambiguously Jan 2 in nearly all timezones
|
||||
gotInc := initialSnapshotTargetKey(inc, "/backup", "/data", util.FullPath("/data/sub/file.txt"), &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: mtime},
|
||||
})
|
||||
wantInc := "/backup/" + time.Unix(mtime, 0).Format("2006-01-02") + "/sub/file.txt"
|
||||
if gotInc != wantInc {
|
||||
t.Errorf("incremental sink: got %q, want %q", gotInc, wantInc)
|
||||
}
|
||||
|
||||
// Trailing-slash sourcePath still produces a clean relative key.
|
||||
gotTrail := initialSnapshotTargetKey(mirror, "/backup", "/data/", util.FullPath("/data/file.txt"), &filer_pb.Entry{})
|
||||
if gotTrail != "/backup/file.txt" {
|
||||
t.Errorf("trailing-slash sourcePath: got %q, want %q", gotTrail, "/backup/file.txt")
|
||||
}
|
||||
|
||||
// Edge cases CodeRabbit called out: sourceKey equal to sourcePath
|
||||
// (non-trailing and trailing variants). Real TraverseBfs walks never emit
|
||||
// the root itself, but the helper must not panic if something else does.
|
||||
if got := initialSnapshotTargetKey(mirror, "/backup", "/data", util.FullPath("/data"), &filer_pb.Entry{}); got != "/backup" {
|
||||
t.Errorf("sourceKey == sourcePath (no slash): got %q, want %q", got, "/backup")
|
||||
}
|
||||
if got := initialSnapshotTargetKey(mirror, "/backup", "/data/", util.FullPath("/data"), &filer_pb.Entry{}); got != "/backup" {
|
||||
t.Errorf("sourceKey == sourcePath (trailing slash mismatch): got %q, want %q", got, "/backup")
|
||||
}
|
||||
}
|
||||
@@ -553,7 +553,7 @@ func detectMimeType(f *os.File) string {
|
||||
return mimeType
|
||||
}
|
||||
|
||||
func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
|
||||
func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64, _ uint64) (chunk *filer_pb.FileChunk, err error) {
|
||||
uploader, uploaderErr := operation.NewUploader()
|
||||
if uploaderErr != nil {
|
||||
return nil, fmt.Errorf("upload data: %w", uploaderErr)
|
||||
|
||||
+31
-13
@@ -653,21 +653,39 @@ func genProcessFunction(sourcePath string, targetPath string, excludePaths []str
|
||||
return processEventFn
|
||||
}
|
||||
|
||||
func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) (key string) {
|
||||
if !dataSink.IsIncremental() {
|
||||
key = util.Join(targetPath, string(sourceKey)[len(sourcePath):])
|
||||
} else {
|
||||
var mTime int64
|
||||
if message.NewEntry != nil {
|
||||
mTime = message.NewEntry.Attributes.Mtime
|
||||
} else if message.OldEntry != nil {
|
||||
mTime = message.OldEntry.Attributes.Mtime
|
||||
}
|
||||
dateKey := time.Unix(mTime, 0).Format("2006-01-02")
|
||||
key = util.Join(targetPath, dateKey, string(sourceKey)[len(sourcePath):])
|
||||
func buildKey(dataSink sink.ReplicationSink, message *filer_pb.EventNotification, targetPath string, sourceKey util.FullPath, sourcePath string) string {
|
||||
var mTime int64
|
||||
if message.NewEntry != nil && message.NewEntry.Attributes != nil {
|
||||
mTime = message.NewEntry.Attributes.Mtime
|
||||
} else if message.OldEntry != nil && message.OldEntry.Attributes != nil {
|
||||
mTime = message.OldEntry.Attributes.Mtime
|
||||
}
|
||||
return destKey(dataSink, targetPath, sourcePath, sourceKey, mTime)
|
||||
}
|
||||
|
||||
return escapeKey(key)
|
||||
// destKey derives the sink-side key for a source entry. Shared between the
|
||||
// event-log path (buildKey) and the initialSnapshot walk (both paths need the
|
||||
// same target layout so a walk-seeded file and an event-replayed file resolve
|
||||
// to the same destination key). Normalizing to a trailing-slash base avoids
|
||||
// indexing past the end of sourceKey when callers differ on trailing-slash
|
||||
// conventions or when sourceKey equals sourcePath exactly.
|
||||
func destKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourceKey util.FullPath, mTime int64) string {
|
||||
base := strings.TrimSuffix(sourcePath, "/") + "/"
|
||||
sk := string(sourceKey)
|
||||
var relative string
|
||||
switch {
|
||||
case strings.HasPrefix(sk, base):
|
||||
relative = sk[len(base):]
|
||||
case sk == strings.TrimSuffix(sourcePath, "/"):
|
||||
relative = ""
|
||||
default:
|
||||
relative = strings.TrimPrefix(sk, "/")
|
||||
}
|
||||
if !dataSink.IsIncremental() {
|
||||
return escapeKey(util.Join(targetPath, relative))
|
||||
}
|
||||
dateKey := time.Unix(mTime, 0).Format("2006-01-02")
|
||||
return escapeKey(util.Join(targetPath, dateKey, relative))
|
||||
}
|
||||
|
||||
// isEntryExcluded checks whether a single side (old or new) of an event is excluded
|
||||
|
||||
@@ -74,6 +74,10 @@ type MasterOptions struct {
|
||||
telemetryEnabled *bool
|
||||
debug *bool
|
||||
debugPort *int
|
||||
// shutdownCtx, when non-nil, tells startMaster to shut down once the ctx
|
||||
// is cancelled. Used by integration tests and by weed mini; nil for
|
||||
// standalone weed master.
|
||||
shutdownCtx context.Context
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -336,9 +340,8 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
ms.Topo.HashicorpRaft.LeadershipTransfer()
|
||||
}
|
||||
})
|
||||
ctx := MiniClusterCtx
|
||||
if ctx != nil {
|
||||
<-ctx.Done()
|
||||
if masterOption.shutdownCtx != nil {
|
||||
<-masterOption.shutdownCtx.Done()
|
||||
ms.Shutdown()
|
||||
grpcS.Stop()
|
||||
} else {
|
||||
|
||||
+172
-21
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -66,6 +67,123 @@ var (
|
||||
MiniClusterCtx context.Context
|
||||
)
|
||||
|
||||
// miniClientsState orchestrates graceful shutdown of admin/s3/webdav/worker on
|
||||
// weed mini Ctrl+C, BEFORE filer/volume/master tear down. It is rebuilt on
|
||||
// each runMini invocation so in-process test reruns see fresh state.
|
||||
//
|
||||
// The ctx chains from MiniClusterCtx so cancelling MiniClusterCtx (how tests
|
||||
// tear down the cluster) also triggers the client-shutdown path.
|
||||
//
|
||||
// Shutdown has two phases:
|
||||
// 1. preCancelFns run synchronously in registration order (worker disconnect,
|
||||
// etc.) so downstream servers don't block on handlers that are about to
|
||||
// close anyway.
|
||||
// 2. ctx is cancelled and the shutdown hook waits on wg for admin/s3/webdav
|
||||
// goroutines (registered via onMiniClientsShutdown / trackMiniClient) to
|
||||
// drain.
|
||||
type miniClientsState struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
preCancelMu sync.Mutex
|
||||
preCancelFns []func()
|
||||
}
|
||||
|
||||
var miniClients *miniClientsState
|
||||
|
||||
// resetMiniClients installs a fresh client-shutdown state chained from
|
||||
// MiniClusterCtx. Called once at the top of runMini; any goroutines from a
|
||||
// prior invocation keep their old state via closure and are unaffected.
|
||||
func resetMiniClients() {
|
||||
parent := context.Background()
|
||||
if MiniClusterCtx != nil {
|
||||
parent = MiniClusterCtx
|
||||
}
|
||||
s := &miniClientsState{}
|
||||
s.ctx, s.cancel = context.WithCancel(parent)
|
||||
miniClients = s
|
||||
}
|
||||
|
||||
// onMiniClientsShutdown runs fn when mini shutdown is triggered, and tracks
|
||||
// it so the interrupt hook can wait for it to drain. No-op outside mini.
|
||||
func onMiniClientsShutdown(fn func()) {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
defer s.wg.Done()
|
||||
<-s.ctx.Done()
|
||||
fn()
|
||||
}()
|
||||
}
|
||||
|
||||
// trackMiniClient registers an externally-managed goroutine (one that
|
||||
// observes miniClientsCtx() itself) so the interrupt hook waits for it.
|
||||
// The caller invokes the returned done func when the goroutine exits.
|
||||
func trackMiniClient() (done func()) {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.wg.Add(1)
|
||||
return s.wg.Done
|
||||
}
|
||||
|
||||
// beforeMiniClientsShutdown registers fn to run synchronously BEFORE the
|
||||
// clients ctx is cancelled. Use for cleanup that must complete before
|
||||
// downstream servers (e.g., the admin worker-gRPC) start waiting on clients.
|
||||
func beforeMiniClientsShutdown(fn func()) {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.preCancelMu.Lock()
|
||||
defer s.preCancelMu.Unlock()
|
||||
s.preCancelFns = append(s.preCancelFns, fn)
|
||||
}
|
||||
|
||||
// miniClientsCtx returns the shutdown context for mini clients, or
|
||||
// context.Background() if not running inside weed mini.
|
||||
func miniClientsCtx() context.Context {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return context.Background()
|
||||
}
|
||||
return s.ctx
|
||||
}
|
||||
|
||||
// triggerMiniClientsShutdown runs preCancel fns synchronously, cancels the
|
||||
// clients ctx, and waits up to timeout for tracked goroutines to finish.
|
||||
// Called from the OnInterrupt hook.
|
||||
func triggerMiniClientsShutdown(timeout time.Duration) {
|
||||
s := miniClients
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
glog.V(0).Infof("Shutting down admin/s3/webdav ...")
|
||||
s.preCancelMu.Lock()
|
||||
fns := s.preCancelFns
|
||||
s.preCancelFns = nil
|
||||
s.preCancelMu.Unlock()
|
||||
for _, fn := range fns {
|
||||
fn()
|
||||
}
|
||||
s.cancel()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
s.wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
glog.V(0).Infof("admin/s3/webdav shut down")
|
||||
case <-time.After(timeout):
|
||||
glog.V(0).Infof("timed out waiting for admin/s3/webdav to shut down")
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdMini.Run = runMini // break init cycle
|
||||
}
|
||||
@@ -193,6 +311,7 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.allowedOrigins = cmdMini.Flag.String("filer.allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
miniFilerOptions.exposeDirectoryData = cmdMini.Flag.Bool("filer.exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
miniFilerOptions.tusBasePath = cmdMini.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path")
|
||||
miniFilerOptions.mountPeerRegistryEnable = cmdMini.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
@@ -869,6 +988,21 @@ func runMini(cmd *Command, args []string) bool {
|
||||
|
||||
miniWhiteList := util.StringSplit(*miniWhiteListOption, ",")
|
||||
|
||||
// Install a fresh clients-shutdown context (chained from MiniClusterCtx)
|
||||
// before any service starts.
|
||||
resetMiniClients()
|
||||
|
||||
// Master/volume/filer observe MiniClusterCtx so tests that cancel it
|
||||
// tear those services down too. On Ctrl+C they rely on their own
|
||||
// OnInterrupt hooks (see grace's LIFO ordering).
|
||||
miniMasterOptions.shutdownCtx = MiniClusterCtx
|
||||
miniOptions.v.shutdownCtx = MiniClusterCtx
|
||||
miniFilerOptions.shutdownCtx = MiniClusterCtx
|
||||
// Mini is a small/dev setup with short-lived RPCs; cap the filer's
|
||||
// gRPC graceful-stop at 1s so Ctrl+C returns quickly instead of sitting
|
||||
// on the default 10s waiting for background subscription streams.
|
||||
miniFilerOptions.gracefulStopTimeout = 1 * time.Second
|
||||
|
||||
// Start all services with proper dependency coordination
|
||||
// This channel will be closed when all services are fully ready
|
||||
allServicesReady := make(chan struct{})
|
||||
@@ -877,6 +1011,13 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// Wait for all services to be fully running before printing welcome message
|
||||
<-allServicesReady
|
||||
|
||||
// Register the clients-shutdown interrupt hook AFTER all services have
|
||||
// registered theirs. Under grace's LIFO firing, this hook runs FIRST on
|
||||
// Ctrl+C so admin/s3/webdav drain before filer/volume/master tear down.
|
||||
grace.OnInterrupt(func() {
|
||||
triggerMiniClientsShutdown(10 * time.Second)
|
||||
})
|
||||
|
||||
// Print welcome message after all services are running
|
||||
printWelcomeMessage()
|
||||
|
||||
@@ -921,17 +1062,27 @@ func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) {
|
||||
// Wait for filer to be ready
|
||||
waitForServiceReady("Filer", *miniFilerOptions.port, bindIp)
|
||||
|
||||
// Start S3 and WebDAV in parallel (both depend on filer)
|
||||
// Start S3 and WebDAV in parallel (both depend on filer). Each observes
|
||||
// miniClientsCtx so it shuts down first on Ctrl+C, tracked via
|
||||
// trackMiniClient so runMini's interrupt hook can wait for them.
|
||||
if *miniEnableS3 {
|
||||
go startMiniService("S3", func() {
|
||||
startS3Service()
|
||||
}, *miniS3Options.port)
|
||||
miniS3Options.shutdownCtx = miniClientsCtx()
|
||||
done := trackMiniClient()
|
||||
go func() {
|
||||
defer done()
|
||||
startMiniService("S3", startS3Service, *miniS3Options.port)
|
||||
}()
|
||||
}
|
||||
|
||||
if *miniEnableWebDAV {
|
||||
go startMiniService("WebDAV", func() {
|
||||
miniWebDavOptions.startWebDav()
|
||||
}, *miniWebDavOptions.port)
|
||||
miniWebDavOptions.shutdownCtx = miniClientsCtx()
|
||||
done := trackMiniClient()
|
||||
go func() {
|
||||
defer done()
|
||||
startMiniService("WebDAV", func() {
|
||||
miniWebDavOptions.startWebDav()
|
||||
}, *miniWebDavOptions.port)
|
||||
}()
|
||||
}
|
||||
|
||||
// Wait for services to be ready
|
||||
@@ -999,12 +1150,8 @@ func startS3Service() {
|
||||
func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
defer close(allServicesReady) // Ensure channel is always closed on all paths
|
||||
|
||||
var ctx context.Context
|
||||
if MiniClusterCtx != nil {
|
||||
ctx = MiniClusterCtx
|
||||
} else {
|
||||
ctx = context.Background()
|
||||
}
|
||||
// Admin shuts down when mini clients shutdown is triggered.
|
||||
ctx := miniClientsCtx()
|
||||
|
||||
// Determine bind IP for health checks
|
||||
bindIp := getBindIp()
|
||||
@@ -1044,8 +1191,12 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
*miniAdminOptions.dataDir = filepath.Join(*miniDataFolders, "admin")
|
||||
}
|
||||
|
||||
// Start admin server in background
|
||||
// Start admin server in background. trackMiniClient lets the Ctrl+C
|
||||
// handler wait for startAdminServer's graceful shutdown before filer/
|
||||
// volume/master tear down.
|
||||
done := trackMiniClient()
|
||||
go func() {
|
||||
defer done()
|
||||
var icebergPort int
|
||||
if miniS3Options.portIceberg != nil {
|
||||
icebergPort = *miniS3Options.portIceberg
|
||||
@@ -1189,13 +1340,13 @@ func startMiniWorker(workerDir string) {
|
||||
|
||||
// Metrics server is already started in the main init function above, so no need to start it again here
|
||||
|
||||
// Start the worker
|
||||
if MiniClusterCtx != nil {
|
||||
go func() {
|
||||
<-MiniClusterCtx.Done()
|
||||
workerInstance.Stop()
|
||||
}()
|
||||
}
|
||||
// Stop the worker BEFORE the clients ctx is cancelled. Otherwise admin's
|
||||
// internal worker gRPC GracefulStop (called during admin.Shutdown) would
|
||||
// wait for the worker stream to close, blocking the whole mini shutdown
|
||||
// by ~10s and cascading into filer's own gRPC graceful stop timeout.
|
||||
beforeMiniClientsShutdown(func() {
|
||||
workerInstance.Stop()
|
||||
})
|
||||
err = workerInstance.Start()
|
||||
if err != nil {
|
||||
glog.Fatalf("Failed to start worker: %v", err)
|
||||
|
||||
@@ -52,6 +52,13 @@ type MountOptions struct {
|
||||
rdmaMaxConcurrent *int
|
||||
rdmaTimeoutMs *int
|
||||
|
||||
// Peer chunk sharing options (design-weed-mount-peer-chunk-sharing.md).
|
||||
peerEnabled *bool
|
||||
peerListen *string
|
||||
peerAdvertise *string
|
||||
peerDataCenter *string
|
||||
peerRack *string
|
||||
|
||||
dirIdleEvictSec *int
|
||||
|
||||
// Distributed lock for cross-mount write coordination
|
||||
@@ -129,6 +136,13 @@ func init() {
|
||||
mountOptions.rdmaMaxConcurrent = cmdMount.Flag.Int("rdma.maxConcurrent", 64, "max concurrent RDMA operations")
|
||||
mountOptions.rdmaTimeoutMs = cmdMount.Flag.Int("rdma.timeoutMs", 5000, "RDMA operation timeout in milliseconds")
|
||||
|
||||
// Peer chunk sharing flags.
|
||||
mountOptions.peerEnabled = cmdMount.Flag.Bool("peer.enable", false, "opt in to peer chunk sharing — mount serves its chunk cache to other mounts and fetches from peers instead of volume servers when available")
|
||||
mountOptions.peerListen = cmdMount.Flag.String("peer.listen", ":18080", "bind address for peer gRPC (directory RPCs + FetchChunk streaming)")
|
||||
mountOptions.peerAdvertise = cmdMount.Flag.String("peer.advertise", "", "externally-reachable host:port other mounts use to reach this one (defaults to autodetected host + -peer.listen port)")
|
||||
mountOptions.peerDataCenter = cmdMount.Flag.String("peer.dataCenter", "", "optional data-center label advertised to peers; used with -peer.rack for two-level locality ranking")
|
||||
mountOptions.peerRack = cmdMount.Flag.String("peer.rack", "", "optional rack label advertised to peers")
|
||||
|
||||
mountOptions.dirIdleEvictSec = cmdMount.Flag.Int("dirIdleEvictSec", 600, "seconds to evict idle cached directories (0 to disable)")
|
||||
|
||||
mountCpuProfile = cmdMount.Flag.String("cpuprofile", "", "cpu profile output file")
|
||||
|
||||
@@ -356,6 +356,12 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
|
||||
WritebackCache: option.writebackCache != nil && *option.writebackCache,
|
||||
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
|
||||
// Peer chunk sharing
|
||||
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
||||
PeerListen: peerStringOrEmpty(option.peerListen),
|
||||
PeerAdvertise: peerStringOrEmpty(option.peerAdvertise),
|
||||
PeerDataCenter: peerStringOrEmpty(option.peerDataCenter),
|
||||
PeerRack: peerStringOrEmpty(option.peerRack),
|
||||
})
|
||||
|
||||
// create mount root
|
||||
@@ -411,3 +417,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func peerStringOrEmpty(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return *p
|
||||
}
|
||||
+52
-7
@@ -74,6 +74,11 @@ type S3Options struct {
|
||||
externalUrl *string
|
||||
defaultFileMode *string
|
||||
cacheSizeMB *int64
|
||||
// shutdownCtx, when non-nil, tells startS3Server/startIcebergServer to
|
||||
// gracefully shut down their HTTP/gRPC servers once the ctx is cancelled.
|
||||
// Used by weed mini to orchestrate an ordered shutdown; nil for standalone
|
||||
// weed s3.
|
||||
shutdownCtx context.Context
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -453,10 +458,9 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}()
|
||||
}
|
||||
httpS := newHttpServer(router, tlsConfig)
|
||||
if MiniClusterCtx != nil {
|
||||
ctx := MiniClusterCtx
|
||||
if s3opt.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
<-s3opt.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
grpcS.Stop()
|
||||
}()
|
||||
@@ -495,9 +499,9 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}()
|
||||
}
|
||||
httpS := newHttpServer(router, nil)
|
||||
if MiniClusterCtx != nil {
|
||||
if s3opt.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-MiniClusterCtx.Done()
|
||||
<-s3opt.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
grpcS.Stop()
|
||||
}()
|
||||
@@ -518,6 +522,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
|
||||
// Create Iceberg server using the S3ApiServer as filer client
|
||||
icebergServer := iceberg.NewServer(s3ApiServer, s3ApiServer)
|
||||
icebergServer.SetCredentialValidator(s3ApiServer)
|
||||
icebergServer.SetS3Endpoint(s3opt.deriveS3AdvertisedEndpoint())
|
||||
icebergServer.RegisterRoutes(icebergRouter)
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portIceberg)
|
||||
@@ -530,9 +535,9 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
|
||||
glog.V(0).Infof("Start Iceberg REST Catalog Server at http://%s", listenAddress)
|
||||
|
||||
httpS := newHttpServer(icebergRouter, nil)
|
||||
if MiniClusterCtx != nil {
|
||||
if s3opt.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-MiniClusterCtx.Done()
|
||||
<-s3opt.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
}()
|
||||
}
|
||||
@@ -548,3 +553,43 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
|
||||
glog.Fatalf("Iceberg REST Catalog Server Fail to serve: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// deriveS3AdvertisedEndpoint builds the S3 endpoint URL to advertise to
|
||||
// Iceberg catalog clients as part of LoadTable FileIO config. To avoid
|
||||
// hijacking correctly-configured clients (Spark/Trino/PyIceberg all bring
|
||||
// their own s3.endpoint), advertising is strictly opt-in and returns ""
|
||||
// whenever no reliable value is available:
|
||||
// - -s3.externalUrl / S3_EXTERNAL_URL wins and supports reverse-proxy
|
||||
// deployments.
|
||||
// - Otherwise the bind IP is used only when it is explicit and not a
|
||||
// wildcard (0.0.0.0 / ::), with the scheme picked from TLS config and
|
||||
// IPv6 literals bracketed via util.JoinHostPort.
|
||||
//
|
||||
// See issue #9103.
|
||||
func (s3opt *S3Options) deriveS3AdvertisedEndpoint() string {
|
||||
if ext := strings.TrimRight(s3opt.resolveExternalUrl(), "/"); ext != "" {
|
||||
return ext
|
||||
}
|
||||
|
||||
host := ""
|
||||
if s3opt.bindIp != nil {
|
||||
host = *s3opt.bindIp
|
||||
}
|
||||
switch host {
|
||||
case "", "0.0.0.0", "::", "[::]":
|
||||
return ""
|
||||
}
|
||||
|
||||
scheme := "http"
|
||||
port := 0
|
||||
if s3opt.port != nil {
|
||||
port = *s3opt.port
|
||||
}
|
||||
if s3opt.tlsPrivateKey != nil && *s3opt.tlsPrivateKey != "" {
|
||||
scheme = "https"
|
||||
if s3opt.portHttps != nil && *s3opt.portHttps > 0 {
|
||||
port = *s3opt.portHttps
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, util.JoinHostPort(host, port))
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func strp(s string) *string { return &s }
|
||||
func intp(i int) *int { return &i }
|
||||
|
||||
func TestDeriveS3AdvertisedEndpoint(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
opt S3Options
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "wildcard bind IP with no externalUrl does not advertise an endpoint",
|
||||
opt: S3Options{
|
||||
bindIp: strp("0.0.0.0"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp(""),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "empty bind IP with no externalUrl does not advertise an endpoint",
|
||||
opt: S3Options{
|
||||
bindIp: strp(""),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp(""),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "explicit bind IP is kept",
|
||||
opt: S3Options{
|
||||
bindIp: strp("10.0.0.5"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp(""),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "http://10.0.0.5:8333",
|
||||
},
|
||||
{
|
||||
name: "IPv6 literals are bracketed",
|
||||
opt: S3Options{
|
||||
bindIp: strp("fe80::1"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp(""),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "http://[fe80::1]:8333",
|
||||
},
|
||||
{
|
||||
name: "TLS key + https port switches scheme and port",
|
||||
opt: S3Options{
|
||||
bindIp: strp("10.0.0.5"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(8443),
|
||||
tlsPrivateKey: strp("/etc/seaweed/tls.key"),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "https://10.0.0.5:8443",
|
||||
},
|
||||
{
|
||||
name: "TLS-only (no separate https port) still uses https on the HTTP port",
|
||||
opt: S3Options{
|
||||
bindIp: strp("10.0.0.5"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp("/etc/seaweed/tls.key"),
|
||||
externalUrl: strp(""),
|
||||
},
|
||||
want: "https://10.0.0.5:8333",
|
||||
},
|
||||
{
|
||||
name: "externalUrl wins and trailing slash is stripped",
|
||||
opt: S3Options{
|
||||
bindIp: strp("10.0.0.5"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(0),
|
||||
tlsPrivateKey: strp(""),
|
||||
externalUrl: strp("https://s3.example.com/"),
|
||||
},
|
||||
want: "https://s3.example.com",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := tc.opt.deriveS3AdvertisedEndpoint()
|
||||
if got != tc.want {
|
||||
t.Fatalf("deriveS3AdvertisedEndpoint() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,7 @@ func init() {
|
||||
filerOptions.diskType = cmdServer.Flag.String("filer.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
|
||||
filerOptions.exposeDirectoryData = cmdServer.Flag.Bool("filer.exposeDirectoryData", true, "expose directory data via filer. If false, filer UI will be innaccessible.")
|
||||
filerOptions.tusBasePath = cmdServer.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
filerOptions.mountPeerRegistryEnable = cmdServer.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
httppprof "net/http/pprof"
|
||||
@@ -75,6 +76,10 @@ type VolumeServerOptions struct {
|
||||
ldbTimeout *int64
|
||||
debug *bool
|
||||
debugPort *int
|
||||
// shutdownCtx, when non-nil, tells startVolumeServer to shut down once the
|
||||
// ctx is cancelled. Used by integration tests and by weed mini; nil for
|
||||
// standalone weed volume.
|
||||
shutdownCtx context.Context
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -327,11 +332,10 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
stopChan <- true
|
||||
})
|
||||
|
||||
ctx := MiniClusterCtx
|
||||
if ctx != nil {
|
||||
if v.shutdownCtx != nil {
|
||||
select {
|
||||
case <-stopChan:
|
||||
case <-ctx.Done():
|
||||
case <-v.shutdownCtx.Done():
|
||||
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -36,6 +36,10 @@ type WebDavOption struct {
|
||||
cacheDir *string
|
||||
cacheSizeMB *int64
|
||||
maxMB *int
|
||||
// shutdownCtx, when non-nil, tells startWebDav to gracefully shut down the
|
||||
// HTTP server once the ctx is cancelled. Used by weed mini; nil for
|
||||
// standalone weed webdav.
|
||||
shutdownCtx context.Context
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -137,9 +141,9 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
glog.Fatalf("WebDav Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
if MiniClusterCtx != nil {
|
||||
if wo.shutdownCtx != nil {
|
||||
go func() {
|
||||
<-MiniClusterCtx.Done()
|
||||
<-wo.shutdownCtx.Done()
|
||||
httpS.Shutdown(context.Background())
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer
|
||||
}
|
||||
}
|
||||
|
||||
manifestChunk, err = saveFunc(bytes.NewReader(data), "", 0, 0)
|
||||
manifestChunk, err = saveFunc(bytes.NewReader(data), "", 0, 0, uint64(len(data)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -281,4 +281,4 @@ func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer
|
||||
return
|
||||
}
|
||||
|
||||
type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error)
|
||||
type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64, tsNs int64, expectedDataSize uint64) (chunk *filer_pb.FileChunk, err error)
|
||||
@@ -132,7 +132,7 @@ func newTestManifestStore() *testManifestStore {
|
||||
}
|
||||
|
||||
func (s *testManifestStore) saveFunc() SaveDataAsChunkFunctionType {
|
||||
return func(reader io.Reader, name string, offset int64, tsNs int64) (*filer_pb.FileChunk, error) {
|
||||
return func(reader io.Reader, name string, offset int64, tsNs int64, _ uint64) (*filer_pb.FileChunk, error) {
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -280,7 +280,7 @@ func TestCompactResolvedOverlappingManifests(t *testing.T) {
|
||||
}
|
||||
|
||||
// Resolve all manifests into sub-chunks
|
||||
allChunks := append(append([]*filer_pb.FileChunk{}, manifest1...), manifest2...)
|
||||
allChunks := append(manifest1, manifest2...)
|
||||
dataChunks, _, err := store.resolveAll(allChunks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -57,6 +57,7 @@ func (f *Filer) assignAndUpload(targetFile string, data []byte) (*operation.Assi
|
||||
Replication: util.Nvl(f.metaLogReplication, rule.Replication),
|
||||
DiskType: rule.DiskType,
|
||||
WritableVolumeCount: rule.VolumeGrowthCount,
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
}
|
||||
|
||||
assignResult, err := operation.Assign(context.Background(), f.GetMaster, f.GrpcDialOption, assignRequest)
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxMountPeerRegistryEntries caps the number of mounts the filer will track to
|
||||
// prevent a burst of buggy or malicious clients from exhausting memory. At
|
||||
// ~80 B per entry (map + struct + strings) a 10k cap costs ~1 MB, which is
|
||||
// ample headroom for real fleets while being well under any filer's budget.
|
||||
// A full registry silently rejects new registrations until expiry frees room.
|
||||
const maxMountPeerRegistryEntries = 10000
|
||||
|
||||
// maxMountPeerRegistryTTL caps a single heartbeat's requested TTL. Prevents a
|
||||
// misconfigured or malicious client from pinning an entry indefinitely.
|
||||
const maxMountPeerRegistryTTL = time.Hour
|
||||
|
||||
// MountPeerRegistry is the in-memory mount-server registry (tier 1 of the peer
|
||||
// chunk sharing design). The filer holds a map of mount-server address ->
|
||||
// metadata with TTL-bounded entries refreshed by MountRegister heartbeats.
|
||||
//
|
||||
// The registry is small (O(fleet_size)) and slow-changing; fid-level state
|
||||
// is NOT stored here — that lives on the mount fleet itself (tier 2).
|
||||
//
|
||||
// See design-weed-mount-peer-chunk-sharing.md §4.2.1.
|
||||
type MountPeerRegistry struct {
|
||||
mu sync.RWMutex
|
||||
entries map[string]*mountPeerRegistryEntry
|
||||
clock func() time.Time // injectable for tests
|
||||
}
|
||||
|
||||
type mountPeerRegistryEntry struct {
|
||||
peerAddr string
|
||||
dataCenter string
|
||||
rack string
|
||||
expiry time.Time
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
// MountPeerInfo is the public view of a registered mount. DataCenter and
|
||||
// Rack are carried as a two-level locality hierarchy: a peer in the same
|
||||
// DC but a different rack is still a much better fetch target than a peer
|
||||
// in a different DC, so both are worth distinguishing for ranking.
|
||||
type MountPeerInfo struct {
|
||||
PeerAddr string
|
||||
DataCenter string
|
||||
Rack string
|
||||
LastSeenNs int64
|
||||
}
|
||||
|
||||
// NewMountPeerRegistry constructs an empty registry using the real wall clock.
|
||||
func NewMountPeerRegistry() *MountPeerRegistry {
|
||||
return newMountPeerRegistryWithClock(time.Now)
|
||||
}
|
||||
|
||||
func newMountPeerRegistryWithClock(clock func() time.Time) *MountPeerRegistry {
|
||||
return &MountPeerRegistry{
|
||||
entries: make(map[string]*mountPeerRegistryEntry),
|
||||
clock: clock,
|
||||
}
|
||||
}
|
||||
|
||||
// Register inserts or renews an entry. A zero or negative ttl is treated as
|
||||
// "use a sane default" (60 s); a ttl exceeding maxMountPeerRegistryTTL is capped.
|
||||
// An empty peerAddr is rejected silently. When the registry is at capacity,
|
||||
// a *new* entry is rejected; renewals of existing entries always succeed.
|
||||
func (r *MountPeerRegistry) Register(peerAddr, dataCenter, rack string, ttl time.Duration) {
|
||||
if peerAddr == "" {
|
||||
return
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = 60 * time.Second
|
||||
}
|
||||
if ttl > maxMountPeerRegistryTTL {
|
||||
ttl = maxMountPeerRegistryTTL
|
||||
}
|
||||
now := r.clock()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
entry, ok := r.entries[peerAddr]
|
||||
if !ok {
|
||||
if len(r.entries) >= maxMountPeerRegistryEntries {
|
||||
return
|
||||
}
|
||||
entry = &mountPeerRegistryEntry{peerAddr: peerAddr}
|
||||
r.entries[peerAddr] = entry
|
||||
}
|
||||
entry.dataCenter = dataCenter
|
||||
entry.rack = rack
|
||||
entry.lastSeen = now
|
||||
entry.expiry = now.Add(ttl)
|
||||
}
|
||||
|
||||
// List returns all entries that have not yet expired, in no particular
|
||||
// order. Expired entries are filtered out of the response but NOT deleted
|
||||
// here — Sweep handles that under a write lock on its own schedule. List
|
||||
// is called on every mount's MountList refresh (30 s cadence per mount)
|
||||
// so keeping it RLock-only lets concurrent callers proceed in parallel.
|
||||
func (r *MountPeerRegistry) List() []MountPeerInfo {
|
||||
now := r.clock()
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
result := make([]MountPeerInfo, 0, len(r.entries))
|
||||
for _, entry := range r.entries {
|
||||
if !entry.expiry.After(now) {
|
||||
continue // Sweep will clean this up
|
||||
}
|
||||
result = append(result, MountPeerInfo{
|
||||
PeerAddr: entry.peerAddr,
|
||||
DataCenter: entry.dataCenter,
|
||||
Rack: entry.rack,
|
||||
LastSeenNs: entry.lastSeen.UnixNano(),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Len returns the current entry count (including entries that may have
|
||||
// expired but not yet been swept).
|
||||
func (r *MountPeerRegistry) Len() int {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return len(r.entries)
|
||||
}
|
||||
|
||||
// Sweep removes expired entries. Safe to call periodically. Returns the
|
||||
// number of entries evicted.
|
||||
func (r *MountPeerRegistry) Sweep() int {
|
||||
now := r.clock()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
evicted := 0
|
||||
for addr, entry := range r.entries {
|
||||
if !entry.expiry.After(now) {
|
||||
delete(r.entries, addr)
|
||||
evicted++
|
||||
}
|
||||
}
|
||||
return evicted
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testClock(t time.Time) func() time.Time {
|
||||
return func() time.Time { return t }
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_RegisterAndList(t *testing.T) {
|
||||
start := time.Unix(1000, 0)
|
||||
current := start
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
r.Register("mount-a:18080", "", "rack1", 30*time.Second)
|
||||
r.Register("mount-b:18080", "", "rack2", 30*time.Second)
|
||||
|
||||
list := r.List()
|
||||
if len(list) != 2 {
|
||||
t.Fatalf("expected 2 entries, got %d", len(list))
|
||||
}
|
||||
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].PeerAddr < list[j].PeerAddr })
|
||||
if list[0].PeerAddr != "mount-a:18080" || list[0].Rack != "rack1" {
|
||||
t.Errorf("entry 0 unexpected: %+v", list[0])
|
||||
}
|
||||
if list[1].PeerAddr != "mount-b:18080" || list[1].Rack != "rack2" {
|
||||
t.Errorf("entry 1 unexpected: %+v", list[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_RenewExtendsExpiry(t *testing.T) {
|
||||
current := time.Unix(1000, 0)
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
r.Register("mount-a:18080", "", "rack1", 30*time.Second)
|
||||
|
||||
// Advance time past original expiry.
|
||||
current = current.Add(25 * time.Second)
|
||||
// Renew — should push expiry to now+30.
|
||||
r.Register("mount-a:18080", "", "rack1-updated", 30*time.Second)
|
||||
|
||||
// Advance to where original expiry would have triggered eviction.
|
||||
current = current.Add(10 * time.Second)
|
||||
list := r.List()
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("expected 1 entry after renew, got %d", len(list))
|
||||
}
|
||||
if list[0].Rack != "rack1-updated" {
|
||||
t.Errorf("rack not updated on renew: %q", list[0].Rack)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_ExpirationDropsEntry(t *testing.T) {
|
||||
current := time.Unix(1000, 0)
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
r.Register("mount-a:18080", "", "", 10*time.Second)
|
||||
if n := r.Len(); n != 1 {
|
||||
t.Fatalf("expected 1 entry, got %d", n)
|
||||
}
|
||||
|
||||
current = current.Add(15 * time.Second)
|
||||
list := r.List()
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected 0 entries after expiry, got %d", len(list))
|
||||
}
|
||||
// List no longer deletes — it's RLock-only so concurrent callers can
|
||||
// proceed in parallel. Sweep is the sole reclamation path.
|
||||
if n := r.Len(); n != 1 {
|
||||
t.Errorf("List should not delete expired entries; Len=%d want 1", n)
|
||||
}
|
||||
if evicted := r.Sweep(); evicted != 1 {
|
||||
t.Errorf("Sweep should have evicted the expired entry; got %d", evicted)
|
||||
}
|
||||
if n := r.Len(); n != 0 {
|
||||
t.Errorf("after Sweep, Len=%d want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_SweepCountsEvictions(t *testing.T) {
|
||||
current := time.Unix(1000, 0)
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
r.Register("mount-a:18080", "", "", 10*time.Second)
|
||||
r.Register("mount-b:18080", "", "", 60*time.Second)
|
||||
|
||||
current = current.Add(30 * time.Second)
|
||||
got := r.Sweep()
|
||||
if got != 1 {
|
||||
t.Errorf("expected 1 eviction, got %d", got)
|
||||
}
|
||||
if n := r.Len(); n != 1 {
|
||||
t.Errorf("expected 1 surviving entry, got %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_NegativeTTLFallsBackToDefault(t *testing.T) {
|
||||
current := time.Unix(1000, 0)
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
r.Register("mount-a:18080", "", "", -5*time.Second)
|
||||
if n := r.Len(); n != 1 {
|
||||
t.Fatalf("expected 1 entry even with bad ttl, got %d", n)
|
||||
}
|
||||
|
||||
// Advance past the default (60s) and confirm it expires.
|
||||
current = current.Add(61 * time.Second)
|
||||
list := r.List()
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected entry to expire after default ttl, got %d entries", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_EmptyList(t *testing.T) {
|
||||
r := NewMountPeerRegistry()
|
||||
list := r.List()
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected empty list, got %d", len(list))
|
||||
}
|
||||
_ = testClock // keep helper exported for future tests
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_EmptyPeerAddrRejected(t *testing.T) {
|
||||
r := NewMountPeerRegistry()
|
||||
r.Register("", "", "rack", 30*time.Second)
|
||||
if n := r.Len(); n != 0 {
|
||||
t.Errorf("empty peer_addr should not insert; Len=%d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_TTLCapped(t *testing.T) {
|
||||
current := time.Unix(1000, 0)
|
||||
r := newMountPeerRegistryWithClock(func() time.Time { return current })
|
||||
|
||||
// Request a ridiculous TTL; should be capped to maxMountPeerRegistryTTL.
|
||||
r.Register("mount-a:18080", "", "", 24*time.Hour)
|
||||
|
||||
// Advance past the cap; entry should now be expired.
|
||||
current = current.Add(maxMountPeerRegistryTTL + time.Second)
|
||||
if list := r.List(); len(list) != 0 {
|
||||
t.Errorf("expected entry to expire after maxMountPeerRegistryTTL, got %d", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMountPeerRegistry_CapacityLimit(t *testing.T) {
|
||||
r := NewMountPeerRegistry()
|
||||
// Fill to capacity.
|
||||
for i := 0; i < maxMountPeerRegistryEntries; i++ {
|
||||
r.Register(fmt.Sprintf("mount-%d:18080", i), "", "", 60*time.Second)
|
||||
}
|
||||
if n := r.Len(); n != maxMountPeerRegistryEntries {
|
||||
t.Fatalf("expected %d entries, got %d", maxMountPeerRegistryEntries, n)
|
||||
}
|
||||
// A brand-new address beyond the cap is rejected.
|
||||
r.Register("new-mount:18080", "", "", 60*time.Second)
|
||||
if n := r.Len(); n != maxMountPeerRegistryEntries {
|
||||
t.Errorf("new entry past cap should be rejected; Len=%d", n)
|
||||
}
|
||||
// A renewal of an existing entry still succeeds.
|
||||
r.Register("mount-0:18080", "", "rack-renewed", 60*time.Second)
|
||||
if n := r.Len(); n != maxMountPeerRegistryEntries {
|
||||
t.Errorf("renewal should not increase size; Len=%d", n)
|
||||
}
|
||||
}
|
||||
@@ -178,6 +178,10 @@ func newSingleChunkCacher(parent *ReaderCache, fileId string, cipherKey []byte,
|
||||
// startCaching downloads the chunk data in the background.
|
||||
// It does NOT hold the lock during the HTTP download to allow concurrent readers
|
||||
// to wait efficiently using the done channel.
|
||||
//
|
||||
// Concurrent downloads of the same chunk are already deduplicated by the
|
||||
// ReaderCache.downloaders map (guarded by the ReaderCache mutex). Each fileId
|
||||
// has at most one active SingleChunkCacher at any time.
|
||||
func (s *SingleChunkCacher) startCaching() {
|
||||
s.wg.Add(1)
|
||||
defer s.wg.Done()
|
||||
|
||||
@@ -433,6 +433,46 @@ func TestSingleChunkCacherMultipleReadersWaitForDownload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestReaderCacheDownloaderDedup tests that concurrent ReadChunkAt calls for
|
||||
// the same fileId result in only one network fetch (lookup call), because
|
||||
// the downloaders map deduplicates in-flight downloads.
|
||||
func TestReaderCacheDownloaderDedup(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
var lookupCount int32
|
||||
lookupGate := make(chan struct{})
|
||||
|
||||
lookupFn := func(ctx context.Context, fileId string) ([]string, error) {
|
||||
atomic.AddInt32(&lookupCount, 1)
|
||||
<-lookupGate
|
||||
// Return an error so we don't need to mock the HTTP fetch.
|
||||
return nil, fmt.Errorf("simulated lookup for %s", fileId)
|
||||
}
|
||||
|
||||
rc := NewReaderCache(10, cache, lookupFn)
|
||||
defer rc.destroy()
|
||||
|
||||
const numReaders = 10
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(numReaders)
|
||||
|
||||
for i := 0; i < numReaders; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
buffer := make([]byte, 100)
|
||||
rc.ReadChunkAt(context.Background(), buffer, "dedup-file", nil, false, 0, 100, false)
|
||||
}()
|
||||
}
|
||||
|
||||
// Allow downloads to proceed.
|
||||
close(lookupGate)
|
||||
wg.Wait()
|
||||
|
||||
count := atomic.LoadInt32(&lookupCount)
|
||||
if count != 1 {
|
||||
t.Errorf("expected exactly 1 lookup call, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSingleChunkCacherOneReaderCancelsOthersContinue tests that when one reader
|
||||
// cancels, other readers waiting on the same chunk continue to wait.
|
||||
func TestSingleChunkCacherOneReaderCancelsOthersContinue(t *testing.T) {
|
||||
|
||||
@@ -72,7 +72,7 @@ func (pages *ChunkedDirtyPages) saveChunkedFileIntervalToStorage(reader io.Reade
|
||||
|
||||
fileFullPath := pages.fh.FullPath()
|
||||
fileName := fileFullPath.Name()
|
||||
chunk, err := pages.fh.wfs.saveDataAsChunk(fileFullPath)(reader, fileName, offset, modifiedTsNs)
|
||||
chunk, err := pages.fh.wfs.saveDataAsChunk(fileFullPath)(reader, fileName, offset, modifiedTsNs, uint64(size))
|
||||
if err != nil {
|
||||
glog.V(0).Infof("%v saveToStorage [%d,%d): %v", fileFullPath, offset, offset+size, err)
|
||||
pages.lastErr = err
|
||||
|
||||
@@ -47,3 +47,28 @@ func grpcErrorToFuseStatus(err error) fuse.Status {
|
||||
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
// isRetryableFilerError reports whether a filer RPC error looks transient
|
||||
// enough to retry. It takes a conservative whitelist approach: only errors
|
||||
// that clearly describe a permanent application-level failure
|
||||
// (NotFound/AlreadyExists/InvalidArgument/PermissionDenied/Unauthenticated/
|
||||
// FailedPrecondition) short-circuit the retry loop. Everything else —
|
||||
// transport errors, Canceled/Unavailable/ResourceExhausted, or errors with no
|
||||
// gRPC status — is treated as potentially transient and retried.
|
||||
func isRetryableFilerError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if s, ok := status.FromError(err); ok {
|
||||
switch s.Code() {
|
||||
case codes.NotFound,
|
||||
codes.AlreadyExists,
|
||||
codes.InvalidArgument,
|
||||
codes.PermissionDenied,
|
||||
codes.Unauthenticated,
|
||||
codes.FailedPrecondition:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Regression: wfs_save.go used to wrap the gRPC error with fmt.Errorf(... %v ...)
|
||||
// which stringified the status and made status.FromError fall through to the
|
||||
// default EIO mapping. Wrapping with %w must preserve the code so that
|
||||
// codes.Canceled from a closing filer connection surfaces as ETIMEDOUT (a
|
||||
// retryable hint for FUSE callers) rather than EIO.
|
||||
func TestGrpcErrorToFuseStatusUnwrapsCanceledThroughFmtErrorf(t *testing.T) {
|
||||
grpcErr := status.Error(codes.Canceled, "grpc: the client connection is closing")
|
||||
|
||||
wrapped := fmt.Errorf("UpdateEntry dir /some/path: %w", grpcErr)
|
||||
|
||||
got := grpcErrorToFuseStatus(wrapped)
|
||||
want := fuse.Status(syscall.ETIMEDOUT)
|
||||
if got != want {
|
||||
t.Fatalf("grpcErrorToFuseStatus(canceled wrapped with %%w) = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Guard against regressing the wrap verb: %v loses the gRPC status and the
|
||||
// classifier must fall through to EIO. This test documents that behavior so
|
||||
// anyone reverting the %w change sees the intent.
|
||||
func TestGrpcErrorToFuseStatusDropsCanceledThroughPercentV(t *testing.T) {
|
||||
grpcErr := status.Error(codes.Canceled, "grpc: the client connection is closing")
|
||||
|
||||
wrapped := fmt.Errorf("UpdateEntry dir /some/path: %v", grpcErr)
|
||||
|
||||
got := grpcErrorToFuseStatus(wrapped)
|
||||
if got != fuse.EIO {
|
||||
t.Fatalf("grpcErrorToFuseStatus(canceled wrapped with %%v) = %v, want EIO (regression guard)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsRetryableFilerError(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"nil", nil, false},
|
||||
{"canceled", status.Error(codes.Canceled, "grpc: the client connection is closing"), true},
|
||||
{"unavailable", status.Error(codes.Unavailable, "connection refused"), true},
|
||||
{"deadline_exceeded", status.Error(codes.DeadlineExceeded, "deadline exceeded"), true},
|
||||
{"resource_exhausted", status.Error(codes.ResourceExhausted, "too many concurrent requests"), true},
|
||||
{"internal", status.Error(codes.Internal, "server crashed"), true},
|
||||
{"not_found", status.Error(codes.NotFound, "entry missing"), false},
|
||||
{"already_exists", status.Error(codes.AlreadyExists, "duplicate"), false},
|
||||
{"invalid_argument", status.Error(codes.InvalidArgument, "bad request"), false},
|
||||
{"permission_denied", status.Error(codes.PermissionDenied, "no access"), false},
|
||||
{"unauthenticated", status.Error(codes.Unauthenticated, "missing creds"), false},
|
||||
{"failed_precondition", status.Error(codes.FailedPrecondition, "not empty"), false},
|
||||
{"plain_error_retries", errors.New("random network glitch"), true},
|
||||
{"wrapped_canceled_still_retries", fmt.Errorf("ctx: %w", status.Error(codes.Canceled, "closing")), true},
|
||||
{"wrapped_not_found_still_skipped", fmt.Errorf("ctx: %w", status.Error(codes.NotFound, "gone")), false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := isRetryableFilerError(tc.err); got != tc.want {
|
||||
t.Fatalf("isRetryableFilerError(%v) = %v, want %v", tc.err, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// retryMetadataFlushIf must short-circuit on non-retryable errors so that
|
||||
// synchronous FUSE ops (chmod/utimes/xattr) don't hang for ~7s on ENOENT/
|
||||
// EACCES/EINVAL.
|
||||
func TestRetryMetadataFlushIfShortCircuitsOnPermanentError(t *testing.T) {
|
||||
originalSleep := metadataFlushSleep
|
||||
t.Cleanup(func() {
|
||||
metadataFlushSleep = originalSleep
|
||||
})
|
||||
metadataFlushSleep = func(_ time.Duration) {
|
||||
t.Fatal("sleep should not be called when shouldRetry returns false")
|
||||
}
|
||||
|
||||
attempts := 0
|
||||
permanent := status.Error(codes.NotFound, "entry missing")
|
||||
err := retryMetadataFlushIf(func() error {
|
||||
attempts++
|
||||
return permanent
|
||||
}, isRetryableFilerError, nil)
|
||||
|
||||
if attempts != 1 {
|
||||
t.Fatalf("attempts = %d, want 1 (permanent error should short-circuit)", attempts)
|
||||
}
|
||||
if !errors.Is(err, permanent) {
|
||||
t.Fatalf("err = %v, want permanent sentinel", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Transient errors must keep retrying up to the attempt cap even when a
|
||||
// predicate is supplied.
|
||||
func TestRetryMetadataFlushIfRetriesTransientErrors(t *testing.T) {
|
||||
originalSleep := metadataFlushSleep
|
||||
t.Cleanup(func() {
|
||||
metadataFlushSleep = originalSleep
|
||||
})
|
||||
metadataFlushSleep = func(_ time.Duration) {}
|
||||
|
||||
attempts := 0
|
||||
transient := status.Error(codes.Canceled, "grpc: the client connection is closing")
|
||||
err := retryMetadataFlushIf(func() error {
|
||||
attempts++
|
||||
return transient
|
||||
}, isRetryableFilerError, nil)
|
||||
|
||||
if attempts != metadataFlushRetries+1 {
|
||||
t.Fatalf("attempts = %d, want %d", attempts, metadataFlushRetries+1)
|
||||
}
|
||||
if !errors.Is(err, transient) {
|
||||
t.Fatalf("err = %v, want transient sentinel", err)
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,23 @@ func (fh *FileHandle) readFromChunksWithContext(ctx context.Context, buff []byte
|
||||
glog.V(4).Infof("RDMA read failed for %s, falling back to HTTP: %v", fileFullPath, err)
|
||||
}
|
||||
|
||||
// Peer chunk sharing: try a peer mount's cache before the volume tier.
|
||||
// Any failure falls through transparently. See design-weed-mount-
|
||||
// peer-chunk-sharing.md §4.3.
|
||||
if fh.wfs.option.PeerEnabled && fh.wfs.peerGrpcServer != nil {
|
||||
totalRead, ts, err := fh.tryPeerRead(ctx, fileSize, buff, offset, entry)
|
||||
if err == nil {
|
||||
glog.V(4).Infof("peer read successful for %s [%d,%d] %d", fileFullPath, offset, offset+int64(totalRead), totalRead)
|
||||
return int64(totalRead), ts, nil
|
||||
}
|
||||
// Skip the "failed" log for benign skip reasons (local cache
|
||||
// hit, no peer owner yet, etc.) — the cache/volume fallback is
|
||||
// the expected outcome, not a failure.
|
||||
if err != errPeerReadSkipped {
|
||||
glog.V(4).Infof("peer read failed for %s, falling back to volume: %v", fileFullPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to normal chunk reading
|
||||
totalRead, ts, err := fh.entryChunkGroup.ReadDataAt(ctx, fileSize, buff, offset)
|
||||
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
// FileIdEntry holds a pre-allocated file ID from the filer/master, ready for
|
||||
// immediate use by an upload worker without an AssignVolume round-trip.
|
||||
type FileIdEntry struct {
|
||||
FileId string
|
||||
Host string // volume server address (already adjusted for access mode)
|
||||
Auth security.EncodedJwt
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// FileIdPool pre-allocates file IDs in batches so that chunk uploads can grab
|
||||
// one instantly instead of blocking on an AssignVolume RPC per chunk.
|
||||
//
|
||||
// The pool is refilled in the background when it drops below a low-water mark.
|
||||
// All IDs are allocated with the mount's global (replication, collection, ttl,
|
||||
// diskType, dataCenter) parameters. Path-based storage rules (filer.conf) are
|
||||
// NOT applied to pooled IDs since the pool allocates ahead of any specific file
|
||||
// path. This is an intentional tradeoff for writeback cache performance.
|
||||
type FileIdPool struct {
|
||||
wfs *WFS
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
entries []FileIdEntry // available pre-allocated IDs
|
||||
filling bool // true when a background refill is in progress
|
||||
|
||||
poolSize int // target pool capacity
|
||||
batchSize int // how many IDs to request per Assign RPC
|
||||
lowWater int // refill trigger threshold
|
||||
maxAge time.Duration
|
||||
}
|
||||
|
||||
func NewFileIdPool(wfs *WFS) *FileIdPool {
|
||||
concurrency := wfs.option.ConcurrentWriters
|
||||
if concurrency <= 0 {
|
||||
concurrency = 128 // match default async flush worker count
|
||||
}
|
||||
pool := &FileIdPool{
|
||||
wfs: wfs,
|
||||
poolSize: concurrency * 2,
|
||||
batchSize: concurrency,
|
||||
lowWater: concurrency,
|
||||
maxAge: 25 * time.Second, // conservative; JWT TTL is typically 30s+
|
||||
}
|
||||
pool.cond = sync.NewCond(&pool.mu)
|
||||
return pool
|
||||
}
|
||||
|
||||
// Get returns a pre-allocated file ID entry. If the pool is empty and a refill
|
||||
// is in progress, callers wait for it to complete rather than failing. Returns
|
||||
// an error only if the Assign RPC fails.
|
||||
func (p *FileIdPool) Get() (FileIdEntry, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
for {
|
||||
p.evictExpired()
|
||||
|
||||
if len(p.entries) > 0 {
|
||||
entry := p.entries[0]
|
||||
p.entries = p.entries[1:]
|
||||
if len(p.entries) < p.lowWater && !p.filling {
|
||||
p.filling = true
|
||||
go p.doRefill()
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// Pool empty.
|
||||
if p.filling {
|
||||
// Wait for the in-flight refill to complete.
|
||||
p.cond.Wait()
|
||||
continue
|
||||
}
|
||||
|
||||
// No refill in progress — start one synchronously.
|
||||
p.filling = true
|
||||
p.mu.Unlock()
|
||||
entries, err := p.assignBatch(p.batchSize)
|
||||
p.mu.Lock()
|
||||
p.filling = false
|
||||
p.cond.Broadcast()
|
||||
|
||||
if err != nil {
|
||||
return FileIdEntry{}, fmt.Errorf("fileIdPool: %w", err)
|
||||
}
|
||||
p.entries = append(p.entries, entries...)
|
||||
// Loop back to pop from entries.
|
||||
}
|
||||
}
|
||||
|
||||
func (p *FileIdPool) evictExpired() {
|
||||
cutoff := time.Now().Add(-p.maxAge)
|
||||
i := 0
|
||||
for i < len(p.entries) && p.entries[i].Time.Before(cutoff) {
|
||||
i++
|
||||
}
|
||||
if i > 0 {
|
||||
p.entries = p.entries[i:]
|
||||
}
|
||||
}
|
||||
|
||||
// doRefill runs in a background goroutine to refill the pool.
|
||||
func (p *FileIdPool) doRefill() {
|
||||
entries, err := p.assignBatch(p.batchSize)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("fileIdPool refill: %v", err)
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
if err == nil {
|
||||
p.entries = append(p.entries, entries...)
|
||||
}
|
||||
p.filling = false
|
||||
p.cond.Broadcast()
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// assignBatch requests `count` file IDs from the filer using individual
|
||||
// Count=1 RPCs over a single gRPC connection. Each response includes a
|
||||
// per-fid JWT, so uploads work correctly when JWT security is enabled.
|
||||
//
|
||||
// We use individual requests instead of Count=N because the master generates
|
||||
// one JWT for the base file ID only (master_grpc_server_assign.go:158), and
|
||||
// the volume server validates that the JWT's Fid matches the upload's file ID
|
||||
// exactly (volume_server_handlers.go:367). Sequential IDs derived from a
|
||||
// Count=N response would fail this check.
|
||||
//
|
||||
// Note: the AssignVolumeRequest intentionally omits the Path field. Pooled IDs
|
||||
// use the mount's global storage parameters, not per-path rules from filer.conf
|
||||
// (detectStorageOption / MatchStorageRule). This is a writeback cache tradeoff.
|
||||
func (p *FileIdPool) assignBatch(count int) ([]FileIdEntry, error) {
|
||||
var entries []FileIdEntry
|
||||
err := p.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
now := time.Now()
|
||||
req := &filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: p.wfs.option.Replication,
|
||||
Collection: p.wfs.option.Collection,
|
||||
TtlSec: p.wfs.option.TtlSec,
|
||||
DiskType: string(p.wfs.option.DiskType),
|
||||
DataCenter: p.wfs.option.DataCenter,
|
||||
ExpectedDataSize: uint64(p.wfs.option.ChunkSizeLimit),
|
||||
}
|
||||
for i := 0; i < count; i++ {
|
||||
resp, assignErr := client.AssignVolume(context.Background(), req)
|
||||
if assignErr != nil {
|
||||
if len(entries) > 0 {
|
||||
break // partial batch is fine
|
||||
}
|
||||
return assignErr
|
||||
}
|
||||
if resp.Error != "" {
|
||||
if len(entries) > 0 {
|
||||
break
|
||||
}
|
||||
return fmt.Errorf("assign: %s", resp.Error)
|
||||
}
|
||||
entries = append(entries, FileIdEntry{
|
||||
FileId: resp.FileId,
|
||||
Host: p.wfs.AdjustedUrl(resp.Location),
|
||||
Auth: security.EncodedJwt(resp.Auth),
|
||||
Time: now,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return entries, err
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// mockFilerClient simulates AssignVolume RPCs with configurable latency.
|
||||
type mockFilerClient struct {
|
||||
latency time.Duration
|
||||
nextVolId uint32
|
||||
nextKey uint64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (m *mockFilerClient) AssignVolume(_ context.Context, req *filer_pb.AssignVolumeRequest, _ ...grpc.CallOption) (*filer_pb.AssignVolumeResponse, error) {
|
||||
if m.latency > 0 {
|
||||
time.Sleep(m.latency)
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
count := int(req.Count)
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
vid := needle.VolumeId(m.nextVolId + 1)
|
||||
key := m.nextKey + 1000 // start at a non-zero key for valid hex encoding
|
||||
m.nextKey += uint64(count)
|
||||
m.nextVolId++
|
||||
|
||||
fid := needle.NewFileId(vid, key, 0x12345678)
|
||||
return &filer_pb.AssignVolumeResponse{
|
||||
FileId: fid.String(),
|
||||
Count: int32(count),
|
||||
Auth: "test-jwt-token",
|
||||
Location: &filer_pb.Location{
|
||||
Url: "127.0.0.1:8080",
|
||||
PublicUrl: "127.0.0.1:8080",
|
||||
GrpcPort: 18080,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TestFileIdPoolSequentialIds verifies that batch assignment generates
|
||||
// correct sequential file IDs from a single AssignVolume response.
|
||||
func TestFileIdPoolSequentialIds(t *testing.T) {
|
||||
mock := &mockFilerClient{}
|
||||
resp, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: 5})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
baseFid, parseErr := needle.ParseFileIdFromString(resp.FileId)
|
||||
if parseErr != nil {
|
||||
t.Fatal(parseErr)
|
||||
}
|
||||
|
||||
baseKey := uint64(baseFid.Key)
|
||||
for i := 0; i < int(resp.Count); i++ {
|
||||
fid := needle.NewFileId(baseFid.VolumeId, baseKey+uint64(i), uint32(baseFid.Cookie))
|
||||
t.Logf("ID %d: %s", i, fid.String())
|
||||
parsed, err := needle.ParseFileIdFromString(fid.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse sequential ID %d: %v", i, err)
|
||||
}
|
||||
if uint64(parsed.Key) != baseKey+uint64(i) {
|
||||
t.Fatalf("ID %d: expected key %d, got %d", i, baseKey+uint64(i), uint64(parsed.Key))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileIdPoolExpiry verifies that expired entries are evicted.
|
||||
func TestFileIdPoolExpiry(t *testing.T) {
|
||||
pool := &FileIdPool{
|
||||
maxAge: time.Second,
|
||||
}
|
||||
pool.cond = sync.NewCond(&pool.mu)
|
||||
now := time.Now()
|
||||
pool.entries = []FileIdEntry{
|
||||
{FileId: "1,old", Time: now.Add(-2 * time.Second)},
|
||||
{FileId: "2,old", Time: now.Add(-2 * time.Second)},
|
||||
{FileId: "3,fresh", Time: now},
|
||||
}
|
||||
pool.evictExpired()
|
||||
if len(pool.entries) != 1 {
|
||||
t.Fatalf("expected 1 entry after eviction, got %d", len(pool.entries))
|
||||
}
|
||||
if pool.entries[0].FileId != "3,fresh" {
|
||||
t.Fatalf("expected fresh entry, got %s", pool.entries[0].FileId)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileIdPoolGetWaitsForRefill verifies that concurrent Get() calls wait
|
||||
// for an in-flight refill instead of returning an error.
|
||||
func TestFileIdPoolGetWaitsForRefill(t *testing.T) {
|
||||
pool := &FileIdPool{
|
||||
poolSize: 10,
|
||||
batchSize: 5,
|
||||
lowWater: 3,
|
||||
maxAge: 30 * time.Second,
|
||||
}
|
||||
pool.cond = sync.NewCond(&pool.mu)
|
||||
|
||||
// Simulate a slow refill in progress.
|
||||
pool.filling = true
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
// After a short delay, deliver entries and signal.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
pool.mu.Lock()
|
||||
now := time.Now()
|
||||
for i := 0; i < 5; i++ {
|
||||
pool.entries = append(pool.entries, FileIdEntry{
|
||||
FileId: fmt.Sprintf("1,%x12345678", 1000+i),
|
||||
Host: "127.0.0.1:8080",
|
||||
Auth: "jwt",
|
||||
Time: now,
|
||||
})
|
||||
}
|
||||
pool.filling = false
|
||||
pool.cond.Broadcast()
|
||||
pool.mu.Unlock()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Get() should wait for the refill, not return an error.
|
||||
entry, err := pool.Get()
|
||||
if err != nil {
|
||||
t.Fatalf("Get() returned error while refill in progress: %v", err)
|
||||
}
|
||||
if entry.FileId == "" {
|
||||
t.Fatal("Get() returned empty entry")
|
||||
}
|
||||
<-done
|
||||
}
|
||||
|
||||
// BenchmarkPoolGetVsDirectAssign measures the latency difference between
|
||||
// getting a file ID from the pool vs a direct (simulated) AssignVolume RPC.
|
||||
func BenchmarkPoolGetVsDirectAssign(b *testing.B) {
|
||||
assignLatencies := []time.Duration{
|
||||
0,
|
||||
100 * time.Microsecond,
|
||||
1 * time.Millisecond,
|
||||
5 * time.Millisecond,
|
||||
}
|
||||
|
||||
for _, latency := range assignLatencies {
|
||||
name := "latency=" + latency.String()
|
||||
|
||||
b.Run("DirectAssign/"+name, func(b *testing.B) {
|
||||
mock := &mockFilerClient{latency: latency}
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: 1})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("PoolGet/"+name, func(b *testing.B) {
|
||||
pool := &FileIdPool{
|
||||
maxAge: 30 * time.Second,
|
||||
lowWater: 1000000, // disable background refill
|
||||
}
|
||||
pool.cond = sync.NewCond(&pool.mu)
|
||||
// Pre-fill with a fixed-size pool; refill under StopTimer when depleted.
|
||||
const preload = 4096
|
||||
refill := func() {
|
||||
now := time.Now()
|
||||
for i := 0; i < preload; i++ {
|
||||
pool.entries = append(pool.entries, FileIdEntry{
|
||||
FileId: fmt.Sprintf("1,%x12345678", i),
|
||||
Host: "127.0.0.1:8080",
|
||||
Auth: security.EncodedJwt("test-jwt"),
|
||||
Time: now,
|
||||
})
|
||||
}
|
||||
}
|
||||
refill()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
pool.mu.Lock()
|
||||
if len(pool.entries) == 0 {
|
||||
pool.mu.Unlock()
|
||||
b.StopTimer()
|
||||
refill()
|
||||
b.StartTimer()
|
||||
pool.mu.Lock()
|
||||
}
|
||||
_ = pool.entries[0]
|
||||
pool.entries = pool.entries[1:]
|
||||
pool.mu.Unlock()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkConcurrentPoolGet measures pool throughput under concurrent access.
|
||||
func BenchmarkConcurrentPoolGet(b *testing.B) {
|
||||
for _, workers := range []int{1, 4, 16, 64} {
|
||||
b.Run(fmt.Sprintf("workers=%d", workers), func(b *testing.B) {
|
||||
pool := &FileIdPool{
|
||||
maxAge: 30 * time.Second,
|
||||
lowWater: 1000000,
|
||||
}
|
||||
pool.cond = sync.NewCond(&pool.mu)
|
||||
// Pre-fill
|
||||
now := time.Now()
|
||||
total := b.N*workers + 1000
|
||||
pool.entries = make([]FileIdEntry, total)
|
||||
for i := range pool.entries {
|
||||
pool.entries[i] = FileIdEntry{
|
||||
FileId: fmt.Sprintf("1,%x12345678", i+1000),
|
||||
Host: "127.0.0.1:8080",
|
||||
Auth: security.EncodedJwt("test-jwt"),
|
||||
Time: now,
|
||||
}
|
||||
}
|
||||
|
||||
var ops atomic.Int64
|
||||
b.ResetTimer()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
perWorker := b.N
|
||||
for w := 0; w < workers; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perWorker; i++ {
|
||||
pool.mu.Lock()
|
||||
if len(pool.entries) > 0 {
|
||||
_ = pool.entries[0]
|
||||
pool.entries = pool.entries[1:]
|
||||
ops.Add(1)
|
||||
}
|
||||
pool.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
b.ReportMetric(float64(ops.Load())/b.Elapsed().Seconds(), "ids/sec")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBatchAssign measures the cost of batch vs individual assign RPCs.
|
||||
func BenchmarkBatchAssign(b *testing.B) {
|
||||
for _, batchSize := range []int{1, 8, 16, 32} {
|
||||
b.Run(fmt.Sprintf("batch=%d", batchSize), func(b *testing.B) {
|
||||
mock := &mockFilerClient{latency: 1 * time.Millisecond}
|
||||
totalIds := 0
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
resp, err := mock.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{Count: int32(batchSize)})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
baseFid, _ := needle.ParseFileIdFromString(resp.FileId)
|
||||
baseKey := uint64(baseFid.Key)
|
||||
for j := 0; j < int(resp.Count); j++ {
|
||||
_ = needle.NewFileId(baseFid.VolumeId, baseKey+uint64(j), uint32(baseFid.Cookie)).String()
|
||||
totalIds++
|
||||
}
|
||||
}
|
||||
b.ReportMetric(float64(totalIds)/b.Elapsed().Seconds(), "ids/sec")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,15 @@ const metadataFlushRetries = 3
|
||||
var metadataFlushSleep = time.Sleep
|
||||
|
||||
func retryMetadataFlush(flush func() error, onRetry func(nextAttempt, totalAttempts int, backoff time.Duration, err error)) error {
|
||||
return retryMetadataFlushIf(flush, nil, onRetry)
|
||||
}
|
||||
|
||||
// retryMetadataFlushIf is retryMetadataFlush with an optional shouldRetry
|
||||
// predicate. If shouldRetry is nil or returns true, the flush is retried with
|
||||
// exponential backoff; if it returns false, the error is returned immediately
|
||||
// so callers don't pay retry latency on clearly permanent errors (e.g.
|
||||
// ENOENT/EACCES/EINVAL from a synchronous setattr).
|
||||
func retryMetadataFlushIf(flush func() error, shouldRetry func(error) bool, onRetry func(nextAttempt, totalAttempts int, backoff time.Duration, err error)) error {
|
||||
totalAttempts := metadataFlushRetries + 1
|
||||
var err error
|
||||
for attempt := 1; attempt <= totalAttempts; attempt++ {
|
||||
@@ -17,6 +26,9 @@ func retryMetadataFlush(flush func() error, onRetry func(nextAttempt, totalAttem
|
||||
if attempt == totalAttempts {
|
||||
break
|
||||
}
|
||||
if shouldRetry != nil && !shouldRetry(err) {
|
||||
break
|
||||
}
|
||||
|
||||
backoff := time.Duration(1<<uint(attempt-1)) * time.Second
|
||||
if onRetry != nil {
|
||||
|
||||
@@ -2,6 +2,21 @@ package page_writer
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// softThresholdRatio is the fraction of cap at which soft throttling begins.
|
||||
// At this level, writes sleep briefly to let uploaders drain.
|
||||
softThresholdRatio = 0.8
|
||||
// hardThresholdRatio is the fraction of cap at which hard throttling kicks in.
|
||||
// Writes sleep longer to aggressively slow intake.
|
||||
hardThresholdRatio = 0.95
|
||||
// softThrottleDelay is the sleep duration when usage exceeds the soft threshold.
|
||||
softThrottleDelay = 10 * time.Millisecond
|
||||
// hardThrottleDelay is the sleep duration when usage exceeds the hard threshold.
|
||||
hardThrottleDelay = 50 * time.Millisecond
|
||||
)
|
||||
|
||||
// WriteBufferAccountant enforces a global byte budget across all
|
||||
@@ -14,16 +29,25 @@ import (
|
||||
//
|
||||
// A nil receiver is treated as "unlimited" for backward compatibility.
|
||||
type WriteBufferAccountant struct {
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
cap int64 // 0 means unlimited
|
||||
used int64
|
||||
evictor func(needBytes int64) bool
|
||||
evicting bool
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
cap int64 // 0 means unlimited
|
||||
used int64
|
||||
softThreshold int64 // pre-computed: cap * softThresholdRatio
|
||||
hardThreshold int64 // pre-computed: cap * hardThresholdRatio
|
||||
evictor func(needBytes int64) bool
|
||||
evicting bool
|
||||
|
||||
softThrottleCount atomic.Int64
|
||||
hardThrottleCount atomic.Int64
|
||||
}
|
||||
|
||||
func NewWriteBufferAccountant(capBytes int64) *WriteBufferAccountant {
|
||||
a := &WriteBufferAccountant{cap: capBytes}
|
||||
a := &WriteBufferAccountant{
|
||||
cap: capBytes,
|
||||
softThreshold: int64(float64(capBytes) * softThresholdRatio),
|
||||
hardThreshold: int64(float64(capBytes) * hardThresholdRatio),
|
||||
}
|
||||
a.cond = sync.NewCond(&a.mu)
|
||||
return a
|
||||
}
|
||||
@@ -57,6 +81,29 @@ func (a *WriteBufferAccountant) Reserve(n int64) {
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
// Graduated backpressure: slow writers before hitting the hard cap.
|
||||
// Use projected usage (used + n) so that a single reservation crossing
|
||||
// a threshold is throttled immediately rather than on the next call.
|
||||
//
|
||||
// This runs once per Reserve, not inside the blocking loop below.
|
||||
// Once usage reaches the cap, the evictor + cond.Wait is the correct
|
||||
// mechanism: it blocks until a sealed chunk upload frees space, which
|
||||
// is strictly more efficient than repeated time-based sleeps that
|
||||
// cannot free capacity on their own.
|
||||
projected := a.used + n
|
||||
if projected >= a.hardThreshold && a.used > 0 {
|
||||
a.hardThrottleCount.Add(1)
|
||||
a.mu.Unlock()
|
||||
time.Sleep(hardThrottleDelay)
|
||||
a.mu.Lock()
|
||||
} else if projected >= a.softThreshold && a.used > 0 {
|
||||
a.softThrottleCount.Add(1)
|
||||
a.mu.Unlock()
|
||||
time.Sleep(softThrottleDelay)
|
||||
a.mu.Lock()
|
||||
}
|
||||
|
||||
for a.used+n > a.cap && a.used > 0 {
|
||||
// Before blocking, try to force-seal a writable chunk somewhere so
|
||||
// its async upload path will eventually Release a slot. Single-flight
|
||||
@@ -115,3 +162,19 @@ func (a *WriteBufferAccountant) Used() int64 {
|
||||
defer a.mu.Unlock()
|
||||
return a.used
|
||||
}
|
||||
|
||||
// SoftThrottleCount returns the number of times soft throttling was triggered.
|
||||
func (a *WriteBufferAccountant) SoftThrottleCount() int64 {
|
||||
if a == nil {
|
||||
return 0
|
||||
}
|
||||
return a.softThrottleCount.Load()
|
||||
}
|
||||
|
||||
// HardThrottleCount returns the number of times hard throttling was triggered.
|
||||
func (a *WriteBufferAccountant) HardThrottleCount() int64 {
|
||||
if a == nil {
|
||||
return 0
|
||||
}
|
||||
return a.hardThrottleCount.Load()
|
||||
}
|
||||
@@ -71,6 +71,116 @@ func TestWriteBufferAccountant_BlocksWhenOverCap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_SoftThrottle(t *testing.T) {
|
||||
// Cap = 1000, soft threshold = 800. Reserve 850 (85%) then measure
|
||||
// that the next Reserve is delayed by at least softThrottleDelay.
|
||||
a := NewWriteBufferAccountant(1000)
|
||||
a.Reserve(850)
|
||||
|
||||
start := time.Now()
|
||||
a.Reserve(10) // should trigger soft throttle (used=850 > 800)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed < softThrottleDelay {
|
||||
t.Fatalf("expected Reserve to take >= %v (soft throttle), took %v", softThrottleDelay, elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_HardThrottle(t *testing.T) {
|
||||
// Cap = 1000, hard threshold = 950. Reserve 960 (96%) then measure
|
||||
// that the next Reserve is delayed by at least hardThrottleDelay.
|
||||
a := NewWriteBufferAccountant(1000)
|
||||
a.Reserve(960)
|
||||
|
||||
start := time.Now()
|
||||
a.Reserve(10) // should trigger hard throttle (used=960 > 950)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed < hardThrottleDelay {
|
||||
t.Fatalf("expected Reserve to take >= %v (hard throttle), took %v", hardThrottleDelay, elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_NoThrottleBelowSoft(t *testing.T) {
|
||||
// Cap = 1000, soft threshold = 800. Reserve 700 (70%) -- below soft
|
||||
// threshold, so subsequent Reserve should return quickly.
|
||||
a := NewWriteBufferAccountant(1000)
|
||||
a.Reserve(700)
|
||||
|
||||
start := time.Now()
|
||||
a.Reserve(10)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed >= softThrottleDelay {
|
||||
t.Fatalf("expected Reserve below soft threshold to avoid throttle delay (< %v), took %v", softThrottleDelay, elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_ThrottleCounters(t *testing.T) {
|
||||
a := NewWriteBufferAccountant(1000)
|
||||
|
||||
// Below soft -- no throttle
|
||||
a.Reserve(700)
|
||||
a.Reserve(10)
|
||||
if a.SoftThrottleCount() != 0 || a.HardThrottleCount() != 0 {
|
||||
t.Fatalf("expected no throttle counts below soft threshold, got soft=%d hard=%d",
|
||||
a.SoftThrottleCount(), a.HardThrottleCount())
|
||||
}
|
||||
|
||||
// Release back down, then fill to soft zone
|
||||
a.Release(710)
|
||||
a.Reserve(850) // now used=850, above soft (800)
|
||||
a.Reserve(10) // triggers soft throttle
|
||||
if a.SoftThrottleCount() != 1 {
|
||||
t.Fatalf("expected soft throttle count 1, got %d", a.SoftThrottleCount())
|
||||
}
|
||||
if a.HardThrottleCount() != 0 {
|
||||
t.Fatalf("expected hard throttle count 0, got %d", a.HardThrottleCount())
|
||||
}
|
||||
|
||||
// Release and fill to hard zone
|
||||
a.Release(860)
|
||||
a.Reserve(960) // now used=960, above hard (950)
|
||||
a.Reserve(10) // triggers hard throttle
|
||||
if a.HardThrottleCount() != 1 {
|
||||
t.Fatalf("expected hard throttle count 1, got %d", a.HardThrottleCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_GraduatedRecovery(t *testing.T) {
|
||||
// Fill to hard threshold, verify hard throttle. Release to soft zone,
|
||||
// verify that throttle level decreases to soft.
|
||||
a := NewWriteBufferAccountant(1000)
|
||||
|
||||
// Fill to hard zone (960 > 950)
|
||||
a.Reserve(960)
|
||||
start := time.Now()
|
||||
a.Reserve(10) // hard throttle
|
||||
elapsed := time.Since(start)
|
||||
if elapsed < hardThrottleDelay {
|
||||
t.Fatalf("expected hard throttle delay, got %v", elapsed)
|
||||
}
|
||||
if a.HardThrottleCount() != 1 {
|
||||
t.Fatalf("expected hard throttle count 1, got %d", a.HardThrottleCount())
|
||||
}
|
||||
|
||||
// Release down to soft zone: used = 970 - 130 = 840 (> 800 soft, < 950 hard)
|
||||
a.Release(130)
|
||||
|
||||
start = time.Now()
|
||||
a.Reserve(10) // should now be soft throttle
|
||||
elapsed = time.Since(start)
|
||||
if elapsed < softThrottleDelay {
|
||||
t.Fatalf("expected soft throttle delay after recovery, got %v", elapsed)
|
||||
}
|
||||
if a.HardThrottleCount() != 1 {
|
||||
t.Fatalf("expected hard throttle count to remain 1 after recovery, got %d", a.HardThrottleCount())
|
||||
}
|
||||
if a.SoftThrottleCount() != 1 {
|
||||
t.Fatalf("expected soft throttle count 1 after recovery, got %d", a.SoftThrottleCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBufferAccountant_AllowsOversizeWhenEmpty(t *testing.T) {
|
||||
// A single request larger than cap must succeed when nothing is in
|
||||
// flight, otherwise a single file handle with a large chunk size would
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// ResolvePeerAdvertiseAddr returns the host:port this mount should
|
||||
// register with the filer and announce to peers. It handles three
|
||||
// common cases:
|
||||
//
|
||||
// 1. The operator set -peer.advertise=host:port explicitly — use it.
|
||||
// 2. -peer.listen contains a specific bind host — use that host with
|
||||
// the bind port (e.g. "10.0.0.5:18080").
|
||||
// 3. -peer.listen is a wildcard bind (":18080", "0.0.0.0:18080", or
|
||||
// "[::]:18080") — combine util.DetectedHostAddress() with the port.
|
||||
//
|
||||
// Returns an error if the listen string is unparseable or if case (3)
|
||||
// hits and auto-detection turns up nothing. We deliberately do NOT fall
|
||||
// back to "localhost": an advertised loopback gets registered with the
|
||||
// filer and hands other mounts a useless address to dial (their own
|
||||
// loopback). Better to fail loudly so the operator sets -peer.advertise.
|
||||
func ResolvePeerAdvertiseAddr(listen, advertise string) (string, error) {
|
||||
if advertise != "" {
|
||||
return advertise, nil
|
||||
}
|
||||
if listen == "" {
|
||||
return "", fmt.Errorf("peer listen address is empty")
|
||||
}
|
||||
host, port, err := net.SplitHostPort(listen)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse -peer.listen %q: %w", listen, err)
|
||||
}
|
||||
if !isWildcardHost(host) {
|
||||
return net.JoinHostPort(host, port), nil
|
||||
}
|
||||
detected := util.DetectedHostAddress()
|
||||
if detected == "" {
|
||||
return "", fmt.Errorf("cannot auto-detect host for wildcard -peer.listen %q; set -peer.advertise=host:port explicitly", listen)
|
||||
}
|
||||
return net.JoinHostPort(detected, port), nil
|
||||
}
|
||||
|
||||
func isWildcardHost(h string) bool {
|
||||
switch h {
|
||||
case "", "0.0.0.0", "::", "[::]":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolvePeerAdvertiseAddr(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
listen string
|
||||
advertise string
|
||||
wantErr bool
|
||||
// addr substring check — DetectedHostAddress is system-dependent so
|
||||
// we don't assert an exact value for the wildcard path.
|
||||
wantSuffix string
|
||||
}{
|
||||
{"explicit advertise wins", ":18080", "10.1.1.9:20000", false, ":20000"},
|
||||
{"bind host used verbatim", "10.0.0.5:18080", "", false, "10.0.0.5:18080"},
|
||||
{"wildcard ipv4 bind", "0.0.0.0:18080", "", false, ":18080"},
|
||||
{"empty host bind", ":18080", "", false, ":18080"},
|
||||
{"ipv6 wildcard", "[::]:18080", "", false, ":18080"},
|
||||
{"unparseable listen errors", "garbage", "", true, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ResolvePeerAdvertiseAddr(tt.listen, tt.advertise)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error, got addr=%q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.HasSuffix(got, tt.wantSuffix) {
|
||||
t.Errorf("addr=%q, expected suffix %q", got, tt.wantSuffix)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsWildcardHost(t *testing.T) {
|
||||
for _, h := range []string{"", "0.0.0.0", "::", "[::]"} {
|
||||
if !isWildcardHost(h) {
|
||||
t.Errorf("%q should be wildcard", h)
|
||||
}
|
||||
}
|
||||
for _, h := range []string{"10.0.0.5", "host.example", "localhost"} {
|
||||
if isWildcardHost(h) {
|
||||
t.Errorf("%q should NOT be wildcard", h)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
)
|
||||
|
||||
// PeerAnnouncer batches and flushes ChunkAnnounce RPCs to the
|
||||
// HRW-assigned owner mounts for each cached fid this mount holds.
|
||||
//
|
||||
// Shape:
|
||||
// * EnqueueAnnounce(fid) is a non-blocking push into an in-memory set.
|
||||
// * A background ticker flushes every announceInterval. Each flush
|
||||
// drains the set, adds fids due for TTL renewal, groups by owner
|
||||
// mount via HRW, and sends one ChunkAnnounce RPC per distinct owner.
|
||||
// * A successful send records announced_at[fid]. A rejected (not-owner)
|
||||
// fid is requeued so it will be retried after the seed view refreshes.
|
||||
//
|
||||
// See design-weed-mount-peer-chunk-sharing.md §4.4.
|
||||
type PeerAnnouncer struct {
|
||||
selfAddr string
|
||||
selfDataCenter string
|
||||
selfRack string
|
||||
ownerFor func(fid string) string
|
||||
dialPeer MountPeerDialer
|
||||
localDir *PeerDirectory // populated directly for fids whose HRW owner == self
|
||||
isCached func(fid string) bool // residency check; set nil to disable
|
||||
announceInterval time.Duration
|
||||
announceTTL time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]struct{}
|
||||
announcedAt map[string]announceRecord
|
||||
|
||||
stopCh chan struct{}
|
||||
stopped atomic.Bool
|
||||
runWg sync.WaitGroup // tracks the run goroutine so Stop can wait
|
||||
|
||||
// flushCancelMu guards flushCancel, which is the cancel fn for the
|
||||
// currently in-flight flush (nil when idle). Stop takes the lock,
|
||||
// cancels the flush to unblock its RPCs fast, then waits on runWg.
|
||||
flushCancelMu sync.Mutex
|
||||
flushCancel context.CancelFunc
|
||||
|
||||
flushes atomic.Int64
|
||||
sentFids atomic.Int64
|
||||
rejectedFids atomic.Int64
|
||||
flushErrs atomic.Int64
|
||||
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// MountPeerDialer opens a MountPeer gRPC client to a given peer. Tests
|
||||
// inject a fake; production uses a real gRPC dial backed by a short
|
||||
// connection cache.
|
||||
type MountPeerDialer func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error)
|
||||
|
||||
// announceRecord is what we remember about a successful announce: who
|
||||
// we told (the HRW owner at the time) and when. On each flush we
|
||||
// recompute the HRW owner and, if it moved — typically because a new
|
||||
// mount joined the seed list and the ring rebalanced — re-announce
|
||||
// against the new owner. Without this, seed-view divergence during
|
||||
// startup silently ages out fids on an owner that the reader never
|
||||
// looks up.
|
||||
type announceRecord struct {
|
||||
owner string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
// NewPeerAnnouncer constructs an announcer. Caller must call Start.
|
||||
// selfDataCenter and selfRack are the locality labels attached to every
|
||||
// ChunkAnnounce so the receiving directory records holders with DC+rack
|
||||
// and the fetcher can later re-rank by locality.
|
||||
//
|
||||
// localDir is optional: when non-nil, any fid whose HRW owner resolves
|
||||
// to self is written directly into localDir instead of sending a
|
||||
// self→self RPC (which the receiver would reject anyway). This is the
|
||||
// only way a fid the writer itself owns becomes visible to peers'
|
||||
// ChunkLookup calls.
|
||||
func NewPeerAnnouncer(selfAddr, selfDataCenter, selfRack string, ownerFor func(fid string) string, dial MountPeerDialer, localDir *PeerDirectory) *PeerAnnouncer {
|
||||
return &PeerAnnouncer{
|
||||
selfAddr: selfAddr,
|
||||
selfDataCenter: selfDataCenter,
|
||||
selfRack: selfRack,
|
||||
ownerFor: ownerFor,
|
||||
dialPeer: dial,
|
||||
localDir: localDir,
|
||||
announceInterval: 15 * time.Second,
|
||||
announceTTL: 300 * time.Second,
|
||||
pending: map[string]struct{}{},
|
||||
announcedAt: map[string]announceRecord{},
|
||||
stopCh: make(chan struct{}),
|
||||
clock: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// EnqueueAnnounce marks a fid as needing announcement. Non-blocking;
|
||||
// dedupes within a flush window.
|
||||
func (a *PeerAnnouncer) EnqueueAnnounce(fid string) {
|
||||
a.mu.Lock()
|
||||
a.pending[fid] = struct{}{}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetCachePresence wires an optional residency check. When set, the
|
||||
// announcer consults it right before dispatching a ChunkAnnounce RPC or
|
||||
// writing a self-owned entry: if the cache no longer has the chunk
|
||||
// (e.g. LRU-evicted under memory pressure between SetChunk and the
|
||||
// next flush tick) we drop the announce rather than advertise bytes we
|
||||
// can't serve back. nil disables the check.
|
||||
func (a *PeerAnnouncer) SetCachePresence(isCached func(fid string) bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.isCached = isCached
|
||||
}
|
||||
|
||||
// Start launches the background flush loop.
|
||||
func (a *PeerAnnouncer) Start() {
|
||||
a.runWg.Add(1)
|
||||
go func() {
|
||||
defer a.runWg.Done()
|
||||
a.run()
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop halts the flush loop and waits for the current flush (if any) to
|
||||
// finish. Safe to call multiple times. Callers that tear down shared
|
||||
// dependencies (conn pool, local directory) can rely on no more
|
||||
// sendTo/localDir.Announce goroutines being live after Stop returns.
|
||||
func (a *PeerAnnouncer) Stop() {
|
||||
if a.stopped.Swap(true) {
|
||||
return
|
||||
}
|
||||
close(a.stopCh)
|
||||
// Cancel the in-flight flush's context so its RPCs return quickly
|
||||
// instead of running out the 10 s timeout.
|
||||
a.flushCancelMu.Lock()
|
||||
if a.flushCancel != nil {
|
||||
a.flushCancel()
|
||||
}
|
||||
a.flushCancelMu.Unlock()
|
||||
a.runWg.Wait()
|
||||
}
|
||||
|
||||
// Stats exposes counters for observability.
|
||||
func (a *PeerAnnouncer) Stats() (flushes, sentFids, rejectedFids, flushErrs int64) {
|
||||
return a.flushes.Load(), a.sentFids.Load(), a.rejectedFids.Load(), a.flushErrs.Load()
|
||||
}
|
||||
|
||||
// announceFlushTimeout caps how long a single flush cycle can run. A slow
|
||||
// or unresponsive owner peer would otherwise block a flush goroutine
|
||||
// indefinitely, and since flushes fan out per owner in parallel a
|
||||
// pileup would bleed into subsequent ticks and grow unbounded. The
|
||||
// bound is set a bit under one flush interval so the next tick's flush
|
||||
// doesn't chase the previous one's tail.
|
||||
const announceFlushTimeout = 10 * time.Second
|
||||
|
||||
func (a *PeerAnnouncer) run() {
|
||||
t := time.NewTicker(a.announceInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-a.stopCh:
|
||||
return
|
||||
case <-t.C:
|
||||
ctx, cancel := context.WithTimeout(context.Background(), announceFlushTimeout)
|
||||
a.flushCancelMu.Lock()
|
||||
a.flushCancel = cancel
|
||||
a.flushCancelMu.Unlock()
|
||||
|
||||
a.flushOnce(ctx)
|
||||
|
||||
a.flushCancelMu.Lock()
|
||||
a.flushCancel = nil
|
||||
a.flushCancelMu.Unlock()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flushOnce is exported via a wrapper for tests.
|
||||
func (a *PeerAnnouncer) FlushForTest(ctx context.Context) {
|
||||
a.flushOnce(ctx)
|
||||
}
|
||||
|
||||
func (a *PeerAnnouncer) flushOnce(ctx context.Context) {
|
||||
a.flushes.Add(1)
|
||||
now := a.clock()
|
||||
|
||||
a.mu.Lock()
|
||||
// Swap pending in O(1) instead of copying.
|
||||
toAnnounce := a.pending
|
||||
a.pending = map[string]struct{}{}
|
||||
|
||||
// Add renewals: (1) fids we announced long enough ago that they'll
|
||||
// expire on the owner side before our next flush tick; (2) fids
|
||||
// whose HRW owner has changed since we last announced them —
|
||||
// usually because a new mount joined the seed list and the ring
|
||||
// rebalanced. Also prune announcedAt entries that are so old
|
||||
// (> 2× TTL) that re-announcing them would be pointless.
|
||||
renewThreshold := now.Add(-a.announceTTL + 2*a.announceInterval)
|
||||
staleCutoff := now.Add(-2 * a.announceTTL)
|
||||
for fid, rec := range a.announcedAt {
|
||||
switch {
|
||||
case rec.at.Before(staleCutoff):
|
||||
delete(a.announcedAt, fid)
|
||||
case rec.at.Before(renewThreshold):
|
||||
toAnnounce[fid] = struct{}{}
|
||||
default:
|
||||
// Same fid, fresh timestamp — but owner may have moved.
|
||||
// Force a re-announce if HRW says a different mount is
|
||||
// the owner now.
|
||||
if a.ownerFor != nil {
|
||||
if cur := a.ownerFor(fid); cur != "" && cur != rec.owner {
|
||||
toAnnounce[fid] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
if len(toAnnounce) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Drop fids the cache no longer has. The write path hooks into
|
||||
// SetChunk + EnqueueAnnounce, but the chunk can be LRU-evicted in
|
||||
// the window between that and the next 15 s flush. Advertising a
|
||||
// chunk we can't actually serve just sends remote fetchers to our
|
||||
// FetchChunk, which then returns NOT_FOUND — a wasted round trip.
|
||||
// Also drop the announcedAt record so we don't keep renewing
|
||||
// evicted fids forever.
|
||||
a.mu.Lock()
|
||||
present := a.isCached
|
||||
a.mu.Unlock()
|
||||
if present != nil {
|
||||
for fid := range toAnnounce {
|
||||
if !present(fid) {
|
||||
delete(toAnnounce, fid)
|
||||
a.mu.Lock()
|
||||
delete(a.announcedAt, fid)
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if len(toAnnounce) == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Classify each fid. Three buckets:
|
||||
// byOwner — HRW owner is a remote mount; send a ChunkAnnounce RPC.
|
||||
// selfOwned — HRW owner is us; write directly into our local
|
||||
// directory (no RPC — we ARE the directory for this
|
||||
// fid). Without this, fids we wrote AND HRW-own stay
|
||||
// invisible to peer ChunkLookup forever.
|
||||
// deferred — HRW owner unknown (empty seed view). Re-queue for
|
||||
// the next flush once listOnce has populated seeds.
|
||||
byOwner := map[string][]string{}
|
||||
var selfOwned []string
|
||||
var deferred []string
|
||||
for fid := range toAnnounce {
|
||||
owner := ""
|
||||
if a.ownerFor != nil {
|
||||
owner = a.ownerFor(fid)
|
||||
}
|
||||
switch owner {
|
||||
case "":
|
||||
deferred = append(deferred, fid)
|
||||
case a.selfAddr:
|
||||
selfOwned = append(selfOwned, fid)
|
||||
default:
|
||||
byOwner[owner] = append(byOwner[owner], fid)
|
||||
}
|
||||
}
|
||||
if len(selfOwned) > 0 && a.localDir != nil {
|
||||
a.localDir.Announce(a.selfAddr, a.selfDataCenter, a.selfRack, selfOwned, a.announceTTL, nil)
|
||||
a.mu.Lock()
|
||||
for _, fid := range selfOwned {
|
||||
a.announcedAt[fid] = announceRecord{owner: a.selfAddr, at: now}
|
||||
a.sentFids.Add(1)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
} else if len(selfOwned) > 0 {
|
||||
// No local directory wired (e.g. unit tests with nil). Re-queue
|
||||
// so a future flush with a possibly-different HRW owner can
|
||||
// send them.
|
||||
deferred = append(deferred, selfOwned...)
|
||||
}
|
||||
if len(deferred) > 0 {
|
||||
a.mu.Lock()
|
||||
for _, fid := range deferred {
|
||||
a.pending[fid] = struct{}{}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
// Diagnostic V(2): shape of the current flush. Helps post-mortem
|
||||
// debugging when an announce pipeline silently stops making progress
|
||||
// (e.g. seed view stuck at self-only, owner unreachable, etc).
|
||||
if len(byOwner) > 0 || len(selfOwned) > 0 || len(deferred) > 0 {
|
||||
glog.V(2).Infof("peer-announce flush: toAnnounce=%d byOwner=%d selfOwned=%d deferred=%d",
|
||||
len(toAnnounce), len(byOwner), len(selfOwned), len(deferred))
|
||||
}
|
||||
|
||||
// Fan out one RPC per owner in parallel. A slow or unreachable
|
||||
// owner blocks only its own goroutine; other owners' announces
|
||||
// proceed immediately.
|
||||
var wg sync.WaitGroup
|
||||
for owner, fids := range byOwner {
|
||||
wg.Add(1)
|
||||
go func(owner string, fids []string) {
|
||||
defer wg.Done()
|
||||
a.sendTo(ctx, owner, fids, now)
|
||||
}(owner, fids)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (a *PeerAnnouncer) sendTo(ctx context.Context, owner string, fids []string, now time.Time) {
|
||||
client, closeFn, err := a.dialPeer(ctx, owner)
|
||||
if err != nil {
|
||||
a.flushErrs.Add(1)
|
||||
// Requeue these fids: a future flush will retry.
|
||||
a.requeue(fids)
|
||||
glog.V(2).Infof("peer-announce dial %s: %v", owner, err)
|
||||
return
|
||||
}
|
||||
defer closeFn()
|
||||
|
||||
resp, err := client.ChunkAnnounce(ctx, &mount_peer_pb.ChunkAnnounceRequest{
|
||||
FileIds: fids,
|
||||
PeerAddr: a.selfAddr,
|
||||
DataCenter: a.selfDataCenter,
|
||||
Rack: a.selfRack,
|
||||
TtlSeconds: int32(a.announceTTL / time.Second),
|
||||
})
|
||||
if err != nil {
|
||||
a.flushErrs.Add(1)
|
||||
a.requeue(fids)
|
||||
glog.V(2).Infof("peer-announce %s: %v", owner, err)
|
||||
return
|
||||
}
|
||||
|
||||
rejected := map[string]struct{}{}
|
||||
for _, f := range resp.RejectedFileIds {
|
||||
rejected[f] = struct{}{}
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
for _, fid := range fids {
|
||||
if _, skip := rejected[fid]; skip {
|
||||
// Owner has changed or doesn't yet agree; retry later.
|
||||
a.pending[fid] = struct{}{}
|
||||
a.rejectedFids.Add(1)
|
||||
continue
|
||||
}
|
||||
a.announcedAt[fid] = announceRecord{owner: owner, at: now}
|
||||
a.sentFids.Add(1)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
|
||||
func (a *PeerAnnouncer) requeue(fids []string) {
|
||||
a.mu.Lock()
|
||||
for _, fid := range fids {
|
||||
a.pending[fid] = struct{}{}
|
||||
}
|
||||
a.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// fakeMountPeerClient records each ChunkAnnounce call; returns rejected
|
||||
// fids from a configured set.
|
||||
type fakeMountPeerClient struct {
|
||||
mu sync.Mutex
|
||||
mount_peer_pb.MountPeerClient
|
||||
announcedBy map[string][]filerAnnouncement
|
||||
rejectedByClient func(fid string) bool
|
||||
}
|
||||
|
||||
type filerAnnouncement struct {
|
||||
fids []string
|
||||
peerAddr string
|
||||
}
|
||||
|
||||
func (f *fakeMountPeerClient) ChunkAnnounce(ctx context.Context, req *mount_peer_pb.ChunkAnnounceRequest, opts ...grpc.CallOption) (*mount_peer_pb.ChunkAnnounceResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
// No owner key in the request; capture keyed by peer_addr (the announcer).
|
||||
f.announcedBy[req.PeerAddr] = append(f.announcedBy[req.PeerAddr], filerAnnouncement{
|
||||
fids: append([]string(nil), req.FileIds...),
|
||||
peerAddr: req.PeerAddr,
|
||||
})
|
||||
resp := &mount_peer_pb.ChunkAnnounceResponse{}
|
||||
if f.rejectedByClient != nil {
|
||||
for _, fid := range req.FileIds {
|
||||
if f.rejectedByClient(fid) {
|
||||
resp.RejectedFileIds = append(resp.RejectedFileIds, fid)
|
||||
}
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// fakeDialer returns the same fakeMountPeerClient for every peer addr,
|
||||
// recording which owner the announcer dialed. Close is a no-op. The
|
||||
// dialed slice is protected by its own mutex because the announcer now
|
||||
// fans RPCs out across goroutines — concurrent appends would race.
|
||||
type dialRecorder struct {
|
||||
mu sync.Mutex
|
||||
dialled []string
|
||||
}
|
||||
|
||||
func (d *dialRecorder) record(addr string) {
|
||||
d.mu.Lock()
|
||||
d.dialled = append(d.dialled, addr)
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
func (d *dialRecorder) snapshot() []string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
out := make([]string, len(d.dialled))
|
||||
copy(out, d.dialled)
|
||||
return out
|
||||
}
|
||||
|
||||
func fakeDialer(fc *fakeMountPeerClient, rec *dialRecorder) MountPeerDialer {
|
||||
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
|
||||
rec.record(peerAddr)
|
||||
return fc, func() {}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAnnouncer_FlushGroupsByOwner(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{
|
||||
announcedBy: map[string][]filerAnnouncement{},
|
||||
}
|
||||
rec := &dialRecorder{}
|
||||
|
||||
// Owner function: static assignment for test.
|
||||
ownerFor := func(fid string) string {
|
||||
if fid == "3,a" || fid == "3,c" {
|
||||
return "owner-1:18081"
|
||||
}
|
||||
return "owner-2:18081"
|
||||
}
|
||||
|
||||
a := NewPeerAnnouncer("self:18080", "", "",ownerFor, fakeDialer(fc, rec), nil)
|
||||
|
||||
a.EnqueueAnnounce("3,a")
|
||||
a.EnqueueAnnounce("3,b")
|
||||
a.EnqueueAnnounce("3,c")
|
||||
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
dialed := rec.snapshot(); sort.Strings(dialed)
|
||||
if len(dialed) != 2 || dialed[0] != "owner-1:18081" || dialed[1] != "owner-2:18081" {
|
||||
t.Errorf("expected both owners dialed once, got %v", dialed)
|
||||
}
|
||||
|
||||
_, sent, _, _ := a.Stats()
|
||||
if sent != 3 {
|
||||
t.Errorf("expected 3 sent fids, got %d", sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAnnouncer_SkipOwnerEqualsSelf(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
|
||||
rec := &dialRecorder{}
|
||||
|
||||
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
|
||||
return "self:18080"
|
||||
}, fakeDialer(fc, rec), nil)
|
||||
|
||||
a.EnqueueAnnounce("3,a")
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
if d := rec.snapshot(); len(d) != 0 {
|
||||
t.Errorf("expected no dial when owner == self, dialed: %v", d)
|
||||
}
|
||||
// Self-owned fids stay in pending so a subsequent flush re-checks
|
||||
// them against a possibly-refreshed seed view. Without this retry a
|
||||
// mount whose initial MountList hadn't yet observed its peers would
|
||||
// silently drop every write-path announce on the floor.
|
||||
a.mu.Lock()
|
||||
_, stillPending := a.pending["3,a"]
|
||||
a.mu.Unlock()
|
||||
if !stillPending {
|
||||
t.Errorf("self-owned fid should stay pending for retry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAnnouncer_RequeueOnRejection(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{
|
||||
announcedBy: map[string][]filerAnnouncement{},
|
||||
rejectedByClient: func(fid string) bool { return fid == "3,x" },
|
||||
}
|
||||
rec := &dialRecorder{}
|
||||
|
||||
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
|
||||
return "owner:18081"
|
||||
}, fakeDialer(fc, rec), nil)
|
||||
a.EnqueueAnnounce("3,x")
|
||||
a.EnqueueAnnounce("3,y")
|
||||
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
_, sent, rejected, _ := a.Stats()
|
||||
if sent != 1 {
|
||||
t.Errorf("expected 1 sent, got %d", sent)
|
||||
}
|
||||
if rejected != 1 {
|
||||
t.Errorf("expected 1 rejected, got %d", rejected)
|
||||
}
|
||||
|
||||
// The rejected fid should be back in pending.
|
||||
a.mu.Lock()
|
||||
_, stillPending := a.pending["3,x"]
|
||||
a.mu.Unlock()
|
||||
if !stillPending {
|
||||
t.Errorf("3,x should have been requeued after rejection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAnnouncer_TTLRenewal(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
|
||||
rec := &dialRecorder{}
|
||||
|
||||
now := time.Unix(1000, 0)
|
||||
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
|
||||
return "owner:18081"
|
||||
}, fakeDialer(fc, rec), nil)
|
||||
a.clock = func() time.Time { return now }
|
||||
a.announceInterval = 10 * time.Second
|
||||
a.announceTTL = 60 * time.Second
|
||||
|
||||
// Announce once.
|
||||
a.EnqueueAnnounce("3,a")
|
||||
a.FlushForTest(context.Background())
|
||||
if _, sent, _, _ := a.Stats(); sent != 1 {
|
||||
t.Fatalf("want 1 sent on initial announce, got %d", sent)
|
||||
}
|
||||
|
||||
// Time passes to within the renewal threshold.
|
||||
now = now.Add(45 * time.Second)
|
||||
|
||||
// No new enqueue, but renewal should fire.
|
||||
a.FlushForTest(context.Background())
|
||||
if _, sent, _, _ := a.Stats(); sent != 2 {
|
||||
t.Errorf("want 2 sent after renewal, got %d", sent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerAnnouncer_ReAnnouncesOnOwnerChange guards the fix for a
|
||||
// startup race where the writer's seed view reaches self-knowledge of
|
||||
// its peers in two stages: first just {self,A}, then {self,A,B}. HRW
|
||||
// may pick different owners across those views, so the announce from
|
||||
// stage 1 is sent to a mount that will NOT be the HRW owner by the
|
||||
// time a reader's seed view is the {self,A,B} version. Without
|
||||
// re-announcing on owner change, the fid silently ages out on the
|
||||
// wrong directory and readers get "no peer holder."
|
||||
func TestPeerAnnouncer_ReAnnouncesOnOwnerChange(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
|
||||
rec := &dialRecorder{}
|
||||
|
||||
ownerNow := "owner-1:18081"
|
||||
a := NewPeerAnnouncer("self:18080", "", "", func(fid string) string {
|
||||
return ownerNow
|
||||
}, fakeDialer(fc, rec), nil)
|
||||
|
||||
a.EnqueueAnnounce("3,x")
|
||||
a.FlushForTest(context.Background())
|
||||
if _, sent, _, _ := a.Stats(); sent != 1 {
|
||||
t.Fatalf("initial announce: want 1 sent, got %d", sent)
|
||||
}
|
||||
|
||||
// Seed view shifts; HRW now picks a different owner for the same
|
||||
// fid. A fresh-timestamped entry in announcedAt should be treated
|
||||
// as stale in owner terms and re-announced even though its age is
|
||||
// well within the TTL renewal window.
|
||||
ownerNow = "owner-2:18081"
|
||||
a.FlushForTest(context.Background())
|
||||
if _, sent, _, _ := a.Stats(); sent != 2 {
|
||||
t.Errorf("after owner change: want 2 sent, got %d", sent)
|
||||
}
|
||||
dialed := rec.snapshot()
|
||||
if len(dialed) != 2 || dialed[0] == dialed[1] {
|
||||
t.Errorf("want dial to both owners, got %v", dialed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerAnnouncer_DropsEvictedFids guards the write→announce race:
|
||||
// a chunk can be LRU-evicted between SetChunk and the next flush tick.
|
||||
// Advertising an evicted fid just hands remote fetchers a NOT_FOUND
|
||||
// from our FetchChunk server. With SetCachePresence wired, the
|
||||
// announcer must drop evicted fids before dispatching the RPC and
|
||||
// also clear them from announcedAt so they stop getting renewed.
|
||||
func TestPeerAnnouncer_DropsEvictedFids(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
|
||||
rec := &dialRecorder{}
|
||||
present := map[string]bool{"3,here": true, "3,gone": false}
|
||||
|
||||
a := NewPeerAnnouncer("self:18080", "", "", func(fid string) string {
|
||||
return "owner:18081"
|
||||
}, fakeDialer(fc, rec), nil)
|
||||
a.SetCachePresence(func(fid string) bool { return present[fid] })
|
||||
|
||||
a.EnqueueAnnounce("3,here")
|
||||
a.EnqueueAnnounce("3,gone")
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
if _, sent, _, _ := a.Stats(); sent != 1 {
|
||||
t.Errorf("only the still-cached fid should be announced, got sent=%d", sent)
|
||||
}
|
||||
fc.mu.Lock()
|
||||
defer fc.mu.Unlock()
|
||||
for _, an := range fc.announcedBy["self:18080"] {
|
||||
for _, fid := range an.fids {
|
||||
if fid == "3,gone" {
|
||||
t.Errorf("evicted fid should not have been announced, saw %q", fid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerAnnouncer_StopWaitsForFlush guards the shutdown race: Stop
|
||||
// must not return while a tick-triggered flushOnce is still dispatching
|
||||
// RPCs, otherwise the owning wfs can tear down the conn pool out from
|
||||
// under the in-flight sendTo goroutines.
|
||||
func TestPeerAnnouncer_StopWaitsForFlush(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
unblock := make(chan struct{})
|
||||
slowDialer := func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
|
||||
close(started)
|
||||
select {
|
||||
case <-unblock:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return nil, func() {}, context.DeadlineExceeded
|
||||
}
|
||||
|
||||
a := NewPeerAnnouncer("self:18080", "", "", func(string) string {
|
||||
return "owner:18081"
|
||||
}, slowDialer, nil)
|
||||
|
||||
// Shortcut straight into a flush on a dedicated goroutine so we
|
||||
// can assert Stop() blocks on it.
|
||||
a.EnqueueAnnounce("3,slow")
|
||||
flushDone := make(chan struct{})
|
||||
go func() {
|
||||
a.FlushForTest(context.Background())
|
||||
close(flushDone)
|
||||
}()
|
||||
<-started
|
||||
|
||||
// Prove Stop() returns only after the flush finishes by racing
|
||||
// them: Stop() normally can't cancel a FlushForTest because
|
||||
// we're not going through run(); but unblocking after stop's
|
||||
// goroutine starts lets us confirm flushDone happens before
|
||||
// stopDone never does under the old code.
|
||||
stopDone := make(chan struct{})
|
||||
go func() {
|
||||
a.Stop()
|
||||
close(stopDone)
|
||||
}()
|
||||
close(unblock)
|
||||
|
||||
select {
|
||||
case <-flushDone:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("flush did not complete within deadline")
|
||||
}
|
||||
select {
|
||||
case <-stopDone:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("Stop() did not return after flush completed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerAnnouncer_SelfOwnedWritesToLocalDir guards the shortcut path
|
||||
// for fids whose HRW owner resolves to self: no RPC should go out, but
|
||||
// the local PeerDirectory must end up with a holder entry pointing at
|
||||
// self — otherwise remote ChunkLookup callers would get an empty
|
||||
// holder list for fids this mount owns directly.
|
||||
func TestPeerAnnouncer_SelfOwnedWritesToLocalDir(t *testing.T) {
|
||||
fc := &fakeMountPeerClient{announcedBy: map[string][]filerAnnouncement{}}
|
||||
rec := &dialRecorder{}
|
||||
dir := NewPeerDirectory()
|
||||
a := NewPeerAnnouncer("self:18080", "dc1", "rackA", func(fid string) string {
|
||||
return "self:18080"
|
||||
}, fakeDialer(fc, rec), dir)
|
||||
|
||||
a.EnqueueAnnounce("3,selfowned")
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
if d := rec.snapshot(); len(d) != 0 {
|
||||
t.Errorf("self-owned fid must not trigger any dial, got %v", d)
|
||||
}
|
||||
holders := dir.Lookup([]string{"3,selfowned"}, nil).PeersByFid["3,selfowned"]
|
||||
if len(holders) != 1 {
|
||||
t.Fatalf("local dir should have 1 holder after self-owned flush, got %d", len(holders))
|
||||
}
|
||||
if h := holders[0]; h.PeerAddr != "self:18080" || h.DataCenter != "dc1" || h.Rack != "rackA" {
|
||||
t.Errorf("local dir entry wrong: %+v", h)
|
||||
}
|
||||
if _, sent, _, _ := a.Stats(); sent != 1 {
|
||||
t.Errorf("sent counter should increment for self-owned too; got %d", sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAnnouncer_DialerErrorRequeues(t *testing.T) {
|
||||
errDialer := func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
|
||||
return nil, func() {}, context.DeadlineExceeded
|
||||
}
|
||||
a := NewPeerAnnouncer("self:18080", "", "",func(fid string) string {
|
||||
return "owner:18081"
|
||||
}, errDialer, nil)
|
||||
a.EnqueueAnnounce("3,a")
|
||||
a.FlushForTest(context.Background())
|
||||
|
||||
_, _, _, errs := a.Stats()
|
||||
if errs != 1 {
|
||||
t.Errorf("expected 1 flush error, got %d", errs)
|
||||
}
|
||||
a.mu.Lock()
|
||||
_, pending := a.pending["3,a"]
|
||||
a.mu.Unlock()
|
||||
if !pending {
|
||||
t.Errorf("fid should be requeued after dial error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/connectivity"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// PeerConnPool caches one long-lived gRPC client connection per peer
|
||||
// address. Both the announcer flush loop and the read-path fetcher hit
|
||||
// the same handful of directory owners repeatedly; without a cache each
|
||||
// call would pay TCP handshake + HTTP/2 preface cost (and on TLS, an
|
||||
// additional handshake). The cache makes steady-state owner RPCs
|
||||
// effectively free after the first call.
|
||||
//
|
||||
// Connections in terminal failure states (Shutdown) are transparently
|
||||
// replaced on next access. Sizing: entries are ~1 KB + the conn itself;
|
||||
// bounded at maxPeerConnPoolEntries to contain runaway growth.
|
||||
type PeerConnPool struct {
|
||||
dialOpts []grpc.DialOption
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[string]*grpc.ClientConn
|
||||
}
|
||||
|
||||
// maxPeerConnPoolEntries caps live peer conns per mount. A 10k-mount
|
||||
// fleet with HRW-sharded directory reaches only ~200 distinct owner
|
||||
// addresses per mount in the worst case, so this is far above any real
|
||||
// footprint while still bounding pathological growth.
|
||||
const maxPeerConnPoolEntries = 4096
|
||||
|
||||
// NewPeerConnPool returns an empty pool. dialOpts should carry transport
|
||||
// credentials matching the server side (production wires
|
||||
// option.GrpcDialOption, which security.LoadClientTLS populates from
|
||||
// security.toml). When no options are supplied we fall back to insecure
|
||||
// cleartext — only safe for in-process tests.
|
||||
func NewPeerConnPool(dialOpts ...grpc.DialOption) *PeerConnPool {
|
||||
if len(dialOpts) == 0 {
|
||||
dialOpts = []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
}
|
||||
return &PeerConnPool{
|
||||
dialOpts: dialOpts,
|
||||
conns: map[string]*grpc.ClientConn{},
|
||||
}
|
||||
}
|
||||
|
||||
// Dialer returns a MountPeerDialer bound to this pool. The returned
|
||||
// closeFn is a no-op — the pool owns the connection lifecycle. Tests
|
||||
// that want per-call dials can keep using the non-pooled variant.
|
||||
func (p *PeerConnPool) Dialer() MountPeerDialer {
|
||||
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
|
||||
conn, err := p.get(peerAddr)
|
||||
if err != nil {
|
||||
return nil, func() {}, err
|
||||
}
|
||||
return mount_peer_pb.NewMountPeerClient(conn), func() {}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PeerConnPool) get(peerAddr string) (*grpc.ClientConn, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if conn, ok := p.conns[peerAddr]; ok {
|
||||
if conn.GetState() != connectivity.Shutdown {
|
||||
return conn, nil
|
||||
}
|
||||
// Pooled conn is unusable — drop it and redial below.
|
||||
_ = conn.Close()
|
||||
delete(p.conns, peerAddr)
|
||||
}
|
||||
if len(p.conns) >= maxPeerConnPoolEntries {
|
||||
// Evict one arbitrary entry. Simple over LRU: the pool is small
|
||||
// in practice, and the victim will be re-dialed if needed.
|
||||
for k, c := range p.conns {
|
||||
_ = c.Close()
|
||||
delete(p.conns, k)
|
||||
break
|
||||
}
|
||||
}
|
||||
conn, err := grpc.NewClient(peerAddr, p.dialOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.conns[peerAddr] = conn
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// Close tears down every cached connection. Safe to call multiple times.
|
||||
func (p *PeerConnPool) Close() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
for addr, c := range p.conns {
|
||||
_ = c.Close()
|
||||
delete(p.conns, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// Size returns the current number of cached connections — useful for
|
||||
// tests and metrics exports.
|
||||
func (p *PeerConnPool) Size() int {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return len(p.conns)
|
||||
}
|
||||
|
||||
// DefaultMountPeerDialer returns a per-call dialer (no pooling). Kept for
|
||||
// tests and for any caller that genuinely wants a fresh connection per
|
||||
// invocation. Production code should prefer PeerConnPool.Dialer().
|
||||
//
|
||||
// Unused options silence dial-time lints when dialOpts is nil.
|
||||
func DefaultMountPeerDialer(dialOpts ...grpc.DialOption) MountPeerDialer {
|
||||
opts := append([]grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}, dialOpts...)
|
||||
return func(ctx context.Context, peerAddr string) (mount_peer_pb.MountPeerClient, func(), error) {
|
||||
conn, err := grpc.NewClient(peerAddr, opts...)
|
||||
if err != nil {
|
||||
return nil, func() {}, err
|
||||
}
|
||||
return mount_peer_pb.NewMountPeerClient(conn), func() { _ = conn.Close() }, nil
|
||||
}
|
||||
}
|
||||
|
||||
// peerConnMaxAge lets external callers (or future metrics) decide when a
|
||||
// pool entry is "stale" for monitoring purposes. The pool itself does not
|
||||
// expire on age — grpc handles reconnect internally.
|
||||
var peerConnMaxAge = 10 * time.Minute
|
||||
|
||||
var _ = peerConnMaxAge // suppress unused-lint until a metric consumes it
|
||||
@@ -0,0 +1,283 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxPeerDirectoryEntries caps the total (fid, holder) edges a single mount
|
||||
// will hold in its shard of the chunk directory. Each edge is a
|
||||
// (uint32, time.Time) map entry (~40 B with Go's map overhead), plus the
|
||||
// per-peer metadata is interned — see peerMetadata below — so 500k edges
|
||||
// come out to roughly 20 MB regardless of fleet size. A full directory
|
||||
// rejects new announces until TTL frees room.
|
||||
const maxPeerDirectoryEntries = 500000
|
||||
|
||||
// peerID is the interned identifier for a peer. Peer addresses and locality
|
||||
// labels live once in the peers slice; the (fid -> holder) index references
|
||||
// peers by this fixed-size id so we avoid paying for the ~48 B worth of
|
||||
// string headers (addr, dc, rack) on every edge.
|
||||
type peerID uint32
|
||||
|
||||
// peerMetadata is the per-peer data that used to be inlined on every
|
||||
// holderEntry. Fields are updated in place on each announce so a peer
|
||||
// reconfiguring its dc/rack is picked up without churn.
|
||||
type peerMetadata struct {
|
||||
addr string
|
||||
dataCenter string
|
||||
rack string
|
||||
}
|
||||
|
||||
// PeerDirectory is the tier-2 chunk directory: an in-memory
|
||||
// `fid -> set<peer>` map, holding entries only for fids for which this
|
||||
// mount is the HRW-assigned owner. Populated by inbound ChunkAnnounce RPCs,
|
||||
// queried by inbound ChunkLookup RPCs. Entries expire on TTL.
|
||||
//
|
||||
// Peer addresses are interned into peerID. That way the hot index stores
|
||||
// `fid -> (peerID -> expiry)`, a map of two fixed-size values, instead of
|
||||
// a full (addr, dc, rack, expiry) struct per edge. The peer slice itself
|
||||
// is bounded by fleet size (typically a few hundred), so the interning
|
||||
// table's memory cost is negligible next to the per-edge savings.
|
||||
//
|
||||
// Lookup takes only a read lock; TTL eviction is the sole responsibility of
|
||||
// the Sweep goroutine, which runs on a periodic ticker. This keeps the hot
|
||||
// read path concurrent even under heavy announce traffic.
|
||||
//
|
||||
// See design-weed-mount-peer-chunk-sharing.md §4.2.2.
|
||||
type PeerDirectory struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Interning table. peers[id] gives the peer's metadata; peerIDByAddr
|
||||
// maps an address back to its id when a new announce comes in.
|
||||
peers []peerMetadata
|
||||
peerIDByAddr map[string]peerID
|
||||
|
||||
// fid -> (peerID -> expiry). The inner map's value is a bare timestamp
|
||||
// — metadata is looked up via peers[id] on demand.
|
||||
index map[string]map[peerID]time.Time
|
||||
|
||||
// entryCount is maintained in lock-step with map mutations (under
|
||||
// mu), so Stats() can report O(1) instead of scanning the index.
|
||||
entryCount int
|
||||
|
||||
announces atomic.Int64
|
||||
lookups atomic.Int64
|
||||
rejected atomic.Int64
|
||||
evictions atomic.Int64
|
||||
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewPeerDirectory constructs a directory using the real wall clock.
|
||||
func NewPeerDirectory() *PeerDirectory {
|
||||
return newPeerDirectoryWithClock(time.Now)
|
||||
}
|
||||
|
||||
func newPeerDirectoryWithClock(clock func() time.Time) *PeerDirectory {
|
||||
return &PeerDirectory{
|
||||
index: map[string]map[peerID]time.Time{},
|
||||
peerIDByAddr: map[string]peerID{},
|
||||
clock: clock,
|
||||
}
|
||||
}
|
||||
|
||||
// AnnounceResult reports how an inbound announce was handled per-fid: fids
|
||||
// this receiver owns were recorded; others were rejected so the caller can
|
||||
// retry the correct owner after refreshing its seed view.
|
||||
type AnnounceResult struct {
|
||||
Rejected []string
|
||||
}
|
||||
|
||||
// OwnerCheck is a predicate provided by the caller (backed by HRW on the
|
||||
// current seed list) that says whether self is the owner for a given fid.
|
||||
type OwnerCheck func(fid string) bool
|
||||
|
||||
// internPeer returns the interned id for peerAddr, allocating a new slot
|
||||
// if this is the first announce from that peer. Must be called under mu
|
||||
// (write). dc/rack are refreshed on each call so reconfig is picked up.
|
||||
func (d *PeerDirectory) internPeer(addr, dc, rack string) peerID {
|
||||
if id, ok := d.peerIDByAddr[addr]; ok {
|
||||
p := &d.peers[id]
|
||||
p.dataCenter = dc
|
||||
p.rack = rack
|
||||
return id
|
||||
}
|
||||
id := peerID(len(d.peers))
|
||||
d.peers = append(d.peers, peerMetadata{addr: addr, dataCenter: dc, rack: rack})
|
||||
d.peerIDByAddr[addr] = id
|
||||
return id
|
||||
}
|
||||
|
||||
// Announce records the caller as a holder for every accepted fid. Any fid
|
||||
// for which ownerCheck returns false is rejected and surfaced back. A
|
||||
// directory at maxPeerDirectoryEntries silently drops *new* edges
|
||||
// (renewals of existing edges continue to succeed).
|
||||
func (d *PeerDirectory) Announce(peerAddr, dataCenter, rack string, fids []string, ttl time.Duration, ownerCheck OwnerCheck) AnnounceResult {
|
||||
if ttl <= 0 {
|
||||
ttl = 60 * time.Second
|
||||
}
|
||||
expiry := d.clock().Add(ttl)
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
pid := d.internPeer(peerAddr, dataCenter, rack)
|
||||
|
||||
result := AnnounceResult{}
|
||||
for _, fid := range fids {
|
||||
if ownerCheck != nil && !ownerCheck(fid) {
|
||||
result.Rejected = append(result.Rejected, fid)
|
||||
d.rejected.Add(1)
|
||||
continue
|
||||
}
|
||||
holders, ok := d.index[fid]
|
||||
if !ok {
|
||||
if d.entryCount >= maxPeerDirectoryEntries {
|
||||
continue
|
||||
}
|
||||
holders = map[peerID]time.Time{}
|
||||
d.index[fid] = holders
|
||||
}
|
||||
if _, exists := holders[pid]; !exists {
|
||||
if d.entryCount >= maxPeerDirectoryEntries {
|
||||
continue
|
||||
}
|
||||
d.entryCount++
|
||||
}
|
||||
holders[pid] = expiry
|
||||
d.announces.Add(1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// LookupHolder is the public form of a holder entry. DataCenter and Rack
|
||||
// are carried through so the fetcher can re-sort by its own locality
|
||||
// before picking a peer to dial.
|
||||
type LookupHolder struct {
|
||||
PeerAddr string
|
||||
DataCenter string
|
||||
Rack string
|
||||
}
|
||||
|
||||
// maxLookupHolders caps how many holders a single ChunkLookup response
|
||||
// returns per fid. The directory stores a holder per mount caching the
|
||||
// fid, which on a large hot file can reach fleet size (hundreds). The
|
||||
// fetcher typically only tries the first 1-3 before succeeding, so
|
||||
// returning every entry is pure wire-overhead. LRU ordering ensures the
|
||||
// freshest holders are the ones kept.
|
||||
const maxLookupHolders = 16
|
||||
|
||||
// LookupResult holds the merged lookup response. Fids for which this
|
||||
// receiver is not the owner are split out so the caller can retry.
|
||||
type LookupResult struct {
|
||||
PeersByFid map[string][]LookupHolder
|
||||
NotOwnerFids []string
|
||||
}
|
||||
|
||||
// Lookup returns known holders for the requested fids. Expired edges are
|
||||
// filtered out of the response but NOT deleted here — Sweep handles that
|
||||
// under a write lock on its own schedule, so Lookup can stay read-only and
|
||||
// concurrent. A fid owned by this receiver with no known holders returns
|
||||
// an empty peer list.
|
||||
//
|
||||
// Holders are returned in LRU order (most recently announced first). Since
|
||||
// each Announce stamps a fresh `now + ttl` expiry, sorting by expiry
|
||||
// descending is equivalent to ordering by last-seen descending. Fetchers
|
||||
// should try these in the returned order — the most recent announcer is
|
||||
// the holder most likely to still have the chunk cached, given that each
|
||||
// mount's chunk_cache is itself LRU.
|
||||
func (d *PeerDirectory) Lookup(fids []string, ownerCheck OwnerCheck) LookupResult {
|
||||
now := d.clock()
|
||||
result := LookupResult{
|
||||
PeersByFid: map[string][]LookupHolder{},
|
||||
}
|
||||
|
||||
// Collect candidate holders under the read lock, including the peer
|
||||
// metadata copies — Announce mutates peers[id] in place when an
|
||||
// existing peer re-announces, so reading peers[pid] outside the lock
|
||||
// would race with that write. Sorting happens after the unlock.
|
||||
type candidate struct {
|
||||
peerMetadata
|
||||
expiry time.Time
|
||||
}
|
||||
perFid := make(map[string][]candidate, len(fids))
|
||||
|
||||
d.mu.RLock()
|
||||
for _, fid := range fids {
|
||||
d.lookups.Add(1)
|
||||
if ownerCheck != nil && !ownerCheck(fid) {
|
||||
result.NotOwnerFids = append(result.NotOwnerFids, fid)
|
||||
continue
|
||||
}
|
||||
holders, ok := d.index[fid]
|
||||
if !ok {
|
||||
result.PeersByFid[fid] = nil
|
||||
continue
|
||||
}
|
||||
cands := make([]candidate, 0, len(holders))
|
||||
for pid, expiry := range holders {
|
||||
if !expiry.After(now) {
|
||||
continue // Sweep will clean this up
|
||||
}
|
||||
cands = append(cands, candidate{peerMetadata: d.peers[pid], expiry: expiry})
|
||||
}
|
||||
perFid[fid] = cands
|
||||
}
|
||||
d.mu.RUnlock()
|
||||
|
||||
for fid, cands := range perFid {
|
||||
sort.Slice(cands, func(i, j int) bool {
|
||||
if !cands[i].expiry.Equal(cands[j].expiry) {
|
||||
return cands[i].expiry.After(cands[j].expiry) // newest first
|
||||
}
|
||||
return cands[i].addr < cands[j].addr // deterministic tiebreak
|
||||
})
|
||||
// Cap response at maxLookupHolders. The fetcher typically tries 1-3
|
||||
// holders before succeeding; shipping every holder for hot fids is
|
||||
// wire-overhead without hit-rate gain.
|
||||
if len(cands) > maxLookupHolders {
|
||||
cands = cands[:maxLookupHolders]
|
||||
}
|
||||
out := make([]LookupHolder, len(cands))
|
||||
for i, c := range cands {
|
||||
out[i] = LookupHolder{PeerAddr: c.addr, DataCenter: c.dataCenter, Rack: c.rack}
|
||||
}
|
||||
result.PeersByFid[fid] = out
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Sweep purges expired edges. Safe to call periodically. Peer slots are
|
||||
// left in place — their count is bounded by fleet size (a few hundred at
|
||||
// most) and never grows faster than the fleet itself, so reclaiming them
|
||||
// isn't worth the bookkeeping.
|
||||
func (d *PeerDirectory) Sweep() int {
|
||||
now := d.clock()
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
n := 0
|
||||
for fid, holders := range d.index {
|
||||
for pid, expiry := range holders {
|
||||
if !expiry.After(now) {
|
||||
delete(holders, pid)
|
||||
d.entryCount--
|
||||
n++
|
||||
}
|
||||
}
|
||||
if len(holders) == 0 {
|
||||
delete(d.index, fid)
|
||||
}
|
||||
}
|
||||
d.evictions.Add(int64(n))
|
||||
return n
|
||||
}
|
||||
|
||||
// Stats exposes counters for observability. O(1) — entryCount is kept in
|
||||
// lock-step with map mutations.
|
||||
func (d *PeerDirectory) Stats() (announces, lookups, rejected, evictions int64, entries int) {
|
||||
d.mu.RLock()
|
||||
defer d.mu.RUnlock()
|
||||
return d.announces.Load(), d.lookups.Load(), d.rejected.Load(), d.evictions.Load(), d.entryCount
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// alwaysOwner is a trivial OwnerCheck used by tests that aren't exercising
|
||||
// ownership rejection.
|
||||
func alwaysOwner(string) bool { return true }
|
||||
|
||||
// ownerSet returns an OwnerCheck that accepts only the listed fids.
|
||||
func ownerSet(fids ...string) OwnerCheck {
|
||||
m := map[string]struct{}{}
|
||||
for _, f := range fids {
|
||||
m[f] = struct{}{}
|
||||
}
|
||||
return func(fid string) bool {
|
||||
_, ok := m[fid]
|
||||
return ok
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_AnnounceAndLookup(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
res := d.Announce("mount-a:18080", "", "r1", []string{"3,a", "3,b"}, 60*time.Second, alwaysOwner)
|
||||
if len(res.Rejected) != 0 {
|
||||
t.Errorf("expected 0 rejected, got %v", res.Rejected)
|
||||
}
|
||||
|
||||
lookup := d.Lookup([]string{"3,a", "3,b", "3,c"}, alwaysOwner)
|
||||
if got := len(lookup.PeersByFid["3,a"]); got != 1 {
|
||||
t.Errorf("3,a: expected 1 holder, got %d", got)
|
||||
}
|
||||
if got := len(lookup.PeersByFid["3,b"]); got != 1 {
|
||||
t.Errorf("3,b: expected 1 holder, got %d", got)
|
||||
}
|
||||
if got := len(lookup.PeersByFid["3,c"]); got != 0 {
|
||||
t.Errorf("3,c (unknown): expected 0 holders, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_OwnerRejection(t *testing.T) {
|
||||
d := NewPeerDirectory()
|
||||
|
||||
res := d.Announce("mount-a:18080", "", "", []string{"3,mine", "3,yours"}, time.Minute, ownerSet("3,mine"))
|
||||
if len(res.Rejected) != 1 || res.Rejected[0] != "3,yours" {
|
||||
t.Errorf("expected 3,yours rejected, got %v", res.Rejected)
|
||||
}
|
||||
|
||||
lookup := d.Lookup([]string{"3,mine", "3,yours"}, ownerSet("3,mine"))
|
||||
if got := len(lookup.PeersByFid["3,mine"]); got != 1 {
|
||||
t.Errorf("3,mine should have 1 holder, got %d", got)
|
||||
}
|
||||
if len(lookup.NotOwnerFids) != 1 || lookup.NotOwnerFids[0] != "3,yours" {
|
||||
t.Errorf("expected 3,yours in not-owner list, got %v", lookup.NotOwnerFids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_MultipleHolders(t *testing.T) {
|
||||
d := NewPeerDirectory()
|
||||
d.Announce("mount-a:18080", "", "r1", []string{"3,x"}, time.Minute, alwaysOwner)
|
||||
d.Announce("mount-b:18080", "", "r2", []string{"3,x"}, time.Minute, alwaysOwner)
|
||||
|
||||
holders := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
|
||||
if len(holders) != 2 {
|
||||
t.Fatalf("expected 2 holders, got %d", len(holders))
|
||||
}
|
||||
sort.Slice(holders, func(i, j int) bool { return holders[i].PeerAddr < holders[j].PeerAddr })
|
||||
if holders[0].PeerAddr != "mount-a:18080" || holders[1].PeerAddr != "mount-b:18080" {
|
||||
t.Errorf("unexpected holder addrs: %+v", holders)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_RenewExtendsExpiry(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 30*time.Second, alwaysOwner)
|
||||
|
||||
now = now.Add(25 * time.Second)
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 30*time.Second, alwaysOwner)
|
||||
|
||||
now = now.Add(10 * time.Second)
|
||||
lookup := d.Lookup([]string{"3,a"}, alwaysOwner)
|
||||
if len(lookup.PeersByFid["3,a"]) != 1 {
|
||||
t.Errorf("renew should keep entry alive, got %d holders", len(lookup.PeersByFid["3,a"]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_TTLExpiry(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 10*time.Second, alwaysOwner)
|
||||
now = now.Add(15 * time.Second)
|
||||
holders := d.Lookup([]string{"3,a"}, alwaysOwner).PeersByFid["3,a"]
|
||||
if len(holders) != 0 {
|
||||
t.Errorf("expected TTL-expired holder to be gone, got %+v", holders)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_Sweep(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,a"}, 10*time.Second, alwaysOwner)
|
||||
d.Announce("mount-b:18080", "", "", []string{"3,b"}, 60*time.Second, alwaysOwner)
|
||||
|
||||
now = now.Add(30 * time.Second)
|
||||
got := d.Sweep()
|
||||
if got != 1 {
|
||||
t.Errorf("expected 1 swept entry, got %d", got)
|
||||
}
|
||||
_, _, _, _, entries := d.Stats()
|
||||
if entries != 1 {
|
||||
t.Errorf("expected 1 surviving entry, got %d", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerDirectory_LookupOrdersByRecency guards the LRU contract: the
|
||||
// most recently-announced holder comes first in the lookup response, so
|
||||
// fetchers that try holders in order hit the holder most likely to still
|
||||
// have the chunk cached locally.
|
||||
func TestPeerDirectory_LookupOrdersByRecency(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
now = now.Add(10 * time.Second)
|
||||
d.Announce("mount-b:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
now = now.Add(10 * time.Second)
|
||||
d.Announce("mount-c:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
|
||||
got := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("expected 3 holders, got %d", len(got))
|
||||
}
|
||||
want := []string{"mount-c:18080", "mount-b:18080", "mount-a:18080"}
|
||||
for i, w := range want {
|
||||
if got[i].PeerAddr != w {
|
||||
t.Errorf("holder[%d] = %q, want %q (LRU order)", i, got[i].PeerAddr, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerDirectory_LookupOrderAfterRenewal ensures renewing an older
|
||||
// holder promotes it to the head — matches LRU touch-on-access semantics
|
||||
// and keeps the freshest liveness signal in front.
|
||||
func TestPeerDirectory_LookupOrderAfterRenewal(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
now = now.Add(10 * time.Second)
|
||||
d.Announce("mount-b:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
now = now.Add(10 * time.Second)
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,x"}, 60*time.Second, alwaysOwner)
|
||||
|
||||
got := d.Lookup([]string{"3,x"}, alwaysOwner).PeersByFid["3,x"]
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 holders, got %d", len(got))
|
||||
}
|
||||
if got[0].PeerAddr != "mount-a:18080" {
|
||||
t.Errorf("after renewal, head should be mount-a; got %q", got[0].PeerAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDirectory_StatsCountersIncrement(t *testing.T) {
|
||||
d := NewPeerDirectory()
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,a", "3,b"}, time.Minute, alwaysOwner)
|
||||
d.Lookup([]string{"3,a", "3,c"}, alwaysOwner)
|
||||
d.Announce("mount-a:18080", "", "", []string{"3,nope"}, time.Minute, ownerSet("nothing"))
|
||||
|
||||
announces, lookups, rejected, _, _ := d.Stats()
|
||||
if announces != 2 {
|
||||
t.Errorf("announces counter: %d", announces)
|
||||
}
|
||||
if lookups != 2 {
|
||||
t.Errorf("lookups counter: %d", lookups)
|
||||
}
|
||||
if rejected != 1 {
|
||||
t.Errorf("rejected counter: %d", rejected)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerDirectory_LookupCapsHolderList verifies that a hot fid with
|
||||
// more than maxLookupHolders holders returns only the top-N LRU entries.
|
||||
// The fetcher typically tries only the first 1-3 anyway, so caching
|
||||
// every holder on the wire is overhead.
|
||||
func TestPeerDirectory_LookupCapsHolderList(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
d := newPeerDirectoryWithClock(func() time.Time { return now })
|
||||
|
||||
// Announce 32 holders at strictly increasing timestamps so LRU order
|
||||
// is well-defined and deterministic.
|
||||
total := 2 * maxLookupHolders
|
||||
for i := 0; i < total; i++ {
|
||||
addr := fmt.Sprintf("mount-%02d:18080", i)
|
||||
d.Announce(addr, "", "", []string{"3,hot"}, 60*time.Second, alwaysOwner)
|
||||
now = now.Add(time.Millisecond)
|
||||
}
|
||||
|
||||
got := d.Lookup([]string{"3,hot"}, alwaysOwner).PeersByFid["3,hot"]
|
||||
if len(got) != maxLookupHolders {
|
||||
t.Fatalf("expected %d holders in response, got %d", maxLookupHolders, len(got))
|
||||
}
|
||||
// Head should be the most recent (last announced).
|
||||
want := fmt.Sprintf("mount-%02d:18080", total-1)
|
||||
if got[0].PeerAddr != want {
|
||||
t.Errorf("head of list: got %q want %q (LRU order)", got[0].PeerAddr, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package mount
|
||||
|
||||
// fakeChunkCache satisfies chunk_cache.ChunkCache with a simple in-memory
|
||||
// map keyed by fid. Just enough to exercise the peer-serve handler paths.
|
||||
type fakeChunkCache struct {
|
||||
chunks map[string][]byte
|
||||
}
|
||||
|
||||
func newFakeChunkCache() *fakeChunkCache {
|
||||
return &fakeChunkCache{chunks: map[string][]byte{}}
|
||||
}
|
||||
|
||||
func (f *fakeChunkCache) Put(fid string, data []byte) {
|
||||
buf := make([]byte, len(data))
|
||||
copy(buf, data)
|
||||
f.chunks[fid] = buf
|
||||
}
|
||||
|
||||
func (f *fakeChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (int, error) {
|
||||
b, ok := f.chunks[fileId]
|
||||
if !ok {
|
||||
return 0, nil
|
||||
}
|
||||
if int(offset) >= len(b) {
|
||||
return 0, nil
|
||||
}
|
||||
return copy(data, b[offset:]), nil
|
||||
}
|
||||
|
||||
func (f *fakeChunkCache) SetChunk(fileId string, data []byte) {
|
||||
f.Put(fileId, data)
|
||||
}
|
||||
|
||||
func (f *fakeChunkCache) IsInCache(fileId string, lockNeeded bool) bool {
|
||||
_, ok := f.chunks[fileId]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (f *fakeChunkCache) GetMaxFilePartSizeInCache() uint64 {
|
||||
return 8 * 1024 * 1024
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// errPeerReadSkipped signals that the read didn't go through the peer
|
||||
// path for a benign reason (local cache hit, no peer owner, etc.) rather
|
||||
// than a genuine failure. Callers fall through to the volume path just
|
||||
// as they would for a real error, but suppress the "peer read failed"
|
||||
// log that would otherwise mislead operators into thinking peer sharing
|
||||
// is broken.
|
||||
var errPeerReadSkipped = fmt.Errorf("peer read skipped (not an error)")
|
||||
|
||||
// peerLookupTimeout bounds the ChunkLookup RPC. Short because the result
|
||||
// is consumed on the read critical path.
|
||||
const peerLookupTimeout = 500 * time.Millisecond
|
||||
|
||||
// peerFetchTimeout bounds a single FetchChunk stream; on expiry we fall
|
||||
// through to the next holder or the volume server.
|
||||
const peerFetchTimeout = 5 * time.Second
|
||||
|
||||
// maxPeerFetchChunkBytes caps how much we will accept from a single
|
||||
// FetchChunk stream. gRPC per-message size is already capped by the
|
||||
// server option; this is belt-and-suspenders against a runaway peer.
|
||||
const maxPeerFetchChunkBytes = 64 * 1024 * 1024
|
||||
|
||||
// tryPeerRead attempts to satisfy a read from a peer mount's chunk cache.
|
||||
// Returns (bytesRead, modifiedTsNs, nil) on success. On any failure it
|
||||
// returns (0, 0, err) so the caller falls through to
|
||||
// entryChunkGroup.ReadDataAt (the volume-server path).
|
||||
//
|
||||
// Flow:
|
||||
// 1. Resolve the offset's leaf chunk (flattening manifests).
|
||||
// 2. Ask the HRW owner mount for current holders via ChunkLookup.
|
||||
// 3. For each holder (LRU order from PR #5), open a FetchChunk stream,
|
||||
// assemble frames into a size-bounded buffer, and verify MD5
|
||||
// end-to-end against FileChunk.ETag.
|
||||
// 4. On success, populate chunk_cache and enqueue an announce so
|
||||
// other mounts can discover us as a new holder.
|
||||
func (fh *FileHandle) tryPeerRead(ctx context.Context, fileSize int64, buff []byte, offset int64, entry *LockedEntry) (int64, int64, error) {
|
||||
if fh.wfs.peerRegistrar == nil || fh.wfs.peerConnPool == nil {
|
||||
return 0, 0, fmt.Errorf("peer sharing not configured")
|
||||
}
|
||||
|
||||
// Resolve offset → leaf chunk, flattening any manifest indirection.
|
||||
readStop := offset + int64(len(buff))
|
||||
if readStop > fileSize {
|
||||
readStop = fileSize
|
||||
}
|
||||
dataChunks, _, err := filer.ResolveChunkManifest(ctx, fh.wfs.LookupFn(), entry.GetEntry().Chunks, offset, readStop)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("resolve manifest: %w", err)
|
||||
}
|
||||
targetChunk, chunkOffset := findChunkContaining(dataChunks, offset)
|
||||
if targetChunk == nil {
|
||||
return 0, 0, fmt.Errorf("no leaf chunk for offset %d", offset)
|
||||
}
|
||||
// Reject reads that cross a chunk boundary. We only fetch one chunk
|
||||
// here, and the caller (readFromChunks) maps a short non-error
|
||||
// return to "success, zero-fill the rest" — which would silently
|
||||
// corrupt reads that should actually span two chunks. Bail so the
|
||||
// fallback ReadDataAt path can handle the multi-chunk case
|
||||
// correctly. See weedfs_file_read.go short-read semantics.
|
||||
chunkEnd := targetChunk.Offset + int64(targetChunk.Size)
|
||||
if readStop > chunkEnd {
|
||||
return 0, 0, errPeerReadSkipped
|
||||
}
|
||||
|
||||
// Fail fast when the chunk is already cached locally: the fallback
|
||||
// ReadDataAt path will satisfy the read from chunkCache with no RPCs,
|
||||
// so dialing a peer (ChunkLookup + FetchChunk) would be pure overhead.
|
||||
if fh.wfs.chunkCache != nil && fh.wfs.chunkCache.IsInCache(targetChunk.FileId, true) {
|
||||
return 0, 0, errPeerReadSkipped
|
||||
}
|
||||
|
||||
selfAddr := ""
|
||||
if fh.wfs.peerGrpcServer != nil {
|
||||
selfAddr = fh.wfs.peerGrpcServer.SelfAddr()
|
||||
}
|
||||
|
||||
owner := fh.wfs.peerRegistrar.OwnerFor(targetChunk.FileId)
|
||||
if owner == "" || owner == selfAddr {
|
||||
return 0, 0, fmt.Errorf("no peer owner for fid %s", targetChunk.FileId)
|
||||
}
|
||||
|
||||
holders, err := peerLookupHolders(ctx, fh.wfs.peerConnPool.Dialer(), owner, targetChunk.FileId)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("peer lookup: %w", err)
|
||||
}
|
||||
if len(holders) == 0 {
|
||||
return 0, 0, fmt.Errorf("no peer holder for fid %s", targetChunk.FileId)
|
||||
}
|
||||
|
||||
// Re-rank holders by locality (same rack > same DC > elsewhere), keeping
|
||||
// the server's LRU order stable within each bucket. The server caps the
|
||||
// list at maxLookupHolders, so this is always a small N.
|
||||
sortHoldersByLocality(holders, fh.wfs.option.PeerDataCenter, fh.wfs.option.PeerRack)
|
||||
|
||||
dial := fh.wfs.peerConnPool.Dialer()
|
||||
for _, h := range holders {
|
||||
if h.addr == selfAddr {
|
||||
continue
|
||||
}
|
||||
data, ferr := fetchChunkFromPeer(ctx, dial, h.addr, targetChunk.FileId, targetChunk.Size, targetChunk.ETag)
|
||||
if ferr != nil {
|
||||
glog.V(2).Infof("peer-fetch %s from %s: %v", targetChunk.FileId, h.addr, ferr)
|
||||
continue
|
||||
}
|
||||
if fh.wfs.chunkCache != nil {
|
||||
fh.wfs.chunkCache.SetChunk(targetChunk.FileId, data)
|
||||
}
|
||||
if fh.wfs.peerAnnouncer != nil {
|
||||
fh.wfs.peerAnnouncer.EnqueueAnnounce(targetChunk.FileId)
|
||||
}
|
||||
if chunkOffset >= int64(len(data)) {
|
||||
return 0, 0, fmt.Errorf("peer returned short chunk")
|
||||
}
|
||||
// Cap the copy to whichever is smaller: the caller's buffer, or
|
||||
// the remaining bytes before logical EOF (readStop already
|
||||
// clamped to fileSize). FileChunk.Size can legitimately exceed
|
||||
// the logical file length when the last chunk is partially
|
||||
// written and the filer stored the full padded buffer, so a
|
||||
// naïve copy(buff, data[chunkOffset:]) would return bytes past
|
||||
// EOF. The caller treats a short non-error return as success
|
||||
// and zero-fills the tail, so returning too many bytes here is
|
||||
// a correctness bug, not just wasted I/O.
|
||||
remaining := readStop - offset
|
||||
available := int64(len(data)) - chunkOffset
|
||||
maxCopy := int64(len(buff))
|
||||
if remaining < maxCopy {
|
||||
maxCopy = remaining
|
||||
}
|
||||
if available < maxCopy {
|
||||
maxCopy = available
|
||||
}
|
||||
copied := copy(buff[:maxCopy], data[chunkOffset:chunkOffset+maxCopy])
|
||||
return int64(copied), targetChunk.ModifiedTsNs, nil
|
||||
}
|
||||
return 0, 0, fmt.Errorf("no peer served fid %s", targetChunk.FileId)
|
||||
}
|
||||
|
||||
func findChunkContaining(chunks []*filer_pb.FileChunk, offset int64) (*filer_pb.FileChunk, int64) {
|
||||
for _, c := range chunks {
|
||||
start := c.Offset
|
||||
stop := c.Offset + int64(c.Size)
|
||||
if offset >= start && offset < stop {
|
||||
return c, offset - start
|
||||
}
|
||||
}
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// peerHolder is a holder entry carried through the fetcher: addr for
|
||||
// dialing plus the DC/Rack labels the owner recorded at announce time, so
|
||||
// the fetcher can re-rank by its own locality before dialing.
|
||||
type peerHolder struct {
|
||||
addr string
|
||||
dc string
|
||||
rack string
|
||||
}
|
||||
|
||||
// peerLookupHolders calls ChunkLookup on the given HRW owner and returns
|
||||
// the holders in the server-reported (LRU) order along with their locality
|
||||
// labels. The pooled dialer is passed in from the caller.
|
||||
func peerLookupHolders(ctx context.Context, dial MountPeerDialer, ownerAddr, fid string) ([]peerHolder, error) {
|
||||
client, closeFn, err := dial(ctx, ownerAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer closeFn()
|
||||
|
||||
callCtx, cancel := context.WithTimeout(ctx, peerLookupTimeout)
|
||||
defer cancel()
|
||||
resp, err := client.ChunkLookup(callCtx, &mount_peer_pb.ChunkLookupRequest{FileIds: []string{fid}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
set, ok := resp.PeersByFid[fid]
|
||||
if !ok || set == nil {
|
||||
return nil, nil
|
||||
}
|
||||
out := make([]peerHolder, 0, len(set.Peers))
|
||||
for _, p := range set.Peers {
|
||||
out = append(out, peerHolder{addr: p.PeerAddr, dc: p.DataCenter, rack: p.Rack})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// localityBucket scores how "close" a peer is to self. Lower is better:
|
||||
//
|
||||
// 0 = same rack in same DC (shortest hop)
|
||||
// 1 = same DC, different rack (cross-rack but still intra-DC)
|
||||
// 2 = different DC, or unknown (anything else)
|
||||
//
|
||||
// Missing labels on either side fall to bucket 2 — we don't claim locality
|
||||
// we can't prove.
|
||||
func localityBucket(selfDC, selfRack, peerDC, peerRack string) int {
|
||||
if selfDC == "" || peerDC == "" || selfDC != peerDC {
|
||||
return 2
|
||||
}
|
||||
if selfRack != "" && peerRack != "" && selfRack == peerRack {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// sortHoldersByLocality stable-sorts holders so the most local peers are
|
||||
// tried first. The server-returned order is LRU (freshest holder first),
|
||||
// and sort.SliceStable preserves that ordering within each locality
|
||||
// bucket, so among equally-local peers we still prefer the freshest.
|
||||
func sortHoldersByLocality(holders []peerHolder, selfDC, selfRack string) {
|
||||
if len(holders) < 2 {
|
||||
return
|
||||
}
|
||||
sort.SliceStable(holders, func(i, j int) bool {
|
||||
return localityBucket(selfDC, selfRack, holders[i].dc, holders[i].rack) <
|
||||
localityBucket(selfDC, selfRack, holders[j].dc, holders[j].rack)
|
||||
})
|
||||
}
|
||||
|
||||
// fetchChunkFromPeer server-streams a chunk from the given peer and
|
||||
// verifies the MD5 of the assembled bytes against expectedETag.
|
||||
//
|
||||
// expectedSize (when > 0) is the authoritative chunk length from the
|
||||
// filer entry; we pre-allocate exactly that to avoid slice growth and
|
||||
// reject streams that overshoot it. A zero expectedSize falls back to
|
||||
// maxPeerFetchChunkBytes as a safety ceiling.
|
||||
func fetchChunkFromPeer(ctx context.Context, dial MountPeerDialer, peerAddr, fid string, expectedSize uint64, expectedETag string) ([]byte, error) {
|
||||
client, closeFn, err := dial(ctx, peerAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer closeFn()
|
||||
|
||||
callCtx, cancel := context.WithTimeout(ctx, peerFetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
stream, err := client.FetchChunk(callCtx, &mount_peer_pb.FetchChunkRequest{
|
||||
FileId: fid,
|
||||
ExpectedEtag: expectedETag,
|
||||
ExpectedSize: expectedSize,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// capHint pre-sizes the assembly buffer from the filer-reported chunk
|
||||
// size. When the caller didn't know the size (expectedSize == 0), we
|
||||
// let append grow the buffer rather than reserve the 64 MiB ceiling —
|
||||
// typical chunks are a few MiB, and the maxPeerFetchChunkBytes check
|
||||
// during Recv is the real safety ceiling.
|
||||
capHint := expectedSize
|
||||
if capHint > maxPeerFetchChunkBytes {
|
||||
capHint = maxPeerFetchChunkBytes
|
||||
}
|
||||
buf := make([]byte, 0, capHint)
|
||||
|
||||
for {
|
||||
resp, rerr := stream.Recv()
|
||||
if rerr == io.EOF {
|
||||
break
|
||||
}
|
||||
if rerr != nil {
|
||||
if status.Code(rerr) == codes.NotFound {
|
||||
return nil, fmt.Errorf("peer not cached")
|
||||
}
|
||||
return nil, rerr
|
||||
}
|
||||
if len(buf)+len(resp.Data) > int(maxPeerFetchChunkBytes) {
|
||||
return nil, fmt.Errorf("peer response exceeds max chunk size %d", maxPeerFetchChunkBytes)
|
||||
}
|
||||
buf = append(buf, resp.Data...)
|
||||
}
|
||||
|
||||
if expectedSize > 0 && uint64(len(buf)) != expectedSize {
|
||||
return nil, fmt.Errorf("peer returned %d bytes, expected %d", len(buf), expectedSize)
|
||||
}
|
||||
|
||||
// Per-chunk integrity check — the peer is treated as untrusted.
|
||||
// FileChunk.ETag is UploadResult.ContentMd5, which is base64 of the
|
||||
// raw 16-byte MD5 (see weed/operation/upload_content.go:64 and
|
||||
// filer's ETagChunks which decodes via util.Base64Md5ToBytes).
|
||||
// Compare raw digests so we don't reject every valid peer response
|
||||
// because of an encoding mismatch.
|
||||
if expectedETag != "" {
|
||||
got := md5.Sum(buf)
|
||||
if !etagMatchesMD5(expectedETag, got[:]) {
|
||||
return nil, fmt.Errorf("etag mismatch: peer=%s got=%x want=%s", peerAddr, got, expectedETag)
|
||||
}
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// etagMatchesMD5 compares a stored FileChunk.ETag string to a raw 16-byte
|
||||
// MD5 digest. FileChunk.ETag is produced as base64(md5) on upload, but
|
||||
// some older chunks (and tests) use hex(md5). Accept either.
|
||||
func etagMatchesMD5(etag string, rawMD5 []byte) bool {
|
||||
if len(rawMD5) != md5.Size {
|
||||
return false
|
||||
}
|
||||
if dec := util.Base64Md5ToBytes(etag); len(dec) == md5.Size {
|
||||
return bytes.Equal(dec, rawMD5)
|
||||
}
|
||||
if dec, err := hex.DecodeString(etag); err == nil && len(dec) == md5.Size {
|
||||
return bytes.Equal(dec, rawMD5)
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// newTestFetchServer stands up a minimal MountPeer gRPC server that only
|
||||
// serves FetchChunk out of a fakeChunkCache. Goes through the same
|
||||
// PeerGrpcServer.Start path production uses (via pb.NewGrpcServer with
|
||||
// the standard keepalive + msg-size options) so future default server
|
||||
// options are exercised by these tests too.
|
||||
func newTestFetchServer(t *testing.T, cache *fakeChunkCache) (addr string, stop func()) {
|
||||
t.Helper()
|
||||
dir := NewPeerDirectory()
|
||||
srv := NewPeerGrpcServer(cache, dir, nil, "")
|
||||
if err := srv.Start("127.0.0.1:0"); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
return srv.Addr(), func() { srv.Stop() }
|
||||
}
|
||||
|
||||
func etagOf(b []byte) string {
|
||||
sum := md5.Sum(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// etagOfBase64 mirrors how the real upload path produces FileChunk.ETag:
|
||||
// base64 of the raw 16-byte MD5 digest. Kept alongside the hex form so
|
||||
// we can test that both encodings work end-to-end.
|
||||
func etagOfBase64(b []byte) string {
|
||||
sum := md5.Sum(b)
|
||||
return base64.StdEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestFetchChunkFromPeer_Hit(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
payload := []byte("hello from peer stream")
|
||||
cache.Put("3,abc", payload)
|
||||
addr, stop := newTestFetchServer(t, cache)
|
||||
defer stop()
|
||||
|
||||
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,abc", uint64(len(payload)), etagOf(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("fetch: %v", err)
|
||||
}
|
||||
if string(got) != string(payload) {
|
||||
t.Errorf("bytes mismatch: got %q want %q", got, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchChunkFromPeer_Base64Etag mirrors the real upload path where
|
||||
// FileChunk.ETag is base64(md5) rather than hex(md5). A regression
|
||||
// there would reject every valid peer response in production.
|
||||
func TestFetchChunkFromPeer_Base64Etag(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
payload := []byte("base64-etag peer bytes")
|
||||
cache.Put("3,b64", payload)
|
||||
addr, stop := newTestFetchServer(t, cache)
|
||||
defer stop()
|
||||
|
||||
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,b64", uint64(len(payload)), etagOfBase64(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("fetch: %v", err)
|
||||
}
|
||||
if string(got) != string(payload) {
|
||||
t.Errorf("bytes mismatch: got %q want %q", got, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchChunkFromPeer_EtagMismatch(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
payload := []byte("unexpected bytes")
|
||||
cache.Put("3,abc", payload)
|
||||
addr, stop := newTestFetchServer(t, cache)
|
||||
defer stop()
|
||||
|
||||
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
_, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,abc", 0, "not-the-real-etag")
|
||||
if err == nil {
|
||||
t.Fatalf("expected etag mismatch error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchChunkFromPeer_NotFound(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
addr, stop := newTestFetchServer(t, cache)
|
||||
defer stop()
|
||||
|
||||
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
_, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,missing", 0, "")
|
||||
if err == nil {
|
||||
t.Errorf("expected error for missing fid, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSortHoldersByLocality verifies that same-rack peers sort ahead of
|
||||
// same-DC-different-rack peers, which in turn sort ahead of cross-DC
|
||||
// peers, and that LRU order is preserved within each bucket.
|
||||
func TestSortHoldersByLocality(t *testing.T) {
|
||||
selfDC, selfRack := "dc1", "r1"
|
||||
// Input order mimics a server-side LRU list (newest first).
|
||||
holders := []peerHolder{
|
||||
{addr: "far-newest", dc: "dc2", rack: "r9"}, // bucket 2 (diff DC)
|
||||
{addr: "mid-newer", dc: "dc1", rack: "r2"}, // bucket 1 (same DC, diff rack)
|
||||
{addr: "local-newer", dc: "dc1", rack: "r1"}, // bucket 0 (same rack)
|
||||
{addr: "far-older", dc: "dc2", rack: "r9"}, // bucket 2
|
||||
{addr: "mid-older", dc: "dc1", rack: "r2"}, // bucket 1
|
||||
{addr: "local-older", dc: "dc1", rack: "r1"}, // bucket 0
|
||||
{addr: "unlabeled-older", dc: "", rack: ""}, // bucket 2 (unknown)
|
||||
}
|
||||
|
||||
sortHoldersByLocality(holders, selfDC, selfRack)
|
||||
|
||||
want := []string{
|
||||
"local-newer", "local-older",
|
||||
"mid-newer", "mid-older",
|
||||
"far-newest", "far-older", "unlabeled-older",
|
||||
}
|
||||
if len(holders) != len(want) {
|
||||
t.Fatalf("len got %d want %d", len(holders), len(want))
|
||||
}
|
||||
for i, w := range want {
|
||||
if holders[i].addr != w {
|
||||
t.Errorf("pos %d: got %q want %q (full: %+v)", i, holders[i].addr, w, holders)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSortHoldersByLocality_NoSelfLabels — when the caller has no DC/rack
|
||||
// labels, every peer falls to bucket 2 and the server-returned LRU order
|
||||
// must pass through unchanged.
|
||||
func TestSortHoldersByLocality_NoSelfLabels(t *testing.T) {
|
||||
holders := []peerHolder{
|
||||
{addr: "a", dc: "dc1", rack: "r1"},
|
||||
{addr: "b", dc: "dc2", rack: "r2"},
|
||||
{addr: "c", dc: "", rack: ""},
|
||||
}
|
||||
sortHoldersByLocality(holders, "", "")
|
||||
want := []string{"a", "b", "c"}
|
||||
for i, w := range want {
|
||||
if holders[i].addr != w {
|
||||
t.Errorf("pos %d: got %q want %q", i, holders[i].addr, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchChunkFromPeer_MultiFrameChunkAssembledCorrectly(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
// Just over 2× the stream frame size so we get at least three frames.
|
||||
payload := make([]byte, fetchChunkStreamSize*2+42)
|
||||
for i := range payload {
|
||||
payload[i] = byte((i * 7) & 0xff)
|
||||
}
|
||||
cache.Put("3,large", payload)
|
||||
addr, stop := newTestFetchServer(t, cache)
|
||||
defer stop()
|
||||
|
||||
dial := DefaultMountPeerDialer(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
got, err := fetchChunkFromPeer(context.Background(), dial, addr, "3,large", uint64(len(payload)), etagOf(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("fetch: %v", err)
|
||||
}
|
||||
if len(got) != len(payload) {
|
||||
t.Fatalf("len got %d want %d", len(got), len(payload))
|
||||
}
|
||||
for i := range payload {
|
||||
if got[i] != payload[i] {
|
||||
t.Fatalf("mismatch at offset %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// fetchChunkStreamSize is the frame size used when server-streaming a chunk's
|
||||
// bytes back to a peer. 1 MiB is well above gRPC's 32 KiB preferred frame but
|
||||
// comfortably under the default 4 MiB message cap, so each Recv on the client
|
||||
// returns quickly and the chunk is assembled with ~16 Recv calls for typical
|
||||
// 16 MiB chunks.
|
||||
const fetchChunkStreamSize = 1 * 1024 * 1024
|
||||
|
||||
// maxFetchChunkBytes caps the size of a single FetchChunk read buffer.
|
||||
// The caller's expected_size is untrusted — a misbehaving peer could
|
||||
// claim 1 TiB and OOM the server. 64 MiB is well above any realistic
|
||||
// chunk (SeaweedFS defaults to 16 MiB, filer manifests cap at 32 MiB);
|
||||
// anything larger is treated as invalid input.
|
||||
const maxFetchChunkBytes = 64 * 1024 * 1024
|
||||
|
||||
// PeerGrpcServer is the single mount-to-mount gRPC endpoint. It serves:
|
||||
// - ChunkAnnounce / ChunkLookup — the tier-2 directory RPCs, populated
|
||||
// by inbound announces and queried by inbound lookups. Each handler
|
||||
// is HRW-gated on the caller-side seed view.
|
||||
// - FetchChunk (server stream) — serves bytes from the local
|
||||
// chunk_cache to peers. Replaces the earlier HTTP-only peer-serve
|
||||
// endpoint: one port, one authentication path, one connection pool.
|
||||
//
|
||||
// Transport credentials (TLS/mTLS) are injected via serverOpts. When the
|
||||
// caller passes nothing the server runs plaintext — only appropriate on
|
||||
// a trusted single-host test cluster. Production wiring passes
|
||||
// security.LoadServerTLS from security.toml so cross-host traffic is
|
||||
// authenticated + encrypted.
|
||||
type PeerGrpcServer struct {
|
||||
mount_peer_pb.UnimplementedMountPeerServer
|
||||
|
||||
dir *PeerDirectory
|
||||
cache chunk_cache.ChunkCache
|
||||
ownerFor func(fid string) string // HRW owner predicate on current seeds
|
||||
selfAddr string
|
||||
serverOpts []grpc.ServerOption
|
||||
grpcS *grpc.Server
|
||||
listener net.Listener
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// NewPeerGrpcServer constructs the server. cache is the local chunk_cache
|
||||
// (used to serve FetchChunk); dir is the local directory shard (used to
|
||||
// answer ChunkAnnounce / ChunkLookup); ownerFor returns the HRW owner of a
|
||||
// fid on the current seed view; serverOpts are forwarded to the underlying
|
||||
// gRPC server (use grpc.Creds(...) for TLS/mTLS).
|
||||
func NewPeerGrpcServer(cache chunk_cache.ChunkCache, dir *PeerDirectory, ownerFor func(fid string) string, selfAddr string, serverOpts ...grpc.ServerOption) *PeerGrpcServer {
|
||||
return &PeerGrpcServer{
|
||||
cache: cache,
|
||||
dir: dir,
|
||||
ownerFor: ownerFor,
|
||||
selfAddr: selfAddr,
|
||||
serverOpts: serverOpts,
|
||||
}
|
||||
}
|
||||
|
||||
// Start binds a TCP listener at addr and registers the MountPeer service.
|
||||
func (s *PeerGrpcServer) Start(addr string) error {
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("peer grpc listen %s: %w", addr, err)
|
||||
}
|
||||
s.listener = ln
|
||||
s.grpcS = pb.NewGrpcServer(s.serverOpts...)
|
||||
mount_peer_pb.RegisterMountPeerServer(s.grpcS, s)
|
||||
go func() {
|
||||
if err := s.grpcS.Serve(ln); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Warningf("peer-grpc terminated: %v", err)
|
||||
}
|
||||
}()
|
||||
glog.V(0).Infof("peer-grpc listening on %s", ln.Addr())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop halts the gRPC server without waiting for in-flight streams.
|
||||
func (s *PeerGrpcServer) Stop() {
|
||||
if s.stopped {
|
||||
return
|
||||
}
|
||||
s.stopped = true
|
||||
if s.grpcS != nil {
|
||||
s.grpcS.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// Addr returns the bound address (useful when the caller used ":0").
|
||||
func (s *PeerGrpcServer) Addr() string {
|
||||
if s.listener == nil {
|
||||
return ""
|
||||
}
|
||||
return s.listener.Addr().String()
|
||||
}
|
||||
|
||||
// SelfAddr returns the advertise address this server was constructed with —
|
||||
// the identity the fetcher compares against to avoid dialing itself.
|
||||
func (s *PeerGrpcServer) SelfAddr() string { return s.selfAddr }
|
||||
|
||||
// ChunkAnnounce accepts holder entries for fids this mount owns; rejects
|
||||
// others so the caller can retry against the correct owner.
|
||||
func (s *PeerGrpcServer) ChunkAnnounce(ctx context.Context, req *mount_peer_pb.ChunkAnnounceRequest) (*mount_peer_pb.ChunkAnnounceResponse, error) {
|
||||
ttl := time.Duration(req.TtlSeconds) * time.Second
|
||||
res := s.dir.Announce(req.PeerAddr, req.DataCenter, req.Rack, req.FileIds, ttl, s.ownerPredicate)
|
||||
return &mount_peer_pb.ChunkAnnounceResponse{
|
||||
RejectedFileIds: res.Rejected,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ChunkLookup returns known holders for each requested fid in LRU order.
|
||||
func (s *PeerGrpcServer) ChunkLookup(ctx context.Context, req *mount_peer_pb.ChunkLookupRequest) (*mount_peer_pb.ChunkLookupResponse, error) {
|
||||
res := s.dir.Lookup(req.FileIds, s.ownerPredicate)
|
||||
resp := &mount_peer_pb.ChunkLookupResponse{
|
||||
PeersByFid: make(map[string]*mount_peer_pb.PeerSet, len(res.PeersByFid)),
|
||||
NotOwnerFileIds: res.NotOwnerFids,
|
||||
}
|
||||
for fid, holders := range res.PeersByFid {
|
||||
peers := &mount_peer_pb.PeerSet{}
|
||||
for _, h := range holders {
|
||||
peers.Peers = append(peers.Peers, &mount_peer_pb.PeerInfo{
|
||||
PeerAddr: h.PeerAddr,
|
||||
DataCenter: h.DataCenter,
|
||||
Rack: h.Rack,
|
||||
})
|
||||
}
|
||||
resp.PeersByFid[fid] = peers
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// FetchChunk streams bytes of a cached chunk back to the caller. Missing
|
||||
// fid → gRPC NOT_FOUND. Bytes are framed at fetchChunkStreamSize so gRPC's
|
||||
// default 4 MiB message cap does not constrain chunk size.
|
||||
func (s *PeerGrpcServer) FetchChunk(req *mount_peer_pb.FetchChunkRequest, stream mount_peer_pb.MountPeer_FetchChunkServer) error {
|
||||
if s.cache == nil {
|
||||
return status.Error(codes.Unavailable, "chunk cache not configured")
|
||||
}
|
||||
fid := req.FileId
|
||||
if fid == "" {
|
||||
return status.Error(codes.InvalidArgument, "missing file_id")
|
||||
}
|
||||
|
||||
// Size the read buffer to the caller-reported chunk length. The
|
||||
// TieredChunkCache.ReadChunkAt wrapper only returns success when n
|
||||
// equals len(data), so a buffer larger than the actual stored chunk
|
||||
// (e.g. an 8 MiB buffer for a 2 MiB chunk) makes every read look
|
||||
// like a miss. Client sends expected_size from FileChunk.Size so we
|
||||
// allocate exactly the right amount. Fall back to the max-part-size
|
||||
// when the caller left it zero (older clients) and hope the chunk
|
||||
// is that big.
|
||||
//
|
||||
// expected_size is untrusted — cap at maxFetchChunkBytes to prevent
|
||||
// a misbehaving peer from requesting an OOM-sized allocation.
|
||||
if req.ExpectedSize > maxFetchChunkBytes {
|
||||
return status.Errorf(codes.InvalidArgument,
|
||||
"expected_size %d exceeds max %d", req.ExpectedSize, maxFetchChunkBytes)
|
||||
}
|
||||
if req.Length > maxFetchChunkBytes {
|
||||
return status.Errorf(codes.InvalidArgument,
|
||||
"length %d exceeds max %d", req.Length, maxFetchChunkBytes)
|
||||
}
|
||||
readSize := int(req.ExpectedSize)
|
||||
if readSize <= 0 {
|
||||
max := s.cache.GetMaxFilePartSizeInCache()
|
||||
if max == 0 {
|
||||
max = 8 * 1024 * 1024
|
||||
}
|
||||
readSize = int(max)
|
||||
}
|
||||
// mem.Allocate rounds up to the nearest power-of-2 slot backed by a
|
||||
// shared sync.Pool; avoids an allocation per FetchChunk call.
|
||||
buf := mem.Allocate(readSize)
|
||||
defer mem.Free(buf)
|
||||
|
||||
n, err := s.cache.ReadChunkAt(buf, fid, 0)
|
||||
if err != nil || n <= 0 {
|
||||
return status.Errorf(codes.NotFound, "fid %s not cached", fid)
|
||||
}
|
||||
|
||||
// Apply optional offset / length range to the whole-chunk buffer.
|
||||
// Default (both 0) is a full-chunk transfer starting at byte 0,
|
||||
// which is what the fetcher uses today. Non-default is reserved
|
||||
// for future range-read callers.
|
||||
lo := int(req.Offset)
|
||||
if lo < 0 || lo > n {
|
||||
return status.Errorf(codes.OutOfRange, "offset %d outside chunk length %d", lo, n)
|
||||
}
|
||||
hi := n
|
||||
if req.Length > 0 {
|
||||
hi = lo + int(req.Length)
|
||||
if hi > n {
|
||||
hi = n
|
||||
}
|
||||
}
|
||||
|
||||
for off := lo; off < hi; off += fetchChunkStreamSize {
|
||||
end := off + fetchChunkStreamSize
|
||||
if end > hi {
|
||||
end = hi
|
||||
}
|
||||
if sendErr := stream.Send(&mount_peer_pb.FetchChunkResponse{
|
||||
Data: buf[off:end],
|
||||
}); sendErr != nil {
|
||||
return sendErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PeerGrpcServer) ownerPredicate(fid string) bool {
|
||||
if s.ownerFor == nil {
|
||||
return true // no HRW configured → accept all (single-mount mode)
|
||||
}
|
||||
return s.ownerFor(fid) == s.selfAddr
|
||||
}
|
||||
|
||||
// peerDirectorySweepInterval is how often the mount evicts expired
|
||||
// directory entries. Lookup no longer deletes inline (it takes only an
|
||||
// RLock), so this sweeper is the sole memory reclamation path.
|
||||
const peerDirectorySweepInterval = 60 * time.Second
|
||||
|
||||
// runPeerDirectorySweeper runs until stopCh closes. Stopping it on
|
||||
// unmount prevents the goroutine from outliving the WFS, which matters
|
||||
// for tests and for any embedded use of NewSeaweedFileSystem where the
|
||||
// filesystem object is recreated without a process exit.
|
||||
func (wfs *WFS) runPeerDirectorySweeper(stopCh <-chan struct{}) {
|
||||
ticker := time.NewTicker(peerDirectorySweepInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
dir := wfs.peerDirectory
|
||||
if dir == nil {
|
||||
return
|
||||
}
|
||||
if evicted := dir.Sweep(); evicted > 0 {
|
||||
glog.V(2).Infof("peer directory: evicted %d expired entries", evicted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func newTestPeerGrpc(t *testing.T, cache chunk_cache.ChunkCache, ownerFor func(fid string) string, selfAddr string) (mount_peer_pb.MountPeerClient, func()) {
|
||||
t.Helper()
|
||||
dir := NewPeerDirectory()
|
||||
srv := NewPeerGrpcServer(cache, dir, ownerFor, selfAddr)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
srv.listener = ln
|
||||
srv.grpcS = grpc.NewServer()
|
||||
mount_peer_pb.RegisterMountPeerServer(srv.grpcS, srv)
|
||||
go srv.grpcS.Serve(ln)
|
||||
|
||||
conn, err := grpc.NewClient(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
client := mount_peer_pb.NewMountPeerClient(conn)
|
||||
cleanup := func() {
|
||||
conn.Close()
|
||||
srv.Stop()
|
||||
}
|
||||
return client, cleanup
|
||||
}
|
||||
|
||||
func TestPeerGrpcServer_AnnounceAndLookup(t *testing.T) {
|
||||
self := "self:18080"
|
||||
client, cleanup := newTestPeerGrpc(t, nil, func(fid string) string {
|
||||
return self
|
||||
}, self)
|
||||
defer cleanup()
|
||||
|
||||
_, err := client.ChunkAnnounce(context.Background(), &mount_peer_pb.ChunkAnnounceRequest{
|
||||
FileIds: []string{"3,a", "3,b"},
|
||||
PeerAddr: "holder:18080",
|
||||
TtlSeconds: 60,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("announce: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.ChunkLookup(context.Background(), &mount_peer_pb.ChunkLookupRequest{
|
||||
FileIds: []string{"3,a", "3,missing"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("lookup: %v", err)
|
||||
}
|
||||
if got := len(resp.PeersByFid["3,a"].Peers); got != 1 {
|
||||
t.Errorf("3,a: expected 1 holder, got %d", got)
|
||||
}
|
||||
if _, ok := resp.PeersByFid["3,missing"]; !ok {
|
||||
t.Errorf("3,missing should have a (nil/empty) peer set entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerGrpcServer_OwnerMismatch(t *testing.T) {
|
||||
client, cleanup := newTestPeerGrpc(t, nil, func(fid string) string {
|
||||
return "some-other:18080"
|
||||
}, "self:18080")
|
||||
defer cleanup()
|
||||
|
||||
ann, err := client.ChunkAnnounce(context.Background(), &mount_peer_pb.ChunkAnnounceRequest{
|
||||
FileIds: []string{"3,x"},
|
||||
PeerAddr: "holder:18080",
|
||||
TtlSeconds: 60,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("announce: %v", err)
|
||||
}
|
||||
if len(ann.RejectedFileIds) != 1 || ann.RejectedFileIds[0] != "3,x" {
|
||||
t.Errorf("expected 3,x rejected, got %v", ann.RejectedFileIds)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerGrpcServer_FetchChunk_StreamsHit exercises the new byte-transfer
|
||||
// path: a cached chunk returned as multiple gRPC frames, concatenated by
|
||||
// the caller into the original payload.
|
||||
func TestPeerGrpcServer_FetchChunk_StreamsHit(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
// A payload deliberately larger than fetchChunkStreamSize to force
|
||||
// multiple Send() calls.
|
||||
payload := make([]byte, fetchChunkStreamSize*2+123)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i & 0xff)
|
||||
}
|
||||
cache.Put("3,stream", payload)
|
||||
|
||||
client, cleanup := newTestPeerGrpc(t, cache, nil, "self:18080")
|
||||
defer cleanup()
|
||||
|
||||
stream, err := client.FetchChunk(context.Background(), &mount_peer_pb.FetchChunkRequest{FileId: "3,stream"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchChunk: %v", err)
|
||||
}
|
||||
var got []byte
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Recv: %v", err)
|
||||
}
|
||||
got = append(got, resp.Data...)
|
||||
}
|
||||
if len(got) != len(payload) {
|
||||
t.Fatalf("got %d bytes, want %d", len(got), len(payload))
|
||||
}
|
||||
for i, b := range got {
|
||||
if b != payload[i] {
|
||||
t.Fatalf("byte mismatch at offset %d: got %02x want %02x", i, b, payload[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerGrpcServer_FetchChunk_NotFound verifies that a miss returns
|
||||
// gRPC NOT_FOUND so the client can distinguish miss from transport error.
|
||||
func TestPeerGrpcServer_FetchChunk_NotFound(t *testing.T) {
|
||||
cache := newFakeChunkCache()
|
||||
client, cleanup := newTestPeerGrpc(t, cache, nil, "self:18080")
|
||||
defer cleanup()
|
||||
|
||||
stream, err := client.FetchChunk(context.Background(), &mount_peer_pb.FetchChunkRequest{FileId: "3,missing"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchChunk dial: %v", err)
|
||||
}
|
||||
_, err = stream.Recv()
|
||||
if err == nil {
|
||||
t.Fatalf("expected error on missing fid, got nil")
|
||||
}
|
||||
if status.Code(err) != codes.NotFound {
|
||||
t.Errorf("expected NotFound code, got %v", status.Code(err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"hash/fnv"
|
||||
)
|
||||
|
||||
// SeedPeer is a mount server present in the filer's mount registry.
|
||||
// DataCenter and Rack ride along so downstream locality-aware decisions
|
||||
// (peer re-ranking in the fetcher) don't have to re-query the filer.
|
||||
type SeedPeer struct {
|
||||
PeerAddr string
|
||||
DataCenter string
|
||||
Rack string
|
||||
}
|
||||
|
||||
// OwnerFor returns the peer_addr of the mount that is the HRW-assigned
|
||||
// directory owner for fid on the given seed list.
|
||||
//
|
||||
// Rendezvous (highest-random-weight) hashing is deterministic for a given
|
||||
// (fid, seed set): every mount computes the same owner without any
|
||||
// consensus. When a mount joins or leaves the seed set, only 1/N of fids
|
||||
// change owner — the rest remain on their existing mount.
|
||||
//
|
||||
// If seeds is empty, returns "".
|
||||
//
|
||||
// See design-weed-mount-peer-chunk-sharing.md §4.2.2.
|
||||
func OwnerFor(fid string, seeds []SeedPeer) string {
|
||||
if len(seeds) == 0 {
|
||||
return ""
|
||||
}
|
||||
var bestScore uint64
|
||||
var bestAddr string
|
||||
for _, s := range seeds {
|
||||
score := hrwScore(s.PeerAddr, fid)
|
||||
if bestAddr == "" || score > bestScore || (score == bestScore && s.PeerAddr < bestAddr) {
|
||||
bestScore = score
|
||||
bestAddr = s.PeerAddr
|
||||
}
|
||||
}
|
||||
return bestAddr
|
||||
}
|
||||
|
||||
// hrwScore combines peer_addr and fid into a 64-bit score. Uses FNV-1a
|
||||
// (cheap and fine for balancing; not a security primitive).
|
||||
func hrwScore(peerAddr, fid string) uint64 {
|
||||
h := fnv.New64a()
|
||||
_, _ = h.Write([]byte(peerAddr))
|
||||
_, _ = h.Write([]byte{0}) // separator so "ab" + "c" != "a" + "bc"
|
||||
_, _ = h.Write([]byte(fid))
|
||||
return h.Sum64()
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func mkSeeds(addrs ...string) []SeedPeer {
|
||||
out := make([]SeedPeer, len(addrs))
|
||||
for i, a := range addrs {
|
||||
out[i] = SeedPeer{PeerAddr: a}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestOwnerFor_EmptySeeds(t *testing.T) {
|
||||
if got := OwnerFor("3,01637037d6", nil); got != "" {
|
||||
t.Errorf("expected empty owner for empty seed list, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerFor_Deterministic(t *testing.T) {
|
||||
seeds := mkSeeds("a:1", "b:1", "c:1", "d:1")
|
||||
fid := "3,01637037d6"
|
||||
first := OwnerFor(fid, seeds)
|
||||
for i := 0; i < 100; i++ {
|
||||
if got := OwnerFor(fid, seeds); got != first {
|
||||
t.Fatalf("non-deterministic: iter %d got %q first %q", i, got, first)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerFor_DistributesEvenly(t *testing.T) {
|
||||
const N = 4
|
||||
seeds := mkSeeds("a:1", "b:1", "c:1", "d:1")
|
||||
counts := map[string]int{}
|
||||
for i := 0; i < 10000; i++ {
|
||||
fid := fmt.Sprintf("%d,%x", i, i*17)
|
||||
counts[OwnerFor(fid, seeds)]++
|
||||
}
|
||||
// Each seed should get roughly 25% (±10% slack for a 10k sample).
|
||||
for addr, c := range counts {
|
||||
ratio := float64(c) / 10000.0
|
||||
if ratio < 0.225 || ratio > 0.275 {
|
||||
t.Errorf("HRW distribution skewed: %s got %.3f", addr, ratio)
|
||||
}
|
||||
}
|
||||
if len(counts) != N {
|
||||
t.Errorf("expected %d distinct owners, got %d", N, len(counts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerFor_MinimalShuffleOnSeedChange(t *testing.T) {
|
||||
// Adding one seed should move ~1/(N+1) fids to the new seed and leave
|
||||
// the rest on their prior owners. Tolerance generous for a 10k sample.
|
||||
const trials = 10000
|
||||
before := mkSeeds("a:1", "b:1", "c:1")
|
||||
after := mkSeeds("a:1", "b:1", "c:1", "d:1")
|
||||
|
||||
moved := 0
|
||||
toNewSeed := 0
|
||||
for i := 0; i < trials; i++ {
|
||||
fid := fmt.Sprintf("%d,%x", i, i*31)
|
||||
pre := OwnerFor(fid, before)
|
||||
post := OwnerFor(fid, after)
|
||||
if pre != post {
|
||||
moved++
|
||||
if post == "d:1" {
|
||||
toNewSeed++
|
||||
}
|
||||
}
|
||||
}
|
||||
// Expected: ~1/4 = 25% of fids move, all to the new seed.
|
||||
ratio := float64(moved) / float64(trials)
|
||||
if ratio < 0.20 || ratio > 0.30 {
|
||||
t.Errorf("expected ~25%% fids to move on seed-add, got %.3f", ratio)
|
||||
}
|
||||
if moved != toNewSeed {
|
||||
t.Errorf("expected every moved fid to land on the new seed; moved=%d toNewSeed=%d", moved, toNewSeed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerFor_TieBreakerDeterministic(t *testing.T) {
|
||||
// Two seeds with equal hash score (engineered collision is unlikely in
|
||||
// practice, but we guarantee determinism by lex-comparing addresses).
|
||||
// This test just confirms OwnerFor runs without panicking on duplicates.
|
||||
seeds := mkSeeds("a:1", "a:1", "b:1")
|
||||
fid := "3,01637037d6"
|
||||
_ = OwnerFor(fid, seeds)
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// PeerRegistrar maintains this mount's presence in every configured
|
||||
// filer's mount registry and its local snapshot of the merged seed set.
|
||||
// It runs two background tickers:
|
||||
//
|
||||
// - MountRegister heartbeats, fanned out to every filer in parallel so
|
||||
// each filer keeps a fresh TTL entry for us. Mounts pointing at
|
||||
// different filers therefore still see each other once all filers
|
||||
// have been heartbeated.
|
||||
// - MountList polling, fanned out identically, merged by peer_addr
|
||||
// (newest LastSeenNs wins) so OwnerFor() has a view of the whole
|
||||
// fleet regardless of which filer each peer happens to heartbeat
|
||||
// through.
|
||||
//
|
||||
// An unreachable filer is tolerated: we log and continue as long as at
|
||||
// least one filer succeeds. Entries cached on a permanently-gone filer
|
||||
// fall out of the merged view on their own TTL.
|
||||
type PeerRegistrar struct {
|
||||
filerAddrs []pb.ServerAddress
|
||||
dialFiler filerDialFn
|
||||
selfPeerAddr string
|
||||
selfDc string
|
||||
selfRack string
|
||||
registerInterval time.Duration
|
||||
registerTTL time.Duration
|
||||
listInterval time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
seeds []SeedPeer
|
||||
|
||||
// stopCtx cancels when Stop() is called. Background RPCs scope their
|
||||
// deadline to this so unmount does not block on pending filer calls.
|
||||
stopCtx context.Context
|
||||
stopCancel context.CancelFunc
|
||||
stopped atomic.Bool
|
||||
}
|
||||
|
||||
// filerDialFn is how the registrar reaches one configured filer. The
|
||||
// production wiring is pb.WithGrpcFilerClient; tests inject a fake.
|
||||
type filerDialFn func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error
|
||||
|
||||
// NewPeerRegistrar constructs the registrar; Start launches the background
|
||||
// loops. Callers must supply the full filer set so heartbeats and list
|
||||
// polls reach every filer — otherwise mounts talking to different filers
|
||||
// never observe each other.
|
||||
func NewPeerRegistrar(filers []pb.ServerAddress, dial filerDialFn, selfAddr, dc, rack string) *PeerRegistrar {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &PeerRegistrar{
|
||||
filerAddrs: filers,
|
||||
dialFiler: dial,
|
||||
selfPeerAddr: selfAddr,
|
||||
selfRack: rack,
|
||||
selfDc: dc,
|
||||
registerInterval: 30 * time.Second,
|
||||
registerTTL: 90 * time.Second,
|
||||
listInterval: 30 * time.Second,
|
||||
stopCtx: ctx,
|
||||
stopCancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// Start does an initial register+list synchronously (so OwnerFor has a
|
||||
// usable view immediately) and then kicks off the background loops.
|
||||
func (r *PeerRegistrar) Start(ctx context.Context) error {
|
||||
if err := r.registerOnce(ctx); err != nil {
|
||||
glog.V(1).Infof("initial MountRegister: %v", err)
|
||||
// Do not fail startup — the mount must still serve reads even if
|
||||
// no filer yet knows about us.
|
||||
}
|
||||
if err := r.listOnce(ctx); err != nil {
|
||||
glog.V(1).Infof("initial MountList: %v", err)
|
||||
}
|
||||
go r.loopRegister()
|
||||
go r.loopList()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop halts the background loops and cancels any in-flight RPCs they
|
||||
// may have launched. Safe to call multiple times.
|
||||
func (r *PeerRegistrar) Stop() {
|
||||
if r.stopped.Swap(true) {
|
||||
return
|
||||
}
|
||||
r.stopCancel()
|
||||
}
|
||||
|
||||
// Seeds returns the currently-known seed set. Callers MUST NOT mutate the
|
||||
// returned slice — it is shared with concurrent listOnce readers. Because
|
||||
// listOnce atomically swaps to a brand-new slice on every refresh rather
|
||||
// than mutating in place, returning the slice header directly is safe and
|
||||
// avoids a per-call allocation on the read-hot OwnerFor path.
|
||||
func (r *PeerRegistrar) Seeds() []SeedPeer {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.seeds
|
||||
}
|
||||
|
||||
// OwnerFor is a convenience wrapper that runs HRW against the current
|
||||
// seed snapshot.
|
||||
func (r *PeerRegistrar) OwnerFor(fid string) string {
|
||||
return OwnerFor(fid, r.Seeds())
|
||||
}
|
||||
|
||||
// filerRPCTimeout bounds a single MountRegister / MountList call so a slow
|
||||
// or partitioned filer can't wedge the background loops (which run on a
|
||||
// 30 s cadence). 20 s gives room for TLS handshakes on cold connections
|
||||
// while leaving headroom before the next tick.
|
||||
const filerRPCTimeout = 20 * time.Second
|
||||
|
||||
// registerOnce fans a MountRegister out to every configured filer in
|
||||
// parallel. Returns an error only if every filer failed; otherwise the
|
||||
// best-effort semantics let the mount proceed when some filer is down.
|
||||
func (r *PeerRegistrar) registerOnce(ctx context.Context) error {
|
||||
if len(r.filerAddrs) == 0 {
|
||||
return fmt.Errorf("no filers configured")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, filerRPCTimeout)
|
||||
defer cancel()
|
||||
req := &filer_pb.MountRegisterRequest{
|
||||
PeerAddr: r.selfPeerAddr,
|
||||
Rack: r.selfRack,
|
||||
DataCenter: r.selfDc,
|
||||
TtlSeconds: int32(r.registerTTL / time.Second),
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
var successes atomic.Int32
|
||||
for _, addr := range r.filerAddrs {
|
||||
wg.Add(1)
|
||||
go func(addr pb.ServerAddress) {
|
||||
defer wg.Done()
|
||||
err := r.dialFiler(ctx, addr, func(c filer_pb.SeaweedFilerClient) error {
|
||||
_, err := c.MountRegister(ctx, req)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(2).Infof("MountRegister %s: %v", addr, err)
|
||||
return
|
||||
}
|
||||
successes.Add(1)
|
||||
}(addr)
|
||||
}
|
||||
wg.Wait()
|
||||
if successes.Load() == 0 {
|
||||
return fmt.Errorf("MountRegister failed on all %d filer(s)", len(r.filerAddrs))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// listOnce polls MountList from every filer in parallel and merges the
|
||||
// responses by peer_addr (newest LastSeenNs wins). This way two mounts
|
||||
// heartbeating through different filers still end up in each other's
|
||||
// seed view as soon as at least one filer has been listed on each side.
|
||||
func (r *PeerRegistrar) listOnce(ctx context.Context) error {
|
||||
if len(r.filerAddrs) == 0 {
|
||||
r.mu.Lock()
|
||||
r.seeds = nil
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, filerRPCTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
mu sync.Mutex
|
||||
merged = map[string]*filer_pb.MountInfo{}
|
||||
fails int
|
||||
)
|
||||
var wg sync.WaitGroup
|
||||
for _, addr := range r.filerAddrs {
|
||||
wg.Add(1)
|
||||
go func(addr pb.ServerAddress) {
|
||||
defer wg.Done()
|
||||
err := r.dialFiler(ctx, addr, func(c filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := c.MountList(ctx, &filer_pb.MountListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mu.Lock()
|
||||
for _, m := range resp.Mounts {
|
||||
if prev, ok := merged[m.PeerAddr]; !ok || m.LastSeenNs > prev.LastSeenNs {
|
||||
merged[m.PeerAddr] = m
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
fails++
|
||||
mu.Unlock()
|
||||
glog.V(2).Infof("MountList %s: %v", addr, err)
|
||||
}
|
||||
}(addr)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if fails == len(r.filerAddrs) {
|
||||
return fmt.Errorf("MountList failed on all %d filer(s)", len(r.filerAddrs))
|
||||
}
|
||||
|
||||
next := make([]SeedPeer, 0, len(merged))
|
||||
for _, m := range merged {
|
||||
next = append(next, SeedPeer{PeerAddr: m.PeerAddr, DataCenter: m.DataCenter, Rack: m.Rack})
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.seeds = next
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *PeerRegistrar) loopRegister() {
|
||||
t := time.NewTicker(r.registerInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.stopCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
if err := r.registerOnce(r.stopCtx); err != nil {
|
||||
glog.V(2).Infof("MountRegister heartbeat: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PeerRegistrar) loopList() {
|
||||
t := time.NewTicker(r.listInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.stopCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
if err := r.listOnce(r.stopCtx); err != nil {
|
||||
glog.V(2).Infof("MountList refresh: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// fakeFilerClient captures MountRegister/MountList calls and lets the test
|
||||
// pre-seed MountList responses. Implements just enough of
|
||||
// filer_pb.SeaweedFilerClient to drive the registrar.
|
||||
type fakeFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient // embed for methods we don't need
|
||||
|
||||
mu sync.Mutex
|
||||
registerCalls []filer_pb.MountRegisterRequest
|
||||
listResponse filer_pb.MountListResponse
|
||||
}
|
||||
|
||||
func (f *fakeFilerClient) MountRegister(ctx context.Context, req *filer_pb.MountRegisterRequest, opts ...grpc.CallOption) (*filer_pb.MountRegisterResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.registerCalls = append(f.registerCalls, *req)
|
||||
return &filer_pb.MountRegisterResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeFilerClient) MountList(ctx context.Context, req *filer_pb.MountListRequest, opts ...grpc.CallOption) (*filer_pb.MountListResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
resp := f.listResponse // value copy
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// fakeFilerFleet maps each addr to its own fakeFilerClient so a test can
|
||||
// simulate several filers with different registered/listed state.
|
||||
type fakeFilerFleet struct {
|
||||
clients map[pb.ServerAddress]*fakeFilerClient
|
||||
}
|
||||
|
||||
func (f *fakeFilerFleet) dial(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error {
|
||||
c, ok := f.clients[addr]
|
||||
if !ok {
|
||||
// Treat unknown filer as "reachable but empty" — lets tests omit
|
||||
// pre-populating a client when they don't care.
|
||||
c = &fakeFilerClient{}
|
||||
f.clients[addr] = c
|
||||
}
|
||||
return fn(c)
|
||||
}
|
||||
|
||||
func singleFilerFleet(c *fakeFilerClient) ([]pb.ServerAddress, filerDialFn) {
|
||||
addr := pb.ServerAddress("filer-1:18888")
|
||||
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{addr: c}}
|
||||
return []pb.ServerAddress{addr}, fleet.dial
|
||||
}
|
||||
|
||||
func TestPeerRegistrar_StartPopulatesSeedsFromFiler(t *testing.T) {
|
||||
fc := &fakeFilerClient{
|
||||
listResponse: filer_pb.MountListResponse{
|
||||
Mounts: []*filer_pb.MountInfo{
|
||||
{PeerAddr: "mount-a:18080", Rack: "r1"},
|
||||
{PeerAddr: "mount-b:18080", Rack: "r2"},
|
||||
},
|
||||
},
|
||||
}
|
||||
filers, dial := singleFilerFleet(fc)
|
||||
|
||||
r := NewPeerRegistrar(filers, dial, "self:18080", "dc1", "r1")
|
||||
if err := r.registerOnce(context.Background()); err != nil {
|
||||
t.Fatalf("registerOnce: %v", err)
|
||||
}
|
||||
if err := r.listOnce(context.Background()); err != nil {
|
||||
t.Fatalf("listOnce: %v", err)
|
||||
}
|
||||
|
||||
fc.mu.Lock()
|
||||
if len(fc.registerCalls) != 1 {
|
||||
t.Errorf("expected 1 register call, got %d", len(fc.registerCalls))
|
||||
} else if fc.registerCalls[0].PeerAddr != "self:18080" {
|
||||
t.Errorf("register sent wrong peer addr: %q", fc.registerCalls[0].PeerAddr)
|
||||
}
|
||||
fc.mu.Unlock()
|
||||
|
||||
seeds := r.Seeds()
|
||||
if len(seeds) != 2 {
|
||||
t.Errorf("expected 2 seeds, got %d", len(seeds))
|
||||
}
|
||||
|
||||
owner := r.OwnerFor("3,01637037d6")
|
||||
if owner != "mount-a:18080" && owner != "mount-b:18080" {
|
||||
t.Errorf("OwnerFor returned unexpected addr: %q", owner)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerRegistrar_HeartbeatTTLMatchesConfig(t *testing.T) {
|
||||
fc := &fakeFilerClient{}
|
||||
filers, dial := singleFilerFleet(fc)
|
||||
r := NewPeerRegistrar(filers, dial, "self:18080", "", "")
|
||||
|
||||
if err := r.registerOnce(context.Background()); err != nil {
|
||||
t.Fatalf("registerOnce: %v", err)
|
||||
}
|
||||
|
||||
fc.mu.Lock()
|
||||
defer fc.mu.Unlock()
|
||||
if len(fc.registerCalls) != 1 {
|
||||
t.Fatalf("expected 1 register call, got %d", len(fc.registerCalls))
|
||||
}
|
||||
want := int32(r.registerTTL.Seconds())
|
||||
if got := fc.registerCalls[0].TtlSeconds; got != want {
|
||||
t.Errorf("TtlSeconds: got %d want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerRegistrar_StopIsIdempotent(t *testing.T) {
|
||||
filers, dial := singleFilerFleet(&fakeFilerClient{})
|
||||
r := NewPeerRegistrar(filers, dial, "self:18080", "", "")
|
||||
r.Stop()
|
||||
r.Stop() // second call must be a no-op (no panic)
|
||||
}
|
||||
|
||||
// TestPeerRegistrar_RegisterBroadcastsToAllFilers guards the core
|
||||
// multi-filer property: a single registerOnce must hit every configured
|
||||
// filer so mounts pointing at different filers still converge.
|
||||
func TestPeerRegistrar_RegisterBroadcastsToAllFilers(t *testing.T) {
|
||||
fc1 := &fakeFilerClient{}
|
||||
fc2 := &fakeFilerClient{}
|
||||
fc3 := &fakeFilerClient{}
|
||||
a1, a2, a3 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888"), pb.ServerAddress("f3:18888")
|
||||
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2, a3: fc3}}
|
||||
|
||||
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2, a3}, fleet.dial, "self:18080", "", "")
|
||||
if err := r.registerOnce(context.Background()); err != nil {
|
||||
t.Fatalf("registerOnce: %v", err)
|
||||
}
|
||||
|
||||
for addr, fc := range fleet.clients {
|
||||
fc.mu.Lock()
|
||||
if len(fc.registerCalls) != 1 {
|
||||
t.Errorf("filer %s: got %d register calls, want 1", addr, len(fc.registerCalls))
|
||||
}
|
||||
fc.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerRegistrar_ListMergesAcrossFilers guards cross-filer convergence:
|
||||
// mount A registered on filer-1, mount B on filer-2; a registrar that
|
||||
// lists both filers must see both mounts.
|
||||
func TestPeerRegistrar_ListMergesAcrossFilers(t *testing.T) {
|
||||
fc1 := &fakeFilerClient{
|
||||
listResponse: filer_pb.MountListResponse{
|
||||
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 200}},
|
||||
},
|
||||
}
|
||||
fc2 := &fakeFilerClient{
|
||||
listResponse: filer_pb.MountListResponse{
|
||||
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-b:18080", Rack: "r2", LastSeenNs: 200}},
|
||||
},
|
||||
}
|
||||
a1, a2 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888")
|
||||
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2}}
|
||||
|
||||
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2}, fleet.dial, "self:18080", "", "")
|
||||
if err := r.listOnce(context.Background()); err != nil {
|
||||
t.Fatalf("listOnce: %v", err)
|
||||
}
|
||||
|
||||
seeds := r.Seeds()
|
||||
if len(seeds) != 2 {
|
||||
t.Fatalf("want 2 merged seeds, got %d: %+v", len(seeds), seeds)
|
||||
}
|
||||
addrs := map[string]bool{}
|
||||
for _, s := range seeds {
|
||||
addrs[s.PeerAddr] = true
|
||||
}
|
||||
if !addrs["mount-a:18080"] || !addrs["mount-b:18080"] {
|
||||
t.Errorf("merged seeds missing an entry: %+v", addrs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPeerRegistrar_ListMergeKeepsNewestLastSeen guards the dedupe rule:
|
||||
// the same mount reported by two filers collapses to one entry, keeping
|
||||
// the freshest LastSeenNs for liveness-ordering decisions.
|
||||
func TestPeerRegistrar_ListMergeKeepsNewestLastSeen(t *testing.T) {
|
||||
fc1 := &fakeFilerClient{
|
||||
listResponse: filer_pb.MountListResponse{
|
||||
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 100}},
|
||||
},
|
||||
}
|
||||
fc2 := &fakeFilerClient{
|
||||
listResponse: filer_pb.MountListResponse{
|
||||
Mounts: []*filer_pb.MountInfo{{PeerAddr: "mount-a:18080", Rack: "r1", LastSeenNs: 500}},
|
||||
},
|
||||
}
|
||||
a1, a2 := pb.ServerAddress("f1:18888"), pb.ServerAddress("f2:18888")
|
||||
fleet := &fakeFilerFleet{clients: map[pb.ServerAddress]*fakeFilerClient{a1: fc1, a2: fc2}}
|
||||
|
||||
r := NewPeerRegistrar([]pb.ServerAddress{a1, a2}, fleet.dial, "self:18080", "", "")
|
||||
if err := r.listOnce(context.Background()); err != nil {
|
||||
t.Fatalf("listOnce: %v", err)
|
||||
}
|
||||
seeds := r.Seeds()
|
||||
if len(seeds) != 1 {
|
||||
t.Fatalf("want 1 deduped seed, got %d", len(seeds))
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,12 @@ type inodeLocks struct {
|
||||
locks []lockRange // currently held locks, sorted by Start
|
||||
waiters []*lockWaiter // blocked SetLkw callers
|
||||
wakeRefs int // woken waiters still retrying on this inodeLocks
|
||||
// dead marks an inodeLocks that has been removed from the table's map.
|
||||
// A caller holding a pointer returned by getInodeLocks/getOrCreateInodeLocks
|
||||
// must recheck this flag after acquiring il.mu: if true, the pointer is
|
||||
// orphaned and must be refreshed from the table so findConflict runs
|
||||
// against the live state.
|
||||
dead bool
|
||||
}
|
||||
|
||||
// lockWaiter represents a blocked SetLkw caller.
|
||||
@@ -48,12 +54,17 @@ func NewPosixLockTable() *PosixLockTable {
|
||||
}
|
||||
}
|
||||
|
||||
// getOrCreateInodeLocks returns the lock state for an inode, creating it if needed.
|
||||
// getOrCreateInodeLocks returns the lock state for an inode, creating it if
|
||||
// needed. A dead entry (which maybeCleanupInode normally evicts together
|
||||
// with setting dead) is replaced transparently so callers never observe one
|
||||
// via this path and the SetLk retry loop cannot spin on a stale map entry.
|
||||
// The il.dead read is safe without il.mu: dead transitions only under both
|
||||
// plt.mu and il.mu, so holding plt.mu here is sufficient happens-before.
|
||||
func (plt *PosixLockTable) getOrCreateInodeLocks(inode uint64) *inodeLocks {
|
||||
plt.mu.Lock()
|
||||
defer plt.mu.Unlock()
|
||||
il, ok := plt.inodes[inode]
|
||||
if !ok {
|
||||
if !ok || il.dead {
|
||||
il = &inodeLocks{}
|
||||
plt.inodes[inode] = il
|
||||
}
|
||||
@@ -61,14 +72,29 @@ func (plt *PosixLockTable) getOrCreateInodeLocks(inode uint64) *inodeLocks {
|
||||
}
|
||||
|
||||
// getInodeLocks returns the lock state for an inode, or nil if none exists.
|
||||
// A dead entry (which maybeCleanupInode normally evicts together with setting
|
||||
// dead) is dropped so callers never observe an orphaned inodeLocks via this
|
||||
// path. The il.dead read is safe without il.mu for the same reason as in
|
||||
// getOrCreateInodeLocks: transitions happen under both plt.mu and il.mu.
|
||||
func (plt *PosixLockTable) getInodeLocks(inode uint64) *inodeLocks {
|
||||
plt.mu.Lock()
|
||||
defer plt.mu.Unlock()
|
||||
return plt.inodes[inode]
|
||||
il, ok := plt.inodes[inode]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if il.dead {
|
||||
delete(plt.inodes, inode)
|
||||
return nil
|
||||
}
|
||||
return il
|
||||
}
|
||||
|
||||
// maybeCleanupInode removes the inodeLocks entry if it has no locks, no waiters,
|
||||
// and no woken waiters still retrying against this inodeLocks.
|
||||
// and no woken waiters still retrying against this inodeLocks. The removed
|
||||
// inodeLocks is marked dead so any caller that is mid-way through acquiring
|
||||
// il.mu with a stale pointer will notice and refetch from the map instead of
|
||||
// mutating an orphaned instance (which would be invisible to future callers).
|
||||
func (plt *PosixLockTable) maybeCleanupInode(inode uint64, il *inodeLocks) {
|
||||
// Caller must NOT hold il.mu. We acquire both locks in the correct order.
|
||||
plt.mu.Lock()
|
||||
@@ -76,7 +102,10 @@ func (plt *PosixLockTable) maybeCleanupInode(inode uint64, il *inodeLocks) {
|
||||
il.mu.Lock()
|
||||
defer il.mu.Unlock()
|
||||
if len(il.locks) == 0 && len(il.waiters) == 0 && il.wakeRefs == 0 {
|
||||
delete(plt.inodes, inode)
|
||||
if plt.inodes[inode] == il {
|
||||
delete(plt.inodes, inode)
|
||||
}
|
||||
il.dead = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,22 +276,32 @@ func removeWaiter(il *inodeLocks, w *lockWaiter) {
|
||||
// GetLk checks for a conflicting lock. If found, it populates out with the
|
||||
// conflict details. If no conflict, out.Typ is set to F_UNLCK.
|
||||
func (plt *PosixLockTable) GetLk(inode uint64, proposed lockRange, out *fuse.LkOut) {
|
||||
il := plt.getInodeLocks(inode)
|
||||
if il == nil {
|
||||
out.Lk.Typ = syscall.F_UNLCK
|
||||
return
|
||||
}
|
||||
il.mu.Lock()
|
||||
conflict, found := findConflict(il.locks, proposed)
|
||||
il.mu.Unlock()
|
||||
for {
|
||||
il := plt.getInodeLocks(inode)
|
||||
if il == nil {
|
||||
out.Lk.Typ = syscall.F_UNLCK
|
||||
return
|
||||
}
|
||||
il.mu.Lock()
|
||||
if il.dead {
|
||||
// Orphaned by a concurrent cleanup: the map may already hold a
|
||||
// fresh inodeLocks with different state, so answering from this
|
||||
// stale pointer would miss real conflicts. Refetch.
|
||||
il.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
conflict, found := findConflict(il.locks, proposed)
|
||||
il.mu.Unlock()
|
||||
|
||||
if found {
|
||||
out.Lk.Start = conflict.Start
|
||||
out.Lk.End = conflict.End
|
||||
out.Lk.Typ = conflict.Typ
|
||||
out.Lk.Pid = conflict.Pid
|
||||
} else {
|
||||
out.Lk.Typ = syscall.F_UNLCK
|
||||
if found {
|
||||
out.Lk.Start = conflict.Start
|
||||
out.Lk.End = conflict.End
|
||||
out.Lk.Typ = conflict.Typ
|
||||
out.Lk.Pid = conflict.Pid
|
||||
} else {
|
||||
out.Lk.Typ = syscall.F_UNLCK
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +315,13 @@ func (plt *PosixLockTable) SetLk(inode uint64, lk lockRange) fuse.Status {
|
||||
return fuse.OK
|
||||
}
|
||||
il.mu.Lock()
|
||||
if il.dead {
|
||||
// Orphaned by a concurrent cleanup: any lock we may have held
|
||||
// is gone with it, and there is no point waking waiters on a
|
||||
// detached inodeLocks.
|
||||
il.mu.Unlock()
|
||||
return fuse.OK
|
||||
}
|
||||
removeLocks(il, func(existing lockRange) bool {
|
||||
return existing.Owner == lk.Owner && existing.IsFlock == lk.IsFlock
|
||||
}, lk.Start, lk.End)
|
||||
@@ -285,15 +331,21 @@ func (plt *PosixLockTable) SetLk(inode uint64, lk lockRange) fuse.Status {
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
il := plt.getOrCreateInodeLocks(inode)
|
||||
il.mu.Lock()
|
||||
if _, found := findConflict(il.locks, lk); found {
|
||||
for {
|
||||
il := plt.getOrCreateInodeLocks(inode)
|
||||
il.mu.Lock()
|
||||
if il.dead {
|
||||
il.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
if _, found := findConflict(il.locks, lk); found {
|
||||
il.mu.Unlock()
|
||||
return fuse.EAGAIN
|
||||
}
|
||||
insertAndCoalesce(il, lk)
|
||||
il.mu.Unlock()
|
||||
return fuse.EAGAIN
|
||||
return fuse.OK
|
||||
}
|
||||
insertAndCoalesce(il, lk)
|
||||
il.mu.Unlock()
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
// SetLkw attempts a blocking lock. It waits until the lock can be acquired
|
||||
@@ -307,6 +359,15 @@ func (plt *PosixLockTable) SetLkw(inode uint64, lk lockRange, cancel <-chan stru
|
||||
var waiter *lockWaiter
|
||||
for {
|
||||
il.mu.Lock()
|
||||
if il.dead {
|
||||
// The inodeLocks we were holding was orphaned by a concurrent
|
||||
// cleanup. Refetch the live instance from the table and retry.
|
||||
// A dead il never has waiters or wakeRefs (the cleanup condition
|
||||
// requires both to be zero), so waiter is guaranteed nil here.
|
||||
il.mu.Unlock()
|
||||
il = plt.getOrCreateInodeLocks(inode)
|
||||
continue
|
||||
}
|
||||
releaseWakeRef(il, waiter)
|
||||
if _, found := findConflict(il.locks, lk); !found {
|
||||
insertAndCoalesce(il, lk)
|
||||
|
||||
@@ -2,6 +2,9 @@ package mount
|
||||
|
||||
import (
|
||||
"math"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -615,3 +618,207 @@ func TestAdjacencyNoOverflowAtMaxUint64(t *testing.T) {
|
||||
t.Fatalf("expected 2 separate locks (no overflow merge), got %d", ownerLocks)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetLkRetriesPastDeadInodeLocks deterministically exercises the
|
||||
// getOrCreateInodeLocks vs maybeCleanupInode race: a caller holding a
|
||||
// pointer to an inodeLocks that is concurrently marked dead must refetch
|
||||
// from the map instead of mutating the orphaned instance (which would be
|
||||
// invisible to subsequent callers and let two exclusive flock holders
|
||||
// coexist). The test bypasses scheduling by hand-installing a dead il into
|
||||
// the table and asserting that the next SetLk routes around it.
|
||||
func TestSetLkRetriesPastDeadInodeLocks(t *testing.T) {
|
||||
plt := NewPosixLockTable()
|
||||
inode := uint64(42)
|
||||
|
||||
// Acquire and release a lock so maybeCleanupInode marks the il dead and
|
||||
// removes it from the map.
|
||||
lock := lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 1, IsFlock: true}
|
||||
if s := plt.SetLk(inode, lock); s != fuse.OK {
|
||||
t.Fatalf("prime SetLk: got %v", s)
|
||||
}
|
||||
dead := plt.getInodeLocks(inode)
|
||||
unlock := lock
|
||||
unlock.Typ = syscall.F_UNLCK
|
||||
if s := plt.SetLk(inode, unlock); s != fuse.OK {
|
||||
t.Fatalf("prime unlock: got %v", s)
|
||||
}
|
||||
if !dead.dead {
|
||||
t.Fatal("expected il to be marked dead after unlock+cleanup")
|
||||
}
|
||||
plt.mu.Lock()
|
||||
_, stillMapped := plt.inodes[inode]
|
||||
plt.mu.Unlock()
|
||||
if stillMapped {
|
||||
t.Fatal("expected the dead il to be removed from the map")
|
||||
}
|
||||
|
||||
// Simulate the race: the next caller's getOrCreateInodeLocks races with
|
||||
// the cleanup and ends up holding a pointer to the dead il. We force that
|
||||
// state by re-publishing `dead` into the map.
|
||||
plt.mu.Lock()
|
||||
plt.inodes[inode] = dead
|
||||
plt.mu.Unlock()
|
||||
|
||||
// SetLk must notice dead, refetch, and install the new lock in a fresh il.
|
||||
if s := plt.SetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 2, IsFlock: true}); s != fuse.OK {
|
||||
t.Fatalf("SetLk after dead: got %v", s)
|
||||
}
|
||||
|
||||
dead.mu.Lock()
|
||||
if n := len(dead.locks); n != 0 {
|
||||
t.Fatalf("dead il should not have accepted the insert, found %d locks", n)
|
||||
}
|
||||
dead.mu.Unlock()
|
||||
|
||||
plt.mu.Lock()
|
||||
live := plt.inodes[inode]
|
||||
plt.mu.Unlock()
|
||||
if live == nil || live == dead {
|
||||
t.Fatalf("expected a fresh live il, got %v", live)
|
||||
}
|
||||
|
||||
// A conflicting owner must see the new lock and be rejected.
|
||||
if s := plt.SetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 3, IsFlock: true}); s != fuse.EAGAIN {
|
||||
t.Fatalf("second owner should conflict with owner 2, got %v", s)
|
||||
}
|
||||
|
||||
// GetLk must report the conflict as well: without the dead-recheck the
|
||||
// GetLk path would answer F_UNLCK off the orphaned il.
|
||||
var out fuse.LkOut
|
||||
plt.GetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 4, IsFlock: true}, &out)
|
||||
if out.Lk.Typ != syscall.F_WRLCK {
|
||||
t.Fatalf("GetLk should report the live conflict, got Typ=%d", out.Lk.Typ)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetInodeLocksEvictsDeadEntry verifies that a dead inodeLocks which
|
||||
// somehow ends up in the map (e.g. through a future refactor that reorders
|
||||
// delete and dead=true) is dropped on read so callers never observe one.
|
||||
// This is the backstop that lets GetLk's and SetLk's retry loops terminate.
|
||||
func TestGetInodeLocksEvictsDeadEntry(t *testing.T) {
|
||||
plt := NewPosixLockTable()
|
||||
inode := uint64(42)
|
||||
|
||||
lock := lockRange{Start: 0, End: math.MaxUint64, Typ: syscall.F_WRLCK, Owner: 1, IsFlock: true}
|
||||
if s := plt.SetLk(inode, lock); s != fuse.OK {
|
||||
t.Fatalf("prime SetLk: got %v", s)
|
||||
}
|
||||
dead := plt.getInodeLocks(inode)
|
||||
unlock := lock
|
||||
unlock.Typ = syscall.F_UNLCK
|
||||
if s := plt.SetLk(inode, unlock); s != fuse.OK {
|
||||
t.Fatalf("prime unlock: got %v", s)
|
||||
}
|
||||
if !dead.dead {
|
||||
t.Fatal("expected dead after cleanup")
|
||||
}
|
||||
|
||||
// Force the broken state that production cannot reach but tests and
|
||||
// future refactors might: dead entry still in the map.
|
||||
plt.mu.Lock()
|
||||
plt.inodes[inode] = dead
|
||||
plt.mu.Unlock()
|
||||
|
||||
if il := plt.getInodeLocks(inode); il != nil {
|
||||
t.Fatalf("getInodeLocks should drop a dead map entry, got %p", il)
|
||||
}
|
||||
plt.mu.Lock()
|
||||
_, stillMapped := plt.inodes[inode]
|
||||
plt.mu.Unlock()
|
||||
if stillMapped {
|
||||
t.Fatal("expected dead entry to be removed from the map")
|
||||
}
|
||||
|
||||
// getOrCreateInodeLocks must also self-heal (replace the dead entry with
|
||||
// a fresh live one) so SetLk's retry path cannot spin.
|
||||
plt.mu.Lock()
|
||||
plt.inodes[inode] = dead
|
||||
plt.mu.Unlock()
|
||||
fresh := plt.getOrCreateInodeLocks(inode)
|
||||
if fresh == dead {
|
||||
t.Fatal("getOrCreateInodeLocks should not return a dead entry")
|
||||
}
|
||||
if fresh.dead {
|
||||
t.Fatal("fresh entry should not be dead")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentFlockChurnPreservesMutualExclusion is a stress companion to
|
||||
// the deterministic tests above. It uses a Swap+CAS detector that flags
|
||||
// overlap at two points (on acquire and on release), so a second granted
|
||||
// holder is caught even if it sneaks in after the first goroutine's claim
|
||||
// but before its release. 16 goroutines churn whole-file exclusive flock on
|
||||
// one inode; with the race the detector fires hundreds of times per run,
|
||||
// with the fix it stays at zero.
|
||||
func TestConcurrentFlockChurnPreservesMutualExclusion(t *testing.T) {
|
||||
plt := NewPosixLockTable()
|
||||
const (
|
||||
inode = uint64(42)
|
||||
numWorkers = 16
|
||||
iterations = 500
|
||||
)
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
holder atomic.Int64 // 0 = nobody; otherwise = holder's claim token
|
||||
overlapSeen atomic.Int32
|
||||
)
|
||||
|
||||
for w := 0; w < numWorkers; w++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
owner := uint64(100 + id)
|
||||
lock := lockRange{
|
||||
Start: 0,
|
||||
End: math.MaxUint64,
|
||||
Typ: syscall.F_WRLCK,
|
||||
Owner: owner,
|
||||
Pid: uint32(id + 1),
|
||||
IsFlock: true,
|
||||
}
|
||||
unlock := lock
|
||||
unlock.Typ = syscall.F_UNLCK
|
||||
token := int64(id + 1)
|
||||
for i := 0; i < iterations; i++ {
|
||||
// SetLk(WRLCK) may only return OK (granted) or EAGAIN
|
||||
// (conflict); anything else indicates a bug and the test
|
||||
// must fail rather than spin. Use Errorf + return because
|
||||
// Fatalf is not safe from a non-test goroutine.
|
||||
for {
|
||||
s := plt.SetLk(inode, lock)
|
||||
if s == fuse.OK {
|
||||
break
|
||||
}
|
||||
if s != fuse.EAGAIN {
|
||||
t.Errorf("worker %d iter %d: unexpected SetLk(WRLCK) status %v", id, i, s)
|
||||
return
|
||||
}
|
||||
runtime.Gosched()
|
||||
}
|
||||
// Claim the slot. If Swap observes a non-zero predecessor,
|
||||
// another goroutine already believes it holds the lock.
|
||||
if prev := holder.Swap(token); prev != 0 {
|
||||
overlapSeen.Add(1)
|
||||
}
|
||||
// Widen the window so a concurrently-granted peer has a
|
||||
// chance to race into its own Swap before we release.
|
||||
runtime.Gosched()
|
||||
runtime.Gosched()
|
||||
// Release the slot. If CAS fails someone else overwrote our
|
||||
// claim, which only happens when two holders raced.
|
||||
if !holder.CompareAndSwap(token, 0) {
|
||||
overlapSeen.Add(1)
|
||||
}
|
||||
if s := plt.SetLk(inode, unlock); s != fuse.OK {
|
||||
t.Errorf("worker %d iter %d: unexpected SetLk(UNLCK) status %v", id, i, s)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if n := overlapSeen.Load(); n != 0 {
|
||||
t.Fatalf("flock overlap detected %d times: two owners simultaneously granted the same exclusive lock", n)
|
||||
}
|
||||
}
|
||||
+129
-6
@@ -82,6 +82,16 @@ type Option struct {
|
||||
RdmaMaxConcurrent int
|
||||
RdmaTimeoutMs int
|
||||
|
||||
// Peer chunk sharing options (design-weed-mount-peer-chunk-sharing.md).
|
||||
// When PeerEnabled is false (default), the mount runs exactly as today.
|
||||
// One gRPC port carries everything: directory RPCs (ChunkAnnounce /
|
||||
// ChunkLookup) and streaming FetchChunk byte transfers.
|
||||
PeerEnabled bool
|
||||
PeerListen string // host:port to bind the peer gRPC server
|
||||
PeerAdvertise string // externally reachable host:port (optional; defaults to auto-detected host + PeerListen port)
|
||||
PeerDataCenter string // optional data-center label advertised to peers
|
||||
PeerRack string // optional rack label advertised to peers (finer than DC)
|
||||
|
||||
// Directory cache refresh/eviction controls
|
||||
DirIdleEvictSec int
|
||||
|
||||
@@ -129,6 +139,12 @@ type WFS struct {
|
||||
hardLinkLockTable *util.LockTable[string]
|
||||
posixLocks *PosixLockTable
|
||||
rdmaClient *RDMAMountClient
|
||||
peerRegistrar *PeerRegistrar
|
||||
peerDirectory *PeerDirectory
|
||||
peerGrpcServer *PeerGrpcServer
|
||||
peerAnnouncer *PeerAnnouncer
|
||||
peerConnPool *PeerConnPool
|
||||
peerDirectoryStop chan struct{} // closed on unmount to stop the sweeper goroutine
|
||||
FilerConf *filer.FilerConf
|
||||
filerClient *wdclient.FilerClient // Cached volume location client
|
||||
refreshMu sync.Mutex
|
||||
@@ -142,7 +158,14 @@ type WFS struct {
|
||||
dirHotWindow time.Duration
|
||||
dirHotThreshold int
|
||||
dirIdleEvict time.Duration
|
||||
fileIdPool *FileIdPool
|
||||
|
||||
// openMtimeCache maps inode -> [mtime_sec, mtime_ns] from the last Open.
|
||||
// Used to decide whether to set FOPEN_KEEP_CACHE on subsequent opens.
|
||||
// Bounded to openMtimeCacheMaxSize entries; when full a random entry is
|
||||
// evicted. This trades a small amount of cache-miss overhead for
|
||||
// predictable memory usage on mounts that touch many files.
|
||||
openMtimeMu sync.Mutex
|
||||
openMtimeCache map[uint64][2]int64
|
||||
|
||||
// asyncFlushWg tracks pending background flush work items for writebackCache mode.
|
||||
// Must be waited on before unmount cleanup to prevent data loss.
|
||||
@@ -221,6 +244,7 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
posixLocks: NewPosixLockTable(),
|
||||
refreshingDirs: make(map[util.FullPath]struct{}),
|
||||
atimeMap: make(map[uint64]time.Time, 8192),
|
||||
openMtimeCache: make(map[uint64][2]int64, 8192),
|
||||
dirMtimeMap: make(map[uint64]time.Time, 1024),
|
||||
entryValidSec: 1,
|
||||
attrValidSec: 1,
|
||||
@@ -318,6 +342,26 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
if wfs.rdmaClient != nil {
|
||||
wfs.rdmaClient.Close()
|
||||
}
|
||||
if wfs.peerAnnouncer != nil {
|
||||
wfs.peerAnnouncer.Stop()
|
||||
}
|
||||
if wfs.peerConnPool != nil {
|
||||
wfs.peerConnPool.Close()
|
||||
}
|
||||
if wfs.peerGrpcServer != nil {
|
||||
wfs.peerGrpcServer.Stop()
|
||||
}
|
||||
if wfs.peerDirectoryStop != nil {
|
||||
select {
|
||||
case <-wfs.peerDirectoryStop:
|
||||
// already closed
|
||||
default:
|
||||
close(wfs.peerDirectoryStop)
|
||||
}
|
||||
}
|
||||
if wfs.peerRegistrar != nil {
|
||||
wfs.peerRegistrar.Stop()
|
||||
}
|
||||
})
|
||||
|
||||
// Initialize RDMA client if enabled
|
||||
@@ -337,6 +381,90 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
}
|
||||
}
|
||||
|
||||
// Peer chunk sharing: register with every configured filer's mount
|
||||
// registry + start the single gRPC server that handles ChunkAnnounce /
|
||||
// ChunkLookup / FetchChunk. Broadcasting registration to the full
|
||||
// filer set is what lets mounts pointing at different filers see
|
||||
// each other — each filer's registry is in-memory with no
|
||||
// filer-to-filer sync, so the registrar reconstructs the union
|
||||
// client-side. One port, one identity — the advertise address
|
||||
// resolved in PR #3 is used for everything.
|
||||
if option.PeerEnabled {
|
||||
selfAddr, err := ResolvePeerAdvertiseAddr(option.PeerListen, option.PeerAdvertise)
|
||||
if err != nil {
|
||||
// Downstream code treats PeerEnabled as "peer infrastructure
|
||||
// is ready": later PRs wire the gRPC server, fetcher hook,
|
||||
// and announcer from this flag. If we can't resolve a
|
||||
// reachable self-address those components would nil-deref
|
||||
// or advertise garbage, so disable the feature instead of
|
||||
// limping along half-initialized.
|
||||
glog.Warningf("peer: cannot resolve advertise addr, disabling peer sharing: %v", err)
|
||||
option.PeerEnabled = false
|
||||
} else {
|
||||
dial := func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, fn)
|
||||
}
|
||||
wfs.peerRegistrar = NewPeerRegistrar(option.FilerAddresses, dial, selfAddr, option.PeerDataCenter, option.PeerRack)
|
||||
if err := wfs.peerRegistrar.Start(context.Background()); err != nil {
|
||||
glog.Warningf("peer registrar start: %v", err)
|
||||
}
|
||||
|
||||
wfs.peerDirectory = NewPeerDirectory()
|
||||
// Wire TLS/mTLS from security.toml's grpc.mount section so
|
||||
// cross-host peer RPCs are authenticated + encrypted. When
|
||||
// the section is empty both options come back nil and the
|
||||
// server runs plaintext — intentional for dev/test.
|
||||
peerTLSCreds, peerTLSVerify := security.LoadServerTLS(util.GetViper(), "grpc.mount")
|
||||
var peerServerOpts []grpc.ServerOption
|
||||
if peerTLSCreds != nil {
|
||||
peerServerOpts = append(peerServerOpts, peerTLSCreds)
|
||||
}
|
||||
if peerTLSVerify != nil {
|
||||
peerServerOpts = append(peerServerOpts, peerTLSVerify)
|
||||
}
|
||||
wfs.peerGrpcServer = NewPeerGrpcServer(
|
||||
wfs.chunkCache,
|
||||
wfs.peerDirectory,
|
||||
wfs.peerRegistrar.OwnerFor,
|
||||
selfAddr,
|
||||
peerServerOpts...,
|
||||
)
|
||||
if err := wfs.peerGrpcServer.Start(option.PeerListen); err != nil {
|
||||
glog.Warningf("peer grpc start: %v", err)
|
||||
wfs.peerGrpcServer = nil
|
||||
} else {
|
||||
wfs.peerDirectoryStop = make(chan struct{})
|
||||
go wfs.runPeerDirectorySweeper(wfs.peerDirectoryStop)
|
||||
|
||||
// Shared connection pool + announcer. Pool reuses one
|
||||
// grpc.ClientConn per owner mount across both the
|
||||
// announcer flush and the fetcher's ChunkLookup +
|
||||
// FetchChunk calls. Transport credentials come from
|
||||
// option.GrpcDialOption (security.LoadClientTLS), so
|
||||
// peer dials match the TLS posture the server wants.
|
||||
wfs.peerConnPool = NewPeerConnPool(option.GrpcDialOption)
|
||||
wfs.peerAnnouncer = NewPeerAnnouncer(
|
||||
selfAddr,
|
||||
option.PeerDataCenter,
|
||||
option.PeerRack,
|
||||
wfs.peerRegistrar.OwnerFor,
|
||||
wfs.peerConnPool.Dialer(),
|
||||
wfs.peerDirectory,
|
||||
)
|
||||
// Close the write→announce race: between SetChunk and
|
||||
// the flush tick (up to 15 s) the cache can LRU-evict
|
||||
// the chunk. Skip announcing fids we no longer hold.
|
||||
if wfs.chunkCache != nil {
|
||||
cache := wfs.chunkCache
|
||||
wfs.peerAnnouncer.SetCachePresence(func(fid string) bool {
|
||||
return cache.IsInCache(fid, true)
|
||||
})
|
||||
}
|
||||
wfs.peerAnnouncer.Start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if wfs.option.ConcurrentWriters > 0 {
|
||||
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(wfs.option.ConcurrentWriters)
|
||||
wfs.concurrentCopiersSem = make(chan struct{}, wfs.option.ConcurrentWriters)
|
||||
@@ -378,11 +506,6 @@ func (wfs *WFS) StartBackgroundTasks() error {
|
||||
go wfs.loopEvictIdleDirCache()
|
||||
go wfs.loopProactiveFlush()
|
||||
|
||||
if wfs.option.WritebackCache {
|
||||
wfs.fileIdPool = NewFileIdPool(wfs)
|
||||
glog.V(0).Infof("file ID pool enabled for writeback cache (batch=%d)", wfs.fileIdPool.batchSize)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,9 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse
|
||||
|
||||
if size, ok := input.GetSize(); ok {
|
||||
glog.V(4).Infof("%v setattr set size=%v chunks=%d", path, size, len(entry.GetChunks()))
|
||||
// Invalidate the open-mtime cache so the next Open does not set
|
||||
// FOPEN_KEEP_CACHE with stale kernel page cache data.
|
||||
wfs.invalidateOpenMtimeCache(input.NodeId)
|
||||
if size < filer.FileSize(entry) {
|
||||
// fmt.Printf("truncate %v \n", fullPath)
|
||||
var chunks []*filer_pb.FileChunk
|
||||
|
||||
@@ -251,7 +251,11 @@ func (wfs *WFS) applyServerSideWholeFileCopyResult(fhIn, fhOut *FileHandle, dstP
|
||||
}
|
||||
fhOut.dirtyMetadata = false
|
||||
wfs.updateServerSideWholeFileCopyMetaCache(dstPath, entry)
|
||||
wfs.invalidateCopyDestinationCache(fhOut.inode, dstPath)
|
||||
// Note: we intentionally skip fuseServer.InodeNotify/EntryNotify here.
|
||||
// This runs inside the CopyFileRange request handler; those notifies
|
||||
// would write onto the same /dev/fuse fd the kernel is still waiting
|
||||
// on for this request's reply, deadlocking the mount. The kernel will
|
||||
// re-read attrs once its attr-cache TTL expires.
|
||||
}
|
||||
|
||||
func (wfs *WFS) updateServerSideWholeFileCopyMetaCache(dstPath util.FullPath, entry *filer_pb.Entry) {
|
||||
@@ -501,16 +505,3 @@ func (wfs *WFS) filerCopyJWT() security.EncodedJwt {
|
||||
return security.GenJwtForFilerServer(wfs.option.FilerSigningKey, wfs.option.FilerSigningExpiresAfterSec)
|
||||
}
|
||||
|
||||
func (wfs *WFS) invalidateCopyDestinationCache(inode uint64, fullPath util.FullPath) {
|
||||
if wfs.fuseServer != nil {
|
||||
if status := wfs.fuseServer.InodeNotify(inode, 0, -1); status != fuse.OK {
|
||||
glog.V(4).Infof("CopyFileRange invalidate inode %d: %v", inode, status)
|
||||
}
|
||||
dir, name := fullPath.DirAndName()
|
||||
if parentInode, found := wfs.inodeToPath.GetInode(util.FullPath(dir)); found {
|
||||
if status := wfs.fuseServer.EntryNotify(parentInode, name); status != fuse.OK {
|
||||
glog.V(4).Infof("CopyFileRange invalidate entry %s: %v", fullPath, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,15 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
|
||||
if status == fuse.OK {
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
out.OpenFlags = 0
|
||||
// TODO https://github.com/libfuse/libfuse/blob/master/include/fuse_common.h#L64
|
||||
|
||||
// For read-only opens, set FOPEN_KEEP_CACHE when the file's mtime
|
||||
// has not changed since the last open. This tells the kernel to
|
||||
// preserve its existing page cache, avoiding redundant reads.
|
||||
if in.Flags&fuse.O_ANYWRITE == 0 {
|
||||
if entry := fileHandle.GetEntry(); entry != nil && entry.Attributes != nil {
|
||||
wfs.applyKeepCacheFlag(in.NodeId, entry, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
return status
|
||||
}
|
||||
@@ -94,6 +102,36 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
|
||||
* @param ino the inode number
|
||||
* @param fi file information
|
||||
*/
|
||||
const openMtimeCacheMaxSize = 8192
|
||||
|
||||
// applyKeepCacheFlag compares the entry's mtime (seconds + nanoseconds) against
|
||||
// the last-seen value and sets FOPEN_KEEP_CACHE when unchanged.
|
||||
func (wfs *WFS) applyKeepCacheFlag(inode uint64, entry *LockedEntry, out *fuse.OpenOut) {
|
||||
currentMtime := [2]int64{entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)}
|
||||
wfs.openMtimeMu.Lock()
|
||||
prev, loaded := wfs.openMtimeCache[inode]
|
||||
if loaded && prev == currentMtime {
|
||||
out.OpenFlags |= fuse.FOPEN_KEEP_CACHE
|
||||
} else {
|
||||
if len(wfs.openMtimeCache) >= openMtimeCacheMaxSize {
|
||||
for k := range wfs.openMtimeCache {
|
||||
delete(wfs.openMtimeCache, k)
|
||||
break
|
||||
}
|
||||
}
|
||||
wfs.openMtimeCache[inode] = currentMtime
|
||||
}
|
||||
wfs.openMtimeMu.Unlock()
|
||||
}
|
||||
|
||||
// invalidateOpenMtimeCache removes an inode's cached mtime so the next Open
|
||||
// does not set FOPEN_KEEP_CACHE with stale kernel page cache data.
|
||||
func (wfs *WFS) invalidateOpenMtimeCache(inode uint64) {
|
||||
wfs.openMtimeMu.Lock()
|
||||
delete(wfs.openMtimeCache, inode)
|
||||
wfs.openMtimeMu.Unlock()
|
||||
}
|
||||
|
||||
func (wfs *WFS) Release(cancel <-chan struct{}, in *fuse.ReleaseIn) {
|
||||
if in.ReleaseFlags&fuse.FUSE_RELEASE_FLOCK_UNLOCK != 0 {
|
||||
wfs.posixLocks.ReleaseFlockOwner(in.NodeId, in.LockOwner)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func newTestWFS() *WFS {
|
||||
return &WFS{
|
||||
openMtimeCache: make(map[uint64][2]int64, 8192),
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_FirstOpen(t *testing.T) {
|
||||
// First open of a file should NOT set FOPEN_KEEP_CACHE because there
|
||||
// is no previously cached mtime to compare against.
|
||||
wfs := newTestWFS()
|
||||
|
||||
var out fuse.OpenOut
|
||||
inode := uint64(42)
|
||||
|
||||
entry := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 123},
|
||||
},
|
||||
}
|
||||
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out)
|
||||
|
||||
if out.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
|
||||
t.Error("first open should not set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_SecondOpenSameMtime(t *testing.T) {
|
||||
// Second open with an unchanged mtime SHOULD set FOPEN_KEEP_CACHE.
|
||||
wfs := newTestWFS()
|
||||
|
||||
inode := uint64(42)
|
||||
|
||||
entry := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 123},
|
||||
},
|
||||
}
|
||||
|
||||
// First open -- populate cache.
|
||||
var out1 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out1)
|
||||
|
||||
// Second open -- mtime unchanged.
|
||||
var out2 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out2)
|
||||
|
||||
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE == 0 {
|
||||
t.Error("second open with same mtime should set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_MtimeChanged(t *testing.T) {
|
||||
// If the file's mtime changes between opens, FOPEN_KEEP_CACHE must NOT
|
||||
// be set so the kernel invalidates its page cache.
|
||||
wfs := newTestWFS()
|
||||
|
||||
inode := uint64(42)
|
||||
|
||||
entry1 := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
|
||||
},
|
||||
}
|
||||
|
||||
// First open.
|
||||
var out1 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry1, &out1)
|
||||
|
||||
// File is modified externally -- mtime changes.
|
||||
entry2 := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 2000, MtimeNs: 0},
|
||||
},
|
||||
}
|
||||
|
||||
var out2 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry2, &out2)
|
||||
|
||||
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
|
||||
t.Error("open after mtime change should not set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_NanosecondPrecision(t *testing.T) {
|
||||
// Two modifications within the same second but different nanoseconds
|
||||
// must NOT reuse cached page data.
|
||||
wfs := newTestWFS()
|
||||
|
||||
inode := uint64(42)
|
||||
|
||||
entry1 := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 100},
|
||||
},
|
||||
}
|
||||
|
||||
var out1 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry1, &out1)
|
||||
|
||||
// Same second, different nanosecond.
|
||||
entry2 := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 200},
|
||||
},
|
||||
}
|
||||
|
||||
var out2 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry2, &out2)
|
||||
|
||||
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
|
||||
t.Error("open after nanosecond-level mtime change should not set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_WriteInvalidation(t *testing.T) {
|
||||
// After a write invalidates the mtime cache, the next open should NOT
|
||||
// set FOPEN_KEEP_CACHE.
|
||||
wfs := newTestWFS()
|
||||
|
||||
inode := uint64(42)
|
||||
|
||||
entry := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
|
||||
},
|
||||
}
|
||||
|
||||
// First open -- populate cache.
|
||||
var out1 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out1)
|
||||
|
||||
// Simulate write invalidation.
|
||||
wfs.invalidateOpenMtimeCache(inode)
|
||||
|
||||
// Next open -- cache was invalidated.
|
||||
var out2 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out2)
|
||||
|
||||
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
|
||||
t.Error("open after write invalidation should not set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_WriteOpenSkipped(t *testing.T) {
|
||||
// Write-mode opens should never evaluate FOPEN_KEEP_CACHE.
|
||||
// The caller (WFS.Open) gates on O_ANYWRITE before calling
|
||||
// applyKeepCacheFlag, so we verify the gate logic here.
|
||||
wfs := newTestWFS()
|
||||
|
||||
inode := uint64(42)
|
||||
|
||||
entry := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
|
||||
},
|
||||
}
|
||||
|
||||
// Populate cache.
|
||||
var out1 fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out1)
|
||||
|
||||
// Simulate write-mode open: the caller would skip applyKeepCacheFlag.
|
||||
var out2 fuse.OpenOut
|
||||
flags := uint32(fuse.O_ANYWRITE)
|
||||
if flags&fuse.O_ANYWRITE == 0 {
|
||||
wfs.applyKeepCacheFlag(inode, entry, &out2)
|
||||
}
|
||||
|
||||
if out2.OpenFlags&fuse.FOPEN_KEEP_CACHE != 0 {
|
||||
t.Error("write open should not set FOPEN_KEEP_CACHE")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenKeepCache_BoundedEviction(t *testing.T) {
|
||||
// Verify the cache doesn't grow beyond openMtimeCacheMaxSize.
|
||||
wfs := newTestWFS()
|
||||
|
||||
entry := &LockedEntry{
|
||||
Entry: &filer_pb.Entry{
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 1000, MtimeNs: 0},
|
||||
},
|
||||
}
|
||||
|
||||
for i := uint64(0); i < openMtimeCacheMaxSize+100; i++ {
|
||||
var out fuse.OpenOut
|
||||
wfs.applyKeepCacheFlag(i, entry, &out)
|
||||
}
|
||||
|
||||
wfs.openMtimeMu.Lock()
|
||||
size := len(wfs.openMtimeCache)
|
||||
wfs.openMtimeMu.Unlock()
|
||||
|
||||
if size > openMtimeCacheMaxSize {
|
||||
t.Errorf("cache size %d exceeds max %d", size, openMtimeCacheMaxSize)
|
||||
}
|
||||
}
|
||||
@@ -489,6 +489,7 @@ func (wfs *WFS) truncateEntry(entryFullPath util.FullPath, entry *filer_pb.Entry
|
||||
}
|
||||
|
||||
if inode, found := wfs.inodeToPath.GetInode(entryFullPath); found {
|
||||
wfs.invalidateOpenMtimeCache(inode)
|
||||
if fh, fhFound := wfs.fhMap.FindFileHandle(inode); fhFound {
|
||||
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("truncateEntry", fh.fh, util.ExclusiveLock)
|
||||
fh.ResetDirtyPages()
|
||||
|
||||
@@ -315,7 +315,7 @@ func (wfs *WFS) maybeMergeChunks(fileFullPath util.FullPath, compactedChunks []*
|
||||
for {
|
||||
n, readErr := io.ReadFull(reader, buf)
|
||||
if n > 0 {
|
||||
chunk, uploadErr := saveFunc(bytes.NewReader(buf[:n]), "", offset, 0)
|
||||
chunk, uploadErr := saveFunc(bytes.NewReader(buf[:n]), "", offset, 0, uint64(n))
|
||||
if uploadErr != nil {
|
||||
return nil, uploadErr
|
||||
}
|
||||
|
||||
@@ -88,6 +88,9 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
|
||||
|
||||
fh.dirtyMetadata = true
|
||||
|
||||
// Invalidate the mtime cache so the next Open will not set FOPEN_KEEP_CACHE.
|
||||
wfs.invalidateOpenMtimeCache(in.NodeId)
|
||||
|
||||
// POSIX: clear SUID/SGID bits on write by non-root users.
|
||||
if in.Uid != 0 {
|
||||
entry.Attributes.FileMode &^= 0o6000
|
||||
|
||||
@@ -231,9 +231,9 @@ func (wfs *WFS) syncHardLinkSiblings(inode uint64, authoritativeEntry *filer_pb.
|
||||
glog.V(4).Infof("syncHardLinkSiblings update %s: %v", p, err)
|
||||
}
|
||||
}
|
||||
if wfs.fuseServer != nil {
|
||||
if status := wfs.fuseServer.InodeNotify(inode, 0, -1); status != fuse.OK {
|
||||
glog.V(4).Infof("syncHardLinkSiblings invalidate inode %d: %v", inode, status)
|
||||
}
|
||||
}
|
||||
// Note: we deliberately do NOT call fuseServer.InodeNotify here. That
|
||||
// call would be made from the FUSE Link request handler goroutine, and
|
||||
// writes onto the same /dev/fuse fd that the kernel is still waiting to
|
||||
// read the Link reply from — causing a self-notify deadlock. The kernel
|
||||
// will re-stat siblings once its attr-cache TTL expires.
|
||||
}
|
||||
+35
-34
@@ -8,13 +8,12 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
|
||||
|
||||
return func(reader io.Reader, filename string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
|
||||
return func(reader io.Reader, filename string, offset int64, tsNs int64, _ uint64) (chunk *filer_pb.FileChunk, err error) {
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
return
|
||||
@@ -35,37 +34,19 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
return fileUrl
|
||||
}
|
||||
|
||||
var fileId string
|
||||
var uploadResult *operation.UploadResult
|
||||
var data []byte
|
||||
|
||||
if wfs.fileIdPool != nil {
|
||||
// Use pre-allocated file ID from pool — avoids AssignVolume RPC.
|
||||
fileId, uploadResult, err, data = uploader.UploadWithAssignFunc(
|
||||
func() (string, string, security.EncodedJwt, error) {
|
||||
entry, getErr := wfs.fileIdPool.Get()
|
||||
if getErr != nil {
|
||||
return "", "", "", getErr
|
||||
}
|
||||
return entry.FileId, entry.Host, entry.Auth, nil
|
||||
},
|
||||
uploadOption, genFileUrlFn, reader,
|
||||
)
|
||||
} else {
|
||||
fileId, uploadResult, err, data = uploader.UploadWithRetry(
|
||||
wfs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: wfs.option.Replication,
|
||||
Collection: wfs.option.Collection,
|
||||
TtlSec: wfs.option.TtlSec,
|
||||
DiskType: string(wfs.option.DiskType),
|
||||
DataCenter: wfs.option.DataCenter,
|
||||
Path: string(fullPath),
|
||||
},
|
||||
uploadOption, genFileUrlFn, reader,
|
||||
)
|
||||
}
|
||||
fileId, uploadResult, err, data := uploader.UploadWithRetry(
|
||||
wfs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Replication: wfs.option.Replication,
|
||||
Collection: wfs.option.Collection,
|
||||
TtlSec: wfs.option.TtlSec,
|
||||
DiskType: string(wfs.option.DiskType),
|
||||
DataCenter: wfs.option.DataCenter,
|
||||
Path: string(fullPath),
|
||||
},
|
||||
uploadOption, genFileUrlFn, reader,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
glog.V(0).Infof("upload data %v: %v", filename, err)
|
||||
@@ -76,9 +57,29 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
}
|
||||
|
||||
if offset == 0 {
|
||||
// When peer sharing is enabled we need EVERY chunk in the
|
||||
// local cache so we can actually serve it back to peers on
|
||||
// FetchChunk — otherwise the directory would advertise us as
|
||||
// a holder and the fetcher would get NOT_FOUND from our
|
||||
// chunk cache. When peer sharing is off we preserve the
|
||||
// original behavior of caching only the first chunk (small
|
||||
// files) to avoid blowing the cache on large uploads. Both
|
||||
// paths gate on chunkCache != nil: -cacheCapacityMB=0 disables
|
||||
// the cache entirely, in which case SetChunk would panic.
|
||||
shouldCache := wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil)
|
||||
if shouldCache {
|
||||
wfs.chunkCache.SetChunk(fileId, data)
|
||||
}
|
||||
// Announce every uploaded chunk so the tier-2 directory fills
|
||||
// in as the file is written. Without this, the per-fetch
|
||||
// announce path only bootstraps after someone else has already
|
||||
// pulled a chunk via peer — which can't happen if nobody has
|
||||
// told the directory who holds the chunk. Skip the announce
|
||||
// when we couldn't cache (no point advertising bytes we can't
|
||||
// actually serve back).
|
||||
if wfs.peerAnnouncer != nil && shouldCache {
|
||||
wfs.peerAnnouncer.EnqueueAnnounce(fileId)
|
||||
}
|
||||
|
||||
chunk = uploadResult.ToPbFileChunk(fileId, offset, tsNs)
|
||||
return chunk, nil
|
||||
|
||||
+25
-14
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -25,21 +26,22 @@ func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.
|
||||
}
|
||||
|
||||
glog.V(1).Infof("save entry: %v", request)
|
||||
resp, err := wfs.streamUpdateEntry(context.Background(), request)
|
||||
|
||||
var resp *filer_pb.UpdateEntryResponse
|
||||
err := retryMetadataFlushIf(func() error {
|
||||
var callErr error
|
||||
resp, callErr = wfs.streamUpdateEntry(context.Background(), request)
|
||||
return callErr
|
||||
}, isRetryableFilerError, func(nextAttempt, totalAttempts int, backoff time.Duration, err error) {
|
||||
glog.Warningf("saveEntry %s: retrying UpdateEntry (attempt %d/%d) after %v: %v",
|
||||
path, nextAttempt, totalAttempts, backoff, err)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
err = fmt.Errorf("UpdateEntry dir %s: %v", path, err)
|
||||
} else {
|
||||
event := resp.GetMetadataEvent()
|
||||
if event == nil {
|
||||
event = metadataUpdateEvent(parentDir, entry)
|
||||
}
|
||||
if applyErr := wfs.applyLocalMetadataEvent(context.Background(), event); applyErr != nil {
|
||||
glog.Warningf("saveEntry %s: best-effort metadata apply failed: %v", path, applyErr)
|
||||
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(parentDir))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
// glog.V(0).Infof("saveEntry %s: %v", path, err)
|
||||
// Wrap with %w so grpcErrorToFuseStatus can still unwrap the gRPC status
|
||||
// (e.g. codes.Canceled → ETIMEDOUT). Using %v would stringify the error and
|
||||
// status.FromError would fall through to the default EIO.
|
||||
err = fmt.Errorf("UpdateEntry dir %s: %w", path, err)
|
||||
fuseStatus := grpcErrorToFuseStatus(err)
|
||||
if fuseStatus == fuse.EIO {
|
||||
glog.Errorf("saveEntry failed for %s: %v (returning EIO)", path, err)
|
||||
@@ -49,6 +51,15 @@ func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.
|
||||
return fuseStatus
|
||||
}
|
||||
|
||||
event := resp.GetMetadataEvent()
|
||||
if event == nil {
|
||||
event = metadataUpdateEvent(parentDir, entry)
|
||||
}
|
||||
if applyErr := wfs.applyLocalMetadataEvent(context.Background(), event); applyErr != nil {
|
||||
glog.Warningf("saveEntry %s: best-effort metadata apply failed: %v", path, applyErr)
|
||||
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(parentDir))
|
||||
}
|
||||
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,8 @@ func (ms MemberState) String() string {
|
||||
// GroupMember represents a consumer in a consumer group
|
||||
type GroupMember struct {
|
||||
ID string // Member ID (generated by gateway)
|
||||
ClientID string // Client ID from consumer
|
||||
ClientID string // Client ID from consumer (raw Kafka header value; not unique across connections)
|
||||
ConnectionID string // TCP connection identifier; distinguishes consumers that share a ClientID
|
||||
ClientHost string // Client host/IP
|
||||
GroupInstanceID *string // Static membership instance ID (optional)
|
||||
SessionTimeout int32 // Session timeout in milliseconds
|
||||
|
||||
@@ -21,6 +21,12 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const (
|
||||
brokerHealthCheckTimeout = 5 * time.Second
|
||||
brokerHealthCheckAttempts = 3
|
||||
brokerHealthCheckBackoff = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
// NewBrokerClientWithFilerAccessor creates a client with a shared filer accessor
|
||||
func NewBrokerClientWithFilerAccessor(brokerAddress string, filerClientAccessor *filer_client.FilerClientAccessor) (*BrokerClient, error) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -98,17 +104,30 @@ func (bc *BrokerClient) Close() error {
|
||||
|
||||
// HealthCheck verifies the broker connection is working
|
||||
func (bc *BrokerClient) HealthCheck() error {
|
||||
// Create a timeout context for health check
|
||||
ctx, cancel := context.WithTimeout(bc.ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Try to list topics as a health check
|
||||
_, err := bc.client.ListTopics(ctx, &mq_pb.ListTopicsRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("broker health check failed: %v", err)
|
||||
if bc.client == nil {
|
||||
return fmt.Errorf("broker client not connected")
|
||||
}
|
||||
|
||||
return nil
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= brokerHealthCheckAttempts; attempt++ {
|
||||
ctx, cancel := context.WithTimeout(bc.ctx, brokerHealthCheckTimeout)
|
||||
_, err := bc.client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{})
|
||||
cancel()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == brokerHealthCheckAttempts {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-bc.ctx.Done():
|
||||
return bc.ctx.Err()
|
||||
case <-time.After(time.Duration(attempt) * brokerHealthCheckBackoff):
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("broker health check failed after %d attempts: %v", brokerHealthCheckAttempts, lastErr)
|
||||
}
|
||||
|
||||
// GetPartitionRangeInfo gets comprehensive range information from SeaweedMQ broker's native range manager
|
||||
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user