Compare commits

..
Author SHA1 Message Date
Chris Lu 3466e74391 test: drive the Lance namespace with Spark
The counterpart of catalog_spark, which does this for the Iceberg REST
catalog. Spark is the engine most likely to be pointed at a lakehouse,
and it reaches the Lance catalog through the connector's DSV2 catalog -
org.lance.spark.LanceNamespaceSparkCatalog with impl=rest - over the same
routes every other client uses.

    SHOW NAMESPACES -> ['`sparklance-lcephd80`.ml']
    SHOW TABLES -> ['sparklance-lcephd80$ml$embeddings']
    count -> 3
    filtered -> [(2, 'two'), (3, 'three')]
    count after a second commit -> 4

The second insert is there on purpose: a store that cannot order commits
fails on the second one, not the first.

Two things the run settled that were guesses beforehand. CREATE TABLE
works, because the connector declares through the namespace and writes the
data itself rather than pushing Arrow at the server. And SHOW TABLES
returns the namespace's own identifiers - bucket, namespace and name
joined by the delimiter - not bare Spark table names.

Credentials go under the catalog's storage.* prefix, which is handed to
lance as object_store options; a gateway without STS vends none, the same
trap the LanceDB suite documents.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-21 12:32:59 -07:00
Chris Lu 49a7d4ff6a test: pin the LanceDB client, and index before searching
Three from review.

The client's dependencies were unpinned, so an unrelated upstream release
could change what an old commit reproduces. Pinned to the versions this
suite was verified against; the client is as much the thing under test as
the server.

The search was called ANN and was not: without an index LanceDB scans.
The test now builds an IVF_PQ index over 1024 rows first, which is worth
more than the wording fix - an index writes into a directory of the table
that the S3 door has to admit, and that guard has refused a Lance
directory before. It builds, covers all 1024 rows, and searches.

The assertion moved with it. Demanding the exact nearest neighbour was
right for a brute-force scan and wrong for a quantized index, which
answered 0 as readily as 1; both are correct, so the check is now the
neighbourhood.

And the pushdown check accepted any failure. It now requires the refusal
to be the catalog's Unsupported and requires that nothing was left behind,
or, when the client falls back, that the table is complete.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-20 19:51:55 -07:00
Chris Lu 2481641abf test: drive the Lance namespace with LanceDB
The Iceberg catalog is checked against Spark, Trino, ClickHouse, Doris,
Dremio and RisingWave. The Lance one had only its own reference client,
which is the same thing as checking it against ourselves.

LanceDB connects with connect_namespace("rest", ...), which speaks the
routes this catalog implements, so the suite exercises the protocol rather
than our idea of it: list the catalog, open a table through it, read the
schema, run a vector search and a filtered scan, create a table, and read
the same dataset straight off its URI with no catalog at all.

    table_names -> ['lancedb-p0guidmm$ml$embeddings']
    open_table  -> 64 rows
    search      -> [1, 0, 2]
    create_table -> 4 rows, listed by the catalog
    direct read without the catalog -> 64 rows

Seeding is pylance, because the namespace records where a table lives and
does not carry its data. That split is the design rather than a limit of
the test.

One interop note the test encodes: a gateway without STS vends
storage_options carrying an endpoint and a region but no credentials, and
LanceDB uses what the namespace vends on some paths. The container gets
credentials in its environment as well, which is what a deployment without
STS would do.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-20 12:38:06 -07:00
114 changed files with 853 additions and 9308 deletions

No files matched your search

-77
View File
@@ -58,52 +58,10 @@ jobs:
grep -q "kind: Deployment" /tmp/s3.yaml && grep -q "seaweedfs-s3" /tmp/s3.yaml
echo "S3 deployment renders correctly"
echo "=== Testing S3 credentials from an existing secret ==="
credential_args=(
--set s3.credentials.admin.existingSecret=minio-root
--set s3.credentials.admin.accessKeyKey=root-user
--set s3.credentials.admin.secretKeyKey=root-password
--set s3.credentials.read.existingSecret=minio-root
)
for workload in \
"s3.enabled=true,s3.enableAuth=true" \
"filer.s3.enabled=true,filer.s3.enableAuth=true" \
"allInOne.enabled=true,allInOne.s3.enabled=true,allInOne.s3.enableAuth=true"
do
helm template test $CHART_DIR --set "$workload" "${credential_args[@]}" > /tmp/s3-existing-credentials.yaml
# The identities file names the variables, and each is bound to the key it was pointed at.
grep -q 'accessKey":"${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}' /tmp/s3-existing-credentials.yaml
grep -q 'secretKey":"${SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY}' /tmp/s3-existing-credentials.yaml
grep -q 'accessKey":"${SEAWEEDFS_S3_READ_ACCESS_KEY_ID}' /tmp/s3-existing-credentials.yaml
for pair in \
"SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID root-user" \
"SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY root-password" \
"SEAWEEDFS_S3_READ_ACCESS_KEY_ID read_access_key_id" \
"SEAWEEDFS_S3_READ_SECRET_ACCESS_KEY read_secret_access_key"
do
set -- $pair
grep -A 4 -- "- name: $1\$" /tmp/s3-existing-credentials.yaml | grep -q "name: \"minio-root\""
grep -A 4 -- "- name: $1\$" /tmp/s3-existing-credentials.yaml | grep -q "key: \"$2\""
done
# The keys stay in the user's secret rather than being copied into the chart's.
! grep -qE "^ (admin|read)_(access_key_id|secret_access_key):" /tmp/s3-existing-credentials.yaml
echo "S3 credentials reference the existing secret for $workload"
done
echo "=== Testing with all-in-one mode ==="
helm template test $CHART_DIR --set allInOne.enabled=true > /tmp/allinone.yaml
grep -q "seaweedfs-all-in-one" /tmp/allinone.yaml
echo "All-in-one deployment renders correctly"
echo "=== Testing the all-in-one s3 secret is created by every flag that mounts it ==="
for auth in allInOne.s3.enableAuth s3.enableAuth filer.s3.enableAuth; do
helm template test $CHART_DIR \
--set allInOne.enabled=true --set allInOne.s3.enabled=true --set "$auth=true" \
> /tmp/allinone-s3-auth.yaml
grep -q "secretName: test-seaweedfs-s3-secret" /tmp/allinone-s3-auth.yaml
grep -q "name: test-seaweedfs-s3-secret" /tmp/allinone-s3-auth.yaml
echo "All-in-one s3 secret renders for $auth"
done
echo "=== Testing with security enabled ==="
helm template test $CHART_DIR --set global.seaweedfs.enableSecurity=true > /tmp/security.yaml
@@ -482,41 +440,6 @@ jobs:
--set filer.s3.enableAuth=true > /tmp/filer-s3.yaml
echo "Filer S3 gateway renders correctly"
echo "=== Testing the mysql filer store gates its secret and env ==="
helm template test $CHART_DIR \
--set-string filer.extraEnvironmentVars.WEED_MONGODB_ENABLED=true \
--set-string filer.extraEnvironmentVars.WEED_LEVELDB2_ENABLED=false > /tmp/filer-mongodb.yaml
! grep -q "db-secret" /tmp/filer-mongodb.yaml
! grep -q "WEED_MYSQL" /tmp/filer-mongodb.yaml
grep -q "name: WEED_MONGODB_ENABLED" /tmp/filer-mongodb.yaml
helm template test $CHART_DIR \
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true > /tmp/filer-mysql.yaml
grep -q "name: test-seaweedfs-db-secret" /tmp/filer-mysql.yaml
grep -q "name: WEED_MYSQL_USERNAME" /tmp/filer-mysql.yaml
grep -q "name: WEED_MYSQL_PASSWORD" /tmp/filer-mysql.yaml
grep -q "name: WEED_MYSQL_HOSTNAME" /tmp/filer-mysql.yaml
# Secret-backed keys follow the same rule as the plain ones.
helm template test $CHART_DIR \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.name=db \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.key=password > /tmp/filer-mysql-off-secret.yaml
! grep -q "WEED_MYSQL" /tmp/filer-mysql-off-secret.yaml
helm template test $CHART_DIR \
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.name=db \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.key=password > /tmp/filer-mysql-on-secret.yaml
grep -A 4 -- "- name: WEED_MYSQL_PASSWORD$" /tmp/filer-mysql-on-secret.yaml | grep -q "name: db"
# A flag the chart cannot read counts as selected, not as off.
helm template test $CHART_DIR \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_ENABLED.secretKeyRef.name=store \
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_ENABLED.secretKeyRef.key=enabled > /tmp/filer-mysql-secret.yaml
grep -q "name: test-seaweedfs-db-secret" /tmp/filer-mysql-secret.yaml
grep -q "name: WEED_MYSQL_HOSTNAME" /tmp/filer-mysql-secret.yaml
helm template test $CHART_DIR \
--set-string filer.extraEnvironmentVars.WEED_MYSQL2_HOSTNAME=other > /tmp/filer-mysql2.yaml
grep -q "name: WEED_MYSQL2_HOSTNAME" /tmp/filer-mysql2.yaml
! grep -q "WEED_MYSQL_" /tmp/filer-mysql2.yaml
echo "The mysql secret and env follow the selected filer store"
echo "=== Testing SFTP enabled ==="
helm template test $CHART_DIR --set sftp.enabled=true > /tmp/sftp.yaml
grep -q "seaweedfs-sftp" /tmp/sftp.yaml
+12 -133
View File
@@ -1,17 +1,4 @@
name: "release: bump version and cut the release"
# One entry point for a SeaweedFS release:
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, commit to master
# 2. push the <appVersion> tag, which fans out to the workflows that trigger on
# `push: tags` (binaries_release*, container_release_unified, helm_manual_release)
# 3. create the GitHub release, with GitHub's generated notes
# 4. dispatch "Prepare release" in seaweedfs-csi-driver and seaweedfs-operator,
# which pick up the new master through `go get -u`, and wait for both
#
# Events raised by the default GITHUB_TOKEN do not start other workflows, and it
# cannot reach the other two repositories at all. Add a repo secret RELEASE_PAT
# with `contents: write` here and `actions: write` on the csi-driver and operator
# repos. Without it the tag is still pushed, but nothing downstream of it runs.
name: "release: bump version"
on:
workflow_dispatch:
@@ -27,37 +14,15 @@ on:
description: "Explicit MAJOR.MINOR to set, e.g. 4.36 (overrides 'bump')"
type: string
required: false
downstream:
description: "Also release the CSI driver and the operator"
type: boolean
default: true
dry_run:
description: "Show the version bump, but change nothing"
type: boolean
default: false
permissions:
contents: write
jobs:
release:
bump-version:
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
app_version: ${{ steps.compute.outputs.app_version }}
sha: ${{ steps.tag.outputs.sha }}
steps:
- uses: actions/checkout@v7
with:
ref: master
fetch-depth: 0
token: ${{ secrets.RELEASE_PAT || secrets.GITHUB_TOKEN }}
- name: Check the release token
env:
HAS_PAT: ${{ secrets.RELEASE_PAT != '' }}
run: |
if [ "$HAS_PAT" != "true" ]; then
echo "::warning::RELEASE_PAT is not set. The tag will be pushed with GITHUB_TOKEN, so the binary, container and helm workflows will not start on their own."
fi
- name: Compute new version
id: compute
@@ -134,103 +99,17 @@ jobs:
sed -i -E "s/^version:.*/version: ${CHART_VERSION}/" "$CHART"
cat "$CHART"
- name: Commit, and push the tag
id: tag
- name: Commit and push
env:
TAG: ${{ steps.compute.outputs.app_version }}
DRY_RUN: ${{ inputs.dry_run }}
APP_VERSION: ${{ steps.compute.outputs.app_version }}
run: |
set -euo pipefail
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
echo "::error::Tag ${TAG} already exists."
exit 1
fi
if [ "$DRY_RUN" = "true" ]; then
git --no-pager diff --stat
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
if git diff --quiet; then
echo "No version change to commit."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if git diff --quiet; then
echo "::warning::Version files are already at ${TAG}; tagging the current HEAD."
else
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
git commit -m "${TAG}"
git push
fi
# Push the tag with git so the `push: tags` triggers fire. Creating the
# tag through the release API alone would only emit a `create` event.
git tag "$TAG"
git push origin "$TAG"
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Create the release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ secrets.RELEASE_PAT || secrets.GITHUB_TOKEN }}
TAG: ${{ steps.compute.outputs.app_version }}
run: gh release create "$TAG" --title "$TAG" --generate-notes --verify-tag
downstream:
needs: release
if: ${{ inputs.downstream && !inputs.dry_run }}
runs-on: ubuntu-latest
permissions: {}
strategy:
fail-fast: false
matrix:
include:
- repo: seaweedfs/seaweedfs-csi-driver
workflow: prepare_release.yaml
- repo: seaweedfs/seaweedfs-operator
workflow: prepare_release.yml
steps:
- name: Release ${{ matrix.repo }}
env:
GH_TOKEN: ${{ secrets.RELEASE_PAT }}
REPO: ${{ matrix.repo }}
WORKFLOW: ${{ matrix.workflow }}
SHA: ${{ needs.release.outputs.sha }}
MODULE: github.com/seaweedfs/seaweedfs
run: |
set -euo pipefail
if [ -z "${GH_TOKEN}" ]; then
echo "::error::RELEASE_PAT with actions:write on ${REPO} is required to release it"
exit 1
fi
# The dispatched workflow pins seaweedfs with `go get -u ...@latest`, so
# wait until the proxy serves the release commit as the tip. Asking for
# the commit by name is what makes the proxy fetch it.
for _ in $(seq 30); do
curl -sf "https://proxy.golang.org/${MODULE}/@v/${SHA}.info" >/dev/null || true
TIP=$(curl -sf "https://proxy.golang.org/${MODULE}/@latest" | jq -r '.Origin.Hash // ""' || true)
[ "$TIP" = "$SHA" ] && break
sleep 10
done
if [ "$TIP" != "$SHA" ]; then
echo "::error::the module proxy still serves ${TIP} as the tip, so ${REPO} would pin a pre-release commit. Run ${WORKFLOW} there once it catches up."
exit 1
fi
# Wait on the release the dispatched workflow publishes, not on the run
# that publishes it: a dispatch cannot be told apart from a concurrent
# one through the API, and the release is what we are here for.
released() { gh api "repos/${REPO}/releases?per_page=30" --jq '[.[].tag_name]'; }
BEFORE=$(released)
gh workflow run -R "$REPO" "$WORKFLOW" --ref master -f bump=patch -f update_seaweedfs=true
for _ in $(seq 80); do
sleep 15
NEW=$(released | jq -c --argjson before "$BEFORE" '. - $before')
[ "$(jq length <<<"$NEW")" -gt 0 ] && break
done
if [ "$(jq length <<<"$NEW")" -eq 0 ]; then
echo "::error::${REPO} published no release within 20 minutes; see https://github.com/${REPO}/actions/workflows/${WORKFLOW}"
exit 1
fi
echo "${REPO} released $(jq -r 'join(", ")' <<<"$NEW")"
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
git commit -m "${APP_VERSION}"
git push
-148
View File
@@ -6,7 +6,6 @@ on:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/worker/tasks/iceberg/**'
- 'test/s3tables/**'
- 'go.mod'
- 'go.sum'
@@ -945,149 +944,6 @@ jobs:
path: test/s3tables/catalog_lancedb/test-output.log
retention-days: 3
table-lifecycle-tests:
name: Table Lifecycle Integration Tests
runs-on: ubuntu-22.04
timeout-minutes: 40
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
id: go
- name: Configure Docker Hub mirror
run: |
echo '{"registry-mirrors": ["https://mirror.gcr.io"]}' | sudo tee /etc/docker/daemon.json
sudo systemctl restart docker
- name: Pre-pull images
run: |
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
pull python:3.11-slim
pull duckdb/duckdb:latest
- name: Run go mod tidy
run: go mod tidy
- name: Build SeaweedFS
run: |
cd weed && go build -buildvcs=false .
- name: Run Table Lifecycle Integration Tests
timeout-minutes: 35
working-directory: test/s3tables/lifecycle
env:
# The Rust worker's own tests cover its handlers; a cold build of the
# lance crate costs more here than the layer it would be checking.
WEED_LANCE_MAINTENANCE: library
run: |
set -x
set -o pipefail
go test -v -timeout 30m . 2>&1 | tee test-output.log || {
echo "Table lifecycle integration tests failed"
exit 1
}
- name: Show test output on failure
if: failure()
working-directory: test/s3tables/lifecycle
run: |
echo "=== Test Output ==="
if [ -f test-output.log ]; then
tail -200 test-output.log
fi
echo "=== Process information ==="
ps aux | grep -E "(weed|test|docker)" || true
- name: Upload test logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: table-lifecycle-test-logs
path: test/s3tables/lifecycle/test-output.log
retention-days: 3
duckdb-lance-tests:
name: DuckDB Lance Integration Tests
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- name: Check out code
uses: actions/checkout@v7
with:
# The job uploads a test log on failure; nothing here needs to push,
# so do not leave a token in the checkout for it to pick up.
persist-credentials: false
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
id: go
- name: Configure Docker Hub mirror
run: |
echo '{"registry-mirrors": ["https://mirror.gcr.io"]}' | sudo tee /etc/docker/daemon.json
sudo systemctl restart docker
- name: Pre-pull images
run: |
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
pull duckdb/duckdb:latest
pull python:3.11-slim
- name: Run go mod tidy
run: go mod tidy
- name: Build SeaweedFS
run: |
cd weed && go build -buildvcs=false .
- name: Run DuckDB Lance Integration Tests
timeout-minutes: 25
working-directory: test/s3tables/catalog_duckdb_lance
run: |
set -x
set -o pipefail
echo "=== System Information ==="
uname -a
free -h
df -h
docker info
echo "=== Starting DuckDB Lance Tests ==="
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
echo "DuckDB Lance integration tests failed"
exit 1
}
- name: Show test output on failure
if: failure()
working-directory: test/s3tables/catalog_duckdb_lance
run: |
echo "=== Test Output ==="
if [ -f test-output.log ]; then
tail -200 test-output.log
fi
echo "=== Process information ==="
ps aux | grep -E "(weed|test|docker|duckdb)" || true
- name: Upload test logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: duckdb-lance-test-logs
path: test/s3tables/catalog_duckdb_lance/test-output.log
retention-days: 3
spark-lance-namespace-tests:
name: Spark Lance Namespace Integration Tests
runs-on: ubuntu-22.04
@@ -1096,10 +952,6 @@ jobs:
steps:
- name: Check out code
uses: actions/checkout@v7
with:
# The job uploads a test log on failure; nothing here needs to push,
# so do not leave a token in the checkout for it to pick up.
persist-credentials: false
- name: Set up Go
uses: actions/setup-go@v7
+1 -1
View File
@@ -90,7 +90,7 @@ S3_BUCKET=my-bucket \
./weed mini -dir=/data
```
That's it — the S3 endpoint is at http://localhost:8333, `my-bucket` already exists, and `admin`/`secret` are valid credentials. `S3_BUCKET` accepts a comma-separated list (e.g. `raw,processed`); use `S3_TABLE_BUCKET` for S3 Tables buckets, each `name` or `name:FORMAT` where the format is `ICEBERG` (the default) or `LANCE`. Drop any of the env vars to skip that piece (no AWS keys → S3 runs in unauthenticated "Allow All" mode for development).
That's it — the S3 endpoint is at http://localhost:8333, `my-bucket` already exists, and `admin`/`secret` are valid credentials. `S3_BUCKET` accepts a comma-separated list (e.g. `raw,processed`); use `S3_TABLE_BUCKET` for S3 Tables (Iceberg) buckets. Drop any of the env vars to skip that piece (no AWS keys → S3 runs in unauthenticated "Allow All" mode for development).
The same command starts everything else too:
- **S3 Endpoint**: http://localhost:8333
+1 -5
View File
@@ -11,8 +11,4 @@ scrape_configs:
- 'master:9324'
- 'volume:9325'
- 'filer:9326'
- 's3:9327'
# A plugin worker publishes its own metrics when started with
# -metricsPort (Go) or --metrics-port (Rust). 9328 continues the
# series, since 9327 is already the S3 gateway's.
# - 'worker:9328'
- 's3:9327'
+1 -1
View File
@@ -141,7 +141,7 @@ require (
github.com/linkedin/goavro/v2 v2.15.0
github.com/minio/crc64nvme v1.1.1
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/parquet-go/parquet-go v0.30.1
github.com/pkg/sftp v1.13.11
github.com/rabbitmq/amqp091-go v1.13.0
github.com/rclone/rclone v1.75.0
+2 -2
View File
@@ -1636,8 +1636,8 @@ github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxP
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/parquet-go/parquet-go v0.30.1 h1:Oy6ganNrAdFiVwy7wNmWagfPTWA2X9Z3tVHBc7JtuX8=
github.com/parquet-go/parquet-go v0.30.1/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.44"
appVersion: "4.42"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.44.0
version: 4.42.0
+2 -28
View File
@@ -22,8 +22,8 @@ helm install --values=values.yaml seaweedfs seaweedfs/seaweedfs
## Info:
* master/filer/volume are stateful sets with anti-affinity on the hostname,
so your deployment will be spread/HA.
* leveldb2 is the default filer backend; a mysql-compatible database (memsql, ...) enables HA (multiple filer instances) and the backup/HA it can provide.
* with `filer.extraEnvironmentVars.WEED_MYSQL_ENABLED` set to `"true"`, mysql user/password are created in a k8s secret (default: `<release>-seaweedfs-db-secret`) and injected to the filer with ENV. On any other store neither the secret nor the `WEED_MYSQL_*` env, plain or secret-backed, is rendered.
* chart is using memsql(mysql) as the filer backend to enable HA (multiple filer instances) and backup/HA memsql can provide.
* mysql user/password are created in a k8s secret (default: `<release>-seaweedfs-db-secret`) and injected to the filer with ENV.
* cert config exists and can be enabled, but not been tested, requires cert-manager to be installed.
## Prerequisites
@@ -289,32 +289,6 @@ stringData:
seaweedfs_s3_config: '{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"snu8yoP6QAlY0ne4","secretKey":"PNzBcmeLNEdR0oviwm04NQAicOrDH1Km"}],"actions":["Admin","Read","Write"]},{"name":"anvReadOnly","credentials":[{"accessKey":"SCigFee6c5lbi04A","secretKey":"kgFhbT38R8WUYVtiFQ1OiSVOrYr3NKku"}],"actions":["Read"]}]}'
```
#### Source S3 credentials from an existing Secret
To keep the keys out of `values.yaml` while still letting the chart generate the
identities file, point an identity at an existing Secret:
```yaml
s3:
enabled: true
enableAuth: true
credentials:
admin:
existingSecret: minio-root
accessKeyKey: root-user
secretKeyKey: root-password
```
`accessKeyKey` and `secretKeyKey` default to the chart's own key names
(`admin_access_key_id`, `admin_secret_access_key`, and the `read_` pair). The
generated `seaweedfs_s3_config` references the keys as `${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}`
and the gateway resolves them from the environment, which the chart wires up
from the Secret. Nothing is read from the cluster at render time, so
`helm template`, `--dry-run` and an Argo CD diff all render what an install
applies. Rotating a key in the Secret takes effect on the next pod restart, as
with any other environment variable. The COSI driver parses the config itself
and does not resolve these references.
## Admin Component
The admin component provides a modern web-based administration interface for managing SeaweedFS clusters. It includes:
@@ -84,9 +84,6 @@ spec:
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
env:
{{- include "seaweedfs.licenseEnv" . | nindent 12 }}
{{- if and .Values.allInOne.s3.enabled (or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth) }}
{{- include "seaweedfs.s3.credentialEnv" . | nindent 12 }}
{{- end }}
{{- /* Determine default cluster alias and the corresponding env var keys to avoid conflicts */}}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.allInOne "target" $mergedExtraEnvironmentVars) }}
@@ -92,7 +92,6 @@ spec:
image: {{ template "seaweedfs.filer.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
env:
{{- $mysqlEnabled := include "seaweedfs.filer.mysqlEnabled" . }}
- name: POD_IP
valueFrom:
fieldRef:
@@ -105,7 +104,6 @@ spec:
valueFrom:
fieldRef:
fieldPath: metadata.namespace
{{- if $mysqlEnabled }}
- name: WEED_MYSQL_USERNAME
valueFrom:
secretKeyRef:
@@ -118,21 +116,10 @@ spec:
name: {{ include "seaweedfs.fullname" . }}-db-secret
key: password
optional: true
{{- end }}
- name: SEAWEEDFS_FULLNAME
value: "{{ include "seaweedfs.fullname" . }}"
{{- if and .Values.filer.s3.enabled .Values.filer.s3.enableAuth }}
{{- include "seaweedfs.s3.credentialEnv" . | nindent 12 }}
{{- end }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.filer "target" $mergedExtraEnvironmentVars) }}
{{- if not $mysqlEnabled }}
{{- range $key := keys $mergedExtraEnvironmentVars }}
{{- if hasPrefix "WEED_MYSQL_" $key }}
{{- $_ := unset $mergedExtraEnvironmentVars $key }}
{{- end }}
{{- end }}
{{- end }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
- name: {{ $key }}
@@ -145,12 +132,10 @@ spec:
{{- end }}
{{- if .Values.filer.secretExtraEnvironmentVars }}
{{- range $key, $value := .Values.filer.secretExtraEnvironmentVars }}
{{- if or $mysqlEnabled (not (hasPrefix "WEED_MYSQL_" $key)) }}
- name: {{ $key }}
valueFrom: {{ toYaml $value | nindent 16 }}
{{- end }}
{{- end }}
{{- end }}
command:
- "/bin/sh"
- "-ec"
@@ -94,9 +94,6 @@ spec:
fieldPath: metadata.namespace
- name: SEAWEEDFS_FULLNAME
value: "{{ include "seaweedfs.fullname" . }}"
{{- if .Values.s3.enableAuth }}
{{- include "seaweedfs.s3.credentialEnv" . | nindent 12 }}
{{- end }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.s3 "target" $mergedExtraEnvironmentVars) }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
@@ -1,7 +1,4 @@
{{- /* Mirrors the condition the all-in-one deployment mounts this secret under,
so the flags that make it mount are exactly the flags that create it. */}}
{{- $allInOneAuth := and .Values.allInOne.enabled .Values.allInOne.s3.enabled (or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth) (not (or .Values.allInOne.s3.existingConfigSecret .Values.s3.existingConfigSecret .Values.filer.s3.existingConfigSecret)) }}
{{- if or (and (or .Values.s3.enabled .Values.allInOne.enabled) .Values.s3.enableAuth (not .Values.s3.existingConfigSecret)) (and .Values.filer.s3.enabled .Values.filer.s3.enableAuth (not .Values.filer.s3.existingConfigSecret)) $allInOneAuth }}
{{- if or (and (or .Values.s3.enabled .Values.allInOne.enabled) .Values.s3.enableAuth (not .Values.s3.existingConfigSecret)) (and .Values.filer.s3.enabled .Values.filer.s3.enableAuth (not .Values.filer.s3.existingConfigSecret)) }}
{{- $secretName := printf "%s-s3-secret" (include "seaweedfs.fullname" .) }}
{{- $legacySecretName := "seaweedfs-s3-secret" }}
{{- $lookupName := $secretName }}
@@ -17,20 +14,14 @@
{{- $adminCreds := $creds.admin | default dict -}}
{{- $access_key_admin := $adminCreds.accessKey -}}
{{- $secret_key_admin := $adminCreds.secretKey -}}
{{- if $adminCreds.existingSecret -}}
{{- $access_key_admin = printf "${%s}" (include "seaweedfs.s3.credentialEnvName" (list "admin" "accessKey")) -}}
{{- $secret_key_admin = printf "${%s}" (include "seaweedfs.s3.credentialEnvName" (list "admin" "secretKey")) -}}
{{- else if not (and $access_key_admin $secret_key_admin) -}}
{{- if not (and $access_key_admin $secret_key_admin) -}}
{{- $access_key_admin = include "seaweedfs.getOrGeneratePassword" (dict "namespace" .Release.Namespace "secretName" $secretName "key" "admin_access_key_id" "length" 20 "existingSecret" (ternary $existingSecret nil $reuse)) -}}
{{- $secret_key_admin = include "seaweedfs.getOrGeneratePassword" (dict "namespace" .Release.Namespace "secretName" $secretName "key" "admin_secret_access_key" "length" 40 "existingSecret" (ternary $existingSecret nil $reuse)) -}}
{{- end -}}
{{- $readCreds := $creds.read | default dict -}}
{{- $access_key_read := $readCreds.accessKey -}}
{{- $secret_key_read := $readCreds.secretKey -}}
{{- if $readCreds.existingSecret -}}
{{- $access_key_read = printf "${%s}" (include "seaweedfs.s3.credentialEnvName" (list "read" "accessKey")) -}}
{{- $secret_key_read = printf "${%s}" (include "seaweedfs.s3.credentialEnvName" (list "read" "secretKey")) -}}
{{- else if not (and $access_key_read $secret_key_read) -}}
{{- if not (and $access_key_read $secret_key_read) -}}
{{- $access_key_read = include "seaweedfs.getOrGeneratePassword" (dict "namespace" .Release.Namespace "secretName" $secretName "key" "read_access_key_id" "length" 20 "existingSecret" (ternary $existingSecret nil $reuse)) -}}
{{- $secret_key_read = include "seaweedfs.getOrGeneratePassword" (dict "namespace" .Release.Namespace "secretName" $secretName "key" "read_secret_access_key" "length" 40 "existingSecret" (ternary $existingSecret nil $reuse)) -}}
{{- end -}}
@@ -50,16 +41,10 @@ metadata:
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: s3
stringData:
{{- /* An identity read from an existing Secret keeps its keys there; the
config below names the environment variables carrying them. */}}
{{- if not $adminCreds.existingSecret }}
admin_access_key_id: {{ $access_key_admin }}
admin_secret_access_key: {{ $secret_key_admin }}
{{- end }}
{{- if not $readCreds.existingSecret }}
read_access_key_id: {{ $access_key_read }}
read_secret_access_key: {{ $secret_key_read }}
{{- end }}
seaweedfs_s3_config: '{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"{{ $access_key_admin }}","secretKey":"{{ $secret_key_admin }}"}],"actions":["Admin","Read","Write"]},{"name":"anvReadOnly","credentials":[{"accessKey":"{{ $access_key_read }}","secretKey":"{{ $secret_key_read }}"}],"actions":["Read"]}]}'
{{- if .Values.filer.s3.auditLogConfig }}
filer_s3_auditLogConfig.json: |
@@ -76,18 +76,6 @@ Inject extra environment vars in the format key:value, if populated
{{- end }}
{{- end -}}
{{/* Whether the mysql filer store is selected; a flag the chart cannot read counts as selected. */}}
{{- define "seaweedfs.filer.mysqlEnabled" -}}
{{- $merged := dict -}}
{{- $_ := include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.filer "target" $merged) -}}
{{- $enabled := index $merged "WEED_MYSQL_ENABLED" -}}
{{- if or (kindIs "map" $enabled) (hasKey (.Values.filer.secretExtraEnvironmentVars | default dict) "WEED_MYSQL_ENABLED") -}}
true
{{- else if and $enabled (eq (lower (toString $enabled)) "true") -}}
true
{{- end -}}
{{- end -}}
{{/* Return the proper filer image */}}
{{- define "seaweedfs.filer.image" -}}
{{- if .Values.filer.imageOverride -}}
@@ -508,39 +496,6 @@ true
{{- end }}
{{- end -}}
{{/* Name of the environment variable carrying one generated S3 credential
field, e.g. SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID. The generated identities file
names it in place of the key when the key lives in an existing Secret.
Usage: include "seaweedfs.s3.credentialEnvName" (list "admin" "accessKey") */}}
{{- define "seaweedfs.s3.credentialEnvName" -}}
{{- $identity := index . 0 -}}
{{- $field := index . 1 -}}
{{- printf "SEAWEEDFS_S3_%s_%s" (upper $identity) (ternary "ACCESS_KEY_ID" "SECRET_ACCESS_KEY" (eq $field "accessKey")) -}}
{{- end -}}
{{/* Environment for the S3 identities the chart generates from an existing
Secret. The gateway resolves the ${VAR} references the identities file
carries, so the keys never enter the rendered manifests and a dry run
renders the same as an install. */}}
{{- define "seaweedfs.s3.credentialEnv" -}}
{{- $creds := $.Values.s3.credentials | default dict -}}
{{- range $identity := list "admin" "read" -}}
{{- $identityCreds := index $creds $identity | default dict -}}
{{- if $identityCreds.existingSecret }}
- name: {{ include "seaweedfs.s3.credentialEnvName" (list $identity "accessKey") }}
valueFrom:
secretKeyRef:
name: {{ $identityCreds.existingSecret | quote }}
key: {{ default (printf "%s_access_key_id" $identity) $identityCreds.accessKeyKey | quote }}
- name: {{ include "seaweedfs.s3.credentialEnvName" (list $identity "secretKey") }}
valueFrom:
secretKeyRef:
name: {{ $identityCreds.existingSecret | quote }}
key: {{ default (printf "%s_secret_access_key" $identity) $identityCreds.secretKeyKey | quote }}
{{- end -}}
{{- end -}}
{{- end -}}
{{/* Generate a compatible trafficDistribution value due to "PreferClose" fast deprecation in k8s v1.35.
Accepts a dict with "value" (the trafficDistribution string) and "Capabilities". */}}
{{- define "seaweedfs.trafficDistribution" -}}
@@ -1,4 +1,4 @@
{{- if and .Values.filer.enabled (include "seaweedfs.filer.mysqlEnabled" .) }}
{{- if .Values.filer.enabled }}
apiVersion: v1
kind: Secret
type: Opaque
-12
View File
@@ -897,7 +897,6 @@ filer:
# extraEnvVars is a list of extra environment variables to set with the stateful set.
extraEnvironmentVars:
# the WEED_MYSQL_* keys and the db credential secret only render while this is "true"
WEED_MYSQL_ENABLED: "false"
WEED_MYSQL_HOSTNAME: "mysql-db-host"
WEED_MYSQL_PORT: "3306"
@@ -1015,24 +1014,13 @@ s3:
# Optionally provide explicit credentials for the S3 gateway.
# When set, these are used in the generated s3 secret instead of
# auto-generating random credentials.
# An identity may instead name an existing Secret to read its keys from. The
# generated config then references the keys through environment variables, so
# nothing is looked up at render time and a dry run renders what an install
# applies. Note the COSI driver parses the config itself and does not resolve
# those references.
# credentials:
# admin:
# accessKey: ""
# secretKey: ""
# existingSecret: ""
# accessKeyKey: admin_access_key_id
# secretKeyKey: admin_secret_access_key
# read:
# accessKey: ""
# secretKey: ""
# existingSecret: ""
# accessKeyKey: read_access_key_id
# secretKeyKey: read_secret_access_key
auditLogConfig: {}
# You may specify buckets to be created during the install or upgrade process.
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
+1 -954
View File
@@ -9263,959 +9263,6 @@
}
]
},
{
"type": "row",
"title": "Plugin Workers",
"collapsed": true,
"id": 229,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 27
},
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Plugin Workers Connected",
"description": "Workers with a live control stream. Unlike the Admin/Maintenance row, this counts plugin workers, which is what a Rust or Go plugin worker actually is.",
"type": "stat",
"id": 219,
"gridPos": {
"h": 4,
"w": 6,
"x": 0,
"y": 28
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "count(SeaweedFS_worker_connected{cluster=~\"$cluster\"} == 1) or vector(0)",
"instant": true,
"range": false,
"refId": "A"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Worker Job Failures (1h)",
"description": "Jobs that ended in failure across all workers in the last hour.",
"type": "stat",
"id": 220,
"gridPos": {
"h": 4,
"w": 6,
"x": 6,
"y": 28
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"reduceOptions": {
"calcs": [
"lastNotNull"
],
"fields": "",
"values": false
},
"textMode": "auto"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(increase(SeaweedFS_worker_jobs_total{cluster=~\"$cluster\",result=\"failed\"}[1h])) or vector(0)",
"instant": true,
"range": false,
"refId": "A"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Objects Seen vs Skipped",
"description": "A sweep that proposes nothing because there was nothing to do and one that proposes nothing because it could read nothing produce the same proposal count. Skips are the difference, and are the thing to alert on.",
"type": "timeseries",
"id": 221,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 32
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (job_type) (rate(SeaweedFS_worker_objects_seen_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "seen {{job_type}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (job_type, reason) (rate(SeaweedFS_worker_objects_skipped_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "skipped {{job_type}} ({{reason}})"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Detections and Proposals",
"description": "Detection sweeps by outcome, and the work they handed to admin.",
"type": "timeseries",
"id": 222,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 32
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (job_type, result) (rate(SeaweedFS_worker_detections_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "detections {{job_type}} ({{result}})"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (job_type) (rate(SeaweedFS_worker_proposals_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "proposals {{job_type}}"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Jobs Executed",
"description": "Jobs run by these workers, by outcome.",
"type": "timeseries",
"id": 223,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 40
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (job_type, result) (rate(SeaweedFS_worker_jobs_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{job_type}} ({{result}})"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Job Duration p99",
"description": "How long a job takes, per job type.",
"type": "timeseries",
"id": 224,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 40
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_worker_job_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, job_type))",
"range": true,
"refId": "A",
"legendFormat": "{{job_type}}"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Worker Slots",
"description": "Capacity a worker advertised and how much of it is in use. Held slots are what admin schedules against.",
"type": "timeseries",
"id": 225,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 48
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (lane) (SeaweedFS_worker_slots_used{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "used {{lane}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (lane) (SeaweedFS_worker_slots_total{cluster=~\"$cluster\"})",
"range": true,
"refId": "B",
"legendFormat": "total {{lane}}"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Control Stream Events",
"description": "Connects, closes and failures. A worker that reconnects steadily is usually two workers sharing one id, evicting each other.",
"type": "timeseries",
"id": 226,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 48
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (event) (rate(SeaweedFS_worker_stream_events_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{event}}"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Lance Maintenance Reclaimed",
"description": "What the Lance jobs actually removed. A job that runs every minute and reclaims nothing is a different thing from a job that never runs.",
"type": "timeseries",
"id": 227,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 56
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(rate(SeaweedFS_worker_lance_fragments_removed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "fragments merged"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(rate(SeaweedFS_worker_lance_rows_indexed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "rows indexed"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(rate(SeaweedFS_worker_lance_versions_removed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "C",
"legendFormat": "versions removed"
}
]
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Storage Reclaimed",
"description": "Bytes freed by version cleanup. Its own panel because bytes and counts do not belong on one axis.",
"type": "timeseries",
"id": 228,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 56
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "Bps",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum(rate(SeaweedFS_worker_lance_bytes_reclaimed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "reclaimed"
}
]
}
]
},
{
"type": "row",
"title": "Go Runtime",
@@ -10225,7 +9272,7 @@
"h": 1,
"w": 24,
"x": 0,
"y": 28
"y": 27
},
"panels": [
{
-10
View File
@@ -330,16 +330,6 @@ pub fn delete_collection_metrics(collection: &str) {
delete_partial_match_collection(&DISK_SIZE_GAUGE, collection);
}
/// Drop a collection's volume server series once its last volume leaves this
/// server. These gauges are only ever set for collections still present, so the
/// values from the heartbeat that saw the last volume would otherwise stand
/// until the process restarts.
pub fn delete_volume_server_collection_metrics(collection: &str) {
let _ = DISK_SIZE_GAUGE.remove_label_values(&[collection, DISK_SIZE_LABEL_NORMAL]);
let _ = DISK_SIZE_GAUGE.remove_label_values(&[collection, DISK_SIZE_LABEL_DELETED_BYTES]);
delete_partial_match_collection(&READ_ONLY_VOLUME_GAUGE, collection);
}
/// Remove all metric entries from a GaugeVec where the "collection" label matches.
/// This emulates Go's `DeletePartialMatch(prometheus.Labels{"collection": collection})`.
fn delete_partial_match_collection(gauge: &GaugeVec, collection: &str) {
+20 -126
View File
@@ -842,7 +842,8 @@ fn build_heartbeat_with_ec_status(
// master can tell whether applying what it was sent leaves it current.
// Volumes skipped below -- quarantined, phantom, expired -- are in neither.
let mut volume_digest: u64 = 0;
let (send_full_list, report_generation, report_pass) = store.volume_report.begin();
let (send_full_list, report_generation) = store.volume_report.begin();
let mut reported_hashes: HashMap<VolumeReportKey, u64> = HashMap::new();
let mut changed_volumes = Vec::new();
let mut max_file_key = NeedleId(0);
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
@@ -940,14 +941,8 @@ fn build_heartbeat_with_ec_status(
let hash = report_hash(&volume_message);
volume_digest ^= hash;
let key: VolumeReportKey = (volume_message.disk_id, volume_message.id);
// A snapshot must leave the reporting state as it found it, so
// it asks rather than marks.
let is_news = if commit_report {
store.volume_report.record(key, hash, report_pass)
} else {
store.volume_report.changed(key, hash)
};
if send_full_list || is_news {
reported_hashes.insert(key, hash);
if send_full_list || store.volume_report.changed(key, hash) {
changed_volumes.push(volume_message.clone());
}
volumes.push(volume_message);
@@ -956,30 +951,24 @@ fn build_heartbeat_with_ec_status(
should_delete_volume = true;
}
// Track disk size by collection. A volume on its way out is left
// out: an entry here is also what says the collection is still on
// this server.
// Track disk size by collection
let entry = disk_sizes.entry(vol.collection.clone()).or_insert((0, 0));
if !should_delete_volume {
let entry = disk_sizes.entry(vol.collection.clone()).or_insert((0, 0));
entry.0 += volume_size;
entry.1 += vol.deleted_size();
}
// An entry here is what says the collection is still on this
// server, so a volume on its way out must not make one.
if !should_delete_volume {
let read_only = ro_counts.entry(vol.collection.clone()).or_default();
if vol.is_read_only() {
read_only.is_read_only += 1;
if vol.is_no_write_or_delete() {
read_only.no_write_or_delete += 1;
}
if vol.is_no_write_can_delete() {
read_only.no_write_can_delete += 1;
}
if loc.is_disk_space_low.load(Ordering::Relaxed) {
read_only.is_disk_space_low += 1;
}
let read_only = ro_counts.entry(vol.collection.clone()).or_default();
if !should_delete_volume && vol.is_read_only() {
read_only.is_read_only += 1;
if vol.is_no_write_or_delete() {
read_only.no_write_or_delete += 1;
}
if vol.is_no_write_can_delete() {
read_only.no_write_can_delete += 1;
}
if loc.is_disk_space_low.load(Ordering::Relaxed) {
read_only.is_disk_space_low += 1;
}
}
@@ -1013,17 +1002,6 @@ fn build_heartbeat_with_ec_status(
.with_label_values(&[col, crate::metrics::READ_ONLY_LABEL_IS_DISK_SPACE_LOW])
.set(counts.is_disk_space_low as f64);
}
// ro_counts has an entry for every collection that kept a volume through
// this pass, including the ones counting zero read-only volumes.
{
let mut reported = store.reported_collections.lock().unwrap();
for col in reported.iter() {
if !ro_counts.contains_key(col) {
crate::metrics::delete_volume_server_collection_metrics(col);
}
}
*reported = ro_counts.keys().cloned().collect();
}
// Update max volumes gauge
let total_max: i64 = max_volume_counts.values().map(|v| *v as i64).sum();
crate::metrics::MAX_VOLUMES.set(total_max);
@@ -1031,7 +1009,7 @@ fn build_heartbeat_with_ec_status(
// Only when this heartbeat is going to be sent: marking volumes reported
// and then discarding the message would leave the master never told.
if commit_report {
store.volume_report.commit(report_pass, report_generation);
store.volume_report.commit(reported_hashes, report_generation);
}
// has_no_volumes says the server holds nothing, so it may only be derived
@@ -1099,14 +1077,6 @@ fn collect_live_ec_shards(
.with_label_values(&[col, crate::metrics::DISK_SIZE_LABEL_EC])
.set(*size as f64);
}
let mut reported = store.reported_ec_collections.lock().unwrap();
for col in reported.iter() {
if !ec_sizes.contains_key(col) {
let _ = crate::metrics::DISK_SIZE_GAUGE
.remove_label_values(&[col, crate::metrics::DISK_SIZE_LABEL_EC]);
}
}
*reported = ec_sizes.keys().cloned().collect();
}
ec_shards
@@ -1458,10 +1428,10 @@ mod tests {
store.volume_report.accept_deltas();
build_heartbeat(&test_config(), &mut store);
let (full, generation, pass) = store.volume_report.begin();
let (full, generation) = store.volume_report.begin();
assert!(!full);
store.volume_report.request_full_list();
store.volume_report.commit(pass, generation);
store.volume_report.commit(HashMap::new(), generation);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert_eq!(heartbeat.volumes.len(), 2);
@@ -1626,82 +1596,6 @@ mod tests {
);
}
fn collection_series(gauge: &prometheus::GaugeVec, collection: &str) -> usize {
use prometheus::core::Collector;
gauge
.collect()
.iter()
.flat_map(|family| family.get_metric().to_vec())
.filter(|metric| {
metric
.get_label()
.iter()
.any(|label| label.get_name() == "collection" && label.get_value() == collection)
})
.count()
}
// The per-collection gauges are only ever set for collections the heartbeat
// still finds on this server. A volume.balance that moves a collection's
// last volume off a server used to leave its read-only count - marked
// read-only for the move, moments before it went - standing on that server
// until a restart, with nothing in volume.list to match it.
#[test]
fn test_build_heartbeat_clears_metrics_of_departed_collection() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let collection = "heartbeat_departed_case";
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
8,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
store
.add_volume(
VolumeId(21),
collection,
None,
None,
0,
DiskType::HardDrive,
Version::current(),
)
.unwrap();
{
let (_, volume) = store.find_volume_mut(VolumeId(21)).unwrap();
volume.set_read_only().unwrap();
}
build_heartbeat(&test_config(), &mut store);
assert_eq!(
READ_ONLY_VOLUME_GAUGE
.with_label_values(&[collection, READ_ONLY_LABEL_IS_READ_ONLY])
.get(),
1.0
);
assert!(store.unmount_volume(VolumeId(21)));
build_heartbeat(&test_config(), &mut store);
assert_eq!(
collection_series(&READ_ONLY_VOLUME_GAUGE, collection),
0,
"read-only series left after the collection left the server"
);
assert_eq!(
collection_series(&DISK_SIZE_GAUGE, collection),
0,
"disk size series left after the collection left the server"
);
}
#[test]
fn test_build_heartbeat_reports_disk_bytes() {
let temp_dir = tempfile::tempdir().unwrap();
-10
View File
@@ -4,10 +4,8 @@
//! It coordinates volume placement, lookup, and lifecycle operations.
//! Matches Go's storage/store.go.
use std::collections::HashSet;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use crate::config::MinFreeSpace;
use crate::pb::master_pb;
@@ -34,12 +32,6 @@ pub struct Store {
pub data_center: String,
pub rack: String,
pub volume_report: crate::storage::volume_report::VolumeReportState,
/// Collections the last heartbeat set per-collection gauges for. Those
/// gauges are only ever set for collections still held here, so one whose
/// last volume leaves - moved away by volume.balance, say - would keep
/// reporting the heartbeat that saw it.
pub reported_collections: Mutex<HashSet<String>>,
pub reported_ec_collections: Mutex<HashSet<String>>,
}
impl Store {
@@ -57,8 +49,6 @@ impl Store {
volume_report: Default::default(),
data_center: String::new(),
rack: String::new(),
reported_collections: Mutex::new(HashSet::new()),
reported_ec_collections: Mutex::new(HashSet::new()),
}
}
+30 -87
View File
@@ -1,6 +1,7 @@
//! Mirror of `weed/storage/store_volume_report.go`.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
/// Identifies one reported copy. Keyed by disk as well as id because a volume
@@ -8,34 +9,6 @@ use std::sync::Mutex;
/// other's changes untold.
pub type VolumeReportKey = (u32, u32);
/// What the master was told about one volume copy: the hash that detects
/// change, and the heartbeat pass that last found the copy held.
#[derive(Clone, Copy)]
struct ReportedVolume {
hash: u64,
pass: u64,
}
/// Everything a heartbeat reads and writes about what the master was told,
/// under one lock. The full-list flag and the generation that answers it have
/// to move together: split across atomics, a request landing between two of
/// them is answered by a heartbeat that never carried a list. Go holds a single
/// mutex over the same fields.
#[derive(Default)]
struct ReportState {
/// Set once the master says it compares digests. Until then the whole list
/// goes every time, which is what an older master needs.
deltas_accepted: bool,
full_list_needed: bool,
/// Counts requests for the whole list, so one arriving while a heartbeat is
/// being built is not marked satisfied by it.
full_list_generation: u64,
/// Numbers heartbeats, so one can mark the copies it finds held without
/// building a second map of them.
pass: u64,
last_reported: HashMap<VolumeReportKey, ReportedVolume>,
}
/// Remembers what the master was last told about each volume, so a heartbeat
/// can carry only what moved since.
///
@@ -45,86 +18,56 @@ struct ReportState {
/// until one accepts changes.
#[derive(Default)]
pub struct VolumeReportState {
state: Mutex<ReportState>,
/// Set once the master says it compares digests. Until then the whole list
/// goes every time, which is what an older master needs.
deltas_accepted: AtomicBool,
full_list_needed: AtomicBool,
/// Counts requests for the whole list, so one arriving while a heartbeat is
/// being built is not marked satisfied by it.
full_list_generation: AtomicU64,
last_reported: Mutex<HashMap<VolumeReportKey, u64>>,
}
impl VolumeReportState {
/// Drops everything known about the master's view.
pub fn reset(&self) {
let mut state = self.state.lock().unwrap();
state.deltas_accepted = false;
state.full_list_needed = true;
state.full_list_generation += 1;
state.last_reported.clear();
self.deltas_accepted.store(false, Ordering::Relaxed);
self.full_list_needed.store(true, Ordering::Relaxed);
self.full_list_generation.fetch_add(1, Ordering::Relaxed);
self.last_reported.lock().unwrap().clear();
}
pub fn accept_deltas(&self) {
self.state.lock().unwrap().deltas_accepted = true;
self.deltas_accepted.store(true, Ordering::Relaxed);
}
pub fn request_full_list(&self) {
let mut state = self.state.lock().unwrap();
state.full_list_needed = true;
state.full_list_generation += 1;
self.full_list_needed.store(true, Ordering::Relaxed);
self.full_list_generation.fetch_add(1, Ordering::Relaxed);
}
/// Opens a heartbeat: whether it must carry the whole list, the request it
/// answers, and the pass number that marks the copies it finds still held.
pub fn begin(&self) -> (bool, u64, u64) {
let mut state = self.state.lock().unwrap();
state.pass += 1;
(
state.full_list_needed || !state.deltas_accepted,
state.full_list_generation,
state.pass,
)
/// Reports whether this heartbeat must carry the whole list, and the
/// request it answers.
pub fn begin(&self) -> (bool, u64) {
let full = self.full_list_needed.load(Ordering::Relaxed)
|| !self.deltas_accepted.load(Ordering::Relaxed);
(full, self.full_list_generation.load(Ordering::Relaxed))
}
/// Reports whether the master needs telling about this volume, given what
/// it was last told. For a caller that is only taking a snapshot and so
/// must leave the reporting state alone; a heartbeat calls `record`.
/// it was last told.
pub fn changed(&self, key: VolumeReportKey, hash: u64) -> bool {
self.state
.lock()
.unwrap()
.last_reported
.get(&key)
.is_none_or(|previous| previous.hash != hash)
self.last_reported.lock().unwrap().get(&key) != Some(&hash)
}
/// Marks one volume copy as held by the heartbeat being built, and reports
/// whether the master needs telling about it. It updates the entry already
/// held rather than build a second map beside it, so a server whose volumes
/// are quiet allocates nothing per volume per heartbeat.
pub fn record(&self, key: VolumeReportKey, hash: u64, pass: u64) -> bool {
let mut state = self.state.lock().unwrap();
match state.last_reported.get_mut(&key) {
Some(previous) => {
let changed = previous.hash != hash;
previous.hash = hash;
previous.pass = pass;
changed
}
None => {
state
.last_reported
.insert(key, ReportedVolume { hash, pass });
true
}
}
}
/// Closes the heartbeat. Copies this pass did not find are forgotten, so one
/// that comes back is reported again.
pub fn commit(&self, pass: u64, generation: u64) {
let mut state = self.state.lock().unwrap();
state
.last_reported
.retain(|_, reported| reported.pass == pass);
/// Records what this heartbeat told the master. Volumes absent from
/// `reported` are forgotten, so one that comes back is reported again.
pub fn commit(&self, reported: HashMap<VolumeReportKey, u64>, generation: u64) {
*self.last_reported.lock().unwrap() = reported;
// A request that arrived while this heartbeat was being built asked
// about a later state than it carries, so it stands.
if state.full_list_generation == generation {
state.full_list_needed = false;
if self.full_list_generation.load(Ordering::Relaxed) == generation {
self.full_list_needed.store(false, Ordering::Relaxed);
}
}
}
+2 -9
View File
@@ -22,19 +22,12 @@ invalid size", which reads like a protocol bug rather than a wrong port.
## Metrics
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646 --metrics-port 9328
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646 --metrics-port 9327
Serves `/health`, `/ready` and `/metrics` on that port, the same three the Go
worker serves under `weed worker -metricsPort`, so one scrape config covers
workers in either language. Off by default, and bound to loopback unless
`--metrics-ip` says otherwise, because the endpoint is unauthenticated. 9328
continues the series the other components use (master 9324, volume 9325, filer
9326, s3 9327); an IPv6 address works with or without brackets.
Grafana: the "Plugin Workers" row of `other/metrics/grafana_seaweedfs.json`
graphs these. Its panels filter on `$cluster`, which comes from the scrape job's
labels, so scrape the worker the way the rest of the cluster is scraped or the
row stays empty.
`--metrics-ip` says otherwise, because the endpoint is unauthenticated.
Names are `SeaweedFS_worker_*`, matching the Go side's convention. The pair
worth alerting on is `objects_seen_total` and `objects_skipped_total`: a sweep
@@ -1,97 +0,0 @@
//! What every integration test in this crate needs to drive a handler: a sender
//! that keeps what the handler sent, and the two settings that make a handler
//! usable against a test gateway.
//!
//! Each test binary compiles this module on its own and uses part of it.
#![allow(dead_code)]
use std::collections::HashMap;
use std::sync::Mutex;
use anyhow::Result;
use seaweed_worker_core::pb::{
config_value::Kind, ActivityEvent, ConfigValue, DetectionComplete, DetectionProposals,
JobCompleted, JobProgressUpdate, JobProposal, ObjectObservation, WorkerObservations,
};
use seaweed_worker_core::{DetectionSender, ExecutionSender};
/// Keeps everything a handler reports, so a test can assert on it afterwards.
#[derive(Default)]
pub struct Recorder {
pub proposals: Mutex<Vec<JobProposal>>,
pub observations: Mutex<Vec<ObjectObservation>>,
pub completed: Mutex<Vec<JobCompleted>>,
}
impl DetectionSender for Recorder {
fn send_proposals(&self, proposals: DetectionProposals) -> Result<()> {
self.proposals.lock().unwrap().extend(proposals.proposals);
Ok(())
}
fn send_complete(&self, _complete: DetectionComplete) -> Result<()> {
Ok(())
}
fn send_activity(&self, _activity: ActivityEvent) -> Result<()> {
Ok(())
}
fn send_observations(&self, observations: WorkerObservations) -> Result<()> {
self.observations
.lock()
.unwrap()
.extend(observations.observations);
Ok(())
}
}
impl ExecutionSender for Recorder {
fn send_progress(&self, _progress: JobProgressUpdate) -> Result<()> {
Ok(())
}
fn send_completed(&self, completed: JobCompleted) -> Result<()> {
self.completed.lock().unwrap().push(completed);
Ok(())
}
}
/// The gateway to run against, or nothing, in which case the caller skips:
/// these handlers rewrite real files, and there is nothing to learn from them
/// against a fake.
pub fn namespace_url() -> Option<String> {
std::env::var("WEED_LANCE_NAMESPACE")
.ok()
.filter(|s| !s.is_empty())
}
pub fn int_config(name: &str, value: i64) -> HashMap<String, ConfigValue> {
let mut values = HashMap::new();
values.insert(
name.to_string(),
ConfigValue {
kind: Some(Kind::Int64Value(value)),
},
);
values
}
/// What to reach the data with where the namespace vends nothing of its own -
/// a gateway without STS vends no credentials, and one bound to a wildcard
/// address vends no endpoint either. Taken from the environment so a harness
/// can point these tests at a gateway that does check what it is given.
pub fn fallback() -> weed_lance_worker::dataset::FallbackOptions {
let mut options = weed_lance_worker::dataset::FallbackOptions::new();
let from_env =
|name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.to_string());
options.insert(
"aws_access_key_id".to_string(),
from_env("AWS_ACCESS_KEY_ID", "any"),
);
options.insert(
"aws_secret_access_key".to_string(),
from_env("AWS_SECRET_ACCESS_KEY", "any"),
);
if let Ok(endpoint) = std::env::var("AWS_ENDPOINT_URL") {
options.insert("aws_endpoint".to_string(), endpoint);
options.insert("allow_http".to_string(), "true".to_string());
}
options
}
@@ -5,26 +5,82 @@
//! nothing to learn from it against a fake.
use std::collections::HashMap;
use std::sync::Mutex;
use anyhow::Result;
use seaweed_worker_core::pb::{
config_value::Kind, ExecuteJobRequest, JobSpec, RunDetectionRequest,
config_value::Kind, ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest,
JobCompleted, JobProgressUpdate, JobProposal, JobSpec, RunDetectionRequest,
};
use seaweed_worker_core::{JobHandler, PreviewProvider};
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler, PreviewProvider};
use weed_lance_worker::catalog::NamespaceClient;
use weed_lance_worker::jobs::cleanup::CleanupVersionsHandler;
use weed_lance_worker::jobs::compact::{CompactHandler, JOB_TYPE};
use weed_lance_worker::jobs::indices::OptimizeIndicesHandler;
use weed_lance_worker::preview::LancePreview;
mod common;
use common::{fallback, int_config, namespace_url, Recorder};
#[derive(Default)]
struct Recorder {
proposals: Mutex<Vec<JobProposal>>,
observations: Mutex<Vec<seaweed_worker_core::pb::ObjectObservation>>,
completed: Mutex<Vec<JobCompleted>>,
}
impl DetectionSender for Recorder {
fn send_proposals(&self, proposals: DetectionProposals) -> Result<()> {
self.proposals.lock().unwrap().extend(proposals.proposals);
Ok(())
}
fn send_complete(&self, _complete: DetectionComplete) -> Result<()> {
Ok(())
}
fn send_activity(&self, _activity: seaweed_worker_core::pb::ActivityEvent) -> Result<()> {
Ok(())
}
fn send_observations(
&self,
observations: seaweed_worker_core::pb::WorkerObservations,
) -> Result<()> {
self.observations
.lock()
.unwrap()
.extend(observations.observations);
Ok(())
}
}
impl ExecutionSender for Recorder {
fn send_progress(&self, _progress: JobProgressUpdate) -> Result<()> {
Ok(())
}
fn send_completed(&self, completed: JobCompleted) -> Result<()> {
self.completed.lock().unwrap().push(completed);
Ok(())
}
}
/// These tests drive one live gateway and one shared catalog: `list_all_tables`
/// sweeps everything, so a table another test is writing shows up in this test's
/// detection. Rust runs a binary's tests concurrently, so take a lock.
static GATEWAY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
fn namespace_url() -> Option<String> {
std::env::var("WEED_LANCE_NAMESPACE")
.ok()
.filter(|s| !s.is_empty())
}
fn int_config(name: &str, value: i64) -> HashMap<String, ConfigValue> {
let mut values = HashMap::new();
values.insert(
name.to_string(),
ConfigValue {
kind: Some(Kind::Int64Value(value)),
},
);
values
}
/// Declares a table through the namespace and writes `fragments` one-row
/// appends into it, so a test brings its own state instead of depending on
/// whatever a previous run left behind.
@@ -149,12 +205,15 @@ async fn compacts_a_fragmented_table() {
eprintln!("WEED_LANCE_NAMESPACE is unset, skipping");
return;
};
let mut fallback = weed_lance_worker::dataset::FallbackOptions::new();
fallback.insert("aws_access_key_id".to_string(), "any".to_string());
fallback.insert("aws_secret_access_key".to_string(), "any".to_string());
// Seeded here rather than by a script, so the test is repeatable: a previous
// run compacts the table it depended on.
let encoded = seed_fragmented_table(&url, "compactme", 12)
.await
.expect("seed a fragmented table");
let handler = CompactHandler::new(url).with_fallback(fallback());
let handler = CompactHandler::new(url).with_fallback(fallback);
let recorder = Recorder::default();
let request = RunDetectionRequest {
@@ -229,6 +288,13 @@ async fn compacts_a_fragmented_table() {
eprintln!("compaction result: {summary}");
}
fn fallback() -> weed_lance_worker::dataset::FallbackOptions {
let mut options = weed_lance_worker::dataset::FallbackOptions::new();
options.insert("aws_access_key_id".to_string(), "any".to_string());
options.insert("aws_secret_access_key".to_string(), "any".to_string());
options
}
/// A table with more versions than the floor is proposed, and running the job
/// reports what it removed. The compaction test above leaves one behind.
#[tokio::test]
@@ -1,123 +0,0 @@
//! Maintains one table someone else wrote, and nothing else.
//!
//! The Go suite in test/s3tables/lifecycle drives a table through its whole
//! life - declared through the namespace, written by a Lance client, maintained,
//! read again, dropped - and this is the maintenance step of it, so that step
//! goes through the handlers a deployed worker runs rather than through the two
//! lance calls they wrap. The table to work on comes in as WEED_LANCE_TABLE
//! because the table is the Go test's, seeded and checked there.
//!
//! Skipped, like the rest of this crate's integration tests, unless
//! WEED_LANCE_NAMESPACE names a live gateway.
use std::collections::HashMap;
use seaweed_worker_core::pb::{ConfigValue, ExecuteJobRequest, JobSpec, RunDetectionRequest};
use seaweed_worker_core::JobHandler;
use weed_lance_worker::jobs::cleanup::{self, CleanupVersionsHandler};
use weed_lance_worker::jobs::compact::{CompactHandler, JOB_TYPE as COMPACT_JOB_TYPE};
mod common;
use common::{fallback, int_config, namespace_url, Recorder};
fn table() -> Option<String> {
std::env::var("WEED_LANCE_TABLE")
.ok()
.filter(|s| !s.is_empty())
}
/// Compacts the named table's fragments, then drops the versions compaction
/// left behind. Both go through the handler's own detect-then-execute path: a
/// proposal the worker would not have made is not one worth running.
#[tokio::test]
async fn maintains_the_named_table() {
let (Some(url), Some(name)) = (namespace_url(), table()) else {
eprintln!("WEED_LANCE_NAMESPACE or WEED_LANCE_TABLE is unset, skipping");
return;
};
// A table written as a fragment per append is the case this exists for, so
// anything above one fragment is worth merging here.
let mut config = int_config("min_fragments", 2);
config.extend(int_config("target_rows_per_fragment", 1_048_576));
let compact = CompactHandler::new(url.clone()).with_fallback(fallback());
run(&compact, COMPACT_JOB_TYPE, &name, config, true).await;
// Keep the current version and retain nothing else, so the versions
// compaction superseded are actually removed rather than counted.
let mut config = int_config("min_versions_to_keep", 1);
config.extend(int_config("retain_hours", 0));
let cleanup = CleanupVersionsHandler::new(url).with_fallback(fallback());
run(&cleanup, cleanup::JOB_TYPE, &name, config, true).await;
}
/// Detects, finds the proposal for `name`, and executes it. The config carries
/// every key both halves read; each ignores what it does not know.
async fn run<H: JobHandler>(
handler: &H,
job_type: &str,
name: &str,
config: HashMap<String, ConfigValue>,
required: bool,
) {
let recorder = Recorder::default();
handler
.detect(
&RunDetectionRequest {
request_id: format!("detect-{job_type}"),
job_type: job_type.to_string(),
worker_config_values: config.clone(),
..Default::default()
},
&recorder,
)
.await
.unwrap_or_else(|err| panic!("{job_type} detection failed: {err}"));
let proposals = recorder.proposals.lock().unwrap().clone();
let Some(proposal) = proposals.iter().find(|p| p.summary.contains(name)) else {
assert!(
!required,
"{job_type} proposed nothing for {name}, out of {} proposals",
proposals.len()
);
eprintln!("{job_type}: nothing to do for {name}");
return;
};
handler
.execute(
&ExecuteJobRequest {
request_id: format!("execute-{job_type}"),
job: Some(JobSpec {
job_id: format!("job-{job_type}"),
job_type: job_type.to_string(),
parameters: proposal.parameters.clone(),
..Default::default()
}),
worker_config_values: config,
..Default::default()
},
&recorder,
)
.await
.unwrap_or_else(|err| panic!("{job_type} execution failed: {err}"));
let completed = recorder.completed.lock().unwrap().clone();
let result = completed
.last()
.unwrap_or_else(|| panic!("{job_type} reported no completion"));
assert!(
result.success,
"{job_type} reported failure: {}",
result.error_message
);
eprintln!(
"{job_type}: {}",
result
.result
.as_ref()
.map(|r| r.summary.clone())
.unwrap_or_default()
);
}
-57
View File
@@ -109,7 +109,6 @@ func startFailoverCluster(t testing.TB, numVolumes, numMounts int) *failoverClus
require.NoError(t, c.waitForMount(mp, 30*time.Second),
"mount %d not ready\n%s", i, c.tailLog(fmt.Sprintf("mount%d", i)))
}
require.NoError(t, c.WaitForVolumeServers(60*time.Second))
return c
}
@@ -345,62 +344,6 @@ func (c *failoverCluster) WaitForHolders(vid uint32, count int, timeout time.Dur
}
}
// WaitForVolumeServers blocks until the master's topology lists every volume
// server. A volume server accepts connections well before the master knows it
// exists: a lone master only elects itself once its bootstrap check expires,
// and heartbeats sent before that are refused and retried with backoff, so
// registration lands seconds after the process is up. Until it does the
// topology has no data node at all, an assign fails with "no free volumes
// left", and the mount reports that as ENOSPC instead of retrying.
func (c *failoverCluster) WaitForVolumeServers(timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
registered := c.registeredVolumeServers()
var missing []string
for i := range c.volumePorts {
if address := c.VolumeServerAddress(i); !registered[address] {
missing = append(missing, address)
}
}
if len(missing) == 0 {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("volume servers %v not registered with the master within %v\n%s",
missing, timeout, c.MasterGet("/dir/status?pretty=y"))
}
time.Sleep(200 * time.Millisecond)
}
}
// registeredVolumeServers is the set of volume server addresses the master
// currently holds in its topology.
func (c *failoverCluster) registeredVolumeServers() map[string]bool {
var status struct {
Topology struct {
DataCenters []struct {
Racks []struct {
DataNodes []struct {
Url string `json:"Url"`
} `json:"DataNodes"`
} `json:"Racks"`
} `json:"DataCenters"`
} `json:"Topology"`
}
if err := json.Unmarshal([]byte(c.MasterGet("/dir/status")), &status); err != nil {
return nil
}
registered := make(map[string]bool)
for _, dc := range status.Topology.DataCenters {
for _, rack := range dc.Racks {
for _, dn := range rack.DataNodes {
registered[dn.Url] = true
}
}
}
return registered
}
// volumeIndexOf maps a server address back to its index, or -1.
func (c *failoverCluster) volumeIndexOf(address string) int {
for i := range c.volumePorts {
+1 -3
View File
@@ -190,9 +190,7 @@ func TestReadWithVolumeServerDown(t *testing.T) {
t.Logf("read %s (held by volume%d) with volume%d down in %v", name, victim, victim, elapsed)
require.NoError(t, c.StartVolume(victim))
// The next iteration picks its victim from the master's placement view,
// so wait for the restarted server to be in it again.
require.NoError(t, c.WaitForVolumeServers(60*time.Second))
time.Sleep(3 * time.Second) // let the master see the heartbeat again
}
}
-186
View File
@@ -1,186 +0,0 @@
package multi_master
import (
"fmt"
"math/rand/v2"
"os"
"strconv"
"testing"
"time"
)
// chaosRounds is one stop or start per round, enough to walk in and out of
// quorum several times without turning this into a soak test.
const chaosRounds = 12
// TestRandomStartStopElection bounces masters at random and holds the election
// to the two things it must never get wrong: two masters claiming leadership at
// once, and a quorum that comes back without agreeing on one. The cluster's
// identity has to survive the whole walk — a master that re-mints a TopologyId
// here is the split brain SetTopologyId kills its peers over.
func TestRandomStartStopElection(t *testing.T) {
for _, impl := range raftImplementations {
t.Run(impl.name, func(t *testing.T) {
seed := chaosSeed(t)
t.Logf("seed %d — replay this walk with MULTI_MASTER_IT_SEED=%d", seed, seed)
rng := rand.New(rand.NewPCG(seed, seed))
mc := NewMasterCluster(t, impl.raftHashicorp)
for i := range 3 {
mc.StartNode(i)
}
if err := mc.WaitForLeader(waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("cluster did not elect a leader: %v", err)
}
topologyId, err := mc.WaitForTopologyId(waitTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("no initial TopologyId: %v", err)
}
for round := 1; round <= chaosRounds; round++ {
target := rng.IntN(3)
if mc.IsNodeRunning(target) {
mc.StopNode(target)
t.Logf("round %d: stopped master %d, %d left running", round, target, runningMasters(mc))
} else {
mc.StartNode(target)
t.Logf("round %d: started master %d, %d now running", round, target, runningMasters(mc))
}
if err := waitForSettledElection(mc, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): %v", round, seed, err)
}
// /dir/status proxies to the leader, so this reads the value the
// cluster as a whole is carrying, not any one master's copy.
if runningMasters(mc) >= 2 {
id, err := mc.WaitForTopologyId(leaderElectionTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): %v", round, seed, err)
}
if id != topologyId {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): TopologyId changed from %s to %s", round, seed, topologyId, id)
}
}
}
// Everything back up, so the walk ends on a full cluster.
for i := range 3 {
mc.StartNode(i)
}
if _, err := waitForCommonLeader(mc, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("cluster did not recover after the walk (seed %d): %v", seed, err)
}
for i := range 3 {
if err := waitForPeerCount(mc, i, 2, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("master %d does not see the full cluster (seed %d): %v", i, seed, err)
}
}
id, err := mc.WaitForTopologyId(leaderElectionTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("no TopologyId after the walk (seed %d): %v", seed, err)
}
if id != topologyId {
mc.DumpLogs()
t.Fatalf("TopologyId changed from %s to %s over the walk (seed %d)", topologyId, id, seed)
}
})
}
}
// waitForSettledElection waits for a quorum to agree on one leader, and fails
// if two masters claim leadership across consecutive polls — anything shorter
// than that is a master on its way down.
//
// Below a quorum there is nothing to wait for: the walk moves on. A master that
// has lost its quorum can keep claiming leadership for tens of seconds under
// goraft, and it cannot commit anything in that window, so stepping down is a
// liveness question rather than a safety one. TestTwoMastersDownAndRestart
// holds that direction to account.
func waitForSettledElection(mc *MasterCluster, timeout time.Duration) error {
if runningMasters(mc) < 2 {
return nil
}
var lastErr error
splitPolls := 0
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
claims, err := leaderClaims(mc)
if err != nil {
lastErr = err
}
if len(claims) > 1 {
splitPolls++
if splitPolls > 1 {
return fmt.Errorf("masters %v all claim leadership", claims)
}
time.Sleep(waitTick)
continue
}
splitPolls = 0
if _, err := commonLeader(mc); err == nil {
return nil
} else {
lastErr = err
}
time.Sleep(waitTick)
}
if lastErr == nil {
lastErr = fmt.Errorf("cluster did not settle within %v", timeout)
}
return lastErr
}
// leaderClaims returns the running masters that call themselves leader. The
// error reports masters that did not answer at all, which is a reason to keep
// waiting rather than a verdict.
func leaderClaims(mc *MasterCluster) (claims []int, err error) {
for i := range 3 {
if !mc.IsNodeRunning(i) {
continue
}
cs, statusErr := mc.GetClusterStatus(i)
if statusErr != nil {
err = fmt.Errorf("master %d: %w", i, statusErr)
continue
}
if cs.IsLeader {
claims = append(claims, i)
}
}
return claims, err
}
func runningMasters(mc *MasterCluster) int {
count := 0
for i := range 3 {
if mc.IsNodeRunning(i) {
count++
}
}
return count
}
// chaosSeed picks the walk. It is random by default and always logged, so a
// failure names the seed that reproduces it.
func chaosSeed(t *testing.T) uint64 {
t.Helper()
if v := os.Getenv("MULTI_MASTER_IT_SEED"); v != "" {
seed, err := strconv.ParseUint(v, 10, 64)
if err != nil {
t.Fatalf("MULTI_MASTER_IT_SEED %q: %v", v, err)
}
return seed
}
return uint64(time.Now().UnixNano())
}
+31 -83
View File
@@ -33,9 +33,6 @@ type masterNode struct {
cmd *exec.Cmd
logFile string
stopped bool
// peersStr overrides the cluster-wide peer list for this node, so a test
// can start a master that only knows about a subset of the cluster.
peersStr string
}
// MasterCluster manages a 3-node master raft cluster for integration tests.
@@ -51,9 +48,6 @@ type MasterCluster struct {
// peers string shared by all nodes, e.g. "127.0.0.1:9333,127.0.0.1:9334,127.0.0.1:9335"
peersStr string
// raftHashicorp starts the masters with -raftHashicorp
raftHashicorp bool
}
// clusterStatus is the JSON returned by /cluster/status.
@@ -67,35 +61,6 @@ type clusterStatus struct {
func StartMasterCluster(t testing.TB) *MasterCluster {
t.Helper()
mc := NewMasterCluster(t, false)
for i := range 3 {
mc.StartNode(i)
}
if err := mc.WaitForLeader(waitTimeout); err != nil {
mc.DumpLogs()
mc.StopAll()
t.Fatalf("cluster did not elect a leader: %v", err)
}
// Wait for TopologyId to be generated and propagated. This is async
// after leader election, and we need it committed before tests can
// reliably stop/restart nodes.
if _, err := mc.WaitForTopologyId(waitTimeout); err != nil {
mc.DumpLogs()
mc.StopAll()
t.Fatalf("TopologyId not generated: %v", err)
}
return mc
}
// NewMasterCluster allocates ports and data directories for a 3-node master
// cluster without starting anything, so a test can choose what each node comes
// up with.
func NewMasterCluster(t testing.TB, raftHashicorp bool) *MasterCluster {
t.Helper()
weedBinary, err := findOrBuildWeedBinary()
if err != nil {
t.Fatalf("resolve weed binary: %v", err)
@@ -129,14 +94,32 @@ func NewMasterCluster(t testing.TB, raftHashicorp bool) *MasterCluster {
}
mc := &MasterCluster{
t: t,
weedBinary: weedBinary,
baseDir: baseDir,
logsDir: logsDir,
keepLogs: keepLogs,
nodes: nodes,
peersStr: strings.Join(peerParts, ","),
raftHashicorp: raftHashicorp,
t: t,
weedBinary: weedBinary,
baseDir: baseDir,
logsDir: logsDir,
keepLogs: keepLogs,
nodes: nodes,
peersStr: strings.Join(peerParts, ","),
}
for i := range 3 {
mc.StartNode(i)
}
if err := mc.WaitForLeader(waitTimeout); err != nil {
mc.DumpLogs()
mc.StopAll()
t.Fatalf("cluster did not elect a leader: %v", err)
}
// Wait for TopologyId to be generated and propagated. This is async
// after leader election, and we need it committed before tests can
// reliably stop/restart nodes.
if err := mc.WaitForTopologyId(waitTimeout); err != nil {
mc.DumpLogs()
mc.StopAll()
t.Fatalf("TopologyId not generated: %v", err)
}
t.Cleanup(func() {
@@ -145,14 +128,6 @@ func NewMasterCluster(t testing.TB, raftHashicorp bool) *MasterCluster {
return mc
}
// SetNodePeers narrows the peer list node i starts with, mirroring a
// StatefulSet whose replica count changed under a running master.
func (mc *MasterCluster) SetNodePeers(i int, peers string) {
mc.mu.Lock()
defer mc.mu.Unlock()
mc.nodes[i].peersStr = peers
}
// StartNode starts the master process at the given index (0–2).
func (mc *MasterCluster) StartNode(i int) {
mc.t.Helper()
@@ -169,24 +144,17 @@ func (mc *MasterCluster) StartNode(i int) {
mc.t.Fatalf("create log for node %d: %v", i, err)
}
peersStr := n.peersStr
if peersStr == "" {
peersStr = mc.peersStr
}
args := []string{
"master",
"-ip=127.0.0.1",
"-port=" + strconv.Itoa(n.port),
"-port.grpc=" + strconv.Itoa(n.grpcPort),
"-mdir=" + n.dataDir,
"-peers=" + peersStr,
"-peers=" + mc.peersStr,
"-electionTimeout=3s",
"-volumeSizeLimitMB=32",
"-defaultReplication=000",
}
if mc.raftHashicorp {
args = append(args, "-raftHashicorp")
}
n.cmd = exec.Command(mc.weedBinary, args...)
n.cmd.Dir = mc.baseDir
@@ -324,24 +292,6 @@ func (mc *MasterCluster) WaitForLeader(timeout time.Duration) error {
return fmt.Errorf("no leader elected within %v", timeout)
}
// WaitForNoLeader waits until no running master claims leadership. goraft only
// checks whether it still has a quorum on an election-timeout ticker, and needs
// its peers to go quiet for a full timeout first, so a master that has lost its
// quorum can keep claiming leadership for tens of seconds. It cannot commit
// anything in that window.
func (mc *MasterCluster) WaitForNoLeader(timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
idx, _ := mc.FindLeader()
if idx < 0 {
return nil
}
time.Sleep(waitTick)
}
idx, addr := mc.FindLeader()
return fmt.Errorf("master %d at %s still claims leadership after %v", idx, addr, timeout)
}
// WaitForNewLeader waits for a leader that is different from the given address.
func (mc *MasterCluster) WaitForNewLeader(oldLeaderAddr string, timeout time.Duration) (int, string, error) {
deadline := time.Now().Add(timeout)
@@ -355,20 +305,18 @@ func (mc *MasterCluster) WaitForNewLeader(oldLeaderAddr string, timeout time.Dur
return -1, "", fmt.Errorf("no new leader (different from %s) within %v", oldLeaderAddr, timeout)
}
// WaitForTopologyId waits until the leader reports a non-empty TopologyId, and
// returns it. It is only readable once the leader has applied the raft entry
// carrying it, which lands after the election it won.
func (mc *MasterCluster) WaitForTopologyId(timeout time.Duration) (string, error) {
// WaitForTopologyId waits until the leader reports a non-empty TopologyId.
func (mc *MasterCluster) WaitForTopologyId(timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if idx, _ := mc.FindLeader(); idx >= 0 {
if id, err := mc.GetTopologyId(idx); err == nil && id != "" {
return id, nil
return nil
}
}
time.Sleep(waitTick)
}
return "", fmt.Errorf("TopologyId not available within %v", timeout)
return fmt.Errorf("TopologyId not available within %v", timeout)
}
// WaitForNodeReady waits for node i to respond to HTTP.
+14 -10
View File
@@ -9,12 +9,7 @@ import (
const (
// Election timeout is 3s in our cluster config; allow generous margin.
leaderElectionTimeout = 30 * time.Second
// Losing a quorum is much slower to show than winning one. goraft only
// notices on an election-timeout ticker, after its peers have been quiet
// for a full timeout, and has been measured taking over 30s to step down.
leaderStepDownTimeout = 60 * time.Second
leaderElectionTimeout = 20 * time.Second
)
// TestLeaderDownAndRecoverQuickly verifies that when the leader is stopped and
@@ -154,11 +149,20 @@ func TestTwoMastersDownAndRestart(t *testing.T) {
mc.StopNode(down1)
mc.StopNode(down2)
// The surviving node alone cannot form a quorum, so it has to give up the
// leadership it is still claiming.
if err := mc.WaitForNoLeader(leaderStepDownTimeout); err != nil {
// The surviving node alone cannot form a quorum — no leader expected.
// Wait long enough for any stale leadership to expire (election timeout
// is 3s in our config, quorum check fires every election timeout).
time.Sleep(5 * time.Second)
soloLeaderIdx, _ := mc.FindLeader()
if soloLeaderIdx >= 0 {
// It's possible the survivor briefly thinks it's leader before stepping down.
// Give it time to realize it lost quorum.
time.Sleep(5 * time.Second)
soloLeaderIdx, _ = mc.FindLeader()
}
if soloLeaderIdx >= 0 {
mc.DumpLogs()
t.Fatalf("expected no leader with only 1 of 3 nodes: %v", err)
t.Fatalf("expected no leader with only 1 of 3 nodes, but node %d claims leadership", soloLeaderIdx)
}
// Restart both downed nodes.
-153
View File
@@ -1,153 +0,0 @@
package multi_master
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
var raftImplementations = []struct {
name string
raftHashicorp bool
}{
{"goraft", false},
{"hashicorp", true},
}
// TestFreshClusterFormsWithoutALeader covers the other half of the bootstrap
// decision: with no leader anywhere, three masters starting together still have
// to mint a cluster between them.
func TestFreshClusterFormsWithoutALeader(t *testing.T) {
for _, impl := range raftImplementations {
t.Run(impl.name, func(t *testing.T) {
mc := NewMasterCluster(t, impl.raftHashicorp)
for i := range 3 {
mc.StartNode(i)
}
if _, err := waitForCommonLeader(mc, waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("fresh cluster did not converge: %v", err)
}
for i := range 3 {
if err := waitForPeerCount(mc, i, 2, waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("master %d does not see the full cluster: %v", i, err)
}
}
})
}
}
// TestScaleUpOntoExistingLeader mirrors a Kubernetes master StatefulSet whose
// replica count goes back from one to three: master 0 keeps running as the
// leader of a single-peer cluster while two fresh masters come up pointing at
// all three. The newcomers start with an empty raft log, so neither raft
// implementation lets them campaign — the sitting leader has to admit them.
func TestScaleUpOntoExistingLeader(t *testing.T) {
for _, impl := range raftImplementations {
t.Run(impl.name, func(t *testing.T) {
mc := NewMasterCluster(t, impl.raftHashicorp)
// Master 0 is alone in its peer list, the way the operator renders
// -peers when spec.master.replicas is 1.
mc.SetNodePeers(0, mc.NodeAddress(0))
mc.StartNode(0)
if err := mc.WaitForLeader(waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("single master did not become leader: %v", err)
}
// Scale up. These two carry the full peer list; master 0 still
// runs with the old one and has never heard of them.
mc.StartNode(1)
mc.StartNode(2)
leader, err := waitForCommonLeader(mc, waitTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("masters did not converge after scaling up: %v", err)
}
if leader != mc.NodeAddress(0) {
t.Fatalf("leader moved to %s, want the sitting leader %s", leader, mc.NodeAddress(0))
}
if err := waitForPeerCount(mc, 0, 2, waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("leader did not admit both new masters: %v", err)
}
})
}
}
// waitForCommonLeader waits until every running master names the same leader,
// and returns it.
func waitForCommonLeader(mc *MasterCluster, timeout time.Duration) (string, error) {
var lastErr error
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
leader, err := commonLeader(mc)
if err == nil {
return leader, nil
}
lastErr = err
time.Sleep(waitTick)
}
return "", lastErr
}
func commonLeader(mc *MasterCluster) (string, error) {
agreed := ""
for i := range 3 {
if !mc.IsNodeRunning(i) {
continue
}
cs, err := mc.GetClusterStatus(i)
if err != nil {
return "", err
}
leader := pb.ServerAddress(cs.Leader).ToHttpAddress()
if leader == "" {
return "", fmt.Errorf("master %d has no leader", i)
}
if agreed == "" {
agreed = leader
} else if agreed != leader {
return "", fmt.Errorf("masters disagree on the leader: %s and %s", agreed, leader)
}
}
if agreed == "" {
return "", fmt.Errorf("no master is running")
}
return agreed, nil
}
// waitForPeerCount waits until node i reports the given number of raft peers.
// The count excludes the node itself.
func waitForPeerCount(mc *MasterCluster, i, want int, timeout time.Duration) error {
got := -1
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
cs, err := mc.GetClusterStatus(i)
if err == nil {
got = peerCountExcludingSelf(cs.Peers, mc.NodeAddress(i))
if got == want {
return nil
}
}
time.Sleep(waitTick)
}
return fmt.Errorf("master %d reports %d peers, want %d", i, got, want)
}
func peerCountExcludingSelf(peers []string, self string) int {
count := 0
for _, peer := range peers {
if pb.ServerAddress(peer).ToHttpAddress() != self {
count++
}
}
return count
}
@@ -1,15 +0,0 @@
# Seeds a Lance dataset so DuckDB has something to read. The catalog records
# where a table lives and does not carry its data, so the writing half is
# pylance; DuckDB then reads it over S3 with no catalog involved.
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir \
"lance-namespace==0.8.6" \
"pylance==10.0.0" \
"pyarrow==25.0.1"
COPY seed_table.py /app/
CMD ["python3", "/app/seed_table.py", "--help"]
@@ -1,66 +0,0 @@
# DuckDB Lance Integration Test
Reads SeaweedFS Lance tables from DuckDB's `lance` core extension, the
counterpart of the DuckDB Iceberg tests in `../catalog/`.
## What this one proves that the others do not
The LanceDB and Spark suites go through the catalog. DuckDB does not: it reaches
the data over S3 with no namespace involved. That exercises the other half of the
design — a table bucket's layout is a valid Lance dataset directory, so a table
stays readable when the catalog is not in the path.
## What it does
`TestDuckDBLance`:
1. Starts a `weed mini` cluster with S3 and the Lance Namespace enabled.
2. Creates a table bucket declared `LANCE`, then declares a table through the
namespace and writes a dataset into it with pylance.
3. Runs `duckdb_lance_ops.sql` in `duckdb/duckdb:latest`.
| Step | What it proves |
| --- | --- |
| `__lance_scan(s3://…)` | DuckDB reads a table this catalog created |
| `DESCRIBE` | the schema survived, vector column included |
| `WHERE id < 5` | the filter path |
| `lance_vector_search` | vector search over data behind SeaweedFS |
| a `.lance` path | the replacement scan works on a suffixed path |
| a suffix-less path | and does **not** see one without the suffix |
## The `.lance` suffix
DuckDB's replacement scan — `SELECT * FROM 's3://…'` — recognises a Lance dataset
by a `.lance` path suffix. Tables created through this catalog deliberately have
none: the catalog entry *is* the dataset directory, table names may not contain a
dot, and a suffix would leak into ARNs and policies.
So from DuckDB, a table in a SeaweedFS table bucket is read with
`__lance_scan('s3://bucket/namespace/table')` rather than the bare `FROM 's3://…'`
form. The test asserts both halves, so if the extension ever recognises a
suffix-less directory the test fails and tells us to update the documentation.
## Credentials
```sql
CREATE SECRET seaweedfs (
TYPE lance,
ACCESS_KEY_ID '…', SECRET_ACCESS_KEY '…',
REGION 'us-east-1',
ENDPOINT 'http://seaweed:8333',
ALLOW_HTTP true,
VIRTUAL_HOSTED_STYLE_REQUEST false
);
```
Those are object_store's key names, the same as everywhere else Lance touches
storage.
## Running it
cd test/s3tables/catalog_duckdb_lance
(cd ../../../weed && go build .) # the harness runs this binary
go test -run TestDuckDBLance -v -timeout 30m .
Skipped without Docker, in `-short` mode, and if the DuckDB image cannot load the
extension.
@@ -1,48 +0,0 @@
-- Read a SeaweedFS Lance table from DuckDB.
--
-- The lance extension reaches the data over S3 rather than through the
-- namespace, so what is exercised here is the layout on the S3 door and the
-- credentials, not the catalog protocol. That is the point: this is the client
-- that proves a Lance table stays readable without a catalog at all.
--
-- Placeholders are substituted by the Go harness: __ENDPOINT__, __KEY__,
-- __SECRET__, __TABLE__ (s3://bucket/ns/table), __SUFFIXED__ (the same data at a
-- path ending in .lance).
INSTALL lance;
LOAD lance;
CREATE SECRET seaweedfs (
TYPE lance,
ACCESS_KEY_ID '__KEY__',
SECRET_ACCESS_KEY '__SECRET__',
REGION 'us-east-1',
ENDPOINT '__ENDPOINT__',
ALLOW_HTTP true,
VIRTUAL_HOSTED_STYLE_REQUEST false
);
-- 1. The table the catalog created, read by URI. A table bucket's layout is a
-- valid Lance dataset directory, which is what makes this possible.
SELECT 'scan_rows=' || count(*) FROM __lance_scan('__TABLE__');
-- 2. Its schema survived, vector column included. Ordered, because string_agg
-- over an unordered relation is free to return the names in any order.
SELECT 'scan_columns=' || string_agg(column_name, ',' ORDER BY column_name)
FROM (DESCRIBE SELECT * FROM __lance_scan('__TABLE__'));
-- 3. A filter, so it is not only a full scan.
SELECT 'filtered_rows=' || count(*) FROM __lance_scan('__TABLE__') WHERE id < 5;
-- 4. Vector search, which is what the format is for. No index is built here, so
-- this is a brute-force search; the ids nearest the query are what matters.
SELECT 'nearest=' || string_agg(id::VARCHAR, ',' ORDER BY _distance ASC, id ASC)
FROM lance_vector_search('__TABLE__', 'vector',
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], k := 3);
-- 5. DuckDB's replacement scan recognises a path by its .lance suffix. Tables
-- this catalog creates deliberately have no suffix - the name is the table's
-- name, and a suffix would leak into ARNs and policies - so the bare
-- SELECT ... FROM 's3://…' form does not see them, and __lance_scan is the
-- way in. This asserts both halves so that a change upstream is noticed.
SELECT 'suffixed_rows=' || count(*) FROM '__SUFFIXED__';
@@ -1,390 +0,0 @@
// Package duckdblance reads SeaweedFS Lance tables from DuckDB's lance
// extension, the counterpart of the DuckDB Iceberg tests next door.
//
// DuckDB reaches the data over S3 rather than through the namespace, so what
// this proves is the other half of the design: a table bucket's layout is a
// valid Lance dataset directory, and a table stays readable with no catalog in
// the path at all. It also pins the one place that costs us - DuckDB's
// replacement scan recognises a dataset by its .lance suffix, which tables
// created through this catalog deliberately do not have.
package duckdblance
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/testutil"
)
const (
// Tracks whatever DuckDB users are actually running; the lance extension is
// a core extension, so there is nothing to pin beyond the image.
duckDBImage = "duckdb/duckdb:latest"
// Seeds a dataset for DuckDB to read.
seedImage = "seaweedfs-lance-seed"
startupTimeout = 60 * time.Second
clientTimeout = 15 * time.Minute
seededRows = 128
)
// TestDuckDBLance reads a table this catalog created, from DuckDB.
func TestDuckDBLance(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !hasDocker() {
t.Skip("Docker not available, skipping DuckDB Lance integration test")
}
env := newEnvironment(t)
defer env.cleanup()
env.start(t)
bucket := "duckdb-" + randomSuffix()
env.createTableBucket(t, bucket)
requireDuckDBLance(t)
buildSeedImage(t)
env.seedTable(t, bucket)
env.runDuckDB(t, bucket)
}
type environment struct {
weedBinary string
dataDir string
bindIP string
masterPort int
masterGrpcPort int
volumePort int
volumeGrpcPort int
filerPort int
filerGrpcPort int
s3Port int
s3GrpcPort int
lancePort int
accessKey string
secretKey string
weedCancel context.CancelFunc
weedCmd *exec.Cmd
}
func newEnvironment(t *testing.T) *environment {
t.Helper()
wd, err := os.Getwd()
if err != nil {
t.Fatalf("get working directory: %v", err)
}
seaweedDir := wd
for i := 0; i < 5; i++ {
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
break
}
seaweedDir = filepath.Dir(seaweedDir)
}
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
if info, statErr := os.Stat(weedBinary); statErr == nil && !info.IsDir() {
// `make test` builds first; a plain `go test` will otherwise drive a
// binary from days ago and report a pass for code it never ran.
t.Logf("using %s, built %s", weedBinary, info.ModTime().Format(time.RFC3339))
} else {
weedBinary = "weed"
if _, err := exec.LookPath(weedBinary); err != nil {
t.Skip("weed binary not found, skipping integration test")
}
}
dataDir, err := os.MkdirTemp("", "seaweed-duckdb-lance-test-*")
if err != nil {
t.Fatalf("create temp dir: %v", err)
}
ports := testutil.MustAllocatePorts(t, 9)
return &environment{
weedBinary: weedBinary,
dataDir: dataDir,
bindIP: testutil.FindBindIP(),
masterPort: ports[0],
masterGrpcPort: ports[1],
volumePort: ports[2],
volumeGrpcPort: ports[3],
filerPort: ports[4],
filerGrpcPort: ports[5],
s3Port: ports[6],
s3GrpcPort: ports[7],
lancePort: ports[8],
accessKey: "AKIAIOSFODNN7EXAMPLE",
secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
}
}
func (env *environment) start(t *testing.T) {
t.Helper()
iamConfigPath, err := testutil.WriteIAMConfig(env.dataDir, env.accessKey, env.secretKey)
if err != nil {
t.Fatalf("write IAM config: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
env.weedCancel = cancel
cmd := exec.CommandContext(ctx, env.weedBinary, "mini",
"-master.port", fmt.Sprintf("%d", env.masterPort),
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
"-volume.port", fmt.Sprintf("%d", env.volumePort),
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
"-filer.port", fmt.Sprintf("%d", env.filerPort),
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
"-s3.port", fmt.Sprintf("%d", env.s3Port),
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
"-s3.port.lance", fmt.Sprintf("%d", env.lancePort),
"-s3.config", iamConfigPath,
"-ip", env.bindIP,
"-ip.bind", "0.0.0.0",
"-dir", env.dataDir,
)
cmd.Dir = env.dataDir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(),
"AWS_ACCESS_KEY_ID="+env.accessKey,
"AWS_SECRET_ACCESS_KEY="+env.secretKey,
)
if err := cmd.Start(); err != nil {
t.Fatalf("start SeaweedFS: %v", err)
}
env.weedCmd = cmd
// The namespace answers /v1/table once it is serving, which is a cheaper
// readiness check than waiting on a bucket that does not exist yet.
url := fmt.Sprintf("http://%s:%d/v1/table", env.bindIP, env.lancePort)
if !waitForHTTP(url, startupTimeout) {
t.Fatalf("the Lance namespace did not become ready at %s", url)
}
}
// waitForHTTP polls until the URL answers at all. An auth refusal counts: it
// means the server is up, which is the only thing being waited on.
func waitForHTTP(url string, timeout time.Duration) bool {
client := &http.Client{Timeout: 2 * time.Second}
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
resp, err := client.Get(url)
if err != nil {
time.Sleep(500 * time.Millisecond)
continue
}
status := resp.StatusCode
resp.Body.Close()
if status < 500 {
return true
}
time.Sleep(500 * time.Millisecond)
}
return false
}
func (env *environment) cleanup() {
if env.weedCancel != nil {
env.weedCancel()
}
if env.weedCmd != nil {
_ = env.weedCmd.Wait()
}
if env.dataDir != "" {
_ = os.RemoveAll(env.dataDir)
}
}
// createTableBucket makes the bucket LanceDB will read through, declared LANCE
// so the catalog refuses anything of another format in it.
func (env *environment) createTableBucket(t *testing.T, bucket string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, env.weedBinary, "shell",
fmt.Sprintf("-master=%s:%d.%d", env.bindIP, env.masterPort, env.masterGrpcPort),
)
cmd.Stdin = strings.NewReader(fmt.Sprintf(
"s3tables.bucket -create -name %s -format LANCE -account 000000000000\nexit\n", bucket))
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("create table bucket %s: %v\n%s", bucket, err, out)
}
// weed shell reports a command's own failure on stdout and still exits 0, so
// the exit code alone would let a missing bucket through and turn a setup
// failure into a confusing engine failure later.
if !env.tableBucketExists(t, bucket) {
t.Fatalf("table bucket %s was not created:\n%s", bucket, out)
}
t.Logf("created LANCE table bucket %s", bucket)
}
// tableBucketExists asks the namespace, which lists table buckets at its root.
func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
t.Helper()
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// runSpark runs the SQL driver inside the stock Spark image. The connector is
// pulled from Maven at submit time, the way the Iceberg Spark suite pulls its
// runtime, so nothing has to be built here.
// requireDuckDBLance skips rather than fails when the image cannot load the
// extension, so a DuckDB build without it reads as "not applicable" rather than
// as a broken catalog.
func requireDuckDBLance(t *testing.T) {
t.Helper()
const ready = "lance extension ready"
cmd := exec.Command("docker", "run", "--rm", "--entrypoint", "duckdb", duckDBImage,
"-c", fmt.Sprintf("INSTALL lance; LOAD lance; SELECT '%s' AS marker;", ready))
out, err := cmd.CombinedOutput()
if err != nil || !strings.Contains(string(out), ready) {
t.Skipf("DuckDB image cannot load the lance extension: %v\n%s", err, out)
}
}
func buildSeedImage(t *testing.T) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "build", "-t", seedImage, "-f", "Dockerfile.seed", ".")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build the seed image: %v\n%s", err, out)
}
}
// seedTable declares a table through the namespace and writes a dataset into
// it, which is the split the catalog serves: it records where a table lives and
// does not carry its data.
func (env *environment) seedTable(t *testing.T, bucket string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
"--add-host", "host.docker.internal:host-gateway",
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
"-e", "AWS_REGION=us-east-1",
seedImage,
"python3", "/app/seed_table.py",
"--namespace-url", fmt.Sprintf("http://host.docker.internal:%d", env.lancePort),
"--s3-endpoint", fmt.Sprintf("http://host.docker.internal:%d", env.s3Port),
"--bucket", bucket,
"--rows", fmt.Sprintf("%d", seededRows),
"--access-key", env.accessKey,
"--secret-key", env.secretKey,
)
out, err := cmd.CombinedOutput()
t.Logf("seeder:\n%s", out)
if err != nil {
t.Fatalf("seeding the table failed: %v", err)
}
}
// runDuckDB substitutes the endpoint and paths into the SQL and runs it.
func (env *environment) runDuckDB(t *testing.T, bucket string) {
t.Helper()
sqlBytes, err := os.ReadFile("duckdb_lance_ops.sql")
if err != nil {
t.Fatalf("read the SQL: %v", err)
}
table := fmt.Sprintf("s3://%s/ml/embeddings", bucket)
sql := strings.NewReplacer(
"__ENDPOINT__", fmt.Sprintf("http://host.docker.internal:%d", env.s3Port),
"__KEY__", env.accessKey,
"__SECRET__", env.secretKey,
"__TABLE__", table,
"__SUFFIXED__", table+"-direct.lance",
).Replace(string(sqlBytes))
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "run", "--rm", "-i",
"--add-host", "host.docker.internal:host-gateway",
"--entrypoint", "duckdb", duckDBImage, "-c", sql)
out, err := cmd.CombinedOutput()
t.Logf("DuckDB output:\n%s", out)
if err != nil {
t.Fatalf("the DuckDB query failed: %v", err)
}
output := string(out)
for _, want := range []string{
fmt.Sprintf("scan_rows=%d", seededRows),
"scan_columns=id,title,vector",
"filtered_rows=5",
"nearest=1,0,2",
fmt.Sprintf("suffixed_rows=%d", seededRows),
} {
if !strings.Contains(output, want) {
t.Fatalf("DuckDB did not report %q", want)
}
}
// The other half of the suffix rule: a table this catalog created has no
// .lance suffix, so DuckDB's replacement scan does not see it and
// __lance_scan is the way in. If this ever starts working, the docs saying
// otherwise are wrong.
bare := exec.CommandContext(ctx, "docker", "run", "--rm", "-i",
"--add-host", "host.docker.internal:host-gateway",
"--entrypoint", "duckdb", duckDBImage,
"-c", fmt.Sprintf("INSTALL lance; LOAD lance; SELECT count(*) FROM '%s';", table))
bareOut, bareErr := bare.CombinedOutput()
// DuckDB exits nonzero for any error, so the exit status alone does not tell
// "the replacement scan refused the path" from "the query never ran": require
// the catalog error either way.
if !strings.Contains(string(bareOut), "does not exist") {
t.Fatalf("a suffix-less path did not fail the way the docs say it does (%v); "+
"if the replacement scan now reads it, update them:\n%s", bareErr, bareOut)
}
t.Logf("a suffix-less path is not seen by the replacement scan, as expected")
}
// hasDocker reports whether a Docker daemon answers. Bounded, because an
// unhealthy daemon makes `docker version` hang, and this runs before the test
// has a timeout of its own: better to skip than to eat the whole budget.
func hasDocker() bool {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return exec.CommandContext(ctx, "docker", "version").Run() == nil
}
func randomSuffix() string {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
suffix := make([]byte, 8)
for i := range suffix {
suffix[i] = charset[rand.Intn(len(charset))]
}
return string(suffix)
}
@@ -1,79 +0,0 @@
#!/usr/bin/env python3
"""Declare a table through the namespace and write a dataset into it.
Also writes the same rows to a second path whose name ends in `.lance`, because
DuckDB's replacement scan recognises a dataset by that suffix and tables created
through this catalog do not have one. The test asserts both behaviours so a
change upstream is noticed rather than silently making the docs wrong.
"""
import argparse
import sys
import warnings
warnings.filterwarnings("ignore")
import lance
import lance_namespace as ln
import pyarrow as pa
DIM = 8
def rows(count):
return pa.table(
{
"id": pa.array(list(range(count)), type=pa.int64()),
"title": pa.array([f"row-{i}" for i in range(count)]),
"vector": pa.array(
[[float(i) + d for d in range(DIM)] for i in range(count)],
type=pa.list_(pa.float32(), DIM),
),
}
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--namespace-url", required=True)
parser.add_argument("--s3-endpoint", required=True)
parser.add_argument("--bucket", required=True)
parser.add_argument("--namespace", default="ml")
parser.add_argument("--table", default="embeddings")
parser.add_argument("--rows", type=int, default=128)
parser.add_argument("--access-key", default="any")
parser.add_argument("--secret-key", default="any")
args = parser.parse_args()
storage = {
"aws_endpoint": args.s3_endpoint,
"allow_http": "true",
"aws_access_key_id": args.access_key,
"aws_secret_access_key": args.secret_key,
"aws_region": "us-east-1",
}
ns = ln.connect("rest", {"uri": args.namespace_url})
ns.create_namespace(ln.CreateNamespaceRequest(id=[args.bucket], mode="EXIST_OK"))
ns.create_namespace(
ln.CreateNamespaceRequest(id=[args.bucket, args.namespace], mode="EXIST_OK")
)
declared = ns.declare_table(
ln.DeclareTableRequest(id=[args.bucket, args.namespace, args.table])
)
lance.write_dataset(rows(args.rows), declared.location, storage_options=storage,
mode="overwrite")
print(f"seeded {args.rows} rows at {declared.location}")
# The same data under a name DuckDB's replacement scan recognises. Written
# directly rather than declared, because a table name containing a dot is
# not a valid catalog name.
suffixed = f"s3://{args.bucket}/{args.namespace}/{args.table}-direct.lance"
lance.write_dataset(rows(args.rows), suffixed, storage_options=storage,
mode="overwrite")
print(f"seeded {args.rows} rows at {suffixed}")
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -3
View File
@@ -33,9 +33,7 @@ Inside Spark:
## Configuration
The connector's catalog properties. The host names below are placeholders — the
test passes dynamically allocated `host.docker.internal` ports, and a real
deployment uses whatever address the gateway answers on:
The connector's catalog properties, for reference:
```
spark.sql.catalog.lance org.lance.spark.LanceNamespaceSparkCatalog
@@ -15,7 +15,6 @@ import argparse
import sys
from pyspark.sql import SparkSession
from pyspark.sql.types import ArrayType, FloatType
def check(condition, message):
@@ -96,21 +95,10 @@ def main():
print(f"count -> {count}")
check(count == 3, f"read back {count} rows, want 3")
# 4. The schema survived the round trip, vector column included - the type
# as well as the name, since a column that came back as ARRAY<DOUBLE> or
# ARRAY<STRING> would still be called "vector".
fields = {field.name: field.dataType for field in spark.table(table).schema.fields}
print(f"schema -> {[(n, t.simpleString()) for n, t in sorted(fields.items())]}")
check({"id", "title", "vector"} <= set(fields), f"schema lost columns: {sorted(fields)}")
vector = fields["vector"]
check(
isinstance(vector, ArrayType) and isinstance(vector.elementType, FloatType),
f"vector came back as {vector.simpleString()}, want array<float>",
)
check(
fields["id"].simpleString() == "bigint",
f"id came back as {fields['id'].simpleString()}, want bigint",
)
# 4. The schema survived the round trip, vector column included.
schema = {field.name for field in spark.table(table).schema.fields}
print(f"schema -> {sorted(schema)}")
check({"id", "title", "vector"} <= schema, f"schema lost columns: {schema}")
# 5. A filter, so it is not only a full scan.
rows = spark.sql(f"SELECT id, title FROM {table} WHERE id >= 2 ORDER BY id").collect()
@@ -125,24 +113,10 @@ def main():
print(f"count after a second commit -> {count}")
check(count == 4, f"after appending, {count} rows, want 4")
# 7. And the dataset is readable straight off its location, with no catalog
# in the path. This is the property that lets duckdb, pandas and
# DataFusion read these tables, so it is read rather than asserted by
# comment: the reader is given the storage options directly and never
# consults spark.sql.catalog.lance.
# 7. And the dataset is readable straight off its location, which is what
# keeps the catalog optional.
location = f"s3://{args.bucket}/{args.namespace}/{args.table}"
direct = (
spark.read.format("lance")
.option("aws_endpoint", args.s3_endpoint)
.option("allow_http", "true")
.option("aws_access_key_id", args.access_key)
.option("aws_secret_access_key", args.secret_key)
.option("aws_region", "us-east-1")
.load(location)
)
direct_count = direct.count()
print(f"direct read of {location} -> {direct_count} rows")
check(direct_count == 4, f"direct read got {direct_count} rows, want 4")
print(f"dataset location -> {location}")
spark.stop()
print("PASS")
@@ -219,32 +219,12 @@ func (env *environment) createTableBucket(t *testing.T, bucket string) {
)
cmd.Stdin = strings.NewReader(fmt.Sprintf(
"s3tables.bucket -create -name %s -format LANCE -account 000000000000\nexit\n", bucket))
out, err := cmd.CombinedOutput()
if err != nil {
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("create table bucket %s: %v\n%s", bucket, err, out)
}
// weed shell reports a command's own failure on stdout and still exits 0, so
// the exit code alone would let a missing bucket through and turn a setup
// failure into a confusing engine failure later.
if !env.tableBucketExists(t, bucket) {
t.Fatalf("table bucket %s was not created:\n%s", bucket, out)
}
t.Logf("created LANCE table bucket %s", bucket)
}
// tableBucketExists asks the namespace, which lists table buckets at its root.
func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
t.Helper()
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// runSpark runs the SQL driver inside the stock Spark image. The connector is
// pulled from Maven at submit time, the way the Iceberg Spark suite pulls its
// runtime, so nothing has to be built here.
@@ -254,23 +234,16 @@ func (env *environment) runSpark(t *testing.T, bucket string) {
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
script, absErr := filepath.Abs("spark_lance_ops.py")
if absErr != nil {
t.Fatalf("resolve the driver script: %v", absErr)
script, err := filepath.Abs("spark_lance_ops.py")
if err != nil {
t.Fatalf("resolve the driver script: %v", err)
}
// Ivy needs somewhere writable, and the Spark image runs as a user without a
// home directory it can write to. Kept outside the run's data directory so
// the 287MB connector bundle is downloaded once rather than on every run,
// and under the user's own cache rather than a shared temp path: this is
// mounted into a container running as root, so another local user must not
// be able to pre-create it and choose what Spark loads.
cacheRoot, err := os.UserCacheDir()
if err != nil {
cacheRoot = env.dataDir
}
ivyDir := filepath.Join(cacheRoot, "seaweedfs-lance-spark-ivy")
if err := os.MkdirAll(ivyDir, 0o755); err != nil {
// the connector bundle is downloaded once rather than on every run.
ivyDir := filepath.Join(os.TempDir(), "seaweedfs-lance-spark-ivy")
if err := os.MkdirAll(ivyDir, 0o777); err != nil {
t.Fatalf("create the ivy directory: %v", err)
}
@@ -320,13 +293,8 @@ func tailLines(out string, n int) string {
strings.Join(lines[len(lines)-n:], "\n")
}
// hasDocker reports whether a Docker daemon answers. Bounded, because an
// unhealthy daemon makes `docker version` hang, and this runs before the test
// has a timeout of its own: better to skip than to eat the whole budget.
func hasDocker() bool {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return exec.CommandContext(ctx, "docker", "version").Run() == nil
return exec.Command("docker", "version").Run() == nil
}
func randomSuffix() string {
-17
View File
@@ -1,17 +0,0 @@
# Lance client for the Lance half of the lifecycle test.
#
# Pinned to the versions this suite was verified against, the way
# catalog_lancedb pins its client: an unrelated upstream release should not be
# able to change what an old commit reproduces.
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir \
"lance-namespace==0.8.6" \
"pylance==10.0.0" \
"pyarrow==25.0.1"
COPY lance_lifecycle.py /app/
CMD ["python3", "/app/lance_lifecycle.py", "--help"]
@@ -1,10 +0,0 @@
# PyIceberg client for the Iceberg half of the lifecycle test.
FROM python:3.11-slim
WORKDIR /app
RUN pip install --no-cache-dir "pyiceberg[s3fs]" pyarrow
COPY iceberg_lifecycle.py /app/
CMD ["python3", "/app/iceberg_lifecycle.py", "--help"]
-77
View File
@@ -1,77 +0,0 @@
# Table Lifecycle Integration Tests
One table, all the way through: created in the catalog, filled by a real client,
maintained, read again, dropped. Once for Iceberg and once for Lance. The
Iceberg half always maintains through the worker; the Lance half maintains
through the Rust worker or through the lance library, depending on what the
environment has - see below.
## Why this suite exists
[#10853](https://github.com/seaweedfs/seaweedfs/issues/10853) was a compaction
that rewrote every dictionary-encoded column onto a single value. It shipped.
The maintenance tests we had were thorough about the bookkeeping - sequence
numbers, added and deleted manifest entries, metadata versions, the manifest
list - and every one of them passed, because not one of them opened the parquet
file the worker had just written.
So the assertion here is the dull one nothing else was making: tally the table
before maintenance, tally it again after, and require the two to be equal. The
tally is a row count, the cardinality of each dictionary-encoded column, and an
md5 over whole rows. The cardinalities name the failure that happened; the
digest catches a rewrite that keeps every column's cardinality and hands the
values to the wrong rows.
The same shape covers Lance, because the exposure is the same: a compaction that
merges fragments can hand back a table that reads without complaint and answers
wrongly.
## What runs
`TestIcebergTableLifecycle` starts a `weed mini` cluster, declares an `ICEBERG`
table bucket, and runs two clients against it:
| Client | Why both |
| --- | --- |
| DuckDB | the client the bug was reported against, and the only one here that writes the deprecated `PLAIN_DICTIONARY` encoding - parquet-go normalizes it away on write, so a Go writer cannot produce it |
| PyIceberg | writes `RLE_DICTIONARY`, the modern spelling, so between the two the merge is checked against both dictionary encodings in the spec |
Between the write and the read, the test runs the worker's whole maintenance
cycle in-process against the live filer: compact, expire snapshots, remove
orphans, rewrite manifests. A compaction that merged nothing fails the test
rather than passing it - otherwise the read afterwards is checking a file the
worker never wrote.
`TestLanceTableLifecycle` does the same against a `LANCE` bucket: declare
through the namespace, write a fragment per append, maintain, read, drop.
Maintenance goes through the Rust worker's own handlers where cargo is
installed, and through the two lance calls those handlers wrap where it is not.
`WEED_LANCE_MAINTENANCE=library|worker` picks one instead of letting the test
guess; CI sets `library`, because a cold build of the lance crate costs more
than the layer it would be checking.
Both tests finish by dropping the table and checking the data actually left the
filer, which is the half of a lifecycle a catalog test never reaches.
## Running it
cd test/s3tables/lifecycle
(cd ../../../weed && go build .) # the harness runs this binary
go test -v -timeout 40m .
Skipped without Docker and in `-short` mode. The first run builds the two client
images and pulls `duckdb/duckdb:latest`; later runs reuse them. The DuckDB half
skips itself, rather than failing, on an image whose iceberg extension cannot
write through a REST catalog.
To watch it catch the bug it was written for, pin parquet-go back to the version
that had it:
go mod edit -require=github.com/parquet-go/parquet-go@v0.30.1 && go mod tidy
go test -run TestIcebergTableLifecycle/DuckDB -v .
maintenance collapsed the category column: 7 distinct values -> 1
maintenance collapsed the value column: 13 distinct values -> 1
The PyIceberg half still passes there, which is the reason both clients are in
this directory.
-277
View File
@@ -1,277 +0,0 @@
// Package lifecycle takes a table through everything that happens to it: made
// through the catalog, filled by a real client, maintained by the worker, read
// again, and dropped.
//
// The step that matters is the read after maintenance. A compaction once
// rewrote every dictionary-encoded column onto a single value and went out in a
// release, because the tests we had checked the bookkeeping - sequence numbers,
// manifest entries, metadata versions - and none of them opened the file the
// worker had just written. A tally taken before maintenance and the same tally
// taken after is the whole idea, and it is the same idea for both formats:
// Iceberg compaction merges parquet files, Lance compaction merges fragments,
// and either can hand back a table that reads without complaint and answers
// wrongly.
package lifecycle
import (
"context"
"errors"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
const (
// The keys the issue's own recipe uses. weed mini turns them into the
// admin identity, which is what the clients then sign with.
accessKey = "AKIAIOSFODNN7EXAMPLE"
secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
startupTimeout = 60 * time.Second
clientTimeout = 20 * time.Minute
)
// shared is the one cluster both formats run against. They use separate table
// buckets, and a bucket holds one format only.
var shared *environment
// errNoBinary is the one setup failure worth skipping over.
var errNoBinary = errors.New("weed binary not found")
func TestMain(m *testing.M) {
flag.Parse()
if testing.Short() {
os.Exit(m.Run())
}
// A checkout without a weed binary cannot run this and says so. Anything
// else - ports, a cluster that will not come up - is a failure, because a
// suite that turns its own breakage into a green run is the thing this
// directory exists to stop.
env, err := newEnvironment()
if errors.Is(err, errNoBinary) {
fmt.Fprintf(os.Stderr, "SKIP: %v\n", err)
os.Exit(m.Run())
}
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL: %v\n", err)
os.Exit(1)
}
if err := env.start(); err != nil {
fmt.Fprintf(os.Stderr, "FAIL: weed mini did not start: %v\n", err)
env.cleanup()
os.Exit(1)
}
shared = env
code := m.Run()
shared.cleanup()
os.Exit(code)
}
type environment struct {
weedBinary string
rootDir string
testDir string
dataDir string
masterPort int
masterGrpcPort int
volumePort int
volumeGrpcPort int
filerPort int
filerGrpcPort int
s3Port int
s3GrpcPort int
icebergPort int
lancePort int
weedCancel context.CancelFunc
weedCmd *exec.Cmd
}
func newEnvironment() (*environment, error) {
wd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("get working directory: %w", err)
}
seaweedDir := wd
for i := 0; i < 5; i++ {
if _, err := os.Stat(filepath.Join(seaweedDir, "go.mod")); err == nil {
break
}
seaweedDir = filepath.Dir(seaweedDir)
}
weedBinary := filepath.Join(seaweedDir, "weed", "weed")
if info, statErr := os.Stat(weedBinary); statErr == nil && !info.IsDir() {
// A plain `go test` will otherwise drive a binary from days ago and
// report a pass for code it never ran.
fmt.Fprintf(os.Stderr, "using %s, built %s\n", weedBinary, info.ModTime().Format(time.RFC3339))
} else {
weedBinary = "weed"
if _, err := exec.LookPath(weedBinary); err != nil {
return nil, errNoBinary
}
}
dataDir, err := os.MkdirTemp("", "seaweed-lifecycle-*")
if err != nil {
return nil, fmt.Errorf("create temp dir: %w", err)
}
ports, err := testutil.AllocatePorts(10)
if err != nil {
return nil, fmt.Errorf("allocate ports: %w", err)
}
return &environment{
weedBinary: weedBinary,
rootDir: seaweedDir,
testDir: wd,
dataDir: dataDir,
masterPort: ports[0],
masterGrpcPort: ports[1],
volumePort: ports[2],
volumeGrpcPort: ports[3],
filerPort: ports[4],
filerGrpcPort: ports[5],
s3Port: ports[6],
s3GrpcPort: ports[7],
icebergPort: ports[8],
lancePort: ports[9],
}, nil
}
func (env *environment) start() error {
ctx, cancel := context.WithCancel(context.Background())
env.weedCancel = cancel
cmd := exec.CommandContext(ctx, env.weedBinary, "mini",
"-master.port", fmt.Sprintf("%d", env.masterPort),
"-master.port.grpc", fmt.Sprintf("%d", env.masterGrpcPort),
"-volume.port", fmt.Sprintf("%d", env.volumePort),
"-volume.port.grpc", fmt.Sprintf("%d", env.volumeGrpcPort),
"-filer.port", fmt.Sprintf("%d", env.filerPort),
"-filer.port.grpc", fmt.Sprintf("%d", env.filerGrpcPort),
"-s3.port", fmt.Sprintf("%d", env.s3Port),
"-s3.port.grpc", fmt.Sprintf("%d", env.s3GrpcPort),
"-s3.port.iceberg", fmt.Sprintf("%d", env.icebergPort),
"-s3.port.lance", fmt.Sprintf("%d", env.lancePort),
"-ip.bind", "0.0.0.0",
"-dir", env.dataDir,
)
cmd.Dir = env.dataDir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// mini makes its admin identity from these, so they are the keys the
// clients sign with rather than a separate IAM file to keep in step.
cmd.Env = append(os.Environ(),
"AWS_ACCESS_KEY_ID="+accessKey,
"AWS_SECRET_ACCESS_KEY="+secretKey,
)
if err := cmd.Start(); err != nil {
cancel()
return err
}
env.weedCmd = cmd
if !testutil.WaitForService(env.catalogURL()+"/v1/config", startupTimeout) {
cancel()
return fmt.Errorf("the Iceberg catalog never answered on port %d", env.icebergPort)
}
if !testutil.WaitForPort(env.lancePort, startupTimeout) {
cancel()
return fmt.Errorf("the Lance namespace never answered on port %d", env.lancePort)
}
return nil
}
func (env *environment) cleanup() {
if env.weedCancel != nil {
env.weedCancel()
}
if env.weedCmd != nil {
_ = env.weedCmd.Wait()
}
if env.dataDir != "" {
_ = os.RemoveAll(env.dataDir)
}
}
func (env *environment) catalogURL() string {
return fmt.Sprintf("http://127.0.0.1:%d", env.icebergPort)
}
// A container reaches the same gateway by another name than the host does.
func (env *environment) containerURL(port int) string {
return fmt.Sprintf("http://host.docker.internal:%d", port)
}
// createTableBucket makes a bucket declared for one format, so the catalog
// refuses tables of any other kind in it.
func (env *environment) createTableBucket(t *testing.T, bucket, format string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, env.weedBinary, "shell",
fmt.Sprintf("-master=127.0.0.1:%d.%d", env.masterPort, env.masterGrpcPort),
)
cmd.Stdin = strings.NewReader(fmt.Sprintf(
"s3tables.bucket -create -name %s -format %s -account 000000000000\nexit\n", bucket, format))
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("create the %s table bucket %s: %v\n%s", format, bucket, err, out)
}
}
// filerClient dials the filer the maintenance handlers talk to.
func (env *environment) filerClient(t *testing.T) filer_pb.SeaweedFilerClient {
t.Helper()
conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", env.filerGrpcPort),
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("dial the filer: %v", err)
}
t.Cleanup(func() { conn.Close() })
return filer_pb.NewSeaweedFilerClient(conn)
}
// entryExists tells "the catalog forgot the table" from "the data is gone".
func (env *environment) entryExists(t *testing.T, path string) bool {
t.Helper()
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d%s", env.filerPort, path))
if err != nil {
t.Fatalf("filer GET %s: %v", path, err)
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
return resp.StatusCode == http.StatusOK
}
func randomSuffix() string {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
suffix := make([]byte, 8)
for i := range suffix {
suffix[i] = charset[rand.Intn(len(charset))]
}
return string(suffix)
}
@@ -1,163 +0,0 @@
#!/usr/bin/env python3
"""PyIceberg half of the table lifecycle, run one phase per invocation.
The Go test calls this three times - write, verify, drop - and runs the
maintenance worker between the first two. Splitting it that way is the whole
point: a tally taken before compaction and the same tally taken after are the
only thing that catches a merge that rewrote every dictionary-encoded column
onto a single value and said nothing.
"""
import argparse
import hashlib
import json
import sys
import time
import pyarrow as pa
from pyiceberg.catalog import load_catalog
from pyiceberg.exceptions import NamespaceAlreadyExistsError, NoSuchTableError
from pyiceberg.schema import Schema
from pyiceberg.types import LongType, NestedField, StringType, TimestamptzType
# Few enough distinct values in the two string columns that any writer worth
# the name dictionary-encodes them, which is the encoding that broke.
CATEGORIES = 7
VALUES = 13
ROWS_PER_BATCH = 4000
BATCHES = 3
SCHEMA = Schema(
NestedField(1, "id", LongType(), required=True),
NestedField(2, "category", StringType(), required=True),
NestedField(3, "value", StringType(), required=True),
NestedField(4, "ts", TimestamptzType(), required=True),
)
ARROW_SCHEMA = pa.schema(
[
pa.field("id", pa.int64(), nullable=False),
pa.field("category", pa.string(), nullable=False),
pa.field("value", pa.string(), nullable=False),
pa.field("ts", pa.timestamp("us", tz="UTC"), nullable=False),
]
)
def batch(start, count):
ids = list(range(start, start + count))
return pa.Table.from_pydict(
{
"id": ids,
"category": [f"cat-{i % CATEGORIES}" for i in ids],
"value": [f"v-{i % VALUES}" for i in ids],
# An hour apart, so the rows spread over months the way a real
# table's do without needing a partition spec to prove it.
"ts": [1772323200000000 + i * 3600000000 for i in ids],
},
schema=ARROW_SCHEMA,
)
def tally(table):
"""Row count, per-column cardinality, and a digest of every row.
The cardinalities catch a column collapsed onto one dictionary entry; the
digest catches everything else, including a merge that keeps the right
number of distinct values while handing them to the wrong rows. Every
column goes into it, not just the two the cardinalities watch - compaction
rewrites the whole row. ts goes in as microseconds so no timezone sits
between the two runs.
"""
scanned = table.scan().to_arrow()
categories = scanned.column("category").to_pylist()
values = scanned.column("value").to_pylist()
rows = [
f"{i}|{t}|{c}|{v}"
for i, t, c, v in zip(
scanned.column("id").to_pylist(),
scanned.column("ts").cast(pa.int64()).to_pylist(),
categories,
values,
strict=True,
)
]
digest = hashlib.md5(
"\n".join(sorted(rows)).encode(), usedforsecurity=False
).hexdigest()
return {
"rows": scanned.num_rows,
"categories": len(set(categories)),
"values": len(set(values)),
"digest": digest,
}
def connect(args):
properties = {
"type": "rest",
"uri": args.catalog_url,
"warehouse": f"s3://{args.bucket}/",
"prefix": args.bucket,
"s3.endpoint": args.s3_endpoint,
"s3.access-key-id": args.access_key,
"s3.secret-access-key": args.secret_key,
"s3.region": "us-east-1",
"s3.path-style-access": "true",
}
last = None
for attempt in range(10):
try:
return load_catalog("rest", **properties)
except Exception as err: # the gateway may still be coming up
last = err
print(f"connect attempt {attempt + 1} failed: {err}", file=sys.stderr)
time.sleep(2)
raise last
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--phase", required=True, choices=["write", "verify", "drop"])
parser.add_argument("--catalog-url", required=True)
parser.add_argument("--s3-endpoint", required=True)
parser.add_argument("--bucket", required=True)
parser.add_argument("--namespace", required=True)
parser.add_argument("--table", required=True)
parser.add_argument("--access-key", required=True)
parser.add_argument("--secret-key", required=True)
args = parser.parse_args()
catalog = connect(args)
identifier = f"{args.namespace}.{args.table}"
if args.phase == "write":
try:
catalog.create_namespace(args.namespace)
except NamespaceAlreadyExistsError:
pass
table = catalog.create_table(identifier, schema=SCHEMA)
# One append per batch, so compaction has several files to merge
# rather than one it would leave alone.
for i in range(BATCHES):
table.append(batch(i * ROWS_PER_BATCH + 1, ROWS_PER_BATCH))
table = catalog.load_table(identifier)
print(json.dumps(tally(table)))
return
if args.phase == "verify":
print(json.dumps(tally(catalog.load_table(identifier))))
return
catalog.drop_table(identifier)
try:
catalog.load_table(identifier)
except NoSuchTableError:
pass
else:
raise SystemExit("the table is still in the catalog after a drop")
catalog.drop_namespace(args.namespace)
if __name__ == "__main__":
main()
@@ -1,389 +0,0 @@
package lifecycle
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/iceberg"
)
const (
pyicebergImage = "seaweedfs-lifecycle-pyiceberg"
duckdbImage = "duckdb/duckdb:latest"
// The phase that installs the extension, and so the only one whose failure
// can mean the image rather than the code.
firstPhase = "write"
// Three appends of this many rows, all inside one month so they land in
// one partition and compaction has something to merge. The two string
// columns hold few enough distinct values to be dictionary-encoded, which
// is the encoding the merge destroyed.
rowsPerBatch = 4000
batches = 3
categories = 7
values = 13
)
// tally is what a client reports about a table. Both halves of this suite
// speak it, and the point of the whole suite is that the one taken before
// maintenance equals the one taken after.
type tally struct {
Rows int `json:"rows"`
Categories int `json:"categories"`
Values int `json:"values"`
Digest string `json:"digest"`
// Lance only: a compaction that merged nothing would otherwise let this
// test pass without having tested anything.
Fragments int `json:"fragments"`
Version int `json:"version"`
}
func TestIcebergTableLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
if shared == nil {
t.Skip("no cluster")
}
if !testutil.HasDocker() {
t.Skip("Docker not available")
}
// DuckDB is the client the bug was reported against, and the only one
// here that writes the deprecated PLAIN_DICTIONARY encoding a Go writer
// will not produce. PyIceberg writes the modern one, so between them the
// merge is checked against both dictionary encodings in the spec.
t.Run("DuckDB", testIcebergLifecycleWithDuckDB)
t.Run("PyIceberg", testIcebergLifecycleWithPyIceberg)
}
func testIcebergLifecycleWithDuckDB(t *testing.T) {
env := shared
bucket := "lifecycle-duckdb-" + randomSuffix()
namespace, table := "sales", "events"
env.createTableBucket(t, bucket, "ICEBERG")
inserts := make([]string, 0, batches)
for i := 0; i < batches; i++ {
inserts = append(inserts, fmt.Sprintf(
"INSERT INTO cat.%s.%s SELECT g, TIMESTAMPTZ '2026-03-01 00:00:00' + INTERVAL (g %% 600) MINUTE, "+
"'cat-' || (g %% %d), 'v-' || (g %% %d) FROM generate_series(%d, %d) t(g);",
namespace, table, categories, values, i*rowsPerBatch+1, (i+1)*rowsPerBatch))
}
before := env.duckdb(t, bucket, "write", strings.Join([]string{
fmt.Sprintf("CREATE SCHEMA cat.%s;", namespace),
// Partitioned, the way the table in the report was. Compaction bins
// per partition, so this is also what puts more than one bin in play.
fmt.Sprintf("CREATE TABLE cat.%s.%s(id int, ts timestamptz, category text, value text) PARTITIONED BY (month(ts));", namespace, table),
strings.Join(inserts, "\n"),
duckdbTallySQL(namespace, table),
}, "\n"))
assertSeeded(t, before)
env.maintainIcebergTable(t, bucket, namespace+"/"+table)
after := env.duckdb(t, bucket, "verify", duckdbTallySQL(namespace, table))
assertSameData(t, before, after)
env.duckdb(t, bucket, "drop", fmt.Sprintf("DROP TABLE cat.%s.%s;\nDROP SCHEMA cat.%s;", namespace, table, namespace))
if env.entryExists(t, fmt.Sprintf("/buckets/%s/%s/%s/", bucket, namespace, table)) {
t.Fatal("the dropped table's data is still on disk")
}
}
func testIcebergLifecycleWithPyIceberg(t *testing.T) {
env := shared
bucket := "lifecycle-pyiceberg-" + randomSuffix()
namespace, table := "sales", "events"
env.createTableBucket(t, bucket, "ICEBERG")
buildClientImage(t, pyicebergImage, "Dockerfile.pyiceberg")
before := env.pyiceberg(t, "write", bucket, namespace, table)
assertSeeded(t, before)
env.maintainIcebergTable(t, bucket, namespace+"/"+table)
after := env.pyiceberg(t, "verify", bucket, namespace, table)
assertSameData(t, before, after)
env.pyiceberg(t, "drop", bucket, namespace, table)
if env.entryExists(t, fmt.Sprintf("/buckets/%s/%s/%s/", bucket, namespace, table)) {
t.Fatal("the dropped table's data is still on disk")
}
}
// maintainIcebergTable runs the worker's whole maintenance cycle against the
// live filer, in the order a scheduled worker would: merge the small files,
// drop the snapshots that referenced them, sweep what nothing references any
// more, then fold the manifests together.
func (env *environment) maintainIcebergTable(t *testing.T, bucket, tablePath string) {
t.Helper()
client := env.filerClient(t)
handler := iceberg.NewHandler(nil)
config := iceberg.Config{
TargetFileSizeBytes: 256 << 20,
MinInputFiles: 2,
MaxCommitRetries: 3,
SnapshotRetentionMs: 1,
MaxSnapshotsToKeep: 1,
OrphanOlderThanHours: 1,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
operations := []struct {
name string
run func() (string, map[string]int64, error)
}{
{"compact", func() (string, map[string]int64, error) {
return handler.CompactDataFiles(ctx, client, bucket, tablePath, config)
}},
{"expire", func() (string, map[string]int64, error) {
return handler.ExpireSnapshots(ctx, client, bucket, tablePath, config)
}},
{"orphans", func() (string, map[string]int64, error) {
return handler.RemoveOrphans(ctx, client, bucket, tablePath, config)
}},
{"manifests", func() (string, map[string]int64, error) {
return handler.RewriteManifests(ctx, client, bucket, tablePath, config)
}},
}
for _, operation := range operations {
result, metrics, err := operation.run()
if err != nil {
t.Fatalf("%s: %v", operation.name, err)
}
t.Logf("%s: %s %v", operation.name, result, metrics)
// A compaction that merged nothing leaves the read below checking a
// file the worker never wrote, which proves nothing at all.
if operation.name == "compact" && metrics[iceberg.MetricFilesMerged] < batches {
t.Fatalf("compaction merged %d files, want all %d written by the client: %s",
metrics[iceberg.MetricFilesMerged], batches, result)
}
}
}
// duckdb runs a script against the catalog and returns whatever tally it
// printed. The prelude is the reporter's own ATTACH, SigV4 and all.
func (env *environment) duckdb(t *testing.T, bucket, phase, body string) tally {
t.Helper()
script := fmt.Sprintf(`INSTALL iceberg;
LOAD iceberg;
CREATE SECRET s3_secret (TYPE S3, KEY_ID '%s', SECRET '%s', ENDPOINT 'host.docker.internal:%d', URL_STYLE 'path', USE_SSL false);
ATTACH 's3://%s' AS cat (TYPE ICEBERG, ENDPOINT '%s', AUTHORIZATION_TYPE SigV4, SECRET 's3_secret', SIGV4_SERVICE 's3', SIGV4_REGION 'us-east-1', ACCESS_DELEGATION_MODE 'none', READ_ONLY false);
%s
`, accessKey, secretKey, env.s3Port, bucket, env.containerURL(env.icebergPort), body)
name := fmt.Sprintf("duckdb-%s-%s.sql", bucket, phase)
if err := os.WriteFile(filepath.Join(env.dataDir, name), []byte(script), 0644); err != nil {
t.Fatalf("write the DuckDB script: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
"-v", fmt.Sprintf("%s:/test", env.dataDir),
"--add-host", "host.docker.internal:host-gateway",
"--entrypoint", "duckdb",
duckdbImage,
"-init", "/test/"+name,
"-c", "SELECT 1",
)
out, err := cmd.CombinedOutput()
t.Logf("DuckDB %s:\n%s", phase, out)
if err != nil {
if phase == firstPhase && lacksIcebergExtension(string(out)) {
t.Skipf("this DuckDB image has no iceberg extension: %v", err)
}
t.Fatalf("DuckDB %s: %v", phase, err)
}
if !strings.Contains(body, "TALLY") {
return tally{}
}
return parseDuckDBTally(t, string(out))
}
func duckdbTallySQL(namespace, table string) string {
// The digest covers whole rows - every column, not just the two the
// cardinalities watch - because counting each column on its own passes a
// merge that keeps every column's cardinality and hands the values to the
// wrong rows. ts goes in as microseconds so the session's timezone cannot
// change how it renders between the two runs.
return fmt.Sprintf("SELECT 'TALLY ' || count(*) || ' ' || count(DISTINCT category) || ' ' || count(DISTINCT value)"+
" || ' ' || md5(string_agg(id || '|' || epoch_us(ts) || '|' || category || '|' || value, chr(10) ORDER BY id)) AS marker"+
" FROM cat.%s.%s;",
namespace, table)
}
var duckdbTallyPattern = regexp.MustCompile(`TALLY (\d+) (\d+) (\d+) ([0-9a-f]{32})`)
func parseDuckDBTally(t *testing.T, out string) tally {
t.Helper()
fields := duckdbTallyPattern.FindStringSubmatch(out)
if fields == nil {
t.Fatalf("DuckDB printed no tally:\n%s", out)
}
number := func(s string) int {
value, err := strconv.Atoi(s)
if err != nil {
t.Fatalf("parse %q: %v", s, err)
}
return value
}
return tally{
Rows: number(fields[1]),
Categories: number(fields[2]),
Values: number(fields[3]),
Digest: fields[4],
}
}
// lacksIcebergExtension reports whether DuckDB never got as far as this
// repository's code, which is the only failure worth skipping over.
//
// The extension ships separately from the image, so an environment that cannot
// fetch it has nothing to say about compaction. Everything past LOAD - a parse
// error on the ATTACH, a refusal from the catalog, a bad read - is ours, and
// has to fail: this is the one test covering the PLAIN_DICTIONARY encoding, and
// a skip nobody reads is how the corruption it was written for shipped.
func lacksIcebergExtension(out string) bool {
for _, marker := range []string{
"iceberg extension is not available",
"Failed to download extension",
`Extension "iceberg" not found`,
"Unknown extension",
} {
if strings.Contains(out, marker) {
return true
}
}
return false
}
func (env *environment) pyiceberg(t *testing.T, phase, bucket, namespace, table string) tally {
t.Helper()
out := env.runClient(t, pyicebergImage, phase, "/app/iceberg_lifecycle.py",
"--catalog-url", env.containerURL(env.icebergPort),
"--s3-endpoint", env.containerURL(env.s3Port),
"--bucket", bucket,
"--namespace", namespace,
"--table", table,
)
if phase == "drop" {
return tally{}
}
return decodeTally(t, out)
}
// runClient runs one phase of a python client and returns its stdout.
func (env *environment) runClient(t *testing.T, image, phase, script string, args ...string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
run := []string{"run", "--rm",
"--add-host", "host.docker.internal:host-gateway",
"-e", "AWS_ACCESS_KEY_ID=" + accessKey,
"-e", "AWS_SECRET_ACCESS_KEY=" + secretKey,
"-e", "AWS_REGION=us-east-1",
"-e", "AWS_ALLOW_HTTP=true",
image, "python3", script, "--phase", phase,
"--access-key", accessKey, "--secret-key", secretKey,
}
cmd := exec.CommandContext(ctx, "docker", append(run, args...)...)
var stderr strings.Builder
cmd.Stderr = &stderr
out, err := cmd.Output()
if stderr.Len() > 0 {
t.Logf("%s %s (stderr):\n%s", image, phase, stderr.String())
}
if err != nil {
t.Fatalf("%s %s: %v\n%s", image, phase, err, out)
}
t.Logf("%s %s: %s", image, phase, strings.TrimSpace(string(out)))
return string(out)
}
func decodeTally(t *testing.T, out string) tally {
t.Helper()
// The clients print the tally last; anything a library logged before it
// is not JSON and not ours.
lines := strings.Split(strings.TrimSpace(out), "\n")
var decoded tally
if err := json.Unmarshal([]byte(lines[len(lines)-1]), &decoded); err != nil {
t.Fatalf("decode the tally from %q: %v", out, err)
}
return decoded
}
func buildClientImage(t *testing.T, image, dockerfile string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "build", "-t", image, "-f", dockerfile, ".")
cmd.Dir = shared.testDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build %s: %v\n%s", image, err, out)
}
}
// assertSeeded checks the client wrote what this suite assumes it wrote. Every
// comparison below is against these numbers, so a client that quietly seeded
// one row would otherwise make the whole test vacuous.
func assertSeeded(t *testing.T, seeded tally) {
t.Helper()
if want := rowsPerBatch * batches; seeded.Rows != want {
t.Fatalf("seeded %d rows, want %d", seeded.Rows, want)
}
if seeded.Categories != categories || seeded.Values != values {
t.Fatalf("seeded %d categories and %d values, want %d and %d",
seeded.Categories, seeded.Values, categories, values)
}
}
// assertSameData is the test. Maintenance rewrites files; it must not change a
// single row, and the cardinalities are called out separately because that is
// the shape the failure took: a dictionary column collapsed onto one entry,
// read back without an error, and answered wrongly.
func assertSameData(t *testing.T, before, after tally) {
t.Helper()
if after.Rows != before.Rows {
t.Errorf("maintenance changed the row count: %d -> %d", before.Rows, after.Rows)
}
if after.Categories != before.Categories {
t.Errorf("maintenance collapsed the category column: %d distinct values -> %d",
before.Categories, after.Categories)
}
if after.Values != before.Values {
t.Errorf("maintenance collapsed the value column: %d distinct values -> %d",
before.Values, after.Values)
}
if after.Digest != before.Digest {
t.Errorf("maintenance changed the rows: digest %s -> %s", before.Digest, after.Digest)
}
}
-168
View File
@@ -1,168 +0,0 @@
#!/usr/bin/env python3
"""Lance half of the table lifecycle, run one phase per invocation.
The Go test calls this for each step and maintains the table in between, so the
tally taken before maintenance and the tally taken after are directly
comparable. That comparison is the test: the Iceberg side of this suite exists
because compaction once rewrote a table's dictionary columns onto a single
value and every check we had still passed, and a Lance dataset is rewritten by
the same kind of job.
The maintain phase is a fallback. When the Rust worker can be built, the Go test
runs its handlers against this table instead and skips this phase - what runs
here are the same two lance calls the handlers make.
"""
import argparse
import hashlib
import json
import sys
import warnings
from datetime import timedelta
warnings.filterwarnings("ignore")
import lance
import lance_namespace as ln
import pyarrow as pa
# Low enough cardinality that these two columns are dictionary-encoded.
CATEGORIES = 7
VALUES = 13
ROWS_PER_BATCH = 4000
BATCHES = 3
DIM = 8
def rows(start, count):
ids = list(range(start, start + count))
return pa.table(
{
"id": pa.array(ids, type=pa.int64()),
"category": pa.array([f"cat-{i % CATEGORIES}" for i in ids]),
"value": pa.array([f"v-{i % VALUES}" for i in ids]),
"vector": pa.array(
[[float(i % 97) + d for d in range(DIM)] for i in ids],
type=pa.list_(pa.float32(), DIM),
),
}
)
def tally(dataset):
"""What the table holds, in a form two runs can be compared by.
The cardinalities catch a column collapsed onto one value; the digest
catches a rewrite that keeps the values and moves them to the wrong rows.
Every column goes into the digest, the vectors included - compaction
rewrites whole fragments, so leaving a column out leaves a place for it to
go wrong unnoticed. Fragments come along because a compaction that merged
nothing would otherwise let this test pass without having tested anything.
"""
scanned = dataset.to_table(columns=["id", "category", "value", "vector"])
ids = scanned.column("id").to_pylist()
categories = scanned.column("category").to_pylist()
values = scanned.column("value").to_pylist()
vectors = scanned.column("vector").to_pylist()
serialized = (
f"{i}|{c}|{v}|{w}"
for i, c, v, w in zip(ids, categories, values, vectors, strict=True)
)
digest = hashlib.md5(
"\n".join(sorted(serialized)).encode(), usedforsecurity=False
).hexdigest()
return {
"rows": scanned.num_rows,
"categories": len(set(categories)),
"values": len(set(values)),
"digest": digest,
"fragments": len(dataset.get_fragments()),
"version": dataset.version,
}
def resolve(args):
"""Ask the namespace where the table lives, the way the worker does."""
namespace = ln.connect("rest", {"uri": args.namespace_url})
table_id = [args.bucket, args.namespace, args.table]
described = namespace.describe_table(ln.DescribeTableRequest(id=table_id))
return namespace, table_id, described.location, storage_options(args, described)
def storage_options(args, described=None):
# The namespace vends an endpoint correct for its own host; this container
# reaches the same gateway by another name. Credentials are filled in
# because a deployment without STS vends none.
options = dict((described.storage_options or {}) if described else {})
options["aws_endpoint"] = args.s3_endpoint
options["allow_http"] = "true"
options.setdefault("aws_access_key_id", args.access_key)
options.setdefault("aws_secret_access_key", args.secret_key)
options.setdefault("aws_region", "us-east-1")
return options
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--phase", required=True, choices=["write", "maintain", "verify", "drop"])
parser.add_argument("--namespace-url", required=True)
parser.add_argument("--s3-endpoint", required=True)
parser.add_argument("--bucket", required=True)
parser.add_argument("--namespace", required=True)
parser.add_argument("--table", required=True)
parser.add_argument("--access-key", default="any")
parser.add_argument("--secret-key", default="any")
args = parser.parse_args()
if args.phase == "write":
namespace = ln.connect("rest", {"uri": args.namespace_url})
for parent in ([args.bucket], [args.bucket, args.namespace]):
namespace.create_namespace(ln.CreateNamespaceRequest(id=parent, mode="EXIST_OK"))
table_id = [args.bucket, args.namespace, args.table]
declared = namespace.declare_table(ln.DeclareTableRequest(id=table_id))
options = storage_options(args)
# A fragment per append, so the compaction that follows has something
# to merge.
for i in range(BATCHES):
lance.write_dataset(
rows(i * ROWS_PER_BATCH + 1, ROWS_PER_BATCH),
declared.location,
storage_options=options,
mode="overwrite" if i == 0 else "append",
)
print(json.dumps(tally(lance.dataset(declared.location, storage_options=options))))
return 0
if args.phase == "maintain":
_, _, location, options = resolve(args)
dataset = lance.dataset(location, storage_options=options)
dataset.optimize.compact_files()
dataset = lance.dataset(location, storage_options=options)
dataset.cleanup_old_versions(older_than=timedelta(seconds=0), delete_unverified=True)
print(json.dumps(tally(lance.dataset(location, storage_options=options))))
return 0
if args.phase == "verify":
_, _, location, options = resolve(args)
print(json.dumps(tally(lance.dataset(location, storage_options=options))))
return 0
namespace, table_id, location, options = resolve(args)
namespace.drop_table(ln.DropTableRequest(id=table_id))
try:
lance.dataset(location, storage_options=options)
except ValueError as err:
# pylance turns every load failure into a ValueError, so the message is
# the only thing separating a dataset that is gone from credentials
# that stopped working halfway through the test.
if "was not found" in str(err):
return 0
print(f"FAIL: reading the dropped dataset failed for another reason: {err}",
file=sys.stderr)
return 1
print("FAIL: the dataset is still readable after a drop", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -1,130 +0,0 @@
package lifecycle
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/test/testutil"
)
const lanceImage = "seaweedfs-lifecycle-lance"
// TestLanceTableLifecycle is the Iceberg test's counterpart. A Lance table is
// declared through the namespace, written a fragment at a time, compacted, its
// superseded versions dropped, and read again - and the read has to answer
// exactly what the write put there. Compaction rewrites fragments the way
// Iceberg compaction rewrites parquet files, and the failure that suite exists
// for is the kind that reads back without an error and answers wrongly.
func TestLanceTableLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
if shared == nil {
t.Skip("no cluster")
}
if !testutil.HasDocker() {
t.Skip("Docker not available")
}
env := shared
bucket := "lifecycle-lance-" + randomSuffix()
namespace, table := "ml", "events"
env.createTableBucket(t, bucket, "LANCE")
buildClientImage(t, lanceImage, "Dockerfile.lance")
before := env.lance(t, "write", bucket, namespace, table)
assertSeeded(t, before)
if before.Fragments != batches {
t.Fatalf("the client wrote %d fragments, want one per append (%d)", before.Fragments, batches)
}
env.maintainLanceTable(t, bucket, namespace, table)
after := env.lance(t, "verify", bucket, namespace, table)
assertSameData(t, before, after)
// Without this the comparison above would pass on a table nothing touched.
if after.Fragments >= before.Fragments {
t.Fatalf("maintenance merged nothing: %d fragments before, %d after",
before.Fragments, after.Fragments)
}
env.lance(t, "drop", bucket, namespace, table)
if env.entryExists(t, fmt.Sprintf("/buckets/%s/%s/%s/", bucket, namespace, table)) {
t.Fatal("the dropped table's data is still on disk")
}
}
// maintainLanceTable compacts the table and drops what compaction superseded.
//
// Lance maintenance lives in the Rust worker, so where its toolchain is around
// the handlers themselves do the work against this table. Where it is not, the
// same two lance calls those handlers wrap run in the client container instead.
// The lifecycle is checked either way; only the layer above the format changes.
// WEED_LANCE_MAINTENANCE picks one - CI sets "library", because a cold build of
// the lance crate costs more than the layer it is checking.
func (env *environment) maintainLanceTable(t *testing.T, bucket, namespace, table string) {
t.Helper()
if !maintainWithWorker(t) {
env.lance(t, "maintain", bucket, namespace, table)
return
}
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "cargo", "test",
"-p", "weed-lance-worker", "--test", "lifecycle", "--", "--nocapture")
cmd.Dir = filepath.Join(env.rootDir, "seaweed-worker")
cmd.Env = append(cmd.Environ(),
fmt.Sprintf("WEED_LANCE_NAMESPACE=http://127.0.0.1:%d", env.lancePort),
fmt.Sprintf("WEED_LANCE_TABLE=%s$%s$%s", bucket, namespace, table),
"AWS_ACCESS_KEY_ID="+accessKey,
"AWS_SECRET_ACCESS_KEY="+secretKey,
"AWS_REGION=us-east-1",
fmt.Sprintf("AWS_ENDPOINT_URL=http://127.0.0.1:%d", env.s3Port),
)
out, err := cmd.CombinedOutput()
t.Logf("lance worker:\n%s", out)
if err != nil {
t.Fatalf("the Lance maintenance worker failed: %v", err)
}
}
// maintainWithWorker says whether to maintain through the Rust worker.
func maintainWithWorker(t *testing.T) bool {
t.Helper()
switch os.Getenv("WEED_LANCE_MAINTENANCE") {
case "library":
t.Log("maintaining through the lance library, as WEED_LANCE_MAINTENANCE asks")
return false
case "worker":
return true
}
if _, err := exec.LookPath("cargo"); err != nil {
t.Log("cargo is not installed, maintaining through the lance library rather than the worker")
return false
}
return true
}
func (env *environment) lance(t *testing.T, phase, bucket, namespace, table string) tally {
t.Helper()
out := env.runClient(t, lanceImage, phase, "/app/lance_lifecycle.py",
"--namespace-url", env.containerURL(env.lancePort),
"--s3-endpoint", env.containerURL(env.s3Port),
"--bucket", bucket,
"--namespace", namespace,
"--table", table,
)
if phase == "drop" {
return tally{}
}
return decodeTally(t, out)
}
-94
View File
@@ -6,7 +6,6 @@ import (
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
@@ -903,96 +902,3 @@ func TestTusResumeAfterInterruption(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, testData, body, "Resumed upload should produce complete file")
}
// TestTusAbortedPatchKeepsStoredChunks checks that a PATCH cut off mid-body
// leaves the sub-chunks it already stored in place. The filer splits a PATCH
// into 4MB sub-chunks and records each one as it lands; the offset a resuming
// client reads back covers them, so their data has to survive the failure.
func TestTusAbortedPatchKeepsStoredChunks(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
defer cancel()
cluster, err := startTestCluster(t, ctx)
require.NoError(t, err)
defer func() {
cluster.Stop()
os.RemoveAll(cluster.dataDir)
}()
const subChunkSize = 4 * 1024 * 1024
testData := make([]byte, 3*subChunkSize)
for i := range testData {
testData[i] = byte(i % 251)
}
targetPath := "/aborted/interrupted.bin"
client := &http.Client{}
createReq, err := http.NewRequest(http.MethodPost, cluster.TusURL()+targetPath, nil)
require.NoError(t, err)
createReq.Header.Set("Tus-Resumable", TusVersion)
createReq.Header.Set("Upload-Length", strconv.Itoa(len(testData)))
createResp, err := client.Do(createReq)
require.NoError(t, err)
createResp.Body.Close()
require.Equal(t, http.StatusCreated, createResp.StatusCode)
uploadLocation := createResp.Header.Get("Location")
// Promise the whole body, then reset the connection while a later
// sub-chunk is still being read.
conn, err := net.Dial("tcp", "127.0.0.1:"+testFilerPort)
require.NoError(t, err)
_, err = fmt.Fprintf(conn, "PATCH %s HTTP/1.1\r\nHost: 127.0.0.1:%s\r\nTus-Resumable: %s\r\nContent-Type: application/offset+octet-stream\r\nUpload-Offset: 0\r\nContent-Length: %d\r\n\r\n",
uploadLocation, testFilerPort, TusVersion, len(testData))
require.NoError(t, err)
_, err = conn.Write(testData[:subChunkSize+1024*1024])
require.NoError(t, err)
time.Sleep(3 * time.Second)
require.NoError(t, conn.(*net.TCPConn).SetLinger(0))
require.NoError(t, conn.Close())
t.Log("PATCH connection reset mid-body")
time.Sleep(5 * time.Second)
headReq, err := http.NewRequest(http.MethodHead, cluster.FullURL(uploadLocation), nil)
require.NoError(t, err)
headReq.Header.Set("Tus-Resumable", TusVersion)
headResp, err := client.Do(headReq)
require.NoError(t, err)
headResp.Body.Close()
require.Equal(t, http.StatusOK, headResp.StatusCode)
currentOffset, err := strconv.Atoi(headResp.Header.Get("Upload-Offset"))
require.NoError(t, err)
require.Equal(t, subChunkSize, currentOffset, "the sub-chunk stored before the reset should count towards the offset")
patchReq, err := http.NewRequest(http.MethodPatch, cluster.FullURL(uploadLocation), bytes.NewReader(testData[currentOffset:]))
require.NoError(t, err)
patchReq.Header.Set("Tus-Resumable", TusVersion)
patchReq.Header.Set("Upload-Offset", strconv.Itoa(currentOffset))
patchReq.Header.Set("Content-Type", "application/offset+octet-stream")
patchResp, err := client.Do(patchReq)
require.NoError(t, err)
patchResp.Body.Close()
require.Equal(t, http.StatusNoContent, patchResp.StatusCode)
// A vacuum reclaims whatever the filer deleted, so the file survives this
// only if the chunks the session kept are still stored.
vacuumResp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%s/vol/vacuum?garbageThreshold=0.001", testMasterPort))
require.NoError(t, err)
vacuumResp.Body.Close()
require.Equal(t, http.StatusOK, vacuumResp.StatusCode)
getResp, err := client.Get(cluster.FilerURL() + targetPath)
require.NoError(t, err)
defer getResp.Body.Close()
require.Equal(t, http.StatusOK, getResp.StatusCode)
body, err := io.ReadAll(getResp.Body)
require.NoError(t, err)
assert.Equal(t, testData, body, "the resumed upload should read back whole")
}
+1 -15
View File
@@ -20,20 +20,8 @@ import (
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
// goBuildTags names the build tags a server the harness compiles must carry to
// hold the same offsets as the test binary asking for it. A 4-byte server and a
// 5-byte one disagree about every .idx row and reject each other's .vif, and
// the mixed Go/Rust suites run both at once.
func goBuildTags() []string {
if types.OffsetSize == 5 {
return []string{"-tags", "5BytesOffset"}
}
return nil
}
const (
defaultWaitTimeout = 30 * time.Second
defaultWaitTick = 200 * time.Millisecond
@@ -407,9 +395,7 @@ func FindOrBuildWeedBinary() (string, error) {
}
binPath := filepath.Join(binDir, "weed")
args := append([]string{"build"}, goBuildTags()...)
args = append(args, "-o", binPath, ".")
cmd := exec.Command("go", args...)
cmd := exec.Command("go", "build", "-o", binPath, ".")
cmd.Dir = filepath.Join(repoRoot, "weed")
var out bytes.Buffer
cmd.Stdout = &out
+2 -10
View File
@@ -14,7 +14,6 @@ import (
"github.com/seaweedfs/seaweedfs/test/testutil"
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
// RustCluster wraps a Go master + Rust volume server for integration testing.
@@ -268,15 +267,8 @@ func FindOrBuildRustBinary() (string, error) {
releaseBin := filepath.Join(rustCrateDir, "target", "release", "weed-volume")
// Always rebuild once per test process so the harness uses current source
// and features. The crate defaults to 5bytes, so a test binary built
// without 5BytesOffset has to turn it off or the Rust server refuses the
// .vif the Go server just wrote.
args := []string{"build", "--release"}
if types.OffsetSize != 5 {
args = append(args, "--no-default-features")
}
cmd := exec.Command("cargo", args...)
// Always rebuild once per test process so the harness uses current source and features.
cmd := exec.Command("cargo", "build", "--release")
cmd.Dir = rustCrateDir
var out bytes.Buffer
cmd.Stdout = &out
-127
View File
@@ -1001,133 +1001,6 @@ func toBucketLifecycleRule(rule *s3lifecycle.Rule) BucketLifecycleRule {
return out
}
// fromBucketLifecycleRule is the inverse of toBucketLifecycleRule, turning a
// rule edited in the admin UI back into the engine's canonical shape.
func fromBucketLifecycleRule(rule BucketLifecycleRule) (*s3lifecycle.Rule, error) {
out := &s3lifecycle.Rule{
ID: rule.ID,
Status: rule.Status,
Prefix: rule.Prefix,
FilterTags: rule.Tags,
FilterSizeGreaterThan: rule.SizeGreaterThan,
FilterSizeLessThan: rule.SizeLessThan,
ExpirationDays: rule.ExpirationDays,
ExpiredObjectDeleteMarker: rule.ExpiredObjectDeleteMarker,
NoncurrentVersionExpirationDays: rule.NoncurrentVersionExpirationDays,
NewerNoncurrentVersions: rule.NewerNoncurrentVersions,
AbortMPUDaysAfterInitiation: rule.AbortMultipartDays,
}
if rule.ExpirationDate != "" {
date, err := time.Parse(time.DateOnly, rule.ExpirationDate)
if err != nil {
return nil, fmt.Errorf("invalid expiration date %q: %w", rule.ExpirationDate, err)
}
out.ExpirationDate = date
}
return out, nil
}
// ErrBucketNotFound reports that the named bucket has no filer entry, so a
// handler can answer 404 rather than 500.
var ErrBucketNotFound = errors.New("bucket not found")
// SetBucketLifecycle replaces the lifecycle configuration stored on a
// bucket's filer entry. An empty rule list clears the configuration
// entirely, mirroring clearStoredBucketLifecycleConfiguration on the S3 API
// side. Callers must validate rules before calling this (see
// validateBucketLifecycleRules) — this only rejects what marshaling itself
// rejects.
func (s *AdminServer) SetBucketLifecycle(bucketName string, rules []BucketLifecycleRule) error {
canonicalRules := make([]*s3lifecycle.Rule, 0, len(rules))
for _, rule := range rules {
canonicalRule, err := fromBucketLifecycleRule(rule)
if err != nil {
return err
}
canonicalRules = append(canonicalRules, canonicalRule)
}
var lifecycleXML []byte
if len(canonicalRules) > 0 {
var err error
lifecycleXML, err = lifecycle_xml.MarshalCanonical(canonicalRules)
if err != nil {
return fmt.Errorf("marshal lifecycle configuration: %w", err)
}
if len(lifecycleXML) > scheduler.MaxBucketLifecycleConfigurationSize {
return fmt.Errorf("lifecycle configuration is %d bytes, which exceeds the %d byte limit", len(lifecycleXML), scheduler.MaxBucketLifecycleConfigurationSize)
}
}
filerConfig, err := s.getFilerConfig()
if err != nil {
return fmt.Errorf("get filer configuration: %w", err)
}
collection := getCollectionName(filerConfig.FilerGroup, bucketName)
return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
// PATCH_EXTENDED is a no-op on a missing entry, so the existence
// check has to happen here rather than fall out of the write.
if _, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
Directory: filerConfig.BucketsPath,
Name: bucketName,
}); err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return fmt.Errorf("%w: %s", ErrBucketNotFound, bucketName)
}
return fmt.Errorf("look up bucket %s: %w", bucketName, err)
}
// Migration: clear any legacy day-TTL filer.conf entries before
// writing the new XML, so a failure here leaves the bucket entry
// untouched instead of committing the new policy alongside a stale
// TTL rule. Same step and ordering as
// PutBucketLifecycleConfigurationHandler.
if err := filer.ClearBucketLifecycleDayTTLs(context.Background(), client, filerConfig.BucketsPath, bucketName, collection); err != nil {
return fmt.Errorf("failed to clear legacy lifecycle TTLs: %w", err)
}
bucketPath := filerConfig.BucketsPath + "/" + bucketName
resp, err := client.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: bucketPath,
RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + bucketPath,
Mutations: []*filer_pb.ObjectMutation{bucketLifecycleMutation(filerConfig.BucketsPath, bucketName, lifecycleXML)},
})
if err != nil {
return fmt.Errorf("failed to update bucket lifecycle: %w", err)
}
if resp.Error != "" {
return fmt.Errorf("failed to update bucket lifecycle: %s", resp.Error)
}
return nil
})
}
// bucketLifecycleMutation patches the two lifecycle keys rather than writing
// the whole entry back: the filer re-reads and merges under the bucket path
// lock, so a concurrent owner/quota/versioning change is preserved instead of
// being reverted by a stale snapshot. Same mutation the S3 gateway uses for
// these keys (see patchBucketEntry in s3api_bucket_config.go). Empty XML
// clears the configuration, transition minimum size included.
func bucketLifecycleMutation(bucketsPath, bucketName string, lifecycleXML []byte) *filer_pb.ObjectMutation {
mutation := &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_PATCH_EXTENDED,
Directory: bucketsPath,
Name: bucketName,
}
if len(lifecycleXML) > 0 {
mutation.SetExtended = map[string][]byte{
scheduler.BucketLifecycleConfigurationXMLKey: lifecycleXML,
}
return mutation
}
mutation.DeleteExtended = []string{
scheduler.BucketLifecycleConfigurationXMLKey,
scheduler.BucketLifecycleTransitionMinimumObjectSizeKey,
}
return mutation
}
// CreateS3Bucket creates a new S3 bucket
func (s *AdminServer) CreateS3Bucket(bucketName string) error {
return s.CreateS3BucketWithQuota(bucketName, 0, false)
-350
View File
@@ -1,350 +0,0 @@
package dash
import (
"errors"
"fmt"
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
)
func minimalLifecycleRule() BucketLifecycleRule {
return BucketLifecycleRule{
ID: "rule-1",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
}
func TestValidateBucketLifecycleRules_Valid(t *testing.T) {
if err := validateBucketLifecycleRules([]BucketLifecycleRule{minimalLifecycleRule()}); err != nil {
t.Fatalf("expected valid rule set to pass, got: %v", err)
}
}
func TestValidateBucketLifecycleRules_Empty(t *testing.T) {
if err := validateBucketLifecycleRules(nil); err != nil {
t.Fatalf("expected empty rule set to pass, got: %v", err)
}
}
func TestValidateBucketLifecycleRules_TooManyRules(t *testing.T) {
rules := make([]BucketLifecycleRule, MaxBucketLifecycleRules+1)
for i := range rules {
rules[i] = BucketLifecycleRule{Status: s3lifecycle.StatusEnabled, ExpirationDays: 30}
}
if err := validateBucketLifecycleRules(rules); err == nil {
t.Fatal("expected error for exceeding the rule count cap")
}
}
func TestValidateBucketLifecycleRules_DuplicateIDs(t *testing.T) {
rule := minimalLifecycleRule()
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule, rule}); err == nil {
t.Fatal("expected error for duplicate rule IDs")
}
}
func TestValidateBucketLifecycleRules_IDTooLong(t *testing.T) {
rule := minimalLifecycleRule()
longID := ""
for i := 0; i < MaxBucketLifecycleRuleIDLength+1; i++ {
longID += "a"
}
rule.ID = longID
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for an ID longer than the cap")
}
}
func TestValidateBucketLifecycleRules_InvalidStatus(t *testing.T) {
rule := minimalLifecycleRule()
rule.Status = "sort-of-enabled"
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for an invalid status")
}
}
func TestValidateBucketLifecycleRules_ExpirationDaysAndDateMutuallyExclusive(t *testing.T) {
rule := minimalLifecycleRule()
rule.ExpirationDate = "2030-01-01"
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error when both expiration_days and expiration_date are set")
}
}
func TestValidateBucketLifecycleRules_DeleteMarkerWithExpirationDaysRejected(t *testing.T) {
// AWS forbids combining ExpiredObjectDeleteMarker with Days/Date in the
// same Expiration element; ruleFromCanonical would otherwise emit both
// on the same <Expiration>.
rule := minimalLifecycleRule()
rule.ExpiredObjectDeleteMarker = true
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error when expired_object_delete_marker is combined with expiration_days")
}
}
func TestValidateBucketLifecycleRules_DeleteMarkerWithExpirationDateRejected(t *testing.T) {
rule := BucketLifecycleRule{
Status: s3lifecycle.StatusEnabled,
ExpirationDate: "2030-01-01",
ExpiredObjectDeleteMarker: true,
}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error when expired_object_delete_marker is combined with expiration_date")
}
}
func TestValidateBucketLifecycleRules_DeleteMarkerAlone(t *testing.T) {
rule := BucketLifecycleRule{
Status: s3lifecycle.StatusEnabled,
ExpiredObjectDeleteMarker: true,
}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err != nil {
t.Fatalf("expected standalone expired_object_delete_marker to be accepted, got: %v", err)
}
}
func TestValidateBucketLifecycleRules_InvalidExpirationDate(t *testing.T) {
rule := BucketLifecycleRule{Status: s3lifecycle.StatusEnabled, ExpirationDate: "01/01/2030"}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for a malformed expiration_date")
}
}
func TestValidateBucketLifecycleRules_NegativeExpirationDays(t *testing.T) {
rule := minimalLifecycleRule()
rule.ExpirationDays = -1
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for negative expiration_days")
}
}
// TestValidateBucketLifecycleRules_StandaloneNewerNoncurrentVersions guards
// against re-adding a NoncurrentVersionExpirationDays requirement:
// s3lifecycle.RuleActionKinds recognizes a standalone NewerNoncurrentVersions
// (no days) as ActionKindNewerNoncurrent, a valid count-only retention rule
// the S3 API already accepts and stores.
func TestValidateBucketLifecycleRules_StandaloneNewerNoncurrentVersions(t *testing.T) {
rule := BucketLifecycleRule{
Status: s3lifecycle.StatusEnabled,
NewerNoncurrentVersions: 2,
}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err != nil {
t.Fatalf("expected standalone newer_noncurrent_versions to be accepted, got: %v", err)
}
}
func TestValidateBucketLifecycleRules_NegativeAbortMultipartDays(t *testing.T) {
rule := minimalLifecycleRule()
rule.AbortMultipartDays = -5
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for negative abort_multipart_days")
}
}
func TestValidateBucketLifecycleRules_SizeGreaterThanNotLessThanSizeLessThan(t *testing.T) {
rule := minimalLifecycleRule()
rule.SizeGreaterThan = 2048
rule.SizeLessThan = 1024
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error when size_greater_than >= size_less_than")
}
}
func TestValidateBucketLifecycleRules_NegativeSizeBounds(t *testing.T) {
rule := minimalLifecycleRule()
rule.SizeGreaterThan = -1
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for a negative size_greater_than")
}
}
func TestValidateBucketLifecycleRules_EmptyTagKey(t *testing.T) {
rule := minimalLifecycleRule()
rule.Tags = map[string]string{"": "value"}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for an empty tag key")
}
}
func TestValidateBucketLifecycleRules_EmptyTagValue(t *testing.T) {
rule := minimalLifecycleRule()
rule.Tags = map[string]string{"env": " "}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for a blank tag value")
}
}
func TestValidateBucketLifecycleRules_NoAction(t *testing.T) {
rule := BucketLifecycleRule{Status: s3lifecycle.StatusEnabled, Prefix: "logs/"}
if err := validateBucketLifecycleRules([]BucketLifecycleRule{rule}); err == nil {
t.Fatal("expected error for a rule with no action")
}
}
func TestFromBucketLifecycleRule_MapsAllFields(t *testing.T) {
rule := BucketLifecycleRule{
ID: "rule-1",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
Tags: map[string]string{"env": "dev"},
SizeGreaterThan: 1024,
SizeLessThan: 2048,
ExpirationDate: "2030-01-15",
ExpiredObjectDeleteMarker: true,
NoncurrentVersionExpirationDays: 30,
NewerNoncurrentVersions: 2,
AbortMultipartDays: 7,
}
out, err := fromBucketLifecycleRule(rule)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.ID != rule.ID {
t.Errorf("ID = %q, want %q", out.ID, rule.ID)
}
if out.Status != rule.Status {
t.Errorf("Status = %q, want %q", out.Status, rule.Status)
}
if out.Prefix != rule.Prefix {
t.Errorf("Prefix = %q, want %q", out.Prefix, rule.Prefix)
}
if len(out.FilterTags) != 1 || out.FilterTags["env"] != "dev" {
t.Errorf("FilterTags = %v, want {env: dev}", out.FilterTags)
}
if out.FilterSizeGreaterThan != rule.SizeGreaterThan {
t.Errorf("FilterSizeGreaterThan = %d, want %d", out.FilterSizeGreaterThan, rule.SizeGreaterThan)
}
if out.FilterSizeLessThan != rule.SizeLessThan {
t.Errorf("FilterSizeLessThan = %d, want %d", out.FilterSizeLessThan, rule.SizeLessThan)
}
wantDate, _ := time.Parse(time.DateOnly, rule.ExpirationDate)
if !out.ExpirationDate.Equal(wantDate) {
t.Errorf("ExpirationDate = %v, want %v", out.ExpirationDate, wantDate)
}
if !out.ExpiredObjectDeleteMarker {
t.Error("expected ExpiredObjectDeleteMarker=true")
}
if out.NoncurrentVersionExpirationDays != rule.NoncurrentVersionExpirationDays {
t.Errorf("NoncurrentVersionExpirationDays = %d, want %d", out.NoncurrentVersionExpirationDays, rule.NoncurrentVersionExpirationDays)
}
if out.NewerNoncurrentVersions != rule.NewerNoncurrentVersions {
t.Errorf("NewerNoncurrentVersions = %d, want %d", out.NewerNoncurrentVersions, rule.NewerNoncurrentVersions)
}
if out.AbortMPUDaysAfterInitiation != rule.AbortMultipartDays {
t.Errorf("AbortMPUDaysAfterInitiation = %d, want %d", out.AbortMPUDaysAfterInitiation, rule.AbortMultipartDays)
}
}
func TestFromBucketLifecycleRule_EmptyExpirationDate(t *testing.T) {
rule := minimalLifecycleRule()
rule.ExpirationDate = ""
out, err := fromBucketLifecycleRule(rule)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !out.ExpirationDate.IsZero() {
t.Errorf("expected zero ExpirationDate, got %v", out.ExpirationDate)
}
}
func TestFromBucketLifecycleRule_InvalidExpirationDate(t *testing.T) {
rule := minimalLifecycleRule()
rule.ExpirationDate = "not-a-date"
if _, err := fromBucketLifecycleRule(rule); err == nil {
t.Fatal("expected error for a malformed expiration date")
}
}
func TestBucketLifecycleMutation_SetsXML(t *testing.T) {
m := bucketLifecycleMutation("/buckets", "mybucket", []byte("<LifecycleConfiguration/>"))
if m.Type != filer_pb.ObjectMutation_PATCH_EXTENDED {
t.Fatalf("expected a PATCH_EXTENDED mutation, got %v", m.Type)
}
if m.Directory != "/buckets" || m.Name != "mybucket" {
t.Fatalf("expected the mutation to target /buckets/mybucket, got %s/%s", m.Directory, m.Name)
}
if got := string(m.SetExtended[scheduler.BucketLifecycleConfigurationXMLKey]); got != "<LifecycleConfiguration/>" {
t.Fatalf("expected the XML key to carry the marshaled config, got %q", got)
}
if len(m.DeleteExtended) != 0 {
t.Fatalf("expected no key deletions when saving rules, got %v", m.DeleteExtended)
}
}
func TestBucketLifecycleMutation_ClearsBothKeys(t *testing.T) {
m := bucketLifecycleMutation("/buckets", "mybucket", nil)
if len(m.SetExtended) != 0 {
t.Fatalf("expected no key writes when clearing, got %v", m.SetExtended)
}
want := map[string]bool{
scheduler.BucketLifecycleConfigurationXMLKey: true,
scheduler.BucketLifecycleTransitionMinimumObjectSizeKey: true,
}
if len(m.DeleteExtended) != len(want) {
t.Fatalf("expected both lifecycle keys to be cleared, got %v", m.DeleteExtended)
}
for _, k := range m.DeleteExtended {
if !want[k] {
t.Fatalf("unexpected key cleared: %s", k)
}
}
}
// A whole-entry write would have carried the rest of the bucket entry with it;
// the patch must name only the keys it owns, so a concurrent owner or quota
// change survives.
func TestBucketLifecycleMutation_TouchesOnlyLifecycleKeys(t *testing.T) {
for _, m := range []*filer_pb.ObjectMutation{
bucketLifecycleMutation("/buckets", "mybucket", []byte("<LifecycleConfiguration/>")),
bucketLifecycleMutation("/buckets", "mybucket", nil),
} {
if m.Entry != nil {
t.Fatal("expected the mutation to carry no entry snapshot")
}
if m.SetContent {
t.Fatal("expected the mutation to leave entry content alone")
}
for k := range m.SetExtended {
if k != scheduler.BucketLifecycleConfigurationXMLKey {
t.Fatalf("unexpected key written: %s", k)
}
}
}
}
func TestSetBucketLifecycle_RejectsOversizedConfiguration(t *testing.T) {
// A single rule ID long enough to blow the cap: this must fail before any
// filer call, which is what makes it testable without one.
rule := minimalLifecycleRule()
rule.ID = strings.Repeat("x", scheduler.MaxBucketLifecycleConfigurationSize+1)
err := (&AdminServer{}).SetBucketLifecycle("mybucket", []BucketLifecycleRule{rule})
if err == nil {
t.Fatal("expected an oversized lifecycle configuration to be rejected")
}
if !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("expected a size-limit error, got: %v", err)
}
}
func TestBucketLifecycleErrorStatus(t *testing.T) {
if got := bucketLifecycleErrorStatus(fmt.Errorf("%w: mybucket", ErrBucketNotFound)); got != http.StatusNotFound {
t.Fatalf("expected a missing bucket to map to 404, got %d", got)
}
if got := bucketLifecycleErrorStatus(errors.New("filer unreachable")); got != http.StatusInternalServerError {
t.Fatalf("expected an unrelated failure to stay 500, got %d", got)
}
}
-155
View File
@@ -2,7 +2,6 @@ package dash
import (
"context"
"errors"
"fmt"
"net/http"
"os"
@@ -14,15 +13,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
// MaxBucketLifecycleRules mirrors AWS S3's limit of 1000 lifecycle rules per bucket.
const MaxBucketLifecycleRules = 1000
// MaxBucketLifecycleRuleIDLength mirrors the S3 API's limit on a lifecycle rule's <ID>.
const MaxBucketLifecycleRuleIDLength = 255
// MaxOwnerNameLength is the maximum allowed length for bucket owner identity names.
// This is a reasonable limit to prevent abuse; AWS IAM user names are limited to 64 chars,
// but we use 256 to allow for more complex identity formats (e.g., email addresses).
@@ -110,153 +102,6 @@ func (s *AdminServer) ShowBucketLifecycle(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, lifecycle)
}
// UpdateBucketLifecycle replaces the entire lifecycle configuration for a bucket.
func (s *AdminServer) UpdateBucketLifecycle(w http.ResponseWriter, r *http.Request) {
if !requireSessionCSRFToken(w, r) {
return
}
bucketName := mux.Vars(r)["bucket"]
if bucketName == "" {
writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
return
}
var req struct {
Rules []BucketLifecycleRule `json:"rules"`
}
if err := decodeJSONBody(newJSONMaxReader(w, r), &req); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid request: "+err.Error())
return
}
if err := validateBucketLifecycleRules(req.Rules); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
if err := s.SetBucketLifecycle(bucketName, req.Rules); err != nil {
writeJSONError(w, bucketLifecycleErrorStatus(err), "Failed to update bucket lifecycle: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"message": "Bucket lifecycle updated successfully",
"bucket": bucketName,
})
}
// DeleteBucketLifecycle clears the entire lifecycle configuration for a bucket.
func (s *AdminServer) DeleteBucketLifecycle(w http.ResponseWriter, r *http.Request) {
if !requireSessionCSRFToken(w, r) {
return
}
bucketName := mux.Vars(r)["bucket"]
if bucketName == "" {
writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
return
}
if err := s.SetBucketLifecycle(bucketName, nil); err != nil {
writeJSONError(w, bucketLifecycleErrorStatus(err), "Failed to delete bucket lifecycle: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"message": "Bucket lifecycle deleted successfully",
"bucket": bucketName,
})
}
// bucketLifecycleErrorStatus keeps a request for a bucket that does not exist
// out of the 5xx bucket, where a client would retry it.
func bucketLifecycleErrorStatus(err error) int {
if errors.Is(err, ErrBucketNotFound) {
return http.StatusNotFound
}
return http.StatusInternalServerError
}
// validateBucketLifecycleRules rejects a rule set before any write is
// attempted, so a malformed PUT can't half-apply. Mirrors the constraints
// AWS enforces on PutBucketLifecycleConfiguration plus the local rule cap.
func validateBucketLifecycleRules(rules []BucketLifecycleRule) error {
if len(rules) > MaxBucketLifecycleRules {
return fmt.Errorf("a bucket may have at most %d lifecycle rules, got %d", MaxBucketLifecycleRules, len(rules))
}
seenIDs := make(map[string]bool, len(rules))
for i, rule := range rules {
label := fmt.Sprintf("rule %d", i+1)
if rule.ID != "" {
label = fmt.Sprintf("rule %q", rule.ID)
if len(rule.ID) > MaxBucketLifecycleRuleIDLength {
return fmt.Errorf("%s: ID must be %d characters or less", label, MaxBucketLifecycleRuleIDLength)
}
if seenIDs[rule.ID] {
return fmt.Errorf("duplicate rule ID %q", rule.ID)
}
seenIDs[rule.ID] = true
}
switch rule.Status {
case s3lifecycle.StatusEnabled, s3lifecycle.StatusDisabled:
default:
return fmt.Errorf("%s: status must be %q or %q, got %q", label, s3lifecycle.StatusEnabled, s3lifecycle.StatusDisabled, rule.Status)
}
if rule.ExpirationDays > 0 && rule.ExpirationDate != "" {
return fmt.Errorf("%s: expiration_days and expiration_date are mutually exclusive", label)
}
if rule.ExpirationDays < 0 {
return fmt.Errorf("%s: expiration_days must be positive", label)
}
if rule.ExpirationDate != "" {
if _, err := time.Parse(time.DateOnly, rule.ExpirationDate); err != nil {
return fmt.Errorf("%s: invalid expiration_date %q, expected YYYY-MM-DD", label, rule.ExpirationDate)
}
}
if rule.ExpiredObjectDeleteMarker && (rule.ExpirationDays > 0 || rule.ExpirationDate != "") {
return fmt.Errorf("%s: expired_object_delete_marker cannot be combined with expiration_days or expiration_date", label)
}
if rule.NoncurrentVersionExpirationDays < 0 {
return fmt.Errorf("%s: noncurrent_version_expiration_days must be positive", label)
}
if rule.NewerNoncurrentVersions < 0 {
return fmt.Errorf("%s: newer_noncurrent_versions must be positive", label)
}
if rule.AbortMultipartDays < 0 {
return fmt.Errorf("%s: abort_multipart_days must be positive", label)
}
if rule.SizeGreaterThan < 0 || rule.SizeLessThan < 0 {
return fmt.Errorf("%s: size_greater_than and size_less_than must be positive", label)
}
if rule.SizeGreaterThan > 0 && rule.SizeLessThan > 0 && rule.SizeGreaterThan >= rule.SizeLessThan {
return fmt.Errorf("%s: size_greater_than must be less than size_less_than", label)
}
for k, v := range rule.Tags {
if strings.TrimSpace(k) == "" {
return fmt.Errorf("%s: tag keys must not be empty", label)
}
if strings.TrimSpace(v) == "" {
return fmt.Errorf("%s: tag value for key %q must not be empty", label, k)
}
}
hasAction := rule.ExpirationDays > 0 || rule.ExpirationDate != "" || rule.ExpiredObjectDeleteMarker ||
rule.NoncurrentVersionExpirationDays > 0 || rule.NewerNoncurrentVersions > 0 || rule.AbortMultipartDays > 0
if !hasAction {
return fmt.Errorf("%s: must specify at least one action (expiration, noncurrent version expiration, or abort incomplete multipart upload)", label)
}
}
return nil
}
// CreateBucket creates a new S3 bucket
func (s *AdminServer) CreateBucket(w http.ResponseWriter, r *http.Request) {
var req CreateBucketRequest
-2
View File
@@ -179,8 +179,6 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
s3Api.Handle("/buckets/{bucket}", wrapWrite(h.adminServer.DeleteBucket)).Methods(http.MethodDelete)
s3Api.HandleFunc("/buckets/{bucket}", h.adminServer.ShowBucketDetails).Methods(http.MethodGet)
s3Api.HandleFunc("/buckets/{bucket}/lifecycle", h.adminServer.ShowBucketLifecycle).Methods(http.MethodGet)
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.UpdateBucketLifecycle)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.DeleteBucketLifecycle)).Methods(http.MethodDelete)
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
@@ -42,26 +42,6 @@ func TestSetupRoutes_RegistersPluginSchedulerStatesAPI_WithAuth(t *testing.T) {
}
}
func TestSetupRoutes_RegistersBucketLifecycleAPI_NoAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
}
func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
}
func TestSetupRoutes_RegistersPluginPages_NoAuth(t *testing.T) {
router := mux.NewRouter()
+5 -5
View File
@@ -634,7 +634,7 @@ function formatDate(date) {
function adminCopyToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(() => {
showToast('Copied to clipboard!');
showAlert('Copied to clipboard!', 'success');
}).catch(err => {
console.error('Failed to copy text: ', err);
fallbackCopyText(text);
@@ -660,7 +660,7 @@ function fallbackCopyText(text) {
try {
const successful = document.execCommand('copy');
if (successful) {
showToast('Copied to clipboard!');
showAlert('Copied to clipboard!', 'success');
} else {
showAlert('Failed to copy to clipboard', 'danger');
}
@@ -2265,11 +2265,11 @@ function copyFromInput(inputId) {
try {
const successful = document.execCommand('copy');
if (successful) {
showToast('Copied to clipboard!');
showAlert('Copied to clipboard!', 'success');
} else {
// Try modern clipboard API as fallback
navigator.clipboard.writeText(input.value).then(() => {
showToast('Copied to clipboard!');
showAlert('Copied to clipboard!', 'success');
}).catch(() => {
showAlert('Failed to copy', 'danger');
});
@@ -2277,7 +2277,7 @@ function copyFromInput(inputId) {
} catch (err) {
// Try modern clipboard API as fallback
navigator.clipboard.writeText(input.value).then(() => {
showToast('Copied to clipboard!');
showAlert('Copied to clipboard!', 'success');
}).catch(() => {
showAlert('Failed to copy', 'danger');
});
-64
View File
@@ -168,36 +168,6 @@
bsModal.show();
};
/**
* Show a transient message that does not have to be dismissed
* @param {string} message - The message to display
* @param {string} type - Bootstrap contextual color, defaults to 'success'
*/
window.showToast = function (message, type) {
let container = document.getElementById('globalToastContainer');
if (!container) {
container = document.createElement('div');
container.id = 'globalToastContainer';
container.className = 'toast-container position-fixed top-0 end-0 p-3';
// Above any modal, however deeply they are stacked.
container.style.zIndex = '9999';
document.body.appendChild(container);
}
const toast = document.createElement('div');
toast.className = 'toast align-items-center text-white bg-' + (type || 'success') + ' border-0';
toast.setAttribute('role', 'alert');
toast.innerHTML = '<div class="d-flex"><div class="toast-body">' + escapeHtml(message) + '</div>' +
'<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button></div>';
container.appendChild(toast);
toast.addEventListener('hidden.bs.toast', function () {
toast.remove();
});
new bootstrap.Toast(toast, { delay: 3000 }).show();
};
/**
* Show a confirmation dialog using Bootstrap modal
* @param {string} message - The confirmation message
@@ -320,40 +290,6 @@
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
// Bootstrap gives every modal and backdrop the same z-index, so a modal
// opened while another one is showing paints behind it and cannot be
// clicked. Lift each nested modal, and its backdrop, above what is already
// on screen.
const MODAL_Z_INDEX = 1055;
const MODAL_Z_INDEX_STEP = 20;
document.addEventListener('show.bs.modal', function (event) {
const depth = document.querySelectorAll('.modal.show').length;
if (depth === 0) {
return;
}
const zIndex = MODAL_Z_INDEX + depth * MODAL_Z_INDEX_STEP;
event.target.style.zIndex = zIndex;
// Bootstrap only creates the backdrop after this event returns.
setTimeout(function () {
const backdrops = document.querySelectorAll('.modal-backdrop');
const backdrop = backdrops[backdrops.length - 1];
if (backdrop) {
backdrop.style.zIndex = zIndex - 1;
}
}, 0);
});
document.addEventListener('hidden.bs.modal', function (event) {
event.target.style.zIndex = '';
// Closing any modal releases the scroll lock the others still need.
if (document.querySelector('.modal.show')) {
document.body.classList.add('modal-open');
}
});
// Auto-initialize on DOMContentLoaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', ensureModalsExist);
Binary file not shown.
Binary file not shown.
+122 -637
View File
@@ -637,7 +637,7 @@ templ S3Buckets(data dash.S3BucketsData) {
<!-- Bucket Lifecycle Modal -->
<div class="modal fade" id="bucketLifecycleModal" tabindex="-1" aria-labelledby="bucketLifecycleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="bucketLifecycleModalLabel">
@@ -649,13 +649,7 @@ templ S3Buckets(data dash.S3BucketsData) {
<div id="bucketLifecycleContent"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger me-auto" id="lifecycleDeleteAllBtn">
<i class="fas fa-trash me-1"></i>Delete all rules
</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="lifecycleSaveAllBtn">
<i class="fas fa-save me-1"></i>Save
</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
@@ -718,69 +712,6 @@ templ S3Buckets(data dash.S3BucketsData) {
let lifecycleRequestSeq = 0;
let cachedUsers = null;
// Working copy of the lifecycle rules currently shown in the modal.
// Edits (add/edit/delete rule) only mutate this local state; nothing is
// sent to the server until "Save" or "Delete all rules" is clicked.
let lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };
function escapeHtml(v) {
return String(v ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Shadows admin.js's formatBytes for this page, so it keeps that
// signature and unit list; the extra guard is for a size the API left
// out, which the shared one renders as "NaN undefined".
function formatBytes(bytes, decimals = 2) {
if (!bytes) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function formatDays(n) {
return n + (n === 1 ? ' day' : ' days');
}
// csrfHeaders reads the token the layout stamps into every page
// (<meta name="csrf-token">) so mutating lifecycle requests pass it the
// same way the newer admin pages (e.g. s3tables) do.
function csrfHeaders() {
const meta = document.querySelector('meta[name="csrf-token"]');
const token = meta ? (meta.getAttribute('content') || '') : '';
const headers = { 'Content-Type': 'application/json' };
if (token) {
headers['X-CSRF-Token'] = token;
}
return headers;
}
// parseLifecycleResponse reads the body as text before parsing, so a
// non-JSON response (a proxy's HTML error page, an empty body, plain
// text from some middleware) surfaces the HTTP status instead of
// throwing a raw JSON syntax error out of response.json().
function parseLifecycleResponse(response) {
return response.text().then(text => {
let data = {};
if (text) {
try {
data = JSON.parse(text);
} catch (e) {
data = { error: response.statusText || ('HTTP ' + response.status) };
}
} else if (!response.ok) {
data = { error: response.statusText || ('HTTP ' + response.status) };
}
return { ok: response.ok, data: data };
});
}
document.addEventListener('DOMContentLoaded', function() {
// Add click handlers to pagination links
document.querySelectorAll('.pagination-link').forEach(link => {
@@ -1143,10 +1074,6 @@ templ S3Buckets(data dash.S3BucketsData) {
button.addEventListener('click', function() {
const bucketName = this.dataset.bucketName;
// Reset the working copy until the GET below repopulates it,
// so Save/Delete-all can't act on the previous bucket's rules.
lifecycleEditor = { bucket: null, rules: [], editingIndex: null, editingRule: null, rawXml: '', hasTransition: false };
document.getElementById('bucketLifecycleModalLabel').innerHTML =
'<i class="fas fa-recycle me-2"></i>Lifecycle - ' + bucketName;
@@ -1163,14 +1090,14 @@ templ S3Buckets(data dash.S3BucketsData) {
// Drop responses that arrive after another bucket was opened
const requestSeq = ++lifecycleRequestSeq;
fetch(basePath('/api/s3/buckets/' + bucketName + '/lifecycle'))
.then(parseLifecycleResponse)
.then(({ ok, data }) => {
.then(response => response.json())
.then(data => {
if (requestSeq !== lifecycleRequestSeq) return;
if (!ok || data.error) {
if (data.error) {
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="alert alert-danger">' +
'<i class="fas fa-exclamation-triangle me-2"></i>' +
'Error loading lifecycle rules: ' + (data.error || 'unknown error') +
'Error loading lifecycle rules: ' + data.error +
'<\/div>';
} else {
displayBucketLifecycle(data);
@@ -1187,67 +1114,6 @@ templ S3Buckets(data dash.S3BucketsData) {
});
});
});
// Save the whole working rule set back to the bucket.
document.getElementById('lifecycleSaveAllBtn').addEventListener('click', function() {
if (!lifecycleEditor.bucket) return;
// Fold in any rule the user is still editing so Save doesn't
// silently discard it; abort if that form isn't valid yet.
if (!commitOpenLifecycleRuleForm()) return;
// An empty list clears the configuration, same as Delete all rules,
// so it gets the same prompt.
if (lifecycleEditor.rules.length === 0 &&
!confirm('No rules left: saving removes the lifecycle configuration for ' + lifecycleEditor.bucket + '. This cannot be undone.')) {
return;
}
fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {
method: 'PUT',
headers: csrfHeaders(),
body: JSON.stringify({ rules: lifecycleEditor.rules })
})
.then(parseLifecycleResponse)
.then(({ ok, data }) => {
if (!ok || data.error) {
alert('Error saving lifecycle rules: ' + (data.error || 'unknown error'));
return;
}
if (lifecycleModalInstance) {
lifecycleModalInstance.hide();
}
setTimeout(() => location.reload(), 500);
})
.catch(error => {
console.error('Error:', error);
alert('Error saving lifecycle rules: ' + error.message);
});
});
// Clear the lifecycle configuration entirely.
document.getElementById('lifecycleDeleteAllBtn').addEventListener('click', function() {
if (!lifecycleEditor.bucket) return;
if (!confirm('Delete all lifecycle rules for ' + lifecycleEditor.bucket + '? This cannot be undone.')) return;
fetch(basePath('/api/s3/buckets/' + lifecycleEditor.bucket + '/lifecycle'), {
method: 'DELETE',
headers: csrfHeaders()
})
.then(parseLifecycleResponse)
.then(({ ok, data }) => {
if (!ok || data.error) {
alert('Error deleting lifecycle rules: ' + (data.error || 'unknown error'));
return;
}
if (lifecycleModalInstance) {
lifecycleModalInstance.hide();
}
setTimeout(() => location.reload(), 500);
})
.catch(error => {
console.error('Error:', error);
alert('Error deleting lifecycle rules: ' + error.message);
});
});
});
function deleteBucket() {
@@ -1279,6 +1145,23 @@ templ S3Buckets(data dash.S3BucketsData) {
function displayBucketDetails(data) {
const bucket = data.bucket;
function escapeHtml(v) {
return String(v ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleString();
@@ -1349,518 +1232,112 @@ function displayBucketDetails(data) {
document.getElementById('bucketDetailsContent').innerHTML = rows.join('');
}
// displayBucketLifecycle loads the GET response into the local working copy
// and renders the editor. Nothing is sent back to the server until Save or
// Delete all rules is clicked.
function displayBucketLifecycle(data) {
lifecycleEditor.bucket = data.bucket || lifecycleEditor.bucket;
lifecycleEditor.rules = (data.rules || []).map(cloneLifecycleRule);
lifecycleEditor.editingIndex = null;
lifecycleEditor.editingRule = null;
lifecycleEditor.rawXml = data.xml || '';
// SeaweedFS doesn't support Transition rules (PutBucketLifecycleConfiguration
// rejects them for Enabled rules), and the canonical rule shape the admin
// edits has no field for one, so a Transition set by another client would
// silently disappear on the next Save. Warn instead.
// Matches <Transition> and <NoncurrentVersionTransition> however they are
// spelled: with attributes, self-closed, or namespace-prefixed.
lifecycleEditor.hasTransition = /<(\w+:)?(NoncurrentVersion)?Transition[\s>\/]/.test(data.xml || '');
renderLifecycleEditor();
}
// normalizeLifecycleStatus maps a stored status onto the two the editor can
// show. The S3 API stores <Status> unvalidated, and the engine runs a rule
// only on an exact "Enabled", so everything else is Disabled - collapsing it
// here keeps an odd spelling from leaving both radios unchecked, which would
// throw out of readLifecycleRuleFromForm and make the modal look dead.
function normalizeLifecycleStatus(status) {
return status === 'Enabled' ? 'Enabled' : 'Disabled';
}
function cloneLifecycleRule(r) {
return {
id: r.id || '',
status: normalizeLifecycleStatus(r.status),
prefix: r.prefix || '',
tags: Object.assign({}, r.tags || {}),
size_greater_than: r.size_greater_than || null,
size_less_than: r.size_less_than || null,
expiration_days: r.expiration_days || null,
expiration_date: r.expiration_date || '',
expired_object_delete_marker: !!r.expired_object_delete_marker,
noncurrent_version_expiration_days: r.noncurrent_version_expiration_days || null,
newer_noncurrent_versions: r.newer_noncurrent_versions || null,
abort_multipart_days: r.abort_multipart_days || null,
};
}
function blankLifecycleRule() {
return {
id: '', status: 'Enabled', prefix: '', tags: {},
size_greater_than: null, size_less_than: null,
expiration_days: null, expiration_date: '',
expired_object_delete_marker: false,
noncurrent_version_expiration_days: null, newer_noncurrent_versions: null,
abort_multipart_days: null,
};
}
function describeLifecycleScope(rule) {
const parts = [];
if (rule.prefix) {
parts.push('<code>' + escapeHtml(rule.prefix) + '<\/code>');
}
Object.entries(rule.tags || {}).forEach(([k, v]) => {
parts.push('<span class="badge bg-light text-dark border">' + escapeHtml(k) + '=' + escapeHtml(v) + '<\/span>');
});
if (rule.size_greater_than) {
parts.push('size &gt; ' + formatBytes(rule.size_greater_than));
}
if (rule.size_less_than) {
parts.push('size &lt; ' + formatBytes(rule.size_less_than));
}
return parts.length ? parts.join(' ') : '<span class="text-muted">Whole bucket<\/span>';
}
function describeLifecycleActions(rule) {
const actions = [];
if (rule.expiration_days) {
actions.push('Expire after ' + formatDays(rule.expiration_days));
}
if (rule.expiration_date) {
actions.push('Expire on ' + escapeHtml(rule.expiration_date));
}
if (rule.expired_object_delete_marker) {
actions.push('Remove expired object delete markers');
}
if (rule.noncurrent_version_expiration_days) {
let action = 'Expire noncurrent versions after ' + formatDays(rule.noncurrent_version_expiration_days);
if (rule.newer_noncurrent_versions) {
action += ', keep ' + rule.newer_noncurrent_versions + ' newest';
}
actions.push(action);
} else if (rule.newer_noncurrent_versions) {
// Standalone (no expiration_days): the engine still recognizes this
// as an action that expires noncurrent versions beyond the N newest.
actions.push('Keep ' + rule.newer_noncurrent_versions + ' newest noncurrent versions');
}
if (rule.abort_multipart_days) {
actions.push('Abort incomplete multipart uploads after ' + formatDays(rule.abort_multipart_days));
}
if (actions.length === 0) {
return '<span class="text-muted">None<\/span>';
}
return actions.join('<br>');
}
function lifecycleRuleRowHtml(rule, idx) {
const statusHtml = rule.status === 'Enabled'
? '<span class="badge bg-success">Enabled<\/span>'
: '<span class="badge bg-secondary">' + escapeHtml(rule.status) + '<\/span>';
return '<tr>' +
'<td>' + (rule.id ? escapeHtml(rule.id) : '<span class="text-muted">unnamed<\/span>') + '<\/td>' +
'<td>' + statusHtml + '<\/td>' +
'<td>' + describeLifecycleScope(rule) + '<\/td>' +
'<td>' + describeLifecycleActions(rule) + '<\/td>' +
'<td class="text-end text-nowrap">' +
'<button type="button" class="btn btn-sm btn-outline-secondary lifecycle-edit-rule-btn" data-index="' + idx + '" title="Edit rule"><i class="fas fa-pen"><\/i><\/button> ' +
'<button type="button" class="btn btn-sm btn-outline-danger lifecycle-delete-rule-btn" data-index="' + idx + '" title="Delete rule"><i class="fas fa-trash"><\/i><\/button>' +
'<\/td>' +
'<\/tr>';
}
function lifecycleRuleFormHtml() {
const rule = lifecycleEditor.editingRule;
const tagRowHtml = (k, v) =>
'<div class="input-group input-group-sm mb-1 lifecycle-tag-row">' +
'<input type="text" class="form-control lifecycle-tag-key" placeholder="Key" value="' + escapeHtml(k) + '">' +
'<input type="text" class="form-control lifecycle-tag-value" placeholder="Value" value="' + escapeHtml(v) + '">' +
'<button type="button" class="btn btn-outline-danger lifecycle-remove-tag-btn"><i class="fas fa-times"><\/i><\/button>' +
'<\/div>';
const tagRows = Object.entries(rule.tags || {}).map(([k, v]) => tagRowHtml(k, v)).join('');
return '' +
'<div class="card mb-3" id="lifecycleRuleForm">' +
'<div class="card-body">' +
'<h6 class="card-title">' + (lifecycleEditor.editingIndex === 'new' ? 'Add rule' : 'Edit rule') + '<\/h6>' +
'<div class="row g-2 mb-2">' +
'<div class="col-md-6">' +
'<label class="form-label small">ID (optional)<\/label>' +
'<input type="text" class="form-control form-control-sm" id="lifecycleRuleId" value="' + escapeHtml(rule.id) + '">' +
'<\/div>' +
'<div class="col-md-6">' +
'<label class="form-label small d-block">Status<\/label>' +
'<div class="form-check form-check-inline">' +
'<input class="form-check-input" type="radio" name="lifecycleRuleStatus" id="lifecycleStatusEnabled" value="Enabled"' + (rule.status === 'Enabled' ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleStatusEnabled">Enabled<\/label>' +
'<\/div>' +
'<div class="form-check form-check-inline">' +
'<input class="form-check-input" type="radio" name="lifecycleRuleStatus" id="lifecycleStatusDisabled" value="Disabled"' + (rule.status === 'Disabled' ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleStatusDisabled">Disabled<\/label>' +
'<\/div>' +
'<\/div>' +
'<\/div>' +
'<div class="mb-2">' +
'<label class="form-label small">Prefix<\/label>' +
'<input type="text" class="form-control form-control-sm" id="lifecycleRulePrefix" placeholder="logs/" value="' + escapeHtml(rule.prefix) + '">' +
'<\/div>' +
'<div class="mb-2">' +
'<label class="form-label small d-block">Tags<\/label>' +
'<div id="lifecycleTagRows">' + tagRows + '<\/div>' +
'<button type="button" class="btn btn-sm btn-outline-secondary" id="lifecycleAddTagBtn"><i class="fas fa-plus me-1"><\/i>Add tag<\/button>' +
'<\/div>' +
'<div class="row g-2 mb-3">' +
'<div class="col-md-6">' +
'<label class="form-label small">Size greater than (bytes)<\/label>' +
'<input type="number" class="form-control form-control-sm" id="lifecycleRuleSizeGT" min="0" step="1" value="' + (rule.size_greater_than || '') + '">' +
'<\/div>' +
'<div class="col-md-6">' +
'<label class="form-label small">Size less than (bytes)<\/label>' +
'<input type="number" class="form-control form-control-sm" id="lifecycleRuleSizeLT" min="0" step="1" value="' + (rule.size_less_than || '') + '">' +
'<\/div>' +
'<\/div>' +
'<hr>' +
'<h6 class="small text-muted text-uppercase">Actions<\/h6>' +
'<div class="row g-2 align-items-center mb-2">' +
'<div class="col-auto">' +
'<div class="form-check">' +
'<input class="form-check-input" type="checkbox" id="lifecycleExpireDaysEnabled"' + (rule.expiration_days ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleExpireDaysEnabled">Expire after<\/label>' +
'<\/div>' +
'<\/div>' +
'<div class="col-auto">' +
'<input type="number" class="form-control form-control-sm" id="lifecycleExpireDays" min="1" step="1" style="width: 6rem;" value="' + (rule.expiration_days || '') + '"' + (rule.expiration_days ? '' : ' disabled') + '>' +
'<\/div><div class="col-auto">days<\/div>' +
'<\/div>' +
'<div class="row g-2 align-items-center mb-2">' +
'<div class="col-auto">' +
'<div class="form-check">' +
'<input class="form-check-input" type="checkbox" id="lifecycleExpireDateEnabled"' + (rule.expiration_date ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleExpireDateEnabled">Expire on date<\/label>' +
'<\/div>' +
'<\/div>' +
'<div class="col-auto">' +
'<input type="date" class="form-control form-control-sm" id="lifecycleExpireDate" value="' + escapeHtml(rule.expiration_date) + '"' + (rule.expiration_date ? '' : ' disabled') + '>' +
'<\/div>' +
'<\/div>' +
'<div class="form-check mb-2">' +
'<input class="form-check-input" type="checkbox" id="lifecycleDeleteMarker"' + (rule.expired_object_delete_marker ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleDeleteMarker">Remove expired object delete markers<\/label>' +
'<\/div>' +
(() => {
const noncurrentActive = !!(rule.noncurrent_version_expiration_days || rule.newer_noncurrent_versions);
return '<div class="row g-2 align-items-center mb-2">' +
'<div class="col-auto">' +
'<div class="form-check">' +
'<input class="form-check-input" type="checkbox" id="lifecycleNoncurrentEnabled"' + (noncurrentActive ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleNoncurrentEnabled">Limit noncurrent versions<\/label>' +
'<\/div>' +
'<\/div>' +
'<div class="col-auto">after<\/div>' +
'<div class="col-auto">' +
'<input type="number" class="form-control form-control-sm" id="lifecycleNoncurrentDays" min="1" step="1" style="width: 6rem;" value="' + (rule.noncurrent_version_expiration_days || '') + '"' + (noncurrentActive ? '' : ' disabled') + '>' +
'<\/div><div class="col-auto">days (optional), keep<\/div>' +
'<div class="col-auto">' +
'<input type="number" class="form-control form-control-sm" id="lifecycleNoncurrentKeep" min="0" step="1" style="width: 6rem;" value="' + (rule.newer_noncurrent_versions || '') + '"' + (noncurrentActive ? '' : ' disabled') + '>' +
'<\/div><div class="col-auto">newest (optional)<\/div>' +
'<\/div>';
})() +
'<div class="row g-2 align-items-center mb-3">' +
'<div class="col-auto">' +
'<div class="form-check">' +
'<input class="form-check-input" type="checkbox" id="lifecycleAbortMPUEnabled"' + (rule.abort_multipart_days ? ' checked' : '') + '>' +
'<label class="form-check-label" for="lifecycleAbortMPUEnabled">Abort incomplete multipart uploads after<\/label>' +
'<\/div>' +
'<\/div>' +
'<div class="col-auto">' +
'<input type="number" class="form-control form-control-sm" id="lifecycleAbortMPUDays" min="1" step="1" style="width: 6rem;" value="' + (rule.abort_multipart_days || '') + '"' + (rule.abort_multipart_days ? '' : ' disabled') + '>' +
'<\/div><div class="col-auto">days<\/div>' +
'<\/div>' +
'<div class="text-end">' +
'<button type="button" class="btn btn-sm btn-secondary" id="lifecycleCancelRuleBtn">Cancel<\/button> ' +
'<button type="button" class="btn btn-sm btn-primary" id="lifecycleSaveRuleBtn">Save rule<\/button>' +
'<\/div>' +
'<\/div>' +
'<\/div>';
}
function renderLifecycleEditor() {
const container = document.getElementById('bucketLifecycleContent');
const rowsHtml = lifecycleEditor.rules.map(lifecycleRuleRowHtml).join('') ||
'<tr><td colspan="5" class="text-center text-muted py-3">No lifecycle rules<\/td><\/tr>';
let html = '';
if (lifecycleEditor.hasTransition) {
html += '<div class="alert alert-warning small">' +
'<i class="fas fa-triangle-exclamation me-1"><\/i>' +
'This bucket has a Transition rule set outside the admin (SeaweedFS does not support storage class transitions). Saving from here will drop it.' +
'<\/div>';
function escapeHtml(v) {
return String(v ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
html += '<div class="table-responsive mb-3">' +
'<table class="table table-sm align-middle">' +
'<thead><tr><th>Rule<\/th><th>Status<\/th><th>Scope<\/th><th>Actions<\/th><th><\/th><\/tr><\/thead>' +
'<tbody>' + rowsHtml + '<\/tbody>' +
'<\/table>' +
'<\/div>' +
'<button type="button" class="btn btn-sm btn-outline-primary mb-3" id="lifecycleAddRuleBtn">' +
'<i class="fas fa-plus me-1"><\/i>Add rule' +
'<\/button>';
if (lifecycleEditor.editingIndex !== null) {
html += lifecycleRuleFormHtml();
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
if (lifecycleEditor.rawXml) {
html += '<details class="mt-2">' +
'<summary class="text-muted small">Raw XML (as currently stored)<\/summary>' +
'<pre class="bg-light border rounded p-2 mt-2 small mb-0">' + escapeHtml(lifecycleEditor.rawXml) + '<\/pre>' +
'<\/details>';
function days(n) {
return n + (n === 1 ? ' day' : ' days');
}
container.innerHTML = html;
bindLifecycleEditorEvents();
}
function bindLifecycleToggle(checkboxId, fieldId, mutuallyExclusiveId) {
const checkbox = document.getElementById(checkboxId);
const field = document.getElementById(fieldId);
if (!checkbox || !field) return;
checkbox.addEventListener('change', function() {
field.disabled = !this.checked;
if (this.checked && mutuallyExclusiveId) {
const other = document.getElementById(mutuallyExclusiveId);
if (other && other.checked) {
other.checked = false;
other.dispatchEvent(new Event('change'));
}
}
});
}
function bindLifecycleEditorEvents() {
const addBtn = document.getElementById('lifecycleAddRuleBtn');
if (addBtn) {
addBtn.addEventListener('click', function() {
// Fold in any rule already being edited before switching forms,
// so an invalid in-progress draft isn't silently discarded.
if (!commitOpenLifecycleRuleForm()) return;
lifecycleEditor.editingIndex = 'new';
lifecycleEditor.editingRule = blankLifecycleRule();
renderLifecycleEditor();
});
}
document.querySelectorAll('.lifecycle-edit-rule-btn').forEach(btn => {
btn.addEventListener('click', function() {
const idx = parseInt(this.dataset.index, 10);
// Same as above: committing never shifts indices (it either
// pushes a new rule at the end or replaces one in place), so
// idx captured above is still valid after this call.
if (!commitOpenLifecycleRuleForm()) return;
lifecycleEditor.editingIndex = idx;
lifecycleEditor.editingRule = cloneLifecycleRule(lifecycleEditor.rules[idx]);
renderLifecycleEditor();
});
});
document.querySelectorAll('.lifecycle-delete-rule-btn').forEach(btn => {
btn.addEventListener('click', function() {
const idx = parseInt(this.dataset.index, 10);
// Fold in an open form first, like every other transition does:
// re-rendering after the splice would otherwise redraw it from the
// snapshot taken when editing began and lose what was typed.
if (lifecycleEditor.editingIndex !== null && lifecycleEditor.editingIndex !== idx) {
if (!commitOpenLifecycleRuleForm()) return;
}
lifecycleEditor.rules.splice(idx, 1);
// Deleting a rule shifts every later index down by one, so an
// open edit form must follow its rule rather than silently
// start targeting whatever now sits at its old index.
if (lifecycleEditor.editingIndex === idx) {
lifecycleEditor.editingIndex = null;
lifecycleEditor.editingRule = null;
} else if (typeof lifecycleEditor.editingIndex === 'number' && lifecycleEditor.editingIndex > idx) {
lifecycleEditor.editingIndex -= 1;
}
renderLifecycleEditor();
});
});
const cancelBtn = document.getElementById('lifecycleCancelRuleBtn');
if (cancelBtn) {
cancelBtn.addEventListener('click', function() {
lifecycleEditor.editingIndex = null;
lifecycleEditor.editingRule = null;
renderLifecycleEditor();
});
}
const addTagBtn = document.getElementById('lifecycleAddTagBtn');
if (addTagBtn) {
addTagBtn.addEventListener('click', function() {
const rows = document.getElementById('lifecycleTagRows');
const row = document.createElement('div');
row.className = 'input-group input-group-sm mb-1 lifecycle-tag-row';
row.innerHTML =
'<input type="text" class="form-control lifecycle-tag-key" placeholder="Key">' +
'<input type="text" class="form-control lifecycle-tag-value" placeholder="Value">' +
'<button type="button" class="btn btn-outline-danger lifecycle-remove-tag-btn"><i class="fas fa-times"><\/i><\/button>';
rows.appendChild(row);
row.querySelector('.lifecycle-remove-tag-btn').addEventListener('click', function() {
row.remove();
});
});
}
document.querySelectorAll('.lifecycle-remove-tag-btn').forEach(btn => {
btn.addEventListener('click', function() {
this.closest('.lifecycle-tag-row').remove();
});
});
bindLifecycleToggle('lifecycleExpireDaysEnabled', 'lifecycleExpireDays', 'lifecycleExpireDateEnabled');
bindLifecycleToggle('lifecycleExpireDateEnabled', 'lifecycleExpireDate', 'lifecycleExpireDaysEnabled');
bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentDays');
bindLifecycleToggle('lifecycleNoncurrentEnabled', 'lifecycleNoncurrentKeep');
bindLifecycleToggle('lifecycleAbortMPUEnabled', 'lifecycleAbortMPUDays');
const saveRuleBtn = document.getElementById('lifecycleSaveRuleBtn');
if (saveRuleBtn) {
saveRuleBtn.addEventListener('click', saveLifecycleRuleFromForm);
}
}
// readLifecycleRuleFromForm builds and validates a rule from the currently
// open edit form's DOM inputs. Returns { rule: null, error: '...' } when the
// form doesn't hold a valid rule, without mutating any state.
function readLifecycleRuleFromForm() {
const id = document.getElementById('lifecycleRuleId').value.trim();
const status = document.querySelector('input[name="lifecycleRuleStatus"]:checked').value;
const prefix = document.getElementById('lifecycleRulePrefix').value.trim();
const tags = {};
document.querySelectorAll('#lifecycleTagRows .lifecycle-tag-row').forEach(row => {
const key = row.querySelector('.lifecycle-tag-key').value.trim();
const value = row.querySelector('.lifecycle-tag-value').value.trim();
if (key) {
tags[key] = value;
}
});
const sizeGT = parseInt(document.getElementById('lifecycleRuleSizeGT').value, 10) || 0;
const sizeLT = parseInt(document.getElementById('lifecycleRuleSizeLT').value, 10) || 0;
const expireDaysEnabled = document.getElementById('lifecycleExpireDaysEnabled').checked;
const expireDateEnabled = document.getElementById('lifecycleExpireDateEnabled').checked;
const expirationDays = expireDaysEnabled ? (parseInt(document.getElementById('lifecycleExpireDays').value, 10) || 0) : 0;
const expirationDate = expireDateEnabled ? document.getElementById('lifecycleExpireDate').value : '';
const deleteMarker = document.getElementById('lifecycleDeleteMarker').checked;
const noncurrentEnabled = document.getElementById('lifecycleNoncurrentEnabled').checked;
const noncurrentDays = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentDays').value, 10) || 0) : 0;
const noncurrentKeep = noncurrentEnabled ? (parseInt(document.getElementById('lifecycleNoncurrentKeep').value, 10) || 0) : 0;
const abortEnabled = document.getElementById('lifecycleAbortMPUEnabled').checked;
const abortDays = abortEnabled ? (parseInt(document.getElementById('lifecycleAbortMPUDays').value, 10) || 0) : 0;
if (expireDaysEnabled && expirationDays <= 0) {
return { rule: null, error: 'Enter a valid number of days for expiration.' };
}
if (expireDateEnabled && !expirationDate) {
return { rule: null, error: 'Enter a valid expiration date.' };
}
if (noncurrentEnabled && noncurrentDays <= 0 && noncurrentKeep <= 0) {
return { rule: null, error: 'Enter a number of days and/or a newest-versions-to-keep count for noncurrent version handling.' };
}
if (abortEnabled && abortDays <= 0) {
return { rule: null, error: 'Enter a valid number of days for aborting incomplete multipart uploads.' };
}
if (!expireDaysEnabled && !expireDateEnabled && !deleteMarker && !noncurrentEnabled && !abortEnabled) {
return { rule: null, error: 'Select at least one action for this rule.' };
}
// The server rejects this combination too; catching it here names the two
// fields instead of surfacing a 400 after the whole set is submitted.
if (deleteMarker && (expireDaysEnabled || expireDateEnabled)) {
return { rule: null, error: 'Removing expired object delete markers cannot be combined with an expiration.' };
}
if (sizeGT > 0 && sizeLT > 0 && sizeGT >= sizeLT) {
return { rule: null, error: '"Size greater than" must be less than "size less than".' };
}
return {
rule: {
id: id,
status: status,
prefix: prefix,
tags: tags,
size_greater_than: sizeGT > 0 ? sizeGT : null,
size_less_than: sizeLT > 0 ? sizeLT : null,
expiration_days: expirationDays > 0 ? expirationDays : null,
expiration_date: expirationDate || '',
expired_object_delete_marker: deleteMarker,
noncurrent_version_expiration_days: noncurrentDays > 0 ? noncurrentDays : null,
newer_noncurrent_versions: noncurrentKeep > 0 ? noncurrentKeep : null,
abort_multipart_days: abortDays > 0 ? abortDays : null,
},
error: null,
};
}
function saveLifecycleRuleFromForm() {
const { rule, error } = readLifecycleRuleFromForm();
if (error) {
alert(error);
const rules = data.rules || [];
if (rules.length === 0) {
document.getElementById('bucketLifecycleContent').innerHTML =
'<div class="text-center text-muted py-4">No lifecycle configuration<\/div>';
return;
}
if (lifecycleEditor.editingIndex === 'new') {
lifecycleEditor.rules.push(rule);
} else {
lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;
}
lifecycleEditor.editingIndex = null;
lifecycleEditor.editingRule = null;
renderLifecycleEditor();
}
// commitOpenLifecycleRuleForm folds an in-progress add/edit form into
// lifecycleEditor.rules before the whole rule set is sent to the server, so
// clicking the modal's "Save" without first clicking "Save rule" doesn't
// silently drop the open edit. Returns false (and leaves the form open) when
// the open form doesn't hold a valid rule, so the caller can abort the save.
function commitOpenLifecycleRuleForm() {
if (lifecycleEditor.editingIndex === null) {
return true;
function describeScope(rule) {
const parts = [];
if (rule.prefix) {
parts.push('<code>' + escapeHtml(rule.prefix) + '<\/code>');
}
Object.entries(rule.tags || {}).forEach(([k, v]) => {
parts.push('<span class="badge bg-light text-dark border">' + escapeHtml(k) + '=' + escapeHtml(v) + '<\/span>');
});
if (rule.size_greater_than) {
parts.push('size &gt; ' + formatBytes(rule.size_greater_than));
}
if (rule.size_less_than) {
parts.push('size &lt; ' + formatBytes(rule.size_less_than));
}
return parts.length ? parts.join(' ') : '<span class="text-muted">Whole bucket<\/span>';
}
const { rule, error } = readLifecycleRuleFromForm();
if (error) {
alert(error);
return false;
function describeActions(rule) {
const actions = [];
if (rule.expiration_days) {
actions.push('Expire after ' + days(rule.expiration_days));
}
if (rule.expiration_date) {
actions.push('Expire on ' + escapeHtml(rule.expiration_date));
}
if (rule.expired_object_delete_marker) {
actions.push('Remove expired object delete markers');
}
if (rule.noncurrent_version_expiration_days) {
let action = 'Expire noncurrent versions after ' + days(rule.noncurrent_version_expiration_days);
if (rule.newer_noncurrent_versions) {
action += ', keep ' + rule.newer_noncurrent_versions + ' newest';
}
actions.push(action);
}
if (rule.abort_multipart_days) {
actions.push('Abort incomplete multipart uploads after ' + days(rule.abort_multipart_days));
}
if (actions.length === 0) {
return '<span class="text-muted">None<\/span>';
}
return actions.join('<br>');
}
if (lifecycleEditor.editingIndex === 'new') {
lifecycleEditor.rules.push(rule);
} else {
lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;
const rows = [
'<div class="table-responsive">',
'<table class="table table-sm">',
'<thead><tr><th>Rule<\/th><th>Status<\/th><th>Scope<\/th><th>Actions<\/th><\/tr><\/thead>',
'<tbody>'
];
rules.forEach(rule => {
const statusHtml = rule.status === 'Enabled'
? '<span class="badge bg-success">Enabled<\/span>'
: '<span class="badge bg-secondary">' + escapeHtml(rule.status) + '<\/span>';
rows.push(
'<tr>' +
'<td>' + (rule.id ? escapeHtml(rule.id) : '<span class="text-muted">unnamed<\/span>') + '<\/td>' +
'<td>' + statusHtml + '<\/td>' +
'<td>' + describeScope(rule) + '<\/td>' +
'<td>' + describeActions(rule) + '<\/td>' +
'<\/tr>'
);
});
rows.push('<\/tbody>', '<\/table>', '<\/div>');
if (data.xml) {
rows.push(
'<details class="mt-2">',
'<summary class="text-muted small">Raw XML<\/summary>',
'<pre class="bg-light border rounded p-2 mt-2 small mb-0">' + escapeHtml(data.xml) + '<\/pre>',
'<\/details>'
);
}
lifecycleEditor.editingIndex = null;
lifecycleEditor.editingRule = null;
renderLifecycleEditor();
return true;
document.getElementById('bucketLifecycleContent').innerHTML = rows.join('');
}
function goToPage(page) {
@@ -1903,6 +1380,14 @@ function commitOpenLifecycleRuleForm() {
return '"' + str + '"';
}
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Fetch all buckets from the API (not just the current page)
fetch(basePath('/api/s3/buckets'))
.then(response => response.json())
+1 -1
View File
@@ -796,7 +796,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
+24 -33
View File
@@ -234,17 +234,15 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
if raftServer == nil {
glog.Fatalf("please verify %s is writable, see https://github.com/seaweedfs/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
}
}
// For single-master mode with a fresh log, initialize cluster immediately.
// When resuming with existing state, the server is already a member and
// will self-elect via fastResume — sending another JoinCommand would block
// because goraft's setCommitIndex returns early on JoinCommand entries,
// preventing the new entry's event from being notified when old uncommitted
// JoinCommands exist in the log.
if isSingleMaster && !raftServer.HasExistingState() {
glog.V(0).Infof("Single-master mode: initializing cluster immediately")
if err := raftServer.Bootstrap(); err != nil {
glog.Errorf("fail to bootstrap the cluster: %v", err)
// For single-master mode with a fresh log, initialize cluster immediately.
// When resuming with existing state, the server is already a member and
// will self-elect via fastResume — sending another JoinCommand would block
// because goraft's setCommitIndex returns early on JoinCommand entries,
// preventing the new entry's event from being notified when old uncommitted
// JoinCommands exist in the log.
if isSingleMaster && !raftServer.HasExistingState() {
glog.V(0).Infof("Single-master mode: initializing cluster immediately")
raftServer.DoJoinCommand()
}
}
ms.SetRaftServer(raftServer)
@@ -274,13 +272,8 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
go grpcS.Serve(grpcL)
pb.ServeGrpcOnLocalSocket(grpcS, grpcPort)
// A master that starts with no raft state cannot elect on its own — neither
// raft implementation lets a server outside the configuration campaign — so
// it has to be pulled in by a leader. Keep asking the peers who the leader is
// until we are in: the leader admits us once our master client registers, and
// only when nobody has one does the first peer mint a new cluster. Restarting
// a master alone, or scaling the peer list up, both land here.
if !isSingleMaster {
// For multi-master mode with non-Hashicorp raft, wait and check if we should join
if !*masterOption.raftHashicorp && !isSingleMaster {
go func() {
// Stagger bootstrap by peer index so masters don't all check
// simultaneously. Peer 0 waits ~1.5s, peer 1 ~3s, etc.
@@ -289,24 +282,22 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
glog.V(0).Infof("bootstrap check in %v (peer index %d of %d)", delay, idx, len(peers))
time.Sleep(delay)
for {
if raftServer.HasExistingState() {
return
}
if leader, err := ms.Topo.MaybeLeader(); err == nil && leader != "" {
return
}
if existingLeader := ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress); existingLeader != "" {
glog.V(0).Infof("waiting to be admitted by existing leader %s", existingLeader)
} else if idx == 0 {
if err := raftServer.Bootstrap(); err != nil {
glog.Errorf("fail to bootstrap the cluster: %v", err)
}
ms.Topo.RaftServerAccessLock.RLock()
isEmptyMaster := ms.Topo.RaftServer.Leader() == "" && ms.Topo.RaftServer.IsLogEmpty()
isFirst := idx == 0
if isEmptyMaster && isFirst {
existingLeader := ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress)
if existingLeader == "" {
raftServer.DoJoinCommand()
} else {
glog.V(0).Infof("skip bootstrap: %v is not the first master in peers (index %d)", myMasterAddress, idx)
glog.V(0).Infof("skip bootstrap: existing leader %s found from peers", existingLeader)
}
time.Sleep(raftJoinCheckDelay)
} else if !isEmptyMaster {
glog.V(0).Infof("skip bootstrap: leader=%q logEmpty=%v", ms.Topo.RaftServer.Leader(), ms.Topo.RaftServer.IsLogEmpty())
} else {
glog.V(0).Infof("skip bootstrap: %v is not the first master in peers (index %d)", myMasterAddress, idx)
}
ms.Topo.RaftServerAccessLock.RUnlock()
}()
}
+37 -133
View File
@@ -394,7 +394,7 @@ var (
miniS3AllowDeleteBucketNotEmpty = cmdMini.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
miniS3AutoCreateBucket = cmdMini.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
miniBucket = cmdMini.Flag.String("bucket", "", "comma-separated S3 bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_BUCKET env var.")
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables buckets to create on startup if they do not already exist, each name[:FORMAT] with FORMAT one of ICEBERG (default) or LANCE, e.g. warehouse,vectors:LANCE; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
)
// getBindIp determines the bind IP address based on miniIp and miniBindIp flags
@@ -1367,20 +1367,14 @@ func runMini(cmd *Command, args []string) bool {
tableBucketSpec := *miniTableBucket
if tableBucketSpec == "" {
tableBucketSpec = os.Getenv("S3_TABLE_BUCKET")
} else if os.Getenv("S3_TABLE_BUCKET") == "" {
// The catalog routes unprefixed requests to the first S3_TABLE_BUCKET
// entry; let the -tableBucket flag mean the same thing.
os.Setenv("S3_TABLE_BUCKET", tableBucketSpec)
}
ready, err := ensureMiniTableBuckets(parseTableBucketList(tableBucketSpec))
if err != nil {
if err := ensureMiniTableBuckets(tableBucketSpec); err != nil {
glog.Warningf("failed to ensure table buckets %q: %v", tableBucketSpec, err)
}
// The Iceberg catalog routes unprefixed requests to the first
// S3_TABLE_BUCKET entry and looks the name up as given, so rewrite the
// variable whichever way the spec arrived: a Lance entry or a :FORMAT
// suffix left in place names a bucket the catalog cannot find.
if names := icebergRoutingNames(ready); len(names) > 0 {
os.Setenv("S3_TABLE_BUCKET", strings.Join(names, ","))
} else {
os.Unsetenv("S3_TABLE_BUCKET")
}
// Print welcome message after all services are running
printWelcomeMessage()
@@ -2018,157 +2012,67 @@ func ensureMiniBuckets(bucketSpec string) error {
})
}
// tableBucketEntry is one -tableBucket entry: a bucket name and the table
// format that bucket will hold.
type tableBucketEntry struct {
name string
format string
}
// ensureMiniTableBuckets creates each named S3 Tables bucket on the embedded
// filer if it does not already exist, and returns the ones that now hold the
// format that was asked for. Per-bucket failures are logged so one bad name
// does not block the rest. Buckets are owned by s3tables.DefaultAccountID
// filer if it does not already exist. bucketSpec is comma-separated; whitespace
// is trimmed and duplicates are dropped. Per-bucket failures are logged so one
// bad name does not block the rest. Buckets are owned by s3tables.DefaultAccountID
// since mini does not yet model multi-account ownership.
func ensureMiniTableBuckets(buckets []tableBucketEntry) ([]tableBucketEntry, error) {
// A bucket holds one format, and the format decides which catalog serves
// it, so one created in a format this mini does not serve is a bucket no
// client can reach.
var servable []tableBucketEntry
for _, bucket := range buckets {
if !miniServesTableFormat(bucket.format) {
// An unsuffixed name means Iceberg, so on a Lance-only mini say how to ask.
hint := ""
if bucket.format == s3tables.FormatIceberg && miniServesTableFormat(s3tables.FormatLance) {
hint = fmt.Sprintf("; name it %s:%s for the Lance namespace", bucket.name, s3tables.FormatLance)
}
glog.Warningf("not creating table bucket %s: no %s endpoint is enabled, so nothing could reach it%s", bucket.name, bucket.format, hint)
continue
}
servable = append(servable, bucket)
func ensureMiniTableBuckets(bucketSpec string) error {
names := parseBucketList(bucketSpec)
if len(names) == 0 {
return nil
}
if len(servable) == 0 {
return nil, nil
// A bucket holds one format, and the format decides which catalog serves it.
// Creating one in a format this mini does not serve leaves a bucket no
// client can reach, so take the format from the endpoint that is running.
format := miniTableBucketFormat()
if format == "" {
glog.Warningf("not creating table buckets %q: neither the Iceberg nor the Lance endpoint is enabled, so nothing could reach them", bucketSpec)
return nil
}
filerAddress := pb.NewServerAddress(*miniIp, *miniFilerOptions.port, *miniFilerOptions.portGrpc)
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
var ready []tableBucketEntry
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
manager := s3tables.NewManager()
mgrClient := s3tables.NewManagerClient(client)
for _, bucket := range servable {
for _, name := range names {
ctx, cancel := context.WithTimeout(miniClientsCtx(), 5*time.Second)
req := &s3tables.CreateTableBucketRequest{Name: bucket.name, Format: bucket.format}
req := &s3tables.CreateTableBucketRequest{Name: name, Format: format}
var resp s3tables.CreateTableBucketResponse
err := manager.Execute(ctx, mgrClient, "CreateTableBucket", req, &resp, s3tables.DefaultAccountID)
cancel()
if err == nil {
glog.V(0).Infof("created %s table bucket %s", bucket.format, bucket.name)
ready = append(ready, bucket)
glog.V(0).Infof("created %s table bucket %s", format, name)
continue
}
var s3Err *s3tables.S3TablesError
if errors.As(err, &s3Err) && s3Err.Type == s3tables.ErrCodeBucketAlreadyExists {
// The name being taken says nothing about what holds it: it
// may be the other format, or an ordinary S3 bucket, which
// answers the same conflict. Only reuse what reads back as
// the format asked for, since the rest fails later at the
// client instead of here.
existing, readErr := existingTableBucketFormat(manager, mgrClient, bucket.name)
switch {
case readErr != nil:
glog.Warningf("%s already exists but does not read back as a table bucket: %v; leaving it alone", bucket.name, readErr)
case existing != "" && existing != bucket.format:
glog.Warningf("table bucket %s already exists holding %s tables, not %s; leaving it alone", bucket.name, existing, bucket.format)
default:
glog.V(0).Infof("table bucket %s already exists", bucket.name)
ready = append(ready, bucket)
}
glog.V(0).Infof("table bucket %s already exists", name)
continue
}
glog.Warningf("create table bucket %s: %v", bucket.name, err)
glog.Warningf("create table bucket %s: %v", name, err)
}
return nil
})
return ready, err
}
// icebergRoutingNames is the bare names of the buckets holding Iceberg tables,
// which are the only ones the Iceberg catalog can take as its default warehouse.
func icebergRoutingNames(buckets []tableBucketEntry) []string {
var names []string
for _, bucket := range buckets {
if bucket.format == s3tables.FormatIceberg {
names = append(names, bucket.name)
}
}
return names
}
// existingTableBucketFormat is the format the named table bucket holds. An empty
// format with no error is a bucket predating declared formats, which accepts
// either; an error means nothing was confirmed, an ordinary S3 bucket wearing
// the name included.
func existingTableBucketFormat(manager *s3tables.Manager, client *s3tables.ManagerClient, name string) (string, error) {
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, name)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(miniClientsCtx(), 5*time.Second)
defer cancel()
var resp s3tables.GetTableBucketResponse
if err := manager.Execute(ctx, client, "GetTableBucket", &s3tables.GetTableBucketRequest{TableBucketARN: arn}, &resp, s3tables.DefaultAccountID); err != nil {
return "", err
}
return resp.Format, nil
}
// miniServesTableFormat reports whether the endpoint that serves format is
// running here: the Iceberg catalog for ICEBERG, the Lance namespace for LANCE.
func miniServesTableFormat(format string) bool {
// miniTableBucketFormat is the format a pre-created table bucket should hold:
// Iceberg when its catalog is running, else Lance, else none because neither
// server is up.
func miniTableBucketFormat() string {
if miniEnableS3 == nil || !*miniEnableS3 {
return false
return ""
}
switch format {
case s3tables.FormatIceberg:
return miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0
case s3tables.FormatLance:
return miniS3Options.portLance != nil && *miniS3Options.portLance > 0
if miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0 {
return s3tables.FormatIceberg
}
return false
}
// parseTableBucketList splits a comma-separated table bucket spec into
// deduplicated name[:FORMAT] entries, in the order given. The format is stated
// rather than read off whichever catalog happens to be listening, so one spec
// means one thing on every mini.
func parseTableBucketList(spec string) []tableBucketEntry {
if spec == "" {
return nil
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
return s3tables.FormatLance
}
seen := make(map[string]bool)
var buckets []tableBucketEntry
for _, raw := range strings.Split(spec, ",") {
name, rawFormat, _ := strings.Cut(raw, ":")
name = strings.TrimSpace(name)
if name == "" || seen[name] {
continue
}
format := s3tables.FormatIceberg
if rawFormat = strings.TrimSpace(rawFormat); rawFormat != "" {
normalized, ok := s3tables.NormalizeFormat(rawFormat)
if !ok {
glog.Warningf("not creating table bucket %s: unsupported format %q", name, rawFormat)
continue
}
format = normalized
}
seen[name] = true
buckets = append(buckets, tableBucketEntry{name: name, format: format})
}
return buckets
return ""
}
// parseBucketList splits a comma-separated bucket spec into a deduplicated list
-93
View File
@@ -3,8 +3,6 @@ package command
import (
"reflect"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
func TestParseBucketList(t *testing.T) {
@@ -30,94 +28,3 @@ func TestParseBucketList(t *testing.T) {
})
}
}
func TestParseTableBucketList(t *testing.T) {
tests := []struct {
name string
in string
want []tableBucketEntry
}{
{"empty", "", nil},
{"defaults to iceberg", "warehouse", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
{"explicit format", "vectors:LANCE", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
{"format is case insensitive", "vectors:lance", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
{"mixed formats", "warehouse,vectors:LANCE", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}}},
{"trims whitespace", " warehouse , vectors : LANCE ", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}}},
{"drops unsupported format", "warehouse,vectors:DELTA", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
{"empty format is the default", "warehouse:", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
{"dedupes by name", "vectors:LANCE,vectors:ICEBERG", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
{"drops empty entries", "one,,two:LANCE,", []tableBucketEntry{{"one", s3tables.FormatIceberg}, {"two", s3tables.FormatLance}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := parseTableBucketList(tt.in)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseTableBucketList(%q) = %v, want %v", tt.in, got, tt.want)
}
})
}
}
// A bucket's format decides which endpoint has to be up for it, so turning one
// catalog off must not change what the other format means.
func TestMiniServesTableFormat(t *testing.T) {
icebergPort, lancePort := *miniS3Options.portIceberg, *miniS3Options.portLance
t.Cleanup(func() {
*miniS3Options.portIceberg, *miniS3Options.portLance = icebergPort, lancePort
})
*miniS3Options.portIceberg, *miniS3Options.portLance = 8181, 9101
if !miniServesTableFormat(s3tables.FormatIceberg) || !miniServesTableFormat(s3tables.FormatLance) {
t.Errorf("both endpoints up: want both formats served")
}
*miniS3Options.portIceberg = 0
if miniServesTableFormat(s3tables.FormatIceberg) {
t.Errorf("iceberg port 0: want ICEBERG unserved")
}
if !miniServesTableFormat(s3tables.FormatLance) {
t.Errorf("iceberg port 0: want LANCE still served")
}
*miniS3Options.portLance = 0
if miniServesTableFormat(s3tables.FormatLance) {
t.Errorf("lance port 0: want LANCE unserved")
}
if miniServesTableFormat("DELTA") {
t.Errorf("unknown format: want unserved")
}
}
// The Iceberg catalog looks its default warehouse up by name, so a Lance entry
// or a leftover :FORMAT suffix in S3_TABLE_BUCKET names a bucket it cannot find.
func TestIcebergRoutingNames(t *testing.T) {
tests := []struct {
name string
in []tableBucketEntry
want []string
}{
{"none", nil, nil},
{"iceberg only", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}, []string{"warehouse"}},
{"lance is not routable", []tableBucketEntry{{"vectors", s3tables.FormatLance}}, nil},
{"lance first", []tableBucketEntry{{"vectors", s3tables.FormatLance}, {"warehouse", s3tables.FormatIceberg}}, []string{"warehouse"}},
{"order preserved", []tableBucketEntry{{"raw", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}, {"curated", s3tables.FormatIceberg}}, []string{"raw", "curated"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := icebergRoutingNames(tt.in)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("icebergRoutingNames(%v) = %v, want %v", tt.in, got, tt.want)
}
})
}
}
// A spec arriving through S3_TABLE_BUCKET carries suffixes too, and the catalog
// reads that same variable, so parsing and routing have to agree on the name.
func TestIcebergRoutingNamesFromEnvSpec(t *testing.T) {
got := icebergRoutingNames(parseTableBucketList("vectors:LANCE,warehouse"))
if want := []string{"warehouse"}; !reflect.DeepEqual(got, want) {
t.Errorf("routing names for env spec = %v, want %v", got, want)
}
}
-171
View File
@@ -3,12 +3,8 @@ package filer
import (
"bytes"
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
@@ -323,173 +319,6 @@ func ClearBucketReadOnly(ctx context.Context, client filer_pb.SeaweedFilerClient
return true, nil
}
// filerConfSnapshot is a read of filer.conf plus enough of the entry (or its
// absence) to make a follow-up write conditional via
// saveFilerConfConditionally, instead of blindly overwriting whatever is
// there by the time the write happens.
type filerConfSnapshot struct {
fc *FilerConf
entry *filer_pb.Entry // nil if filer.conf did not exist at read time
}
func readFilerConfSnapshot(ctx context.Context, client filer_pb.SeaweedFilerClient) (*filerConfSnapshot, error) {
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
Directory: DirectoryEtcSeaweedFS,
Name: FilerConfName,
})
fc := NewFilerConf()
if errors.Is(err, filer_pb.ErrNotFound) {
return &filerConfSnapshot{fc: fc}, nil
}
if err != nil {
return nil, fmt.Errorf("read %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
}
if len(resp.Entry.Content) > 0 {
if err := fc.LoadFromBytes(resp.Entry.Content); err != nil {
return nil, fmt.Errorf("parse %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
}
}
return &filerConfSnapshot{fc: fc, entry: resp.Entry}, nil
}
// saveFilerConfConditionally writes snap.fc back to filer.conf, conditioned
// on nothing having created or modified the file since snap was read. The
// filer evaluates the condition under its per-path lock, so a racing writer
// fails the precondition instead of silently losing its change.
//
// The condition is an exact content check (IF_ETAG_MATCH against the MD5
// every writer stamps, see SaveInsideFiler), which mtime's one-second
// resolution cannot match. A filer.conf written before that stamp existed
// carries no hash, so that one write falls back to IF_UNMODIFIED_SINCE and
// self-heals from the next write on.
func saveFilerConfConditionally(ctx context.Context, client filer_pb.SeaweedFilerClient, snap *filerConfSnapshot) error {
var buf bytes.Buffer
if err := snap.fc.ToText(&buf); err != nil {
return err
}
content := buf.Bytes()
contentMd5 := md5.Sum(content)
if snap.entry == nil {
err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
Directory: DirectoryEtcSeaweedFS,
Entry: &filer_pb.Entry{
Name: FilerConfName,
IsDirectory: false,
Attributes: &filer_pb.FuseAttributes{
Mtime: time.Now().Unix(),
Crtime: time.Now().Unix(),
FileMode: uint32(0644),
FileSize: uint64(len(content)),
Md5: contentMd5[:],
},
Content: content,
},
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS},
}},
})
if err != nil {
return fmt.Errorf("create %s/%s: %w", DirectoryEtcSeaweedFS, FilerConfName, err)
}
return nil
}
entry := snap.entry
var condition *filer_pb.WriteCondition
if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
condition = &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{fmt.Sprintf("%x", entry.Attributes.Md5)}},
}}
} else {
var unmodifiedSince int64
if entry.Attributes != nil {
unmodifiedSince = entry.Attributes.Mtime
} else {
entry.Attributes = &filer_pb.FuseAttributes{}
}
condition = &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: unmodifiedSince},
}}
}
entry.Content = content
entry.Attributes.Mtime = time.Now().Unix()
entry.Attributes.FileSize = uint64(len(content))
entry.Attributes.Md5 = contentMd5[:]
err := filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
Directory: DirectoryEtcSeaweedFS,
Entry: entry,
Condition: condition,
})
if err != nil {
return fmt.Errorf("update %s/%s: %w", DirectoryEtcSeaweedFS, FilerConfName, err)
}
return nil
}
// ClearBucketLifecycleDayTTLs removes any day-TTL filer.conf rules a legacy
// PutBucketLifecycleConfiguration handler installed under the bucket's path.
// Per-write TTL is now driven by the LifecycleTTLResolver built off the
// stored lifecycle XML, so a lingering day-TTL rule would double-stamp
// expiration (volume server expires under the old rule) or contradict a
// newly saved XML. The write is conditioned on filer.conf being unchanged
// since it was read here, so a concurrent writer fails this call rather than
// silently losing one side's change.
func ClearBucketLifecycleDayTTLs(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketsPath, bucketName, collection string) error {
snap, err := readFilerConfSnapshot(ctx, client)
if err != nil {
return err
}
if snap.entry == nil {
return nil
}
changed := false
bucketPrefix := fmt.Sprintf("%s/%s/", bucketsPath, bucketName)
for prefix, ttl := range snap.fc.GetCollectionTtls(collection) {
if !strings.HasPrefix(prefix, bucketPrefix) || !strings.HasSuffix(ttl, "d") {
continue
}
locConf, found := snap.fc.GetLocationConf(prefix)
if !found {
continue
}
// Logged either way: this is a one-way migration, and the prefix and
// TTL are all an operator needs to put a rule back by hand.
if isLifecycleOwnedPathConf(locConf) {
glog.V(0).Infof("lifecycle migration: dropping legacy day-TTL rule %s ttl=%s", prefix, ttl)
snap.fc.DeleteLocationConf(prefix)
} else {
glog.V(0).Infof("lifecycle migration: clearing legacy day-TTL %s on operator rule %s", ttl, prefix)
updated := ClonePathConf(locConf)
updated.Ttl = ""
if err := snap.fc.SetLocationConf(updated); err != nil {
return err
}
}
changed = true
}
if !changed {
return nil
}
return saveFilerConfConditionally(ctx, client, snap)
}
// isLifecycleOwnedPathConf reports whether a rule looks like one the removed
// PutBucketLifecycleConfiguration add path created, which set only the
// routing and TTL fields. That path merged onto whatever already sat at the
// prefix, so anything else here - a disk type, WORM settings, a read-only
// flag, a placement pin - is an operator's, and deleting the whole rule to
// retire its TTL would take their configuration with it.
func isLifecycleOwnedPathConf(c *filer_pb.FilerConf_PathConf) bool {
return c.GetDiskType() == "" && !c.GetFsync() && !c.GetReadOnly() &&
c.GetDataCenter() == "" && c.GetRack() == "" && c.GetDataNode() == "" &&
c.GetMaxFileNameLength() == 0 && !c.GetDisableChunkDeletion() &&
c.Worm == nil && c.GetWormGracePeriodSeconds() == 0 && c.GetWormRetentionTimeSeconds() == 0
}
func (fc *FilerConf) GetCollectionTtls(collection string) (ttls map[string]string) {
ttls = make(map[string]string)
fc.rules.Walk(func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
-341
View File
@@ -2,17 +2,11 @@ package filer
import (
"bytes"
"context"
"errors"
"fmt"
"reflect"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
)
@@ -254,338 +248,3 @@ func TestClearReadOnly(t *testing.T) {
assert.False(t, rule.ReadOnly)
assert.Equal(t, "7d", rule.Ttl)
}
// fakeFilerConfClient is a minimal in-memory filer_pb.SeaweedFilerClient that
// only supports the single-file round trip ReadInsideFiler/SaveInsideFiler
// need: lookup, create-if-absent, update. Embedding the interface satisfies
// the rest of it; calling any other method panics on the nil embedded value.
type fakeFilerConfClient struct {
filer_pb.SeaweedFilerClient
mu sync.Mutex
entries map[string]*filer_pb.Entry // key: dir+"/"+name
}
func newFakeFilerConfClient() *fakeFilerConfClient {
return &fakeFilerConfClient{entries: make(map[string]*filer_pb.Entry)}
}
func (c *fakeFilerConfClient) key(dir, name string) string { return dir + "/" + name }
func (c *fakeFilerConfClient) LookupDirectoryEntry(_ context.Context, in *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.entries[c.key(in.Directory, in.Name)]
if !ok {
return nil, filer_pb.ErrNotFound
}
// A real gRPC round trip always hands back an independent copy (proto
// marshal/unmarshal), so mutating what the caller gets back (as
// saveFilerConfConditionally does before re-sending it) must not affect
// what conditionHoldsLocked below compares against.
return &filer_pb.LookupDirectoryEntryResponse{Entry: cloneFakeEntry(e)}, nil
}
func cloneFakeEntry(e *filer_pb.Entry) *filer_pb.Entry {
if e == nil {
return nil
}
// proto.Clone rather than a struct copy: filer_pb.Entry embeds
// protoimpl.MessageState (a sync.Mutex), which a plain `*e` copy would
// duplicate by value — exactly what go vet's copylocks check flags.
return proto.Clone(e).(*filer_pb.Entry)
}
func (c *fakeFilerConfClient) CreateEntry(_ context.Context, in *filer_pb.CreateEntryRequest, _ ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
key := c.key(in.Directory, in.Entry.Name)
if !conditionHoldsLocked(in.Condition, c.entries[key]) {
return nil, errors.New("precondition failed")
}
c.entries[key] = in.Entry
return &filer_pb.CreateEntryResponse{}, nil
}
func (c *fakeFilerConfClient) UpdateEntry(_ context.Context, in *filer_pb.UpdateEntryRequest, _ ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
key := c.key(in.Directory, in.Entry.Name)
if !conditionHoldsLocked(in.Condition, c.entries[key]) {
return nil, errors.New("precondition failed")
}
c.entries[key] = in.Entry
return &filer_pb.UpdateEntryResponse{}, nil
}
// conditionHoldsLocked is a minimal stand-in for the filer server's
// writeConditionSatisfied (weed/server/filer_grpc_server_condition.go),
// covering just the clause kinds saveFilerConfConditionally uses, so tests
// can exercise the CAS path without a real filer server.
func conditionHoldsLocked(cond *filer_pb.WriteCondition, current *filer_pb.Entry) bool {
if cond == nil {
return true
}
for _, clause := range cond.Clauses {
switch clause.Kind {
case filer_pb.WriteCondition_IF_NOT_EXISTS:
if current != nil {
return false
}
case filer_pb.WriteCondition_IF_UNMODIFIED_SINCE:
if current != nil && current.Attributes != nil && current.Attributes.Mtime > clause.UnixTime {
return false
}
case filer_pb.WriteCondition_IF_ETAG_MATCH:
if current == nil {
return false
}
stored := ""
if current.Attributes != nil {
stored = fmt.Sprintf("%x", current.Attributes.Md5)
}
matched := false
for _, want := range clause.Etags {
if want == stored {
matched = true
break
}
}
if !matched {
return false
}
}
}
return true
}
// putFilerConf seeds the fake client's filer.conf with the given rules.
func putFilerConf(t *testing.T, client *fakeFilerConfClient, rules ...*filer_pb.FilerConf_PathConf) {
t.Helper()
fc := NewFilerConf()
for _, r := range rules {
require.NoError(t, fc.SetLocationConf(r))
}
var buf bytes.Buffer
require.NoError(t, fc.ToText(&buf))
client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)] = &filer_pb.Entry{
Name: FilerConfName,
Content: buf.Bytes(),
Attributes: &filer_pb.FuseAttributes{},
}
}
// readFilerConfText returns the current filer.conf content stored in the fake
// client, or "" if none exists yet.
func readFilerConfText(client *fakeFilerConfClient) string {
e, ok := client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)]
if !ok {
return ""
}
return string(e.Content)
}
func TestClearBucketLifecycleDayTTLs_NoFilerConf(t *testing.T) {
client := newFakeFilerConfClient()
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
assert.Empty(t, readFilerConfText(client))
}
func TestClearBucketLifecycleDayTTLs_NoMatchingRule(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/other/",
Collection: "other",
Ttl: "7d",
})
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
assert.Contains(t, readFilerConfText(client), "other")
}
func TestClearBucketLifecycleDayTTLs_RemovesDayTTLUnderBucket(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/mybucket/",
Collection: "mybucket",
Ttl: "7d",
})
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
reloaded := NewFilerConf()
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
assert.False(t, found, "day-TTL rule should have been removed")
}
func TestClearBucketLifecycleDayTTLs_KeepsNonDayTTL(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/mybucket/",
Collection: "mybucket",
Ttl: "7m", // minutes, not days: not a legacy lifecycle TTL rule
})
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
reloaded := NewFilerConf()
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
assert.True(t, found, "non-day TTL rule should be left alone")
}
func TestClearBucketLifecycleDayTTLs_KeepsOperatorSettingsAndClearsOnlyTheTTL(t *testing.T) {
// The removed add path merged its TTL onto whatever already sat at the
// prefix, so a rule carrying operator settings must survive with only its
// TTL retired - deleting it outright would drop the disk type and the
// read-only flag with it.
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/mybucket/logs/",
Collection: "mybucket",
Ttl: "30d",
DiskType: "hdd",
ReadOnly: true,
})
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
reloaded := NewFilerConf()
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
rule, found := reloaded.GetLocationConf("/buckets/mybucket/logs/")
require.True(t, found, "a rule carrying operator settings must not be deleted")
assert.Equal(t, "", rule.Ttl, "the legacy day TTL should be gone")
assert.Equal(t, "hdd", rule.DiskType, "the operator's disk type must survive")
assert.True(t, rule.ReadOnly, "the operator's read-only flag must survive")
}
func TestClearBucketLifecycleDayTTLs_KeepsWormSettings(t *testing.T) {
worm := true
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/mybucket/locked/",
Collection: "mybucket",
Ttl: "7d",
Worm: &worm,
WormRetentionTimeSeconds: 3600,
})
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
reloaded := NewFilerConf()
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
rule, found := reloaded.GetLocationConf("/buckets/mybucket/locked/")
require.True(t, found, "a WORM rule must not be deleted to retire a TTL")
assert.Equal(t, "", rule.Ttl)
assert.True(t, rule.GetWorm())
assert.Equal(t, uint64(3600), rule.WormRetentionTimeSeconds)
}
func TestClearBucketLifecycleDayTTLs_KeepsOtherBucketsAndCollections(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client,
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/mybucket/", Collection: "mybucket", Ttl: "7d"},
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/other/", Collection: "other", Ttl: "7d"},
// nested under the target bucket's path but tagged to a different
// collection (e.g. a filer-group-prefixed name): must not be swept up
// by this bucket's cleanup, since GetCollectionTtls filters by collection.
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/mybucket/nested/", Collection: "group_mybucket", Ttl: "7d"},
)
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
reloaded := NewFilerConf()
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
assert.False(t, found, "the target bucket's day-TTL rule should be gone")
text := readFilerConfText(client)
assert.Contains(t, text, "other")
assert.Contains(t, text, "group_mybucket")
}
// bumpMtime models a writer that landed after unmodifiedSince, so an
// IF_UNMODIFIED_SINCE precondition built on that timestamp no longer holds.
func bumpMtime(client *fakeFilerConfClient, unmodifiedSince int64) {
client.mu.Lock()
defer client.mu.Unlock()
e := client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)]
if e == nil {
return
}
if e.Attributes == nil {
e.Attributes = &filer_pb.FuseAttributes{}
}
e.Attributes.Mtime = unmodifiedSince + 1
}
func TestSaveFilerConfConditionally_RejectsUpdateModifiedConcurrently(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Collection: "a", Ttl: "7d"})
snap, err := readFilerConfSnapshot(context.Background(), client)
require.NoError(t, err)
require.NotNil(t, snap.entry)
require.Empty(t, snap.entry.Attributes.Md5, "test setup should model a pre-existing filer.conf with no stamped Md5")
// Someone else writes filer.conf after our read but before our write.
bumpMtime(client, snap.entry.Attributes.Mtime)
err = saveFilerConfConditionally(context.Background(), client, snap)
assert.Error(t, err, "expected a concurrent modification to fail the conditional write")
}
// TestSaveFilerConfConditionally_ExactContentCheckRejectsConcurrentModification
// exercises the primary path: once an entry has been written through this
// function (so it carries a content Md5), a later write with a stale
// snapshot is rejected by the exact IF_ETAG_MATCH check even when the
// concurrent writer happened to leave mtime unchanged — something a
// mtime-only precondition would have missed.
func TestSaveFilerConfConditionally_ExactContentCheckRejectsConcurrentModification(t *testing.T) {
client := newFakeFilerConfClient()
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Collection: "a", Ttl: "7d"})
// First write through saveFilerConfConditionally stamps Md5, moving
// subsequent reads onto the exact-content check.
snap, err := readFilerConfSnapshot(context.Background(), client)
require.NoError(t, err)
require.NoError(t, saveFilerConfConditionally(context.Background(), client, snap))
snap2, err := readFilerConfSnapshot(context.Background(), client)
require.NoError(t, err)
require.NotEmpty(t, snap2.entry.Attributes.Md5, "expected Md5 to have been stamped by the prior write")
// A concurrent writer goes through SaveInsideFiler, the path every
// other filer.conf writer uses. It lands in the same wall-clock second,
// so only the content hash can catch it.
concurrentFc := NewFilerConf()
require.NoError(t, concurrentFc.LoadFromBytes([]byte(readFilerConfText(client))))
require.NoError(t, concurrentFc.SetLocationConf(&filer_pb.FilerConf_PathConf{
LocationPrefix: "/buckets/other/", Collection: "other", Ttl: "3d",
}))
var buf bytes.Buffer
require.NoError(t, concurrentFc.ToText(&buf))
require.NoError(t, SaveInsideFiler(context.Background(), client, DirectoryEtcSeaweedFS, FilerConfName, buf.Bytes()))
client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)].Attributes.Mtime = snap2.entry.Attributes.Mtime
err = saveFilerConfConditionally(context.Background(), client, snap2)
assert.Error(t, err, "expected the exact-content check to reject a write whose baseline content hash no longer matches")
assert.Contains(t, readFilerConfText(client), "/buckets/other/", "the concurrent writer's content must survive")
}
func TestSaveFilerConfConditionally_RejectsCreateWhenCreatedConcurrently(t *testing.T) {
client := newFakeFilerConfClient()
snap, err := readFilerConfSnapshot(context.Background(), client)
require.NoError(t, err)
require.Nil(t, snap.entry, "filer.conf should not exist yet")
// Someone else creates filer.conf after our read but before our write.
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/", Collection: "b", Ttl: "3d"})
err = saveFilerConfConditionally(context.Background(), client, snap)
assert.Error(t, err, "expected a concurrent create to fail the conditional write")
assert.Contains(t, readFilerConfText(client), "/buckets/b/", "the concurrent writer's content must survive")
}
+14 -77
View File
@@ -49,19 +49,8 @@ type MetaAggregator struct {
// whose unflushed events still exist, and de-accounting it at once would
// let subscribers advance past them. A re-add clears the mark; a peer
// gone past the grace is dropped so it cannot pin the low-watermarks.
peerRemovedAtNs map[pb.ServerAddress]int64
// lowWatermarkTsNs and lowFlushWatermarkTsNs are the last minima signalled
// on deliveryAdvanced and flushAdvanced, each closed and replaced when its
// own minimum rises. Held readers park on the one that bounds them:
// arriving data cannot release a watermark hold, only a peer reporting
// the progress that hold waits on. The two are kept apart because a
// delivery advance - one per event a peer streams - cannot release a read
// held at the flush watermark, and waking it costs a whole pass.
lowWatermarkTsNs int64
lowFlushWatermarkTsNs int64
deliveryAdvanced chan struct{}
flushAdvanced chan struct{}
peerWatermarksLock sync.Mutex
peerRemovedAtNs map[pb.ServerAddress]int64
peerWatermarksLock sync.Mutex
}
// MetaAggregator only aggregates data "on the fly". The logs are not re-persisted to disk.
@@ -127,7 +116,6 @@ func (ma *MetaAggregator) initPeerWatermark(peer pb.ServerAddress) {
ma.peerFlushWatermarks[peer] = 0
}
delete(ma.peerRemovedAtNs, peer)
ma.noteLowWatermarksLocked()
}
func (ma *MetaAggregator) markPeerWatermarkRemoved(peer pb.ServerAddress) {
@@ -156,8 +144,6 @@ func (ma *MetaAggregator) dropExpiredRemovedPeersLocked() {
delete(ma.peerFlushWatermarks, peer)
}
}
// Dropping the peer that pinned a minimum raises it, same as it reporting.
ma.noteLowWatermarksLocked()
}
// advancePeerWatermark records the peer as received-through tsNs. Monotonic,
@@ -168,7 +154,6 @@ func (ma *MetaAggregator) advancePeerWatermark(peer pb.ServerAddress, tsNs int64
defer ma.peerWatermarksLock.Unlock()
if cur, found := ma.peerWatermarks[peer]; found && tsNs > cur {
ma.peerWatermarks[peer] = tsNs
ma.noteLowWatermarksLocked()
}
}
@@ -179,7 +164,6 @@ func (ma *MetaAggregator) advancePeerFlushWatermark(peer pb.ServerAddress, tsNs
defer ma.peerWatermarksLock.Unlock()
if cur, found := ma.peerFlushWatermarks[peer]; found && tsNs > cur {
ma.peerFlushWatermarks[peer] = tsNs
ma.noteLowWatermarksLocked()
}
}
@@ -190,7 +174,16 @@ func (ma *MetaAggregator) PeerLowFlushWatermarkTsNs() int64 {
ma.peerWatermarksLock.Lock()
defer ma.peerWatermarksLock.Unlock()
ma.dropExpiredRemovedPeersLocked()
return lowWatermarkOf(ma.peerFlushWatermarks)
if len(ma.peerFlushWatermarks) == 0 {
return 0
}
var low int64 = math.MaxInt64
for _, tsNs := range ma.peerFlushWatermarks {
if tsNs < low {
low = tsNs
}
}
return low
}
// PeerLowWatermarkTsNs returns the minimum received-through timestamp across
@@ -201,67 +194,11 @@ func (ma *MetaAggregator) PeerLowWatermarkTsNs() int64 {
ma.peerWatermarksLock.Lock()
defer ma.peerWatermarksLock.Unlock()
ma.dropExpiredRemovedPeersLocked()
return lowWatermarkOf(ma.peerWatermarks)
}
// DeliveryWatermarkAdvancedChan returns a channel closed the next time the
// delivery low-watermark rises, which is what releases an in-memory read held
// at it. PeerLowFlushWatermarkTsNs has FlushWatermarkAdvancedChan. Callers
// must take the channel before reading the watermark they hold at, so a rise
// in between wakes them instead of being missed.
func (ma *MetaAggregator) DeliveryWatermarkAdvancedChan() <-chan struct{} {
ma.peerWatermarksLock.Lock()
defer ma.peerWatermarksLock.Unlock()
if ma.deliveryAdvanced == nil {
ma.deliveryAdvanced = make(chan struct{})
}
return ma.deliveryAdvanced
}
// FlushWatermarkAdvancedChan returns a channel closed the next time the flush
// low-watermark rises, which is what releases a persisted-log read held at it.
func (ma *MetaAggregator) FlushWatermarkAdvancedChan() <-chan struct{} {
ma.peerWatermarksLock.Lock()
defer ma.peerWatermarksLock.Unlock()
if ma.flushAdvanced == nil {
ma.flushAdvanced = make(chan struct{})
}
return ma.flushAdvanced
}
// noteLowWatermarksLocked recomputes both minima and wakes the readers parked
// on each one that rose. Caller must hold peerWatermarksLock.
func (ma *MetaAggregator) noteLowWatermarksLocked() {
low, flushLow := lowWatermarkOf(ma.peerWatermarks), lowWatermarkOf(ma.peerFlushWatermarks)
// Falls are recorded too (a joining peer sits at 0 until it signals), so
// the climb back out of one is seen as a rise.
if low > ma.lowWatermarkTsNs {
ma.deliveryAdvanced = closeWatermarkChan(ma.deliveryAdvanced)
}
if flushLow > ma.lowFlushWatermarkTsNs {
ma.flushAdvanced = closeWatermarkChan(ma.flushAdvanced)
}
ma.lowWatermarkTsNs, ma.lowFlushWatermarkTsNs = low, flushLow
}
// closeWatermarkChan wakes everyone parked on ch and clears it, so the next
// caller parks on a fresh one.
func closeWatermarkChan(ch chan struct{}) chan struct{} {
if ch != nil {
close(ch)
}
return nil
}
// lowWatermarkOf returns the minimum across the tracked peers, or 0 when none
// are tracked: a peer that has not signalled sits at 0 and pins the minimum
// there, which is what makes completeness unknown.
func lowWatermarkOf(watermarks map[pb.ServerAddress]int64) int64 {
if len(watermarks) == 0 {
if len(ma.peerWatermarks) == 0 {
return 0
}
var low int64 = math.MaxInt64
for _, tsNs := range watermarks {
for _, tsNs := range ma.peerWatermarks {
if tsNs < low {
low = tsNs
}
-23
View File
@@ -1,23 +0,0 @@
package filer
import (
"github.com/seaweedfs/seaweedfs/weed/pb"
)
// TrackPeerForTesting registers a peer as if the master had announced it, but
// without starting its subscription goroutine, so loop tests can drive the
// low-watermarks by hand. Test support only.
func (ma *MetaAggregator) TrackPeerForTesting(peer pb.ServerAddress) {
ma.peerChansLock.Lock()
ma.peerChans[peer] = make(chan struct{})
ma.peerChansLock.Unlock()
ma.initPeerWatermark(peer)
}
// ReportPeerWatermarksForTesting stands in for what a peer's stream reports:
// its delivery watermark (events and idle heartbeats) and its flush
// watermark. Test support only.
func (ma *MetaAggregator) ReportPeerWatermarksForTesting(peer pb.ServerAddress, deliveredTsNs, flushedTsNs int64) {
ma.advancePeerWatermark(peer, deliveredTsNs)
ma.advancePeerFlushWatermark(peer, flushedTsNs)
}
@@ -147,67 +147,3 @@ func TestPeerFlushWatermarkBookkeeping(t *testing.T) {
}
_ = a
}
// closed reports whether ch has been signalled, without blocking.
func closed(ch <-chan struct{}) bool {
select {
case <-ch:
return true
default:
return false
}
}
// TestWatermarkAdvancedChansAreScoped pins what each wake channel promises. A
// held read re-runs a whole pass - a persisted-log listing in it - so waking
// one whose bound did not move is pure waste, and peers advance their delivery
// watermark on every event they stream.
func TestWatermarkAdvancedChansAreScoped(t *testing.T) {
ma := newTestAggregator()
a, b := pb.ServerAddress("filer-a:8888"), pb.ServerAddress("filer-b:8888")
ma.initPeerWatermark(a)
ma.initPeerWatermark(b)
delivery, flush := ma.DeliveryWatermarkAdvancedChan(), ma.FlushWatermarkAdvancedChan()
// One peer alone does not move either minimum: the other still pins both.
ma.advancePeerWatermark(a, 100)
ma.advancePeerFlushWatermark(a, 100)
if closed(delivery) || closed(flush) {
t.Fatalf("a single peer moved a minimum: delivery=%v flush=%v", closed(delivery), closed(flush))
}
// Delivery progress on every peer wakes the in-memory holds only.
ma.advancePeerWatermark(b, 50)
if !closed(delivery) {
t.Fatal("delivery low-watermark rose without waking the in-memory holds")
}
if closed(flush) {
t.Fatal("delivery progress woke the persisted-log holds, which it cannot release")
}
// And flush progress the persisted-log holds only.
delivery = ma.DeliveryWatermarkAdvancedChan()
ma.advancePeerFlushWatermark(b, 50)
if !closed(flush) {
t.Fatal("flush low-watermark rose without waking the persisted-log holds")
}
if closed(delivery) {
t.Fatal("flush progress woke the in-memory holds, which it cannot release")
}
// A fresh channel is handed out after each signal, so the next park is on
// the next rise rather than on one already consumed.
flush = ma.FlushWatermarkAdvancedChan()
if closed(flush) {
t.Fatal("re-handed a signalled channel")
}
ma.advancePeerFlushWatermark(a, 200)
if closed(flush) {
t.Fatal("one peer above the minimum signalled a rise")
}
ma.advancePeerFlushWatermark(b, 200)
if !closed(flush) {
t.Fatal("the trailing peer catching up did not signal a rise")
}
}
-10
View File
@@ -3,7 +3,6 @@ package filer
import (
"bytes"
"context"
"crypto/md5"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -42,11 +41,6 @@ func ReadInsideFiler(ctx context.Context, filerClient filer_pb.SeaweedFilerClien
return
}
// SaveInsideFiler writes content into the entry's inline Content. The content
// MD5 is stamped on every write so the entry's ETag always describes what is
// actually stored: conditional writers key IF_ETAG_MATCH off it, and a hash
// left behind by an earlier write would make that condition pass against
// content that has since changed.
func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, name string, content []byte) error {
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
@@ -54,8 +48,6 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
Name: name,
})
contentMd5 := md5.Sum(content)
if err == filer_pb.ErrNotFound {
err = filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
Directory: dir,
@@ -67,7 +59,6 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
Crtime: time.Now().Unix(),
FileMode: uint32(0644),
FileSize: uint64(len(content)),
Md5: contentMd5[:],
},
Content: content,
},
@@ -78,7 +69,6 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
entry.Content = content
entry.Attributes.Mtime = time.Now().Unix()
entry.Attributes.FileSize = uint64(len(content))
entry.Attributes.Md5 = contentMd5[:]
err = filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
Directory: dir,
Entry: entry,
-9
View File
@@ -288,15 +288,6 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
}
if err != nil {
// a failed chunk leaves its window untouched while the tasks after it
// may well have filled theirs, so only the prefix up to the hole is
// data the caller may use
for _, task := range tasks {
if int64(task.bytesRead) != task.bufferEnd-task.bufferStart {
n = int(task.bufferStart) + task.bytesRead
break
}
}
return n, ts, err
}
}
-55
View File
@@ -3,14 +3,10 @@ package filer
import (
"bytes"
"context"
"errors"
"io"
"math"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type mockChunkCache struct {
@@ -206,54 +202,3 @@ func TestReaderAtSparseFileDoesNotLeak(t *testing.T) {
testReadAt(t, readerAt, 0, 3, 3, io.EOF, []byte{2, 2, 2}, []byte{0, 0, 0})
testReadAt(t, readerAt, 1, 2, 2, io.EOF, []byte{2, 2}, []byte{0, 0})
}
// holeChunkCache serves every chunk but one, so that chunk falls through to a
// lookup that fails.
type holeChunkCache struct {
mockChunkCache
missingFileId string
}
func (c *holeChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (int, error) {
if fileId == c.missingFileId {
return 0, nil
}
return c.mockChunkCache.ReadChunkAt(data, fileId, offset)
}
func (c *holeChunkCache) GetMaxFilePartSizeInCache() uint64 {
return math.MaxUint64
}
// The parallel reads place their bytes directly in the output buffer, so a
// failing middle chunk leaves a hole with valid data after it. Reporting that
// length would hand the caller bytes it never read.
func TestReaderAtParallelFailureReturnsContiguousPrefix(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
for i, fileId := range []string{"1", "2", "3"} {
addVisibleInterval(visibles, &VisibleInterval{
start: int64(i) * 4,
stop: int64(i)*4 + 4,
fileId: fileId,
chunkSize: 4,
})
}
readerAt := &ChunkReadAt{
ctx: context.Background(),
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 12,
readerCache: NewReaderCache(3, &holeChunkCache{missingFileId: "2"}, func(ctx context.Context, fileId string) ([]string, error) {
return nil, errors.New("volume down")
}, nil),
readerPattern: NewReaderPattern(),
prefetchCount: 3,
}
buf := make([]byte, 12)
n, err := readerAt.ReadAt(buf, 0)
require.Error(t, err)
assert.Equal(t, 4, n, "only the bytes before the failed chunk are readable")
assert.Equal(t, []byte{1, 1, 1, 1}, buf[:n])
}
-55
View File
@@ -9,7 +9,6 @@ import (
"net/http"
"net/url"
"os"
"regexp"
"slices"
"strings"
"sync"
@@ -662,10 +661,6 @@ func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []b
s3ApiConfiguration.Groups = nil
}
if fromStaticFile {
expandCredentialEnvRefs(s3ApiConfiguration)
}
if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
return nil, err
}
@@ -676,56 +671,6 @@ func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []b
return s3ApiConfiguration, nil
}
var credentialEnvRef = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}`)
// expandCredentialEnvRefs resolves ${VAR} references in the keys of a static
// config file, so a deployment can keep the keys in its own secret store and
// hand them to the process as environment variables. A credential still holding
// an unresolved reference is dropped instead of becoming a literal key.
//
// A variable that is set but empty counts as unresolved: a secret store handing
// over a blank value must not leave an access key signed by an empty secret.
func expandCredentialEnvRefs(config *iam_pb.S3ApiConfiguration) {
for _, ident := range config.Identities {
kept := ident.Credentials[:0]
for _, cred := range ident.Credentials {
accessKey, accessResolved := expandEnvRefs(cred.AccessKey)
secretKey, secretResolved := expandEnvRefs(cred.SecretKey)
if !accessResolved || !secretResolved {
glog.Warningf("identity %s: dropping credential %s, it references an unset environment variable", ident.Name, cred.AccessKey)
continue
}
cred.AccessKey, cred.SecretKey = accessKey, secretKey
kept = append(kept, cred)
}
ident.Credentials = kept
}
}
// expandEnvRefs reports false when any reference is malformed or names a
// variable that is unset or empty, leaving the reference in place for the
// caller to reject.
func expandEnvRefs(value string) (string, bool) {
if !strings.Contains(value, "${") {
return value, true
}
// Every ${ has to open a well-formed reference. A typo like ${MY-VAR} matches
// nothing, so it would otherwise survive substitution as a literal key.
if strings.Count(value, "${") != len(credentialEnvRef.FindAllString(value, -1)) {
return value, false
}
resolved := true
expanded := credentialEnvRef.ReplaceAllStringFunc(value, func(ref string) string {
env, found := os.LookupEnv(ref[2 : len(ref)-1])
if !found || env == "" {
resolved = false
return ref
}
return env
})
return expanded, resolved
}
func (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {
return iam.loadS3ApiConfigurationWithSource(config, false)
}
@@ -343,145 +343,3 @@ func writeTempIamConfig(t *testing.T, content string) string {
}
return path
}
// A static config file may hold ${VAR} in place of a key, so a deployment can
// keep the keys in its own secret store and pass them in as environment
// variables rather than baking them into the file.
func TestStaticConfigExpandsEnvCredentialRefs(t *testing.T) {
t.Setenv("SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID", "AKIAFROMENV")
t.Setenv("SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY", "secretfromenv")
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}","secretKey":"${SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
_, cred, found := s3a.iam.lookupByAccessKey("AKIAFROMENV")
if !found {
t.Fatalf("expected the access key from the environment to be loaded")
}
if cred.SecretKey != "secretfromenv" {
t.Fatalf("expected the secret key from the environment, got %q", cred.SecretKey)
}
if _, _, found := s3a.iam.lookupByAccessKey("${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}"); found {
t.Fatalf("the unexpanded reference must not remain usable as an access key")
}
}
// An unset variable must not leave the reference behind as a literal key.
func TestStaticConfigDropsUnresolvedEnvCredentialRefs(t *testing.T) {
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"${SEAWEEDFS_S3_MISSING_ACCESS_KEY_ID}","secretKey":"${SEAWEEDFS_S3_MISSING_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
if _, _, found := s3a.iam.lookupByAccessKey("${SEAWEEDFS_S3_MISSING_ACCESS_KEY_ID}"); found {
t.Fatalf("a credential referencing an unset variable must be dropped")
}
if !hasIdentity(s3a.iam, "anvAdmin") {
t.Fatalf("expected the identity itself to still load")
}
}
// Keys that merely contain a dollar sign are literal, and identities coming
// from the filer are never expanded.
func TestEnvCredentialRefsOnlyApplyToStaticConfig(t *testing.T) {
t.Setenv("SEAWEEDFS_S3_DYNAMIC_SECRET_ACCESS_KEY", "secretfromenv")
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
if err := s3a.iam.LoadS3ApiConfigurationFromBytes([]byte(`{"identities":[{"name":"dynamic","credentials":[{"accessKey":"AKIALITERAL","secretKey":"${SEAWEEDFS_S3_DYNAMIC_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`)); err != nil {
t.Fatalf("failed to load dynamic config: %v", err)
}
_, cred, found := s3a.iam.lookupByAccessKey("AKIALITERAL")
if !found {
t.Fatalf("expected the dynamic identity to load")
}
if cred.SecretKey != "${SEAWEEDFS_S3_DYNAMIC_SECRET_ACCESS_KEY}" {
t.Fatalf("a dynamic identity must keep its secret key verbatim, got %q", cred.SecretKey)
}
}
// A key holding a dollar sign that is not a reference stays untouched.
func TestStaticConfigKeepsLiteralDollarSigns(t *testing.T) {
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"AKIALITERAL","secretKey":"pa$$word"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
_, cred, found := s3a.iam.lookupByAccessKey("AKIALITERAL")
if !found {
t.Fatalf("expected the identity to load")
}
if cred.SecretKey != "pa$$word" {
t.Fatalf("expected the literal secret key, got %q", cred.SecretKey)
}
}
// A secret store handing over a blank value must not leave an access key that
// any signature matches.
func TestStaticConfigDropsEmptyEnvCredentialRefs(t *testing.T) {
t.Setenv("SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID", "AKIAFROMENV")
t.Setenv("SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY", "")
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}","secretKey":"${SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
if _, _, found := s3a.iam.lookupByAccessKey("AKIAFROMENV"); found {
t.Fatalf("a credential whose secret key resolves to empty must be dropped")
}
}
// A reference the substitution cannot match, such as a typo in the variable
// name, must not survive as a literal key.
func TestStaticConfigDropsMalformedEnvCredentialRefs(t *testing.T) {
for _, malformed := range []string{"${MY-VAR}", "${1VAR}", "${}", "${UNTERMINATED", "${A}${B"} {
t.Run(malformed, func(t *testing.T) {
t.Setenv("SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY", "secretfromenv")
t.Setenv("A", "a")
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, fmt.Sprintf(`{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":%q,"secretKey":"${SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`, malformed))
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
if _, _, found := s3a.iam.lookupByAccessKey(malformed); found {
t.Fatalf("%s must not become a usable access key", malformed)
}
})
}
}
// A resolved value that happens to contain ${ is still the key the operator set.
func TestStaticConfigKeepsBracesComingFromTheEnvironment(t *testing.T) {
t.Setenv("SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID", "AKIAFROMENV")
t.Setenv("SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY", "pa${ss}word")
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"anvAdmin","credentials":[{"accessKey":"${SEAWEEDFS_S3_ADMIN_ACCESS_KEY_ID}","secretKey":"${SEAWEEDFS_S3_ADMIN_SECRET_ACCESS_KEY}"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
_, cred, found := s3a.iam.lookupByAccessKey("AKIAFROMENV")
if !found {
t.Fatalf("expected the identity to load")
}
if cred.SecretKey != "pa${ss}word" {
t.Fatalf("expected the secret key from the environment verbatim, got %q", cred.SecretKey)
}
}
-141
View File
@@ -3,7 +3,6 @@ package lifecycle_xml
import (
"bytes"
"encoding/xml"
"sort"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
@@ -82,146 +81,6 @@ func ruleToCanonical(r *Rule) *s3lifecycle.Rule {
return out
}
// CanonicalToLifecycle is the inverse of LifecycleToCanonical: it builds a
// marshalable Lifecycle from the engine's flat Rule shape. Only the fields
// s3lifecycle.Rule can represent are populated — there is no way back to
// Transition / NoncurrentVersionTransition, which the canonical form never
// carries.
func CanonicalToLifecycle(rules []*s3lifecycle.Rule) *Lifecycle {
lc := &Lifecycle{
Rules: make([]Rule, 0, len(rules)),
}
for _, r := range rules {
lc.Rules = append(lc.Rules, ruleFromCanonical(r))
}
return lc
}
// s3XMLNamespace is the namespace every S3 client stamps on a lifecycle
// document it PUTs. GetBucketLifecycleConfiguration replays the stored bytes
// verbatim, so a document written here has to carry it too or it would come
// back stripped of a namespace the client-written ones have.
const s3XMLNamespace = "http://s3.amazonaws.com/doc/2006-03-01/"
// MarshalCanonical serializes the canonical rules straight to a
// BucketLifecycleConfiguration XML document, mirroring ParseCanonical.
func MarshalCanonical(rules []*s3lifecycle.Rule) ([]byte, error) {
lc := CanonicalToLifecycle(rules)
out, err := xml.Marshal(struct {
Lifecycle
XMLNS string `xml:"xmlns,attr"`
}{Lifecycle: *lc, XMLNS: s3XMLNamespace})
if err != nil {
return nil, err
}
return append([]byte(xml.Header), out...), nil
}
func ruleFromCanonical(r *s3lifecycle.Rule) Rule {
out := Rule{
ID: r.ID,
Status: RuleStatus(r.Status),
Filter: filterFromCanonical(r.Prefix, r.FilterTags, r.FilterSizeGreaterThan, r.FilterSizeLessThan),
}
if r.ExpirationDays > 0 || !r.ExpirationDate.IsZero() || r.ExpiredObjectDeleteMarker {
out.Expiration = Expiration{
set: true,
Days: r.ExpirationDays,
}
if !r.ExpirationDate.IsZero() {
out.Expiration.Date = ExpirationDate{Time: r.ExpirationDate}
}
if r.ExpiredObjectDeleteMarker {
out.Expiration.DeleteMarker = ExpireDeleteMarker{val: true, set: true}
}
}
if r.NoncurrentVersionExpirationDays > 0 || r.NewerNoncurrentVersions > 0 {
out.NoncurrentVersionExpiration = NoncurrentVersionExpiration{
set: true,
NoncurrentDays: r.NoncurrentVersionExpirationDays,
NewerNoncurrentVersions: r.NewerNoncurrentVersions,
}
}
if r.AbortMPUDaysAfterInitiation > 0 {
out.AbortIncompleteMultipartUpload = AbortIncompleteMultipartUpload{
set: true,
DaysAfterInitiation: r.AbortMPUDaysAfterInitiation,
}
}
return out
}
// filterFromCanonical is the inverse of flattenFilter: it picks the
// narrowest Filter shape that represents the given prefix/tags/size bounds,
// matching what Filter.MarshalXML (single Prefix|Tag branch plus optional
// size bounds) and its And branch can each express.
func filterFromCanonical(prefix string, tags map[string]string, sizeGT, sizeLT int64) Filter {
hasSize := sizeGT > 0 || sizeLT > 0
// <Filter> holds exactly one predicate; anything more goes under <And>,
// two size bounds included, which is the form AWS documents for a range.
discriminants := 0
if prefix != "" {
discriminants++
}
discriminants += len(tags)
if sizeGT > 0 {
discriminants++
}
if sizeLT > 0 {
discriminants++
}
f := Filter{set: true, ObjectSizeGreaterThan: sizeGT, ObjectSizeLessThan: sizeLT}
switch {
case discriminants > 1:
f.andSet = true
f.And = And{
ObjectSizeGreaterThan: sizeGT,
ObjectSizeLessThan: sizeLT,
}
if prefix != "" {
f.And.Prefix = NewPrefix(prefix)
}
if len(tags) > 0 {
keys := make([]string, 0, len(tags))
for k := range tags {
keys = append(keys, k)
}
sort.Strings(keys)
f.And.Tags = make([]Tag, 0, len(keys))
for _, k := range keys {
f.And.Tags = append(f.And.Tags, Tag{Key: k, Value: tags[k]})
}
}
// The And branch carries its own size bounds; the enclosing
// Filter only emits them on the non-And path (see
// Filter.MarshalXML), so clear them here to avoid duplication.
f.ObjectSizeGreaterThan = 0
f.ObjectSizeLessThan = 0
case len(tags) == 1:
f.tagSet = true
for k, v := range tags {
f.Tag = Tag{Key: k, Value: v}
}
case hasSize:
// Single discriminant and it's a size range: the bounds set above
// already cover it — no <Prefix> (not even an empty one; nothing
// was requested) and no <And> (nothing else to combine with).
default:
// Either a single prefix or no discriminant at all (whole-bucket
// filter) — both are expressed as a <Prefix> element, empty or not.
f.Prefix = NewPrefix(prefix)
}
return f
}
func flattenFilter(f *Filter) (prefix string, tags map[string]string, sizeGT, sizeLT int64) {
if !f.set {
return
-323
View File
@@ -4,9 +4,6 @@ import (
"encoding/xml"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
)
func TestLifecycleXMLRoundTrip_NoncurrentVersionExpiration(t *testing.T) {
@@ -277,323 +274,3 @@ func TestLifecycleXMLRoundTrip_CompleteRule(t *testing.T) {
}
}
}
// assertCanonicalRoundTrip drives a canonical rule through
// CanonicalToLifecycle -> MarshalCanonical -> ParseCanonical and checks the
// result matches the input, proving the admin write path (which only ever
// has the canonical form) produces XML the S3 API can read back unchanged.
func assertCanonicalRoundTrip(t *testing.T, in *s3lifecycle.Rule) *s3lifecycle.Rule {
t.Helper()
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
out, err := ParseCanonical(xmlBytes)
if err != nil {
t.Fatalf("ParseCanonical(%s): %v", xmlBytes, err)
}
if len(out) != 1 {
t.Fatalf("expected 1 rule after round trip, got %d: %s", len(out), xmlBytes)
}
return out[0]
}
func TestCanonicalRoundTrip_WholeBucket(t *testing.T) {
in := &s3lifecycle.Rule{ID: "whole-bucket", Status: s3lifecycle.StatusEnabled, ExpirationDays: 30}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "" {
t.Errorf("expected empty prefix, got %q", out.Prefix)
}
if out.ExpirationDays != 30 {
t.Errorf("expected ExpirationDays=30, got %d", out.ExpirationDays)
}
}
func TestCanonicalRoundTrip_PrefixOnly(t *testing.T) {
in := &s3lifecycle.Rule{ID: "prefix-only", Status: s3lifecycle.StatusEnabled, Prefix: "logs/", ExpirationDays: 7}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "logs/" {
t.Errorf("expected prefix 'logs/', got %q", out.Prefix)
}
if len(out.FilterTags) != 0 {
t.Errorf("expected no tags, got %v", out.FilterTags)
}
}
func TestCanonicalRoundTrip_TagOnly(t *testing.T) {
in := &s3lifecycle.Rule{
ID: "tag-only",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{"env": "dev"},
ExpirationDays: 7,
}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "" {
t.Errorf("expected empty prefix, got %q", out.Prefix)
}
if len(out.FilterTags) != 1 || out.FilterTags["env"] != "dev" {
t.Errorf("expected tags {env:dev}, got %v", out.FilterTags)
}
}
func TestCanonicalRoundTrip_PrefixAndTags(t *testing.T) {
in := &s3lifecycle.Rule{
ID: "prefix-and-tags",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
FilterTags: map[string]string{"env": "dev", "tier": "hot"},
ExpirationDays: 7,
}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "logs/" {
t.Errorf("expected prefix 'logs/', got %q", out.Prefix)
}
if len(out.FilterTags) != 2 || out.FilterTags["env"] != "dev" || out.FilterTags["tier"] != "hot" {
t.Errorf("expected tags {env:dev, tier:hot}, got %v", out.FilterTags)
}
}
func TestCanonicalRoundTrip_SizeBounds(t *testing.T) {
in := &s3lifecycle.Rule{
ID: "size-bounds",
Status: s3lifecycle.StatusEnabled,
FilterSizeGreaterThan: 512,
FilterSizeLessThan: 1048576,
ExpirationDays: 30,
}
out := assertCanonicalRoundTrip(t, in)
if out.FilterSizeGreaterThan != 512 {
t.Errorf("expected FilterSizeGreaterThan=512, got %d", out.FilterSizeGreaterThan)
}
if out.FilterSizeLessThan != 1048576 {
t.Errorf("expected FilterSizeLessThan=1048576, got %d", out.FilterSizeLessThan)
}
}
func TestCanonicalRoundTrip_PrefixAndTagsWithSizeBounds(t *testing.T) {
// Multiple discriminants (prefix + tags) force the <And> branch, which
// carries its own size bounds distinct from the single-branch Filter.
in := &s3lifecycle.Rule{
ID: "and-with-size",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
FilterTags: map[string]string{"env": "dev"},
FilterSizeGreaterThan: 1024,
FilterSizeLessThan: 2048,
ExpirationDays: 7,
}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "logs/" || len(out.FilterTags) != 1 {
t.Errorf("expected prefix 'logs/' and 1 tag, got prefix=%q tags=%v", out.Prefix, out.FilterTags)
}
if out.FilterSizeGreaterThan != 1024 || out.FilterSizeLessThan != 2048 {
t.Errorf("expected size bounds 1024/2048, got %d/%d", out.FilterSizeGreaterThan, out.FilterSizeLessThan)
}
}
func TestCanonicalRoundTrip_ExpirationDate(t *testing.T) {
date := time.Date(2030, 1, 15, 0, 0, 0, 0, time.UTC)
in := &s3lifecycle.Rule{ID: "expire-on-date", Status: s3lifecycle.StatusEnabled, ExpirationDate: date}
out := assertCanonicalRoundTrip(t, in)
if !out.ExpirationDate.Equal(date) {
t.Errorf("expected ExpirationDate=%v, got %v", date, out.ExpirationDate)
}
}
func TestCanonicalRoundTrip_ExpiredObjectDeleteMarker(t *testing.T) {
in := &s3lifecycle.Rule{ID: "delete-marker", Status: s3lifecycle.StatusEnabled, ExpiredObjectDeleteMarker: true}
out := assertCanonicalRoundTrip(t, in)
if !out.ExpiredObjectDeleteMarker {
t.Error("expected ExpiredObjectDeleteMarker=true")
}
}
func TestCanonicalRoundTrip_NoncurrentVersionExpiration(t *testing.T) {
in := &s3lifecycle.Rule{
ID: "noncurrent",
Status: s3lifecycle.StatusEnabled,
NoncurrentVersionExpirationDays: 30,
NewerNoncurrentVersions: 2,
}
out := assertCanonicalRoundTrip(t, in)
if out.NoncurrentVersionExpirationDays != 30 {
t.Errorf("expected NoncurrentVersionExpirationDays=30, got %d", out.NoncurrentVersionExpirationDays)
}
if out.NewerNoncurrentVersions != 2 {
t.Errorf("expected NewerNoncurrentVersions=2, got %d", out.NewerNoncurrentVersions)
}
}
func TestCanonicalRoundTrip_AbortMultipartUpload(t *testing.T) {
in := &s3lifecycle.Rule{ID: "abort-mpu", Status: s3lifecycle.StatusEnabled, AbortMPUDaysAfterInitiation: 7}
out := assertCanonicalRoundTrip(t, in)
if out.AbortMPUDaysAfterInitiation != 7 {
t.Errorf("expected AbortMPUDaysAfterInitiation=7, got %d", out.AbortMPUDaysAfterInitiation)
}
}
func TestCanonicalRoundTrip_Disabled(t *testing.T) {
in := &s3lifecycle.Rule{ID: "disabled-rule", Status: s3lifecycle.StatusDisabled, ExpirationDays: 30}
out := assertCanonicalRoundTrip(t, in)
if out.Status != s3lifecycle.StatusDisabled {
t.Errorf("expected Status=Disabled, got %q", out.Status)
}
}
func TestCanonicalRoundTrip_TagOrderIsStable(t *testing.T) {
// FilterTags is a map; And.Tags must be emitted in a deterministic
// (sorted) order so re-saving an unchanged rule doesn't churn the
// stored XML.
in := &s3lifecycle.Rule{
ID: "stable-order",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
FilterTags: map[string]string{"zeta": "1", "alpha": "2", "mu": "3"},
}
var firstXML []byte
for i := 0; i < 5; i++ {
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if i == 0 {
firstXML = xmlBytes
continue
}
if string(xmlBytes) != string(firstXML) {
t.Fatalf("marshal output is not stable across runs:\n%s\nvs\n%s", firstXML, xmlBytes)
}
}
if !strings.Contains(string(firstXML), "<Tag><Key>alpha</Key>") {
t.Errorf("expected tags sorted alphabetically (alpha first), got: %s", firstXML)
}
}
func TestCanonicalRoundTrip_PrefixWithSizeBoundsUsesAnd(t *testing.T) {
// A size range paired with a prefix is two different attributes, which
// requires <And> — unlike a size range alone (see
// TestCanonicalRoundTrip_SizeBounds), which doesn't need one.
in := &s3lifecycle.Rule{
ID: "prefix-with-size",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
FilterSizeGreaterThan: 1024,
ExpirationDays: 7,
}
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if !strings.Contains(string(xmlBytes), "<And>") {
t.Errorf("expected prefix+size to be wrapped in <And>, got: %s", xmlBytes)
}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "logs/" {
t.Errorf("expected prefix 'logs/', got %q", out.Prefix)
}
if out.FilterSizeGreaterThan != 1024 {
t.Errorf("expected FilterSizeGreaterThan=1024, got %d", out.FilterSizeGreaterThan)
}
}
func TestCanonicalRoundTrip_TagWithSizeBoundsUsesAnd(t *testing.T) {
in := &s3lifecycle.Rule{
ID: "tag-with-size",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{"env": "dev"},
FilterSizeLessThan: 2048,
ExpirationDays: 7,
}
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if !strings.Contains(string(xmlBytes), "<And>") {
t.Errorf("expected tag+size to be wrapped in <And>, got: %s", xmlBytes)
}
out := assertCanonicalRoundTrip(t, in)
if len(out.FilterTags) != 1 || out.FilterTags["env"] != "dev" {
t.Errorf("expected tags {env:dev}, got %v", out.FilterTags)
}
if out.FilterSizeLessThan != 2048 {
t.Errorf("expected FilterSizeLessThan=2048, got %d", out.FilterSizeLessThan)
}
}
func TestCanonicalRoundTrip_SizeOnlyOmitsPrefixElement(t *testing.T) {
// A size-only filter must not stamp a spurious empty <Prefix> — nothing
// was requested, so nothing besides the size bounds should appear.
in := &s3lifecycle.Rule{
ID: "size-only-no-prefix",
Status: s3lifecycle.StatusEnabled,
FilterSizeGreaterThan: 512,
ExpirationDays: 7,
}
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if strings.Contains(string(xmlBytes), "<Prefix>") {
t.Errorf("expected no <Prefix> element for a size-only filter, got: %s", xmlBytes)
}
out := assertCanonicalRoundTrip(t, in)
if out.Prefix != "" {
t.Errorf("expected empty prefix, got %q", out.Prefix)
}
if out.FilterSizeGreaterThan != 512 {
t.Errorf("expected FilterSizeGreaterThan=512, got %d", out.FilterSizeGreaterThan)
}
}
func TestCanonicalRoundTrip_SizeRangeUsesAnd(t *testing.T) {
// <Filter> holds one predicate; a range is two, so it belongs under <And>,
// which is the form AWS documents.
in := &s3lifecycle.Rule{
ID: "size-range",
Status: s3lifecycle.StatusEnabled,
FilterSizeGreaterThan: 512,
FilterSizeLessThan: 1048576,
ExpirationDays: 30,
}
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{in})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if !strings.Contains(string(xmlBytes), "<And><ObjectSizeGreaterThan>512</ObjectSizeGreaterThan><ObjectSizeLessThan>1048576</ObjectSizeLessThan></And>") {
t.Errorf("expected both size bounds under <And>, got: %s", xmlBytes)
}
out := assertCanonicalRoundTrip(t, in)
if out.FilterSizeGreaterThan != 512 || out.FilterSizeLessThan != 1048576 {
t.Errorf("expected the size range to survive the round trip, got %+v", out)
}
}
func TestMarshalCanonical_CarriesTheS3Namespace(t *testing.T) {
// GetBucketLifecycleConfiguration replays these bytes verbatim, so a
// document written here has to look like one a client PUT.
xmlBytes, err := MarshalCanonical([]*s3lifecycle.Rule{{
ID: "ns",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 1,
}})
if err != nil {
t.Fatalf("MarshalCanonical: %v", err)
}
if !strings.Contains(string(xmlBytes), `<LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`) {
t.Errorf("expected the S3 namespace on the root element, got: %s", xmlBytes)
}
if _, err := ParseCanonical(xmlBytes); err != nil {
t.Errorf("the namespaced document must still parse: %v", err)
}
}
-5
View File
@@ -3,9 +3,4 @@ package s3_constants
const (
// DefaultBucketsPath is the default path for S3 buckets in the filer
DefaultBucketsPath = "/buckets"
// ObjectWriteRouteKeyPrefix namespaces a full path into the ring key used to
// resolve and forward writes to it. Every writer of an object or bucket
// entry hashes this same key, so they serialize on one filer's path lock.
ObjectWriteRouteKeyPrefix = "s3.object.write:"
)
+56 -9
View File
@@ -1132,13 +1132,37 @@ func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWr
// (volume server expires under the old rule) or contradict the new
// XML after a rule change. The add path is gone — this loop only
// shrinks the conf, never grows it.
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.ClearBucketLifecycleDayTTLs(context.Background(), client, s3a.option.BucketsPath, bucket, s3a.getCollectionName(bucket))
}); err != nil {
glog.Errorf("PutBucketLifecycleConfigurationHandler clear legacy day-TTLs: %s", err)
fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil)
if err != nil {
glog.Errorf("PutBucketLifecycleConfigurationHandler read filer config: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
collectionTtls := fc.GetCollectionTtls(s3a.getCollectionName(bucket))
changed := false
bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
for prefix, ttl := range collectionTtls {
if !strings.HasPrefix(prefix, bucketPrefix) || !strings.HasSuffix(ttl, "d") {
continue
}
fc.DeleteLocationConf(prefix)
changed = true
}
if changed {
var buf bytes.Buffer
if err := fc.ToText(&buf); err != nil {
glog.Errorf("PutBucketLifecycleConfigurationHandler save config to text: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(context.Background(), client, filer.DirectoryEtcSeaweedFS, filer.FilerConfName, buf.Bytes())
}); err != nil {
glog.Errorf("PutBucketLifecycleConfigurationHandler save config inside filer: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
}
if errCode := s3a.storeBucketLifecycleConfiguration(bucket, lifecycleXML, r.Header.Get(bucketLifecycleTransitionMinimumObjectSizeHeader)); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
@@ -1160,14 +1184,37 @@ func (s3a *S3ApiServer) DeleteBucketLifecycleHandler(w http.ResponseWriter, r *h
return
}
// Same legacy day-TTL migration as the PUT handler.
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.ClearBucketLifecycleDayTTLs(context.Background(), client, s3a.option.BucketsPath, bucket, s3a.getCollectionName(bucket))
}); err != nil {
glog.Errorf("DeleteBucketLifecycleHandler clear legacy day-TTLs: %s", err)
fc, err := filer.ReadFilerConfFromFilers(s3a.option.Filers, s3a.option.GrpcDialOption, nil)
if err != nil {
glog.Errorf("DeleteBucketLifecycleHandler read filer config: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
collectionTtls := fc.GetCollectionTtls(s3a.getCollectionName(bucket))
changed := false
bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
for prefix, ttl := range collectionTtls {
if !strings.HasPrefix(prefix, bucketPrefix) || !strings.HasSuffix(ttl, "d") {
continue
}
fc.DeleteLocationConf(prefix)
changed = true
}
if changed {
var buf bytes.Buffer
if err := fc.ToText(&buf); err != nil {
glog.Errorf("DeleteBucketLifecycleHandler save config to text: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
}
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(context.Background(), client, filer.DirectoryEtcSeaweedFS, filer.FilerConfName, buf.Bytes())
}); err != nil {
glog.Errorf("DeleteBucketLifecycleHandler save config inside filer: %s", err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
}
if errCode := s3a.clearStoredBucketLifecycleConfiguration(bucket); errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
+3 -7
View File
@@ -4,18 +4,14 @@ import (
"strings"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
)
const (
// The stored form is defined in the scheduler package, which callers
// outside the gateway also read; these are local shorthands for it.
bucketLifecycleConfigurationXMLKey = scheduler.BucketLifecycleConfigurationXMLKey
bucketLifecycleTransitionMinimumObjectSizeKey = scheduler.BucketLifecycleTransitionMinimumObjectSizeKey
maxBucketLifecycleConfigurationSize = scheduler.MaxBucketLifecycleConfigurationSize
bucketLifecycleConfigurationXMLKey = "s3-bucket-lifecycle-configuration-xml"
bucketLifecycleTransitionMinimumObjectSizeKey = "s3-bucket-lifecycle-transition-default-minimum-object-size"
bucketLifecycleTransitionMinimumObjectSizeHeader = "X-Amz-Transition-Default-Minimum-Object-Size"
defaultLifecycleTransitionMinimumObjectSize = "all_storage_classes_128K"
maxBucketLifecycleConfigurationSize = 1 << 20
)
func normalizeBucketLifecycleTransitionMinimumObjectSize(value string) string {
@@ -1,318 +0,0 @@
package s3api
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// stubReaderAt stands in for ChunkReadAt in probe unit tests.
type stubReaderAt struct {
n int
err error
}
func (s stubReaderAt) ReadAtWithTime(ctx context.Context, p []byte, offset int64) (int, int64, error) {
return s.n, 0, s.err
}
// blockingReaderAt never returns until the context is cancelled.
type blockingReaderAt struct{}
func (blockingReaderAt) ReadAtWithTime(ctx context.Context, p []byte, offset int64) (int, int64, error) {
<-ctx.Done()
return 0, 0, ctx.Err()
}
func TestProbeReadable(t *testing.T) {
t.Run("readable local copy", func(t *testing.T) {
assert.NoError(t, probeReadable(context.Background(), stubReaderAt{n: 1}, 0, time.Second))
})
t.Run("final byte with trailing EOF counts as readable", func(t *testing.T) {
assert.NoError(t, probeReadable(context.Background(), stubReaderAt{n: 1, err: io.EOF}, 0, time.Second))
})
t.Run("zero-byte EOF is unreadable", func(t *testing.T) {
assert.Error(t, probeReadable(context.Background(), stubReaderAt{n: 0, err: io.EOF}, 0, time.Second))
})
t.Run("zero-byte read without error is unreadable", func(t *testing.T) {
assert.ErrorIs(t, probeReadable(context.Background(), stubReaderAt{n: 0, err: nil}, 0, time.Second), io.ErrUnexpectedEOF)
})
t.Run("read error surfaces", func(t *testing.T) {
boom := errors.New("volume: connection refused")
assert.ErrorIs(t, probeReadable(context.Background(), stubReaderAt{err: boom}, 0, time.Second), boom)
})
t.Run("stuck volume trips the timeout instead of blocking", func(t *testing.T) {
start := time.Now()
err := probeReadable(context.Background(), blockingReaderAt{}, 0, 50*time.Millisecond)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.Less(t, time.Since(start), time.Second, "must not block past the probe timeout")
})
}
func TestShouldFallBackToRemote(t *testing.T) {
const size = int64(100)
remoteEntry := func() *filer_pb.Entry {
return &filer_pb.Entry{
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(size)},
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: size},
}
}
server := func() *S3ApiServer {
return &S3ApiServer{option: &S3ApiServerOption{}}
}
t.Run("matching remote", func(t *testing.T) {
assert.True(t, server().shouldFallBackToRemote(remoteEntry(), size, ""))
})
t.Run("null versionId is treated as unversioned", func(t *testing.T) {
assert.True(t, server().shouldFallBackToRemote(remoteEntry(), size, "null"))
})
t.Run("versioned read cannot use the unversioned remote key", func(t *testing.T) {
assert.False(t, server().shouldFallBackToRemote(remoteEntry(), size, "v123"))
})
t.Run("latest read that resolves to a version cannot use the unversioned key", func(t *testing.T) {
versioned := remoteEntry()
versioned.Extended = map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v9")}
assert.False(t, server().shouldFallBackToRemote(versioned, size, ""))
})
t.Run("no remote entry", func(t *testing.T) {
local := &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{FileSize: uint64(size)}}
assert.False(t, server().shouldFallBackToRemote(local, size, ""))
})
t.Run("size mismatch is not served as identical bytes", func(t *testing.T) {
assert.False(t, server().shouldFallBackToRemote(remoteEntry(), size+1, ""))
})
}
// The fake filer does not implement LookupVolume, so every chunk read through
// this ReaderCache fails, standing in for an unreachable volume server.
func newLocalReadFallbackServer(t *testing.T, filerAddr pb.ServerAddress) *S3ApiServer {
t.Helper()
s3a := newRemoteCacheTestServer(filerAddr)
fc := wdclient.NewFilerClient(s3a.option.Filers, s3a.option.GrpcDialOption, s3a.option.DataCenter)
s3a.filerClient = fc
s3a.readerCache = filer.NewReaderCache(8, (*chunk_cache.TieredChunkCache)(nil), fc.GetLookupFileIdFunction(), fc)
return s3a
}
// a remote-mounted object whose cached copy is in the metadata but unreadable
func cachedEntry(content []byte) *filer_pb.Entry {
return &filer_pb.Entry{
Name: "obj.bin",
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))},
Chunks: []*filer_pb.FileChunk{{FileId: "1,0123456789ab", Size: uint64(len(content)), Offset: 0}},
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: int64(len(content))},
}
}
func TestS3CachedReadFallsBackToRemote(t *testing.T) {
content := []byte("0123456789")
t.Run("unreadable local copy is served from the mounted remote", func(t *testing.T) {
client := &fakeStreamRemoteClient{data: content}
remote_storage.RemoteStorageClientMakers["faketest"] = &fakeStreamRemoteMaker{client: client}
s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-cachedfail", nil))
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
err := s3a.streamFromVolumeServers(w, r, cachedEntry(content), "", "mybucket", "dir/obj.bin", "")
require.NoError(t, err)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, content, w.Body.Bytes())
require.NotNil(t, client.gotLoc, "must read from the mounted remote")
assert.Equal(t, "/data/dir/obj.bin", client.gotLoc.Path)
})
t.Run("range fallback serves the requested window from the remote", func(t *testing.T) {
client := &fakeStreamRemoteClient{data: content}
remote_storage.RemoteStorageClientMakers["faketest"] = &fakeStreamRemoteMaker{client: client}
s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-cachedrange", nil))
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
r.Header.Set("Range", "bytes=2-5")
err := s3a.streamFromVolumeServers(w, r, cachedEntry(content), "", "mybucket", "dir/obj.bin", "")
require.NoError(t, err)
assert.Equal(t, http.StatusPartialContent, w.Code)
assert.Equal(t, content[2:6], w.Body.Bytes())
assert.Equal(t, int64(2), client.gotOffset)
assert.Equal(t, int64(4), client.gotSize)
})
t.Run("a local-only object keeps the existing error", func(t *testing.T) {
client := &fakeStreamRemoteClient{data: content}
remote_storage.RemoteStorageClientMakers["faketest"] = &fakeStreamRemoteMaker{client: client}
s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-nofallback", nil))
local := cachedEntry(content)
local.RemoteEntry = nil
w := httptest.NewRecorder()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil).WithContext(ctx)
err := s3a.streamFromVolumeServers(w, r, local, "", "mybucket", "dir/obj.bin", "")
require.Error(t, err)
assert.Nil(t, client.gotLoc, "an object that is not remote-mounted has no remote to fall back to")
})
t.Run("versioned read does not fall back to the unversioned remote key", func(t *testing.T) {
client := &fakeStreamRemoteClient{data: content}
remote_storage.RemoteStorageClientMakers["faketest"] = &fakeStreamRemoteMaker{client: client}
s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-cachedversioned", nil))
versioned := cachedEntry(content)
versioned.Extended = map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v456")}
w := httptest.NewRecorder()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin?versionId=v456", nil).WithContext(ctx)
err := s3a.streamFromVolumeServers(w, r, versioned, "", "mybucket", "dir/obj.bin", "v456")
require.Error(t, err)
assert.Nil(t, client.gotLoc, "a versioned read must not serve the unversioned remote object")
})
}
// a multi-chunk object whose later chunk's volume server is unreachable
type truncatedReaderAt struct {
data []byte
breakAt int64
err error
}
func (t truncatedReaderAt) ReadAt(p []byte, offset int64) (int, error) {
if offset >= t.breakAt {
return 0, t.err
}
return copy(p, t.data[offset:t.breakAt]), nil
}
// a client that disconnected mid-response
type failingWriter struct{ err error }
func (f failingWriter) Write(p []byte) (int, error) { return 0, f.err }
// the window the probe cannot cover: the byte at offset reads fine, the response
// is committed, and only then does a later chunk turn out to be unreadable
func TestStreamRangeToClientFinishesFromRemote(t *testing.T) {
content := []byte("0123456789")
size := int64(len(content))
newServer := func(t *testing.T, name string) (*S3ApiServer, *fakeStreamRemoteClient) {
client := &fakeStreamRemoteClient{data: content}
remote_storage.RemoteStorageClientMakers["faketest"] = &fakeStreamRemoteMaker{client: client}
return newLocalReadFallbackServer(t, startStreamThroughFiler(t, name, nil)), client
}
t.Run("later chunk failure is finished from the remote", func(t *testing.T) {
s3a, client := newServer(t, "faketest-midstream")
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
local := truncatedReaderAt{data: content, breakAt: 4, err: errors.New("volume: connection refused")}
written, err := s3a.streamRangeToClient(w, r, local, cachedEntry(content), "mybucket", "dir/obj.bin", 0, size, size, "")
require.NoError(t, err)
assert.Equal(t, size, written)
assert.Equal(t, content, w.Body.Bytes())
assert.Equal(t, int64(4), client.gotOffset, "the remote must resume where the local copy stopped")
assert.Equal(t, int64(6), client.gotSize)
})
t.Run("a short local read reported as clean EOF is not served truncated", func(t *testing.T) {
s3a, client := newServer(t, "faketest-shortread")
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
local := truncatedReaderAt{data: content, breakAt: 7, err: io.EOF}
written, err := s3a.streamRangeToClient(w, r, local, cachedEntry(content), "mybucket", "dir/obj.bin", 0, size, size, "")
require.NoError(t, err)
assert.Equal(t, size, written)
assert.Equal(t, content, w.Body.Bytes())
assert.Equal(t, int64(7), client.gotOffset)
})
t.Run("range read resumes at the absolute offset", func(t *testing.T) {
s3a, client := newServer(t, "faketest-midstreamrange")
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
local := truncatedReaderAt{data: content, breakAt: 5, err: errors.New("volume: connection refused")}
written, err := s3a.streamRangeToClient(w, r, local, cachedEntry(content), "mybucket", "dir/obj.bin", 2, 6, size, "")
require.NoError(t, err)
assert.Equal(t, int64(6), written)
assert.Equal(t, content[2:8], w.Body.Bytes())
assert.Equal(t, int64(5), client.gotOffset)
assert.Equal(t, int64(3), client.gotSize)
})
t.Run("a remote overwritten since caching is not spliced onto the local prefix", func(t *testing.T) {
s3a, client := newServer(t, "faketest-midstreamchanged")
client.stat = &filer_pb.RemoteEntry{RemoteSize: size, RemoteETag: "reuploaded"}
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
boom := errors.New("volume: connection refused")
written, err := s3a.streamRangeToClient(w, r, truncatedReaderAt{data: content, breakAt: 4, err: boom}, cachedEntry(content), "mybucket", "dir/obj.bin", 0, size, size, "")
require.Error(t, err)
assert.Equal(t, int64(4), written, "a truncated body beats one mixing two generations")
assert.Nil(t, client.gotLoc, "must not read a remote that no longer matches what was cached")
})
t.Run("a local-only object keeps the mid-stream error", func(t *testing.T) {
s3a, client := newServer(t, "faketest-midstreamlocal")
local := cachedEntry(content)
local.RemoteEntry = nil
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
boom := errors.New("volume: connection refused")
written, err := s3a.streamRangeToClient(w, r, truncatedReaderAt{data: content, breakAt: 4, err: boom}, local, "mybucket", "dir/obj.bin", 0, size, size, "")
assert.ErrorIs(t, err, boom)
assert.Equal(t, int64(4), written)
assert.Nil(t, client.gotLoc, "an object that is not remote-mounted has no remote to fall back to")
})
t.Run("a failed write to the client is not refetched from the remote", func(t *testing.T) {
s3a, client := newServer(t, "faketest-midstreamwrite")
r := httptest.NewRequest(http.MethodGet, "/mybucket/dir/obj.bin", nil)
broken := errors.New("write: broken pipe")
written, err := s3a.streamRangeToClient(failingWriter{err: broken}, r, bytes.NewReader(content), cachedEntry(content), "mybucket", "dir/obj.bin", 0, size, size, "")
assert.ErrorIs(t, err, broken)
assert.Zero(t, written)
assert.Nil(t, client.gotLoc, "the client is gone; refetching from the remote is wasted work")
})
}
+51 -182
View File
@@ -43,17 +43,13 @@ var zeroBuf = make([]byte, 32*1024)
// countingWriter wraps an io.Writer to count bytes written
type countingWriter struct {
w io.Writer
written int64
writeErr error
w io.Writer
written int64
}
func (cw *countingWriter) Write(p []byte) (int, error) {
n, err := cw.w.Write(p)
cw.written += int64(n)
if err != nil {
cw.writeErr = err
}
return n, err
}
@@ -1041,11 +1037,33 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
// latest-version read -- has no origin key, so it keeps the error
// paths below.
if cacheVersionId == "" || cacheVersionId == "null" {
if served, streamErr := s3a.serveObjectFromRemoteMount(w, r, entry, bucket, object, offset, size, isRangeRequest, totalSize, t0); served {
if streamErr != nil {
return newStreamErrorWithResponse(streamErr)
if remoteReader, remoteErr := s3a.openRemoteStream(r.Context(), bucket, object, offset, size); remoteErr == nil {
defer remoteReader.Close()
s3a.setResponseHeaders(w, r, entry, totalSize)
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
if isRangeRequest {
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, totalSize))
w.WriteHeader(http.StatusPartialContent)
} else {
w.WriteHeader(http.StatusOK)
}
TimeToFirstByte(r.Method, t0, r)
cw := &countingWriter{w: w}
_, copyErr := io.CopyN(cw, remoteReader, size)
if copyErr == io.EOF {
// the origin returned fewer bytes than the entry's RemoteSize
copyErr = io.ErrUnexpectedEOF
}
if cw.written > 0 {
BucketTrafficSent(cw.written, r)
}
if copyErr != nil {
glog.V(2).Infof("streamFromVolumeServers: origin stream %s/%s ended after %d bytes: %v", bucket, object, cw.written, copyErr)
return newStreamErrorWithResponse(copyErr)
}
return nil
} else {
glog.Warningf("streamFromVolumeServers: origin stream %s/%s: %v", bucket, object, remoteErr)
}
}
// Origin unreadable. A permanent cache error is final; a transient one
@@ -1101,15 +1119,6 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
} else {
glog.Errorf("streamFromVolumeServers: failed to resolve chunks: %v", err)
}
if s3a.shouldFallBackToRemote(entry, totalSize, versionId) {
glog.V(1).Infof("streamFromVolumeServers: resolving chunks for %s/%s failed, falling back to remote mount", bucket, object)
if served, streamErr := s3a.serveObjectFromRemoteMount(w, r, entry, bucket, object, offset, size, isRangeRequest, totalSize, t0); served {
if streamErr != nil {
return newStreamErrorWithResponse(streamErr)
}
return nil
}
}
// Write S3-compliant XML error response
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return newStreamErrorWithResponse(fmt.Errorf("failed to resolve chunks: %v", err))
@@ -1133,28 +1142,6 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
reader := filer.NewChunkReaderAtFromClient(ctx, s3a.readerCache, chunkViews, totalSize, filer.DefaultPrefetchCount)
streamPrepTime = time.Since(tStreamPrep)
// A cached chunk whose volume server is down, or whose needle was evicted and
// now 404s under retry-backoff, would stall and then 500 after the headers are
// already sent -- serve the authoritative remote instead.
if s3a.shouldFallBackToRemote(entry, totalSize, versionId) {
if probeErr := probeReadable(ctx, reader, offset, localReadProbeTimeout); probeErr != nil {
if isCanceledStreamingError(probeErr) {
glog.V(3).Infof("streamFromVolumeServers: request canceled while probing %s/%s: %v", bucket, object, probeErr)
return probeErr
}
glog.V(1).Infof("streamFromVolumeServers: local read of %s/%s failed (%v), falling back to remote mount", bucket, object, probeErr)
if served, streamErr := s3a.serveObjectFromRemoteMount(w, r, entry, bucket, object, offset, size, isRangeRequest, totalSize, t0); served {
if streamErr != nil {
return newStreamErrorWithResponse(streamErr)
}
return nil
}
glog.Errorf("streamFromVolumeServers: local read of %s/%s failed and remote mount unavailable: %v", bucket, object, probeErr)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return newStreamErrorWithResponse(probeErr)
}
}
// All validation and preparation successful - NOW set headers and write status
tHeaderSet := time.Now()
s3a.setResponseHeaders(w, r, entry, totalSize)
@@ -1183,145 +1170,38 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
// io.CopyBuffer drains them as fast memcpys.
tStreamExec := time.Now()
glog.V(4).Infof("streamFromVolumeServers: starting chunk reader, offset=%d, size=%d", offset, size)
written, err := s3a.streamRangeToClient(w, r, reader, entry, bucket, object, offset, size, totalSize, versionId)
streamExecTime = time.Since(tStreamExec)
// Track traffic even on partial writes for accurate egress accounting
if written > 0 {
BucketTrafficSent(written, r)
}
if err != nil {
switch {
case isCanceledStreamingError(err):
// Client disconnected mid-stream (e.g. Nginx upstream timeout, browser cancel) - expected
glog.V(3).Infof("streamFromVolumeServers: client disconnected after writing %d bytes: %v", written, err)
case errors.Is(err, context.DeadlineExceeded):
// Server-side deadline exceeded - unexpected, warrants operator attention
glog.Warningf("streamFromVolumeServers: server-side deadline exceeded after writing %d bytes: %v", written, err)
default:
glog.Errorf("streamFromVolumeServers: streamFn failed after writing %d bytes: %v", written, err)
}
// Streaming error after WriteHeader was called - response already partially written
return newStreamErrorWithResponse(err)
}
glog.V(4).Infof("streamFromVolumeServers: streamFn completed successfully, wrote %d bytes", written)
return nil
}
// short, so a down volume server or an evicted needle under retry-backoff falls
// back promptly instead of stalling the request
const localReadProbeTimeout = 2 * time.Second
// shouldFallBackToRemote reports whether a failed local read may be served from
// the mounted remote instead: openRemoteStream only reads the unversioned key,
// and the sizes must match for the bytes to be identical under the
// already-computed Content-Length.
func (s3a *S3ApiServer) shouldFallBackToRemote(entry *filer_pb.Entry, totalSize int64, versionId string) bool {
if v := resolvedSourceVersionId(versionId, entry); v != "" && v != "null" {
return false
}
remote := entry.GetRemoteEntry()
return totalSize > 0 && remote != nil && remote.GetRemoteSize() == totalSize
}
// the context-honoring read of filer.ChunkReadAt, so probeReadable can bound it
type ctxReaderAt interface {
ReadAtWithTime(ctx context.Context, p []byte, offset int64) (int, int64, error)
}
// probeReadable decides whether the local copy is usable by reading one byte at
// offset. Only a returned byte counts -- a zero-byte read, EOF or not, would
// otherwise wave through a stream that then truncates.
func probeReadable(ctx context.Context, reader ctxReaderAt, offset int64, timeout time.Duration) error {
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var b [1]byte
n, _, err := reader.ReadAtWithTime(probeCtx, b[:], offset)
if n == len(b) {
return nil
}
if err == nil {
err = io.ErrUnexpectedEOF
}
return err
}
// serveObjectFromRemoteMount serves [offset, offset+size) straight from the
// mounted remote. served=false means nothing was written and the caller still
// owns the error path; once served is true the response is committed.
func (s3a *S3ApiServer) serveObjectFromRemoteMount(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, bucket, object string, offset, size int64, isRangeRequest bool, totalSize int64, t0 time.Time) (served bool, err error) {
remoteReader, remoteErr := s3a.openRemoteStream(r.Context(), bucket, object, offset, size, nil)
if remoteErr != nil {
glog.Warningf("streamFromVolumeServers: origin stream %s/%s: %v", bucket, object, remoteErr)
return false, nil
}
defer remoteReader.Close()
s3a.setResponseHeaders(w, r, entry, totalSize)
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
if isRangeRequest {
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, totalSize))
w.WriteHeader(http.StatusPartialContent)
} else {
w.WriteHeader(http.StatusOK)
}
TimeToFirstByte(r.Method, t0, r)
cw := &countingWriter{w: w}
_, copyErr := io.CopyN(cw, remoteReader, size)
if copyErr == io.EOF {
// the origin returned fewer bytes than the entry's RemoteSize
copyErr = io.ErrUnexpectedEOF
}
if cw.written > 0 {
BucketTrafficSent(cw.written, r)
}
if copyErr != nil {
glog.V(2).Infof("streamFromVolumeServers: origin stream %s/%s ended after %d bytes: %v", bucket, object, cw.written, copyErr)
return true, copyErr
}
return true, nil
}
// streamRangeToClient copies the local copy into the already-committed response.
// The probe only proved the byte at offset readable, so a later chunk can still
// be gone: finish such a body from the remote -- if it is still the generation
// that was cached -- instead of truncating it under the Content-Length already
// sent.
func (s3a *S3ApiServer) streamRangeToClient(w io.Writer, r *http.Request, reader io.ReaderAt, entry *filer_pb.Entry, bucket, object string, offset, size, totalSize int64, versionId string) (int64, error) {
// small-object GETs shouldn't allocate a 256 KiB scratch buffer per request
// Cap the copy buffer to the response size so small-object GETs (common
// for thumbnails, config files, etc.) don't allocate a 256 KiB scratch
// buffer per request.
const maxCopyBuf = 256 * 1024
copyBufSize := int64(maxCopyBuf)
if size > 0 && size < copyBufSize {
copyBufSize = size
}
cw := &countingWriter{w: w}
_, err := io.CopyBuffer(cw, io.NewSectionReader(reader, offset, size), make([]byte, copyBufSize))
if err == nil && cw.written < size {
// a short local read surfaces as a clean EOF
err = io.ErrUnexpectedEOF
copyBuf := make([]byte, copyBufSize)
_, err = io.CopyBuffer(cw, io.NewSectionReader(reader, offset, size), copyBuf)
streamExecTime = time.Since(tStreamExec)
// Track traffic even on partial writes for accurate egress accounting
if cw.written > 0 {
BucketTrafficSent(cw.written, r)
}
if err == nil || cw.writeErr != nil || isCanceledStreamingError(err) || !s3a.shouldFallBackToRemote(entry, totalSize, versionId) {
return cw.written, err
}
remaining := size - cw.written
glog.V(1).Infof("streamFromVolumeServers: local read of %s/%s failed after %d bytes (%v), finishing from the remote mount", bucket, object, cw.written, err)
// the bytes already sent are the cached generation, so splice on the remote
// only while it still is that generation
remoteReader, remoteErr := s3a.openRemoteStream(r.Context(), bucket, object, offset+cw.written, remaining, entry.GetRemoteEntry())
if remoteErr != nil {
glog.Warningf("streamFromVolumeServers: origin stream %s/%s: %v", bucket, object, remoteErr)
return cw.written, err
}
defer remoteReader.Close()
if _, copyErr := io.CopyN(cw, remoteReader, remaining); copyErr != nil {
if copyErr == io.EOF {
copyErr = io.ErrUnexpectedEOF
if err != nil {
switch {
case isCanceledStreamingError(err):
// Client disconnected mid-stream (e.g. Nginx upstream timeout, browser cancel) - expected
glog.V(3).Infof("streamFromVolumeServers: client disconnected after writing %d bytes: %v", cw.written, err)
case errors.Is(err, context.DeadlineExceeded):
// Server-side deadline exceeded - unexpected, warrants operator attention
glog.Warningf("streamFromVolumeServers: server-side deadline exceeded after writing %d bytes: %v", cw.written, err)
default:
glog.Errorf("streamFromVolumeServers: streamFn failed after writing %d bytes: %v", cw.written, err)
}
glog.V(2).Infof("streamFromVolumeServers: origin stream %s/%s ended after %d bytes: %v", bucket, object, cw.written, copyErr)
return cw.written, copyErr
// Streaming error after WriteHeader was called - response already partially written
return newStreamErrorWithResponse(err)
}
return cw.written, nil
glog.V(4).Infof("streamFromVolumeServers: streamFn completed successfully, wrote %d bytes", cw.written)
return nil
}
// Shared HTTP client for volume server requests (connection pooling)
@@ -3259,9 +3139,7 @@ func (s3a *S3ApiServer) buildRemoteObjectPath(bucket, object string) (dir, name
// openRemoteStream opens a ranged read of a remote-only object straight from
// its mounted origin, resolving the mount and storage conf from the filer.
// cached, when set, is the remote generation the local copy was made from: the
// stream is refused unless the remote still matches it.
func (s3a *S3ApiServer) openRemoteStream(ctx context.Context, bucket, object string, offset, size int64, cached *filer_pb.RemoteEntry) (io.ReadCloser, error) {
func (s3a *S3ApiServer) openRemoteStream(ctx context.Context, bucket, object string, offset, size int64) (io.ReadCloser, error) {
dir, name := s3a.buildRemoteObjectPath(bucket, object)
var storageConf *remote_pb.RemoteConf
@@ -3302,15 +3180,6 @@ func (s3a *S3ApiServer) openRemoteStream(ctx context.Context, bucket, object str
}
loc := filer.MapFullPathToRemoteStorageLocation(util.FullPath(localMountedDir), mountedLocation, util.FullPath(dir).Child(name))
if cached != nil {
current, statErr := client.StatFile(loc)
if statErr != nil {
return nil, statErr
}
if current.GetRemoteSize() != cached.GetRemoteSize() || current.GetRemoteETag() != cached.GetRemoteETag() || current.GetRemoteMtime() != cached.GetRemoteMtime() {
return nil, fmt.Errorf("remote %s/%s changed since it was cached", bucket, object)
}
}
return streamer.ReadFileAsStream(ctx, loc, offset, size)
}
+2 -2
View File
@@ -17,8 +17,8 @@ import (
// objectWriteRouteKeyPrefix namespaces an object's full path into the ring key
// used to resolve and forward its writes. Shared by every routed builder so the
// gateway, the admin dashboard and the filer hash the same key.
const objectWriteRouteKeyPrefix = s3_constants.ObjectWriteRouteKeyPrefix
// gateway and filer hash the same key.
const objectWriteRouteKeyPrefix = "s3.object.write:"
// objectRouteKey is the ring key the gateway hashes to resolve an object's owner
// filer. It is also sent as route_key on each routed transaction, so a non-owner
-8
View File
@@ -609,19 +609,11 @@ func TestCacheRemoteObjectForStreamingCached(t *testing.T) {
type fakeStreamRemoteClient struct {
remote_storage.RemoteStorageClient
data []byte
stat *filer_pb.RemoteEntry // what the remote reports now; defaults to matching data
gotLoc *remote_pb.RemoteStorageLocation
gotOffset int64
gotSize int64
}
func (c *fakeStreamRemoteClient) StatFile(loc *remote_pb.RemoteStorageLocation) (*filer_pb.RemoteEntry, error) {
if c.stat != nil {
return c.stat, nil
}
return &filer_pb.RemoteEntry{RemoteSize: int64(len(c.data))}, nil
}
func (c *fakeStreamRemoteClient) ReadFileAsStream(ctx context.Context, loc *remote_pb.RemoteStorageLocation, offset int64, size int64) (io.ReadCloser, error) {
c.gotLoc, c.gotOffset, c.gotSize = loc, offset, size
end := min(offset+size, int64(len(c.data)))
+1 -12
View File
@@ -11,18 +11,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
)
// The bucket lifecycle configuration lives here rather than in weed/s3api so
// callers outside the gateway (the admin dashboard, the scheduler itself) and
// the gateway share one definition of the extended-attribute keys and the
// size cap. weed/s3api aliases these; nothing redeclares the values.
const (
BucketLifecycleConfigurationXMLKey = "s3-bucket-lifecycle-configuration-xml"
BucketLifecycleTransitionMinimumObjectSizeKey = "s3-bucket-lifecycle-transition-default-minimum-object-size"
// MaxBucketLifecycleConfigurationSize caps the serialized XML, mirroring
// the S3 API's limit.
MaxBucketLifecycleConfigurationSize = 1 << 20
)
const BucketLifecycleConfigurationXMLKey = "s3-bucket-lifecycle-configuration-xml"
// ParseError is returned alongside successfully-loaded inputs so callers can
// surface malformed bucket configs rather than silently dropping them.
+10 -48
View File
@@ -50,21 +50,6 @@ const (
// newer. It keeps freshness signals such as filer.sync's sync_offset metric
// from looking stuck during read-only periods on the source.
idleHeartbeatInterval = 5 * time.Second
// peerDeliveryClaimInterval paces that heartbeat on the local stream of a
// filer with peers, where it is not a keepalive but a delivery claim: the
// peer aggregator turns it into its delivery low-watermark, and every
// aggregated subscriber in the cluster holds at the minimum across peers.
// So this, not idleHeartbeatInterval, is how far behind live writes a
// quiet filer leaves them. Rounded up to the reader's own poll interval.
peerDeliveryClaimInterval = 200 * time.Millisecond
// heldWakeFloor coalesces hold releases. Peers advance their watermarks
// per event they stream, and each release costs a whole pass - a log file
// listing included - so releasing on every advance turns a busy cluster
// into a listing storm. It is added to delivery latency, so it stays well
// under the claim interval that already bounds it.
heldWakeFloor = 20 * time.Millisecond
)
// metadataStreamSender is satisfied by both gRPC stream types and pipelinedSender.
@@ -260,9 +245,8 @@ func memoryHoldsGap(currentTsNs, lastEvictedTsNs int64) bool {
// errHeldByPeerWatermark aborts a read at an entry beyond the hold point; the
// caller rewinds to the last delivered entry, waits, and re-reads (the
// re-listing is what picks up a late-landing log file). Holding is the normal
// state on a cluster that keeps writing, hence the quiet stop.
var errHeldByPeerWatermark = fmt.Errorf("held by aggregated peer watermark: %w", log_buffer.StopReadingError)
// re-listing is what picks up a late-landing log file).
var errHeldByPeerWatermark = errors.New("held by aggregated peer watermark")
// resolveAggReadHoldTsNs bounds how far an aggregated subscriber may read: a
// cursor that passes T before every source has provably made T visible loses
@@ -670,28 +654,15 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
var diskPassProvenTsNs int64
diskEachLogEntryFn := guardedEachLogEntryFn(func() int64 { return diskPassHoldTsNs })
memEachLogEntryFn := guardedEachLogEntryFn(holdMemTsNs)
// waitHeld pauses a held read until a peer reports further progress, or
// the retry interval elapses (a peer dropped past its grace, or a log file
// landing that no watermark covers). Arriving data is deliberately not a
// wake-up: on a cluster that keeps writing there is always an entry past
// the hold, so waking on it spins the loop without ever releasing the
// hold. The channel is the one for this read's own watermark - a delivery
// advance cannot release a flush-held read - and was taken before the pass
// sampled it, so a rise in between wakes us here instead of being missed.
// False: context ended.
waitHeld := func(scope string, watermarkChan <-chan struct{}) bool {
stats.FilerSubscribeWatermarkHolds.WithLabelValues(scope).Inc()
// waitHeld pauses a held read until new data or the retry interval (holds
// also release on heartbeats, which do not notify). False: context ended.
waitHeld := func() bool {
glog.V(3).Infof("held at %v (deliveredUpTo %v, flushLow %v, deliveryLow %v) for %v",
time.Unix(0, heldAtTsNs), time.Unix(0, deliveredUpToTsNs),
time.Unix(0, fs.filer.MetaAggregator.PeerLowFlushWatermarkTsNs()),
time.Unix(0, fs.filer.MetaAggregator.PeerLowWatermarkTsNs()), clientName)
select {
case <-ctx.Done():
return false
case <-time.After(heldWakeFloor):
}
select {
case <-watermarkChan:
case <-aggNotifyChan:
case <-ctx.Done():
return false
case <-time.After(unflushedGapRetryInterval):
@@ -725,10 +696,6 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
glog.V(4).Infof("read on disk %v aggregated subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
// Taken before either read samples its watermark, so a rise mid-pass
// cannot land between the sample and the park below.
flushChan := fs.filer.MetaAggregator.FlushWatermarkAdvancedChan()
deliveryChan := fs.filer.MetaAggregator.DeliveryWatermarkAdvancedChan()
cursorBeforeDiskTsNs := lastReadTime.Time.UnixNano()
// Observe the flush low-watermark before the pass lists files (see
@@ -763,7 +730,7 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
// A hold is not a gap: clear any stale ResumeFromDiskError so the
// next pass's disk-miss handling cannot skip past the held entry.
readInMemoryLogErr = nil
if !waitHeld("disk", flushChan) {
if !waitHeld() {
return nil
}
continue
@@ -869,7 +836,7 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
// the last delivered entry so nothing in between is skipped.
lastReadTime = log_buffer.NewMessagePosition(deliveredUpToTsNs, gapResumeCursorOffset)
readInMemoryLogErr = nil
if !waitHeld("memory", deliveryChan) {
if !waitHeld() {
return nil
}
continue
@@ -1172,13 +1139,8 @@ func (fs *FilerServer) maybeSendIdleHeartbeat(req *filer_pb.SubscribeMetadataReq
// the buffer holds data the subscriber has not reached yet
return lastHeartbeatNs
}
isLocalStream := fs.filer != nil && logBuffer == fs.filer.LocalMetaLogBuffer
interval := idleHeartbeatInterval
if isLocalStream && fs.filer.MetaAggregator != nil && fs.filer.MetaAggregator.HasRemotePeers() {
interval = peerDeliveryClaimInterval
}
now := time.Now().UnixNano()
if now-lastHeartbeatNs < int64(interval) {
if now-lastHeartbeatNs < int64(idleHeartbeatInterval) {
return lastHeartbeatNs
}
// On the local stream the heartbeat is a delivery claim to a peer
@@ -1190,7 +1152,7 @@ func (fs *FilerServer) maybeSendIdleHeartbeat(req *filer_pb.SubscribeMetadataReq
// (fenced above it), or already appended here - and then the head check
// proves this stream has sent it before the heartbeat.
heartbeat := &filer_pb.SubscribeMetadataResponse{TsNs: now}
if isLocalStream {
if fs.filer != nil && logBuffer == fs.filer.LocalMetaLogBuffer {
heartbeat.TsNs = fs.filer.LocalDeliveredThroughTsNs(now)
heartbeat.FlushedTsNs = fs.filer.LocalFlushedThroughTsNs(now)
if logBuffer.LastTsNs.Load() > floorTsNs {
+20 -4
View File
@@ -632,6 +632,7 @@ func (fs *FilerServer) tusWriteData(ctx context.Context, session *TusSession, of
// Upload in streaming chunks to avoid buffering entire content in memory
var totalWritten int64
var uploadErr error
var uploadedChunks []*TusChunkInfo
// Create one uploader for all sub-chunks to reuse HTTP client connections
uploader, uploaderErr := operation.NewUploader()
@@ -691,19 +692,34 @@ func (fs *FilerServer) tusWriteData(ctx context.Context, session *TusSession, of
}
if saveErr := fs.saveTusChunk(ctx, session.ID, chunk); saveErr != nil {
fs.deleteTusChunk(ctx, session, chunk)
// Cleanup this chunk on failure
fs.filer.DeleteChunks(ctx, util.FullPath(session.TargetPath), []*filer_pb.FileChunk{
{FileId: fileId},
})
uploadErr = fmt.Errorf("update session: %w", saveErr)
break
}
uploadedChunks = append(uploadedChunks, chunk)
totalWritten += int64(uploadResult.Size)
currentOffset += int64(uploadResult.Size)
stats.FilerHandlerCounter.WithLabelValues("tusUploadChunk").Inc()
}
// Sub-chunks already recorded stay: the session offset a resuming client
// reads back covers them, and the completed entry is assembled from them.
return totalWritten, uploadErr
if uploadErr != nil {
// Cleanup all uploaded chunks on error
if len(uploadedChunks) > 0 {
var chunksToDelete []*filer_pb.FileChunk
for _, c := range uploadedChunks {
chunksToDelete = append(chunksToDelete, &filer_pb.FileChunk{FileId: c.FileId})
}
fs.filer.DeleteChunks(ctx, util.FullPath(session.TargetPath), chunksToDelete)
}
return 0, uploadErr
}
return totalWritten, nil
}
// parseTusMetadata parses the Upload-Metadata header
-12
View File
@@ -417,18 +417,6 @@ func (fs *FilerServer) saveTusChunk(ctx context.Context, uploadID string, chunk
return nil
}
// deleteTusChunk drops a chunk's record before freeing its data, so a save that
// failed after the record landed cannot leave the session pointing at a needle
// that is about to be deleted. Data outliving a lost record only leaks.
func (fs *FilerServer) deleteTusChunk(ctx context.Context, session *TusSession, chunk *TusChunkInfo) {
chunkPath := util.FullPath(fs.tusChunkPath(session.ID, chunk.Offset, chunk.Size, chunk.FileId))
if err := fs.filer.DeleteEntryMetaAndData(ctx, chunkPath, false, false, false, false, nil, 0); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
glog.Errorf("TUS chunk %s record kept, its data leaks: %v", chunkPath, err)
return
}
fs.filer.DeleteChunks(ctx, util.FullPath(session.TargetPath), []*filer_pb.FileChunk{{FileId: chunk.FileId}})
}
// deleteTusSession removes a TUS upload session and all its data
func (fs *FilerServer) deleteTusSession(ctx context.Context, uploadID string) error {
sessionPath := util.FullPath(fs.tusSessionPath(uploadID))
-318
View File
@@ -1,318 +0,0 @@
package weed_server
// End-to-end tests for the aggregated (SubscribeMetadata) loop's peer
// watermark holds. Peers report their progress at their own pace, so on a
// cluster that keeps writing there is almost always an entry newer than the
// low-watermark: a hold is the normal state, and has to be quiet and paced
// rather than logged and retried per arriving event.
import (
"context"
"fmt"
"net"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"google.golang.org/grpc/peer"
"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/stats"
)
const (
testSelfAddress = pb.ServerAddress("self:8888")
testPeerAddress = pb.ServerAddress("peer:8888")
)
// startAggregator gives the harness a meta aggregator with one remote peer, so
// SubscribeMetadata takes the aggregated path instead of delegating to
// SubscribeLocalMetadata.
func (h *subscribeHarness) startAggregator() *filer.MetaAggregator {
ma := filer.NewMetaAggregator(h.f, testSelfAddress, nil)
ma.TrackPeerForTesting(testSelfAddress)
ma.TrackPeerForTesting(testPeerAddress)
h.f.MetaAggregator = ma
h.t.Cleanup(ma.MetaLogBuffer.ShutdownLogBuffer)
return ma
}
// reportPeers stands in for both peers' streams reporting through tsNs.
func reportPeers(ma *filer.MetaAggregator, tsNs int64) {
reportPeersAt(ma, tsNs, tsNs)
}
// reportPeersAt is reportPeers with the two watermarks apart: a peer streams
// an event well before it flushes it, so they advance independently.
func reportPeersAt(ma *filer.MetaAggregator, deliveredTsNs, flushedTsNs int64) {
ma.ReportPeerWatermarksForTesting(testSelfAddress, deliveredTsNs, flushedTsNs)
ma.ReportPeerWatermarksForTesting(testPeerAddress, deliveredTsNs, flushedTsNs)
}
func (h *subscribeHarness) appendAggregated(tsNs int64) {
if err := h.f.MetaAggregator.MetaLogBuffer.AddLogEntryToBuffer(testEvent(tsNs, fmt.Sprintf("a-%d", tsNs))); err != nil {
h.t.Fatalf("append aggregated: %v", err)
}
}
func (h *subscribeHarness) subscribeAggregated(sinceNs int64) *runningSubscribe {
// A peer in the context keeps findClientAddress quiet, so an ERROR count
// across the run sees only what the subscribe loop itself writes.
ctx, cancel := context.WithCancel(peer.NewContext(context.Background(),
&peer.Peer{Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 12345}}))
stream := &fakeSubscribeStream{ctx: ctx}
req := &filer_pb.SubscribeMetadataRequest{
ClientName: "agg-loop-test",
ClientId: 11,
ClientEpoch: 1,
SinceNs: sinceNs,
}
r := &runningSubscribe{stream: stream, cancel: cancel, done: make(chan error, 1), finished: make(chan struct{})}
go func() {
r.done <- h.fs.SubscribeMetadata(req, stream)
close(r.finished)
}()
h.t.Cleanup(func() {
cancel()
select {
case <-r.finished:
case <-time.After(5 * time.Second):
h.t.Error("aggregated subscribe loop did not exit on cancel")
}
})
return r
}
// heldSubscriber starts a subscriber whose peers reported a moment ago and
// then went quiet - the hold sits just behind live writes, exactly where a
// quiet peer's idle heartbeat leaves it - and returns it with the write
// timestamp the peers last reported.
func (h *subscribeHarness) heldSubscriber() (*filer.MetaAggregator, *runningSubscribe, int64) {
ma := h.startAggregator()
frozen := time.Now().Add(-500 * time.Millisecond).UnixNano()
reportPeers(ma, frozen)
return ma, h.subscribeAggregated(frozen), frozen
}
// writeFor appends an entry every 2ms for d, reporting the peers through the
// PREVIOUS entry each time when report is set: the live-cluster shape, where
// the low-watermark keeps moving but always trails the newest entry, so every
// read ends held.
func (h *subscribeHarness) writeFor(ma *filer.MetaAggregator, d time.Duration, report bool) (written []int64, elapsed time.Duration) {
start := time.Now()
for stop := time.After(d); ; {
select {
case <-stop:
if report && len(written) > 0 {
reportPeers(ma, written[len(written)-1])
}
return written, time.Since(start)
default:
}
ts := time.Now().UnixNano()
h.appendAggregated(ts)
if report && len(written) > 0 {
reportPeers(ma, written[len(written)-1])
}
written = append(written, ts)
time.Sleep(2 * time.Millisecond)
}
}
// heldReads reads back the hold counter the loop keeps in place of the log
// line, which is also how an operator sees a held subscriber now.
func heldReads(scopes ...string) int {
if len(scopes) == 0 {
scopes = []string{"memory", "disk"}
}
var total int
for _, scope := range scopes {
total += int(testutil.ToFloat64(stats.FilerSubscribeWatermarkHolds.WithLabelValues(scope)))
}
return total
}
// waitForEventsAtLeastOnce asserts every want arrives, in order. The cursor a
// hold rewinds to is inclusive of the last delivered entry, so each cycle
// repeats it - at-least-once, which is the contract; a skip is not.
func waitForEventsAtLeastOnce(t *testing.T, r *runningSubscribe, want []int64, timeout time.Duration) {
t.Helper()
last := want[len(want)-1]
deadline := time.Now().Add(timeout)
var got []int64
for time.Now().Before(deadline) {
got = eventTimestamps(r.stream.snapshot())
if len(got) > 0 && got[len(got)-1] >= last {
break
}
time.Sleep(10 * time.Millisecond)
}
seen := make(map[int64]bool, len(got))
var prev int64
for _, ts := range got {
if ts < prev {
t.Fatalf("delivered %v after %v: out of order", time.Unix(0, ts), time.Unix(0, prev))
}
prev, seen[ts] = ts, true
}
for i, ts := range want {
if !seen[ts] {
t.Fatalf("event %d of %d (%v) never delivered", i+1, len(want), time.Unix(0, ts))
}
}
}
// TestSubscribeLoop_AggregatedHoldIsQuiet: every held read used to log an
// ERROR, so a busy cluster wrote one line per arriving event.
func TestSubscribeLoop_AggregatedHoldIsQuiet(t *testing.T) {
h := newSubscribeHarness(t)
ma, r, _ := h.heldSubscriber()
errorsBefore := glog.Stats.Error.Lines()
written, elapsed := h.writeFor(ma, time.Second, false)
errorLines := glog.Stats.Error.Lines() - errorsBefore
t.Logf("%d writes over %v produced %d ERROR lines", len(written), elapsed, errorLines)
if errorLines > 0 {
t.Fatalf("a held read logged %d ERROR lines over %d writes; holds are control flow", errorLines, len(written))
}
if got := eventTimestamps(r.stream.snapshot()); len(got) > 0 {
t.Fatalf("delivered %d events past the peers' watermark", len(got))
}
}
// TestSubscribeLoop_AggregatedHoldIsPaced is the other half: a held read used
// to wait on the buffer's data channel, which the very next write signalled,
// so the loop re-ran a whole pass - a log file listing in it - per event.
// Arriving data cannot release a hold; only peer progress can.
func TestSubscribeLoop_AggregatedHoldIsPaced(t *testing.T) {
h := newSubscribeHarness(t)
// Long enough that a hold paced by the retry interval alone is far below
// one hold per write, short enough to keep the test quick.
prevRetry := unflushedGapRetryInterval
unflushedGapRetryInterval = 200 * time.Millisecond
t.Cleanup(func() { unflushedGapRetryInterval = prevRetry })
ma, _, _ := h.heldSubscriber()
holdsBefore := heldReads()
written, elapsed := h.writeFor(ma, time.Second, false)
holds := heldReads() - holdsBefore
t.Logf("%d writes over %v produced %d holds", len(written), elapsed, holds)
// The watermarks never moved, so the retry interval alone paces the holds.
if maxHolds := int(elapsed/unflushedGapRetryInterval) + 2; holds > maxHolds {
t.Fatalf("held %d times in %v, want at most %d: a hold must wait for peer progress, not for the next write",
holds, elapsed, maxHolds)
}
}
// TestSubscribeLoop_AggregatedHoldReleasesOnPeerProgress pins what pacing the
// hold may not cost: once the peers report through the held entry it must be
// delivered, without waiting out the retry interval.
func TestSubscribeLoop_AggregatedHoldReleasesOnPeerProgress(t *testing.T) {
h := newSubscribeHarness(t)
// Far longer than this test runs: only the watermark signal can deliver.
prevRetry := unflushedGapRetryInterval
unflushedGapRetryInterval = 30 * time.Second
t.Cleanup(func() { unflushedGapRetryInterval = prevRetry })
ma, r, _ := h.heldSubscriber()
ts := time.Now().UnixNano()
h.appendAggregated(ts)
assertNoEventsFor(t, r, 200*time.Millisecond)
reportPeers(ma, ts)
waitForEvents(t, r, []int64{ts}, 3*time.Second)
}
// TestSubscribeLoop_AggregatedHoldCoalescesPeerProgress covers the rest of the
// cost: peers advance their watermark on every event they stream, so releasing
// a hold per advance is the same pass-per-event storm as releasing per write,
// just without the log lines.
func TestSubscribeLoop_AggregatedHoldCoalescesPeerProgress(t *testing.T) {
h := newSubscribeHarness(t)
ma, r, _ := h.heldSubscriber()
holdsBefore := heldReads()
written, elapsed := h.writeFor(ma, time.Second, true)
holds := heldReads() - holdsBefore
t.Logf("%d writes over %v produced %d holds", len(written), elapsed, holds)
if maxHolds := int(elapsed/heldWakeFloor) + 2; holds > maxHolds {
t.Fatalf("held %d times in %v, want at most %d: releases must coalesce", holds, elapsed, maxHolds)
}
// Coalescing may not lose anything the peers reported through.
waitForEventsAtLeastOnce(t, r, written, 3*time.Second)
}
// TestPeerDeliveryClaimPacing pins what a filer with peers owes them: the idle
// heartbeat on its local stream is a delivery claim every aggregated
// subscriber in the cluster holds at, so it refreshes at the claim interval,
// not at the keepalive interval that used to park them ~5s behind live writes.
func TestPeerDeliveryClaimPacing(t *testing.T) {
h := newSubscribeHarness(t)
req := &filer_pb.SubscribeMetadataRequest{ClientSupportsIdleHeartbeat: true}
lb := h.f.LocalMetaLogBuffer
// Claimed a second ago: stale for a delivery claim, fresh for a keepalive.
claimedAtNs := time.Now().Add(-time.Second).UnixNano()
s := &collectingStream{}
if got := h.fs.maybeSendIdleHeartbeat(req, s, lb, 0, 0, claimedAtNs); got != claimedAtNs || len(s.messages) != 0 {
t.Fatalf("standalone filer sent %d heartbeats early", len(s.messages))
}
h.startAggregator()
s = &collectingStream{}
if got := h.fs.maybeSendIdleHeartbeat(req, s, lb, 0, 0, claimedAtNs); got == claimedAtNs || len(s.messages) != 1 {
t.Fatalf("filer with peers sent %d delivery claims, want 1", len(s.messages))
}
if s.messages[0].TsNs <= claimedAtNs {
t.Fatalf("claim ts %d did not advance past %d", s.messages[0].TsNs, claimedAtNs)
}
}
// TestSubscribeLoop_AggregatedDiskHoldIgnoresDeliveryProgress pins that each
// hold parks on its own watermark. A persisted-log read is held by what the
// peers have FLUSHED, and peers advance their DELIVERY watermark on every
// event they stream, so waking it on delivery progress would re-list a day of
// log files per event and re-park on the same entry.
func TestSubscribeLoop_AggregatedDiskHoldIgnoresDeliveryProgress(t *testing.T) {
h := newSubscribeHarness(t)
prevRetry := unflushedGapRetryInterval
unflushedGapRetryInterval = 500 * time.Millisecond
t.Cleanup(func() { unflushedGapRetryInterval = prevRetry })
// Recent enough that the settled horizon does not take the hold over.
onDisk := time.Now().Add(-30 * time.Second).UnixNano()
h.append(onDisk)
h.f.LocalMetaLogBuffer.ForceFlush()
waitForFlushedFiles(t, h, onDisk)
ma := h.startAggregator()
// Flushed below the entry on disk, delivered well past it: only the disk
// pass is held.
reportPeersAt(ma, time.Now().UnixNano(), onDisk-int64(time.Second))
r := h.subscribeAggregated(onDisk - int64(5*time.Second))
assertNoEventsFor(t, r, 200*time.Millisecond)
holdsBefore := heldReads("disk")
start := time.Now()
for deadline := start.Add(time.Second); time.Now().Before(deadline); {
reportPeersAt(ma, time.Now().UnixNano(), 0)
time.Sleep(2 * time.Millisecond)
}
holds, elapsed := heldReads("disk")-holdsBefore, time.Since(start)
t.Logf("%v of delivery-only progress produced %d disk holds", elapsed, holds)
if maxHolds := int(elapsed/unflushedGapRetryInterval) + 2; holds > maxHolds {
t.Fatalf("held on disk %d times in %v, want at most %d: delivery progress cannot release a flush hold",
holds, elapsed, maxHolds)
}
// The flush watermark reaching the entry is what delivers it.
reportPeersAt(ma, 0, onDisk)
waitForEvents(t, r, []int64{onDisk}, 3*time.Second)
}
+8 -20
View File
@@ -139,12 +139,10 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
}
if !ms.Topo.IsLeader() {
// tell the volume servers about the leader we know of right now, so
// that a follower without one hands the heartbeat back immediately
// instead of holding it through an election
newLeader, err := ms.Topo.MaybeLeader()
if err != nil || newLeader == "" {
glog.V(1).Infof("SendHeartbeat find leader: %v", err)
// tell the volume servers about the leader
newLeader, err := ms.Topo.Leader()
if err != nil {
glog.Warningf("SendHeartbeat find leader: %v", err)
return raft.NotLeaderError
}
if err := stream.Send(&master_pb.HeartbeatResponse{
@@ -403,13 +401,6 @@ func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServ
if req.ClientType == cluster.FilerType {
ms.LockRingManager.AddServer(cluster.FilerGroupName(req.FilerGroup), peerAddress)
}
if req.ClientType == cluster.MasterType {
// Only the leader gets this far, and a master that starts with no raft
// state cannot campaign its way in, so this registration is where it
// joins the quorum. The broadcast below is not enough: it only reaches
// masters already connected to us.
ms.AdmitRaftPeer(peerAddress)
}
defer func() {
for _, update := range ms.Cluster.RemoveClusterNode(req.FilerGroup, req.ClientType, peerAddress) {
@@ -548,12 +539,9 @@ func (ms *MasterServer) broadcastVolumeLocationsToClients(locations []*master_pb
}
func (ms *MasterServer) informNewLeader(stream master_pb.Seaweed_KeepConnectedServer) error {
// Answer from what raft knows now. Waiting out an election here pins the
// client to a master that cannot serve it, right when it should be moving
// on to the next peer to find the one that can.
leader, err := ms.Topo.MaybeLeader()
if err != nil || leader == "" {
glog.V(1).Infof("topo leader: %v", err)
leader, err := ms.Topo.Leader()
if err != nil {
glog.Errorf("topo leader: %v", err)
return raft.NotLeaderError
}
if err := stream.Send(&master_pb.KeepConnectedResponse{
@@ -618,7 +606,7 @@ func findClientAddress(ctx context.Context, grpcPort uint32) string {
func (ms *MasterServer) GetMasterConfiguration(ctx context.Context, req *master_pb.GetMasterConfigurationRequest) (*master_pb.GetMasterConfigurationResponse, error) {
// tell the volume servers about the leader
leader, _ := ms.Topo.MaybeLeader()
leader, _ := ms.Topo.Leader()
// MIGRATION: expose maintenance scripts for admin server seeding. Remove after March 2027.
v := util.GetViper()
+32 -59
View File
@@ -6,7 +6,6 @@ import (
"net"
"github.com/hashicorp/raft"
goraft "github.com/seaweedfs/raft"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
@@ -97,62 +96,6 @@ func (ms *MasterServer) RaftListClusterServers(ctx context.Context, req *master_
return resp, nil
}
// raftAddServer admits a master into the quorum. A master that starts with no
// raft state cannot elect on its own, so the leader has to pull it in; this is
// the one place that knows how to do that for either raft implementation.
// goraft has no non-voting members, so an admitted peer always votes there.
func (ms *MasterServer) raftAddServer(id string, grpcAddress string, voter bool) error {
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if ms.Topo.HashicorpRaft != nil {
if ms.Topo.HashicorpRaft.State() != raft.Leader {
return fmt.Errorf("raft add server %s failed: %s is no current leader", id, ms.Topo.HashicorpRaft.String())
}
var idxFuture raft.IndexFuture
if voter {
idxFuture = ms.Topo.HashicorpRaft.AddVoter(raft.ServerID(id), raft.ServerAddress(grpcAddress), 0, 0)
} else {
idxFuture = ms.Topo.HashicorpRaft.AddNonvoter(raft.ServerID(id), raft.ServerAddress(grpcAddress), 0, 0)
}
return idxFuture.Error()
}
if ms.Topo.RaftServer == nil {
return nil
}
if ms.Topo.RaftServer.State() != goraft.Leader {
return fmt.Errorf("raft add server %s failed: %s is no current leader", id, ms.Topo.RaftServer.Name())
}
_, err := ms.Topo.RaftServer.Do(&goraft.DefaultJoinCommand{
Name: id,
ConnectionString: grpcAddress,
})
return err
}
// raftRemoveServer drops a master from the quorum.
func (ms *MasterServer) raftRemoveServer(id string) error {
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if ms.Topo.HashicorpRaft != nil {
if ms.Topo.HashicorpRaft.State() != raft.Leader {
return fmt.Errorf("raft remove server %s failed: %s is no current leader", id, ms.Topo.HashicorpRaft.String())
}
return ms.Topo.HashicorpRaft.RemoveServer(raft.ServerID(id), 0, 0).Error()
}
if ms.Topo.RaftServer == nil {
return nil
}
if ms.Topo.RaftServer.State() != goraft.Leader {
return fmt.Errorf("raft remove server %s failed: %s is no current leader", id, ms.Topo.RaftServer.Name())
}
_, err := ms.Topo.RaftServer.Do(&goraft.DefaultLeaveCommand{Name: id})
return err
}
func (ms *MasterServer) RaftAddServer(ctx context.Context, req *master_pb.RaftAddServerRequest) (*master_pb.RaftAddServerResponse, error) {
resp := &master_pb.RaftAddServerResponse{}
@@ -160,7 +103,25 @@ func (ms *MasterServer) RaftAddServer(ctx context.Context, req *master_pb.RaftAd
return resp, err
}
if err := ms.raftAddServer(req.Id, req.Address, req.Voter); err != nil {
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if ms.Topo.HashicorpRaft == nil {
return resp, nil
}
if ms.Topo.HashicorpRaft.State() != raft.Leader {
return nil, fmt.Errorf("raft add server %s failed: %s is no current leader", req.Id, ms.Topo.HashicorpRaft.String())
}
var idxFuture raft.IndexFuture
if req.Voter {
idxFuture = ms.Topo.HashicorpRaft.AddVoter(raft.ServerID(req.Id), raft.ServerAddress(req.Address), 0, 0)
} else {
idxFuture = ms.Topo.HashicorpRaft.AddNonvoter(raft.ServerID(req.Id), raft.ServerAddress(req.Address), 0, 0)
}
if err := idxFuture.Error(); err != nil {
return nil, err
}
return resp, nil
@@ -173,6 +134,17 @@ func (ms *MasterServer) RaftRemoveServer(ctx context.Context, req *master_pb.Raf
return resp, err
}
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if ms.Topo.HashicorpRaft == nil {
return resp, nil
}
if ms.Topo.HashicorpRaft.State() != raft.Leader {
return nil, fmt.Errorf("raft remove server %s failed: %s is no current leader", req.Id, ms.Topo.HashicorpRaft.String())
}
if !req.Force {
ms.clientChansLock.RLock()
_, ok := ms.clientChans[fmt.Sprintf("%s@%s", cluster.MasterType, req.Id)]
@@ -182,7 +154,8 @@ func (ms *MasterServer) RaftRemoveServer(ctx context.Context, req *master_pb.Raf
}
}
if err := ms.raftRemoveServer(req.Id); err != nil {
idxFuture := ms.Topo.HashicorpRaft.RemoveServer(raft.ServerID(req.Id), 0, 0)
if err := idxFuture.Error(); err != nil {
return nil, err
}
return resp, nil
+38 -106
View File
@@ -82,9 +82,6 @@ type MasterServer struct {
topologyIdGenLock sync.Mutex
// masters currently being admitted into the raft quorum, keyed by raft id
raftPeerAdmissions sync.Map
MasterClient *wdclient.MasterClient
adminLocks *AdminLocks
@@ -219,10 +216,9 @@ func (ms *MasterServer) healthzHandler(w http.ResponseWriter, r *http.Request) {
}
func (ms *MasterServer) readyzHandler(w http.ResponseWriter, r *http.Request) {
// Readiness: check we can serve traffic. Answer from what raft knows now
// rather than waiting out an election, so the probe's own timeout decides.
leader, err := ms.Topo.MaybeLeader()
if err != nil || leader == "" {
// Readiness: check we can serve traffic.
leader, err := ms.Topo.Leader()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
@@ -503,115 +499,51 @@ func (ms *MasterServer) createSequencer(option *MasterOption) sequence.Sequencer
}
func (ms *MasterServer) OnPeerUpdate(update *master_pb.ClusterNodeUpdate, startFrom time.Time) {
if update.NodeType != cluster.MasterType {
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if update.NodeType != cluster.MasterType || ms.Topo.HashicorpRaft == nil {
return
}
glog.V(4).Infof("OnPeerUpdate: %+v", update)
peerAddress := pb.ServerAddress(update.Address)
peerName := raftServerID(peerAddress)
if ms.Topo.HashicorpRaft.State() != hashicorpRaft.Leader {
return
}
if update.IsAdd {
ms.AdmitRaftPeer(peerAddress)
return
}
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
// goraft rebuilds its peer set from -peers on every start, so a departed
// master is already out of the list there and would come back on the next
// restart anyway; only hashicorp raft carries membership across restarts.
if ms.Topo.HashicorpRaft == nil || ms.Topo.HashicorpRaft.State() != hashicorpRaft.Leader {
return
}
// A master that is merely down is still a member: -peers is what declares
// membership, and updatePeers reconciles the configuration against it on
// every leadership change. Evicting one here would shrink the quorum behind
// the operator's back, and a restart then races the eviction — the master
// gets re-admitted, the removal lands after it, and it is left out of the
// configuration with nobody left to vote it back in.
for _, peer := range ms.MasterClient.GetMasters(context.Background()) {
if peer.ToHttpAddress() == peerAddress.ToHttpAddress() {
return
}
}
peerName := raftServerID(peerAddress)
pb.WithMasterClient(context.Background(), false, peerAddress, ms.grpcDialOption, true, func(client master_pb.SeaweedClient) error {
ctx, cancel := context.WithTimeout(context.TODO(), 15*time.Second)
defer cancel()
if _, err := client.Ping(ctx, &master_pb.PingRequest{Target: string(peerAddress), TargetType: cluster.MasterType}); err != nil {
glog.V(0).Infof("master %s didn't respond to pings. remove raft server", peerName)
// We are the leader here, so drop the dead peer through the local
// raft handle instead of dialing our own RaftRemoveServer RPC.
if err := ms.Topo.HashicorpRaft.RemoveServer(hashicorpRaft.ServerID(peerName), 0, 0).Error(); err != nil {
glog.Warningf("failed removing old raft server: %v", err)
return err
}
} else {
glog.V(0).Infof("master %s successfully responded to ping", peerName)
}
return nil
})
}
// AdmitRaftPeer pulls a master into the raft quorum, if we are the leader and
// do not have it yet. A master that starts with no raft state cannot campaign
// under either implementation, so this is its only way in.
func (ms *MasterServer) AdmitRaftPeer(peerAddress pb.ServerAddress) {
if peerAddress.ToHttpAddress() == ms.option.Master.ToHttpAddress() {
return
}
peerName, ok := ms.missingRaftPeerName(peerAddress)
if !ok {
return
}
if _, alreadyAdmitting := ms.raftPeerAdmissions.LoadOrStore(peerName, struct{}{}); alreadyAdmitting {
return
}
glog.V(0).Infof("adding new raft server: %s", peerName)
// The join commits through raft, which waits on the other peers, so keep it
// off the caller: this runs on the peer update stream and on the grpc
// handler that a joining master is still blocked in.
go func() {
defer ms.raftPeerAdmissions.Delete(peerName)
if err := ms.raftAddServer(peerName, peerAddress.ToGrpcAddress(), true); err != nil {
glog.Warningf("failed adding raft server %s: %v", peerName, err)
}
}()
}
// missingRaftPeerName returns the raft id to admit peerAddress under, and
// whether this master is the leader and is missing that peer.
func (ms *MasterServer) missingRaftPeerName(peerAddress pb.ServerAddress) (string, bool) {
ms.Topo.RaftServerAccessLock.RLock()
defer ms.Topo.RaftServerAccessLock.RUnlock()
if ms.Topo.RaftServer != nil {
if ms.Topo.RaftServer.State() != raft.Leader {
return "", false
}
// Peers are keyed by the name a master calls itself, which carries the
// grpc port; match on the http address so a peer already known under
// another spelling is not added twice.
for name := range ms.Topo.RaftServer.Peers() {
if pb.ServerAddress(name).ToHttpAddress() == peerAddress.ToHttpAddress() {
return "", false
raftServerFound := false
for _, server := range ms.Topo.HashicorpRaft.GetConfiguration().Configuration().Servers {
if string(server.ID) == peerName {
raftServerFound = true
}
}
return string(peerAddress), true
}
if ms.Topo.HashicorpRaft == nil || ms.Topo.HashicorpRaft.State() != hashicorpRaft.Leader {
return "", false
}
peerName := raftServerID(peerAddress)
for _, server := range ms.Topo.HashicorpRaft.GetConfiguration().Configuration().Servers {
if string(server.ID) == peerName {
return "", false
if !raftServerFound {
glog.V(0).Infof("adding new raft server: %s", peerName)
ms.Topo.HashicorpRaft.AddVoter(
hashicorpRaft.ServerID(peerName),
hashicorpRaft.ServerAddress(peerAddress.ToGrpcAddress()), 0, 0)
}
} else {
pb.WithMasterClient(context.Background(), false, peerAddress, ms.grpcDialOption, true, func(client master_pb.SeaweedClient) error {
ctx, cancel := context.WithTimeout(context.TODO(), 15*time.Second)
defer cancel()
if _, err := client.Ping(ctx, &master_pb.PingRequest{Target: string(peerAddress), TargetType: cluster.MasterType}); err != nil {
glog.V(0).Infof("master %s didn't respond to pings. remove raft server", peerName)
// We are the leader here, so drop the dead peer through the local
// raft handle, mirroring the AddVoter branch above, instead of
// dialing our own RaftRemoveServer RPC.
if err := ms.Topo.HashicorpRaft.RemoveServer(hashicorpRaft.ServerID(peerName), 0, 0).Error(); err != nil {
glog.Warningf("failed removing old raft server: %v", err)
return err
}
} else {
glog.V(0).Infof("master %s successfully responded to ping", peerName)
}
return nil
})
}
return peerName, true
}
func (ms *MasterServer) Shutdown() {
+33 -7
View File
@@ -11,6 +11,7 @@ import (
"os"
"path"
"path/filepath"
"sort"
"time"
transport "github.com/Jille/raft-grpc-transport"
@@ -32,6 +33,26 @@ const (
updatePeersTimeout = 15 * time.Minute
)
func getPeerIdx(self pb.ServerAddress, mapPeers map[string]pb.ServerAddress) int {
peerIDs := make([]string, 0, len(mapPeers))
seen := make(map[string]struct{}, len(mapPeers))
for _, peer := range mapPeers {
id := raftServerID(peer)
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
peerIDs = append(peerIDs, id)
}
sort.Strings(peerIDs)
selfID := raftServerID(self)
idx := sort.SearchStrings(peerIDs, selfID)
if idx < len(peerIDs) && peerIDs[idx] == selfID {
return idx
}
return -1
}
func raftServerID(server pb.ServerAddress) string {
return server.ToHttpAddress()
}
@@ -204,15 +225,20 @@ func NewHashicorpRaftServer(option *RaftServerOption) (*RaftServer, error) {
return nil, fmt.Errorf("raft.NewRaft: %w", err)
}
// An explicit -raftBootstrap mints the cluster right here. Otherwise the
// caller bootstraps, once it has confirmed no peer already has a leader:
// bootstrapping next to a live leader forms a second cluster instead of
// joining the first one.
updatePeers := len(s.RaftHashicorp.GetConfiguration().Configuration().Servers) > 0
if option.RaftBootstrap {
if err := s.Bootstrap(); err != nil {
updatePeers := false
if option.RaftBootstrap || len(s.RaftHashicorp.GetConfiguration().Configuration().Servers) == 0 {
cfg := s.AddPeersConfiguration()
// Need to get lock, in case all servers do this at the same time.
peerIdx := getPeerIdx(s.serverAddr, s.peers)
timeSleep := time.Duration(float64(c.LeaderLeaseTimeout) * (rand.Float64()*0.25 + 1) * float64(peerIdx))
glog.V(0).Infof("Bootstrapping idx: %d sleep: %v new cluster: %+v", peerIdx, timeSleep, cfg)
time.Sleep(timeSleep)
f := s.RaftHashicorp.BootstrapCluster(cfg)
if err := f.Error(); err != nil {
return nil, fmt.Errorf("raft.Raft.BootstrapCluster: %w", err)
}
} else {
updatePeers = true
}
go s.monitorLeaderLoop(updatePeers)
+13
View File
@@ -35,6 +35,19 @@ func TestRaftServerID(t *testing.T) {
}
}
func TestGetPeerIdxUsesCanonicalID(t *testing.T) {
peers := map[string]pb.ServerAddress{
"master-0:9333": pb.ServerAddress("master-0:9333"),
"master-1:9333": pb.ServerAddress("master-1:9333"),
"master-2:9333": pb.ServerAddress("master-2:9333"),
}
self := pb.NewServerAddress("master-2", 9333, 19333)
if got := getPeerIdx(self, peers); got != 2 {
t.Fatalf("getPeerIdx(%q) = %d, want 2", self, got)
}
}
func TestAddPeersConfigurationUsesCanonicalIDs(t *testing.T) {
rs := &RaftServer{
peers: map[string]pb.ServerAddress{
+7 -14
View File
@@ -303,22 +303,15 @@ func (s *RaftServer) HasExistingState() bool {
return false
}
// Bootstrap mints a new raft cluster out of the configured peers. Only call it
// when no leader exists anywhere: a master that starts with no raft state and
// finds a leader must be admitted by that leader instead, or the two clusters
// never merge.
func (s *RaftServer) Bootstrap() error {
func (s *RaftServer) DoJoinCommand() {
glog.V(0).Infoln("Initializing new cluster")
if s.RaftHashicorp != nil {
return s.RaftHashicorp.BootstrapCluster(s.AddPeersConfiguration()).Error()
}
if s.raftServer == nil {
return nil
}
_, err := s.raftServer.Do(&raft.DefaultJoinCommand{
if _, err := s.raftServer.Do(&raft.DefaultJoinCommand{
Name: s.raftServer.Name(),
ConnectionString: s.serverAddr.ToGrpcAddress(),
})
return err
}); err != nil {
glog.Errorf("fail to send join command: %v", err)
}
}
+3 -6
View File
@@ -24,18 +24,15 @@ func (s *RaftServer) StatusHandler(w http.ResponseWriter, r *http.Request) {
MaxVolumeId: s.topo.GetMaxVolumeId(),
}
// Report the leader raft knows right now. Waiting for one to be elected
// holds the response past every health probe's timeout, which is exactly
// when a master is most likely to still be joining.
if leader, e := s.topo.MaybeLeader(); e == nil {
if leader, e := s.topo.Leader(); e == nil {
ret.Leader = leader
}
writeJsonQuiet(w, r, http.StatusOK, ret)
}
func (s *RaftServer) HealthzHandler(w http.ResponseWriter, r *http.Request) {
leader, err := s.topo.MaybeLeader()
if err != nil || leader == "" {
leader, err := s.topo.Leader()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
-19
View File
@@ -242,14 +242,6 @@ var (
Help: "Times a metadata subscriber moved past a log range without proof it was persisted: scope=aggregated means a peer may not have flushed it, scope=local means this filer's own log flush was wedged past the give-up bound.",
}, []string{"scope"})
FilerSubscribeWatermarkHolds = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemFiler,
Name: "subscribe_watermark_holds",
Help: "Times an aggregated metadata read stopped at an entry newer than the peers' low-watermark and waited for a peer to report further progress: scope=memory held at the delivery watermark, scope=disk at the flush watermark.",
}, []string{"scope"})
FilerSubscribeGapStalledGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
@@ -915,7 +907,6 @@ func init() {
Gather.MustRegister(FilerServerLastSendTsOfSubscribeGauge)
Gather.MustRegister(FilerSubscribeGapStalledGauge)
Gather.MustRegister(FilerSubscribeUnprovenGapCrossings)
Gather.MustRegister(FilerSubscribeWatermarkHolds)
Gather.MustRegister(FilerMetaAggregatorReplayFailures)
Gather.MustRegister(FilerObjectSizeBytesHistogram)
Gather.MustRegister(collectors.NewGoCollector())
@@ -1101,16 +1092,6 @@ func DeleteCollectionMetrics(collection string) {
glog.V(0).Infof("delete collection metrics, %s: %d", collection, c)
}
// DeleteVolumeServerCollectionMetrics drops a collection's volume server series
// once its last volume leaves this server. These gauges are only ever set for
// collections still present, so the values from the heartbeat that saw the last
// volume would otherwise stand until the process restarts.
func DeleteVolumeServerCollectionMetrics(collection string) {
VolumeServerDiskSizeGauge.DeleteLabelValues(collection, "normal")
VolumeServerDiskSizeGauge.DeleteLabelValues(collection, "deleted_bytes")
VolumeServerReadOnlyVolumeGauge.DeletePartialMatch(prometheus.Labels{"collection": collection})
}
func bucketMetricTTLControl() {
ttlNs := bucketAtiveTTL.Nanoseconds()
for {
+1 -1
View File
@@ -289,7 +289,7 @@ func TestRemoteTier_LiveTierUpload_StillReportsToMaster(t *testing.T) {
require.True(t, v.HasRemoteFile(), "a tier-uploaded volume is in remote mode even before any reload")
require.False(t, util.FileExists(v.FileName(".dat")), "tier-up should have removed the local .dat")
_, msg := v.ToVolumeInformationMessage(nil)
_, msg := v.ToVolumeInformationMessage()
require.NotNil(t, msg, "tier-uploaded volume must still report to master")
require.NotEmpty(t, msg.RemoteStorageName, "reported volume must carry its remote backend name")
}
+53 -58
View File
@@ -82,16 +82,6 @@ type Store struct {
DeletedEcShardsChan chan *master_pb.VolumeEcShardInformationMessage
isStopping atomic.Bool
volumeReport volumeReportState
// One heartbeat at a time: the report state is marked in place as the scan
// runs, so two overlapping scans would each forget what the other marked
// and name every volume it holds as departed.
collectHeartbeatLock sync.Mutex
// Collections the last heartbeat set per-collection gauges for. Those gauges
// are only ever set for collections still held here, so one whose last
// volume leaves - moved away by volume.balance, say - would keep reporting
// the heartbeat that saw it. Written only from the heartbeat goroutine.
reportedCollections map[string]struct{}
reportedEcCollections map[string]struct{}
}
func (s *Store) String() (str string) {
@@ -438,15 +428,13 @@ func (s *Store) GetRack() string {
}
func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
s.collectHeartbeatLock.Lock()
defer s.collectHeartbeatLock.Unlock()
var volumeMessages []*master_pb.VolumeInformationMessage
// Covers every volume held, whether or not this heartbeat names it, so the
// master can tell whether applying what it was sent leaves it current.
// Volumes skipped below -- quarantined, phantom, expired -- are in neither.
var volumeDigest uint64
sendFullList, reportGeneration, reportPass := s.volumeReport.begin()
sendFullList, reportGeneration := s.volumeReport.begin()
reported := make(map[volumeReportKey]reportedVolume)
maxVolumeCounts := make(map[string]uint32)
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
diskMaxByID := make(map[int]int32)
@@ -455,10 +443,7 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
var maxFileKey NeedleId
collectionVolumeSize := make(map[string]int64)
collectionVolumeDeletedBytes := make(map[string]int64)
collectionVolumeReadOnlyCount := make(map[string]map[string]int)
// Filled once per volume and kept only by the heartbeat that carries it, so
// a server with nothing to say fills the same message all the way through.
scratchMessage := &master_pb.VolumeInformationMessage{}
collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
for diskID, location := range s.Locations {
if location.isDiskUnavailable.Load() {
continue
@@ -486,7 +471,7 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
diskFreeBytes[string(location.DiskType)] += location.diskFreeBytes.Load()
location.volumesLock.RLock()
for _, v := range location.volumes {
curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage(scratchMessage)
curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage()
if volumeMessage == nil {
continue
}
@@ -524,9 +509,20 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
reportHash := reportHashOf(volumeMessage)
volumeDigest ^= reportHash
if s.volumeReport.record(volumeMessage, reportHash, reportPass) || sendFullList {
reported[volumeReportKey{diskId: volumeMessage.DiskId, volumeId: volumeMessage.Id}] = reportedVolume{
hash: reportHash,
short: &master_pb.VolumeShortInformationMessage{
Id: volumeMessage.Id,
Collection: volumeMessage.Collection,
ReplicaPlacement: volumeMessage.ReplicaPlacement,
Version: volumeMessage.Version,
Ttl: volumeMessage.Ttl,
DiskType: volumeMessage.DiskType,
DiskId: volumeMessage.DiskId,
},
}
if sendFullList || s.volumeReport.changed(volumeMessage, reportHash) {
volumeMessages = append(volumeMessages, volumeMessage)
scratchMessage = &master_pb.VolumeInformationMessage{}
}
} else {
if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
@@ -537,35 +533,38 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
}
}
// The totals are rebuilt from scratch every heartbeat, so a volume
// on its way out is simply not added. Subtracting it took the
// surviving volumes' sizes down with it, and an entry here is also
// what says the collection is still on this server.
if _, exist := collectionVolumeSize[v.Collection]; !exist {
collectionVolumeSize[v.Collection] = 0
collectionVolumeDeletedBytes[v.Collection] = 0
}
if !shouldDeleteVolume {
collectionVolumeSize[v.Collection] += int64(volumeMessage.Size)
collectionVolumeDeletedBytes[v.Collection] += int64(volumeMessage.DeletedByteCount)
counts, exist := collectionVolumeReadOnlyCount[v.Collection]
if !exist {
counts = map[string]int{
stats.IsReadOnly: 0,
stats.NoWriteOrDelete: 0,
stats.NoWriteCanDelete: 0,
stats.IsDiskSpaceLow: 0,
}
collectionVolumeReadOnlyCount[v.Collection] = counts
} else {
collectionVolumeSize[v.Collection] -= int64(volumeMessage.Size)
if collectionVolumeSize[v.Collection] <= 0 {
delete(collectionVolumeSize, v.Collection)
}
if readOnly, noWriteOrDelete, noWriteCanDelete, diskSpaceLow := v.ReadOnlyReasons(); readOnly {
counts[stats.IsReadOnly] += 1
if noWriteOrDelete {
counts[stats.NoWriteOrDelete] += 1
}
if noWriteCanDelete {
counts[stats.NoWriteCanDelete] += 1
}
if diskSpaceLow {
counts[stats.IsDiskSpaceLow] += 1
}
}
if _, exist := collectionVolumeReadOnlyCount[v.Collection]; !exist {
collectionVolumeReadOnlyCount[v.Collection] = map[string]uint8{
stats.IsReadOnly: 0,
stats.NoWriteOrDelete: 0,
stats.NoWriteCanDelete: 0,
stats.IsDiskSpaceLow: 0,
}
}
if !shouldDeleteVolume && v.IsReadOnly() {
collectionVolumeReadOnlyCount[v.Collection][stats.IsReadOnly] += 1
if v.noWriteOrDelete {
collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteOrDelete] += 1
}
if v.noWriteCanDelete {
collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteCanDelete] += 1
}
if v.location.isDiskSpaceLow.Load() {
collectionVolumeReadOnlyCount[v.Collection][stats.IsDiskSpaceLow] += 1
}
}
}
@@ -619,20 +618,16 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
}
}
// collectionVolumeReadOnlyCount has an entry for every collection that kept
// a volume through this pass, including the ones counting zero read-only
// volumes.
for col := range s.reportedCollections {
if _, stillHere := collectionVolumeReadOnlyCount[col]; !stillHere {
stats.DeleteVolumeServerCollectionMetrics(col)
}
}
s.reportedCollections = make(map[string]struct{}, len(collectionVolumeReadOnlyCount))
for col := range collectionVolumeReadOnlyCount {
s.reportedCollections[col] = struct{}{}
// A delta says nothing through silence, so volumes gone since the last
// report -- a deleted collection, an expired ttl -- must be named, or the
// master counts them until a digest mismatch buys it a full list. A full
// list needs no such naming: it is already the whole truth.
var departedVolumes []*master_pb.VolumeShortInformationMessage
if !sendFullList {
departedVolumes = s.volumeReport.departed(reported)
}
departedVolumes := s.volumeReport.commit(reportPass, reportGeneration, sendFullList)
s.volumeReport.commit(reported, reportGeneration)
// has_no_volumes says the server holds nothing, so it may only be derived
// from a full list. Deriving it from a changed-only heartbeat would make a
@@ -1,182 +0,0 @@
package storage
import (
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
)
// fillTestVolume writes one needle and dates the volume now. A volume with no
// content never expires, and the needle carries no append time of its own,
// which would leave the volume dated to the epoch.
func fillTestVolume(t *testing.T, v *Volume) {
t.Helper()
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(v.Id)), true, false, false); err != nil {
t.Fatalf("write needle: %v", err)
}
v.lastModifiedTsSeconds = uint64(time.Now().Unix())
}
// The per-collection gauges are only ever set for collections the heartbeat
// still finds on this server. A volume.balance that moves a collection's last
// volume off a server used to leave its read-only count - marked read-only for
// the move, moments before it went - standing on that server until a restart,
// with nothing in volume.list to match it.
func TestCollectHeartbeatClearsMetricsOfDepartedCollection(t *testing.T) {
stats.VolumeServerReadOnlyVolumeGauge.Reset()
stats.VolumeServerDiskSizeGauge.Reset()
t.Cleanup(stats.VolumeServerReadOnlyVolumeGauge.Reset)
t.Cleanup(stats.VolumeServerDiskSizeGauge.Reset)
store := newTestStore(t, 1)
mountTestVolume(t, store.Locations[0], 1, "pics").noWriteOrDelete = true
store.CollectHeartbeat()
if got := testutil.ToFloat64(stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues("pics", stats.IsReadOnly)); got != 1 {
t.Fatalf("read-only volumes of pics = %v, want 1", got)
}
if err := store.UnmountVolume(1); err != nil {
t.Fatalf("UnmountVolume: %v", err)
}
store.CollectHeartbeat()
if n := testutil.CollectAndCount(stats.VolumeServerReadOnlyVolumeGauge); n != 0 {
t.Errorf("%d read-only series left after the collection left the server", n)
}
if n := testutil.CollectAndCount(stats.VolumeServerDiskSizeGauge); n != 0 {
t.Errorf("%d disk size series left after the collection left the server", n)
}
}
// A volume being deleted for expiry is already gone as far as the gauges are
// concerned, so the heartbeat that drops the collection's last one has to take
// its series along rather than leave them standing for another pass.
func TestCollectHeartbeatClearsMetricsWhenTheLastVolumeExpires(t *testing.T) {
stats.VolumeServerReadOnlyVolumeGauge.Reset()
stats.VolumeServerDiskSizeGauge.Reset()
t.Cleanup(stats.VolumeServerReadOnlyVolumeGauge.Reset)
t.Cleanup(stats.VolumeServerDiskSizeGauge.Reset)
store := newTestStore(t, 1)
store.SetVolumeSizeLimit(30 << 30)
v := mountTestVolume(t, store.Locations[0], 1, "pics")
v.Ttl = &needle.TTL{Count: 1, Unit: needle.Minute}
fillTestVolume(t, v)
store.CollectHeartbeat()
if got := testutil.ToFloat64(stats.VolumeServerDiskSizeGauge.WithLabelValues("pics", "normal")); got == 0 {
t.Fatal("disk size of pics = 0, want the written needle")
}
v.lastModifiedTsSeconds = uint64(time.Now().Add(-time.Hour).Unix())
store.CollectHeartbeat()
if store.findVolume(1) != nil {
t.Fatal("the expired volume outlived the heartbeat")
}
if n := testutil.CollectAndCount(stats.VolumeServerReadOnlyVolumeGauge); n != 0 {
t.Errorf("%d read-only series left after the last volume expired", n)
}
if n := testutil.CollectAndCount(stats.VolumeServerDiskSizeGauge); n != 0 {
t.Errorf("%d disk size series left after the last volume expired", n)
}
}
// A collection that loses one volume to expiry and keeps another must report
// what is left, not what is left minus what went.
func TestCollectHeartbeatSizesOnlySurvivingVolumes(t *testing.T) {
stats.VolumeServerDiskSizeGauge.Reset()
t.Cleanup(stats.VolumeServerDiskSizeGauge.Reset)
store := newTestStore(t, 2)
store.SetVolumeSizeLimit(30 << 30)
// One volume per location, so the surviving one is always scanned first.
surviving := mountTestVolume(t, store.Locations[0], 1, "pics")
fillTestVolume(t, surviving)
expiring := mountTestVolume(t, store.Locations[1], 2, "pics")
expiring.Ttl = &needle.TTL{Count: 1, Unit: needle.Minute}
fillTestVolume(t, expiring)
// Both volumes carry deleted bytes, which are totalled the same way.
for _, v := range []*Volume{surviving, expiring} {
n := newRandomNeedle(uint64(v.Id) + 100)
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle: %v", err)
}
if _, err := v.deleteNeedle2(n); err != nil {
t.Fatalf("delete needle: %v", err)
}
}
heartbeat := store.CollectHeartbeat()
var survivingSize, survivingDeleted uint64
for _, m := range heartbeat.Volumes {
if m.Id == 1 {
survivingSize, survivingDeleted = m.Size, m.DeletedByteCount
}
}
if survivingSize == 0 || survivingDeleted == 0 {
t.Fatalf("the surviving volume reported size %d and %d deleted bytes, want both", survivingSize, survivingDeleted)
}
expiring.lastModifiedTsSeconds = uint64(time.Now().Add(-time.Hour).Unix())
store.CollectHeartbeat()
if store.findVolume(1) == nil {
t.Fatal("the volume without a ttl was deleted")
}
if got := testutil.ToFloat64(stats.VolumeServerDiskSizeGauge.WithLabelValues("pics", "normal")); got != float64(survivingSize) {
t.Errorf("disk size of pics = %v, want %d, the volume still here", got, survivingSize)
}
if got := testutil.ToFloat64(stats.VolumeServerDiskSizeGauge.WithLabelValues("pics", "deleted_bytes")); got != float64(survivingDeleted) {
t.Errorf("deleted bytes of pics = %v, want %d, the volume still here", got, survivingDeleted)
}
}
// The counts are per collection and per server, and a server holds far more
// than 255 volumes of one collection.
func TestCollectHeartbeatCountsPast255ReadOnlyVolumes(t *testing.T) {
stats.VolumeServerReadOnlyVolumeGauge.Reset()
t.Cleanup(stats.VolumeServerReadOnlyVolumeGauge.Reset)
store := newTestStore(t, 1)
const readOnlyVolumes = 300
for i := 1; i <= readOnlyVolumes; i++ {
mountTestVolume(t, store.Locations[0], needle.VolumeId(i), "pics")
store.findVolume(needle.VolumeId(i)).noWriteOrDelete = true
}
store.CollectHeartbeat()
if got := testutil.ToFloat64(stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues("pics", stats.IsReadOnly)); got != readOnlyVolumes {
t.Errorf("read-only volumes of pics = %v, want %d", got, readOnlyVolumes)
}
}
func TestCollectErasureCodingHeartbeatClearsMetricsOfDepartedCollection(t *testing.T) {
stats.VolumeServerDiskSizeGauge.Reset()
t.Cleanup(stats.VolumeServerDiskSizeGauge.Reset)
store, _, vid, collection, plant := setupECStoreWithMixedDisks(t)
plant()
if err := store.MountEcShards(collection, vid, 0, ""); err != nil {
t.Fatalf("MountEcShards: %v", err)
}
store.CollectErasureCodingHeartbeat()
if got := testutil.ToFloat64(stats.VolumeServerDiskSizeGauge.WithLabelValues(collection, "ec")); got == 0 {
t.Fatalf("ec disk size of %s = 0, want the mounted shard's size", collection)
}
if err := store.UnmountEcShards(vid, erasure_coding.ShardId(0), 0); err != nil {
t.Fatalf("UnmountEcShards: %v", err)
}
store.CollectErasureCodingHeartbeat()
if n := testutil.CollectAndCount(stats.VolumeServerDiskSizeGauge); n != 0 {
t.Errorf("%d disk size series left after the collection's shards left the server", n)
}
}
-10
View File
@@ -153,16 +153,6 @@ func (s *Store) CollectErasureCodingHeartbeat() *master_pb.Heartbeat {
stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "ec").Set(float64(size))
}
for col := range s.reportedEcCollections {
if _, stillHere := collectionEcShardSize[col]; !stillHere {
stats.VolumeServerDiskSizeGauge.DeleteLabelValues(col, "ec")
}
}
s.reportedEcCollections = make(map[string]struct{}, len(collectionEcShardSize))
for col := range collectionEcShardSize {
s.reportedEcCollections[col] = struct{}{}
}
return &master_pb.Heartbeat{
EcShards: ecShardMessages,
HasNoEcShards: len(ecShardMessages) == 0,
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more