Compare commits

..
Author SHA1 Message Date
Chris Lu 6d0489de6e metrics: graph the plugin workers
Nothing displayed the worker metrics, and the panels that look like they
did are about something else: Workers Connected, Worker Slots and Worker
Events in the Admin / Maintenance row read SeaweedFS_admin_*, which the
older maintenance queue feeds. A cluster running plugin workers - Go or
Rust - reads zero there while they are connected and busy.

A Plugin Workers row graphs what the workers themselves publish: how many
are connected, jobs and their failures, detection and proposal rates, job
duration, slot usage, stream events, and what the Lance jobs reclaimed.
The panel worth having is Objects Seen vs Skipped, since a sweep with
nothing to do and a sweep that could read nothing report the same number
of proposals.

Also a commented scrape target in the sample Prometheus config. It is 9328
rather than 9327: the sample compose already gives 9327 to the S3 gateway,
so the port the worker's own usage text suggests collides with it on a
single host.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-20 10:44:32 -07:00
Chris Lu 88d61ca4cd seaweed-worker: fix the metrics address, the count, and a dead field
Three from review.

--metrics-ip ::1 failed at startup: the address was built by joining host
and port with a colon, and "::1:9327" is not an address. It is parsed as a
host and combined with SocketAddr::new now, so an IPv6 literal works, with
or without the brackets an operator will reasonably type after seeing one
in a URL.

proposals_total counted before the send rather than after, so a stream
that closed mid-sweep left the counter claiming proposals admin never
received.

And MeteredSender carried a Metrics clone and a job type it never read,
kept alive by two statements that existed only to silence the warning
about them. Everything is recorded by the caller, so both are gone.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-20 08:43:00 -07:00
Chris Lu 99975a527a seaweed-worker: serve health, readiness and metrics
A Rust worker had no surface of its own. If it wedged, the only signals
were its stdout and whatever admin could infer from a stream that had gone
quiet; nothing could be scraped and nothing could be alerted on.

--metrics-port serves /health, /ready and /metrics, the same three the Go
worker serves under -metricsPort, so one scrape config covers workers in
either language. Off by default, loopback unless --metrics-ip says
otherwise, since the endpoint is unauthenticated. Names follow the Go
convention, SeaweedFS_worker_*.

The counters live in core and are raised where the stream already knows
what happened - connect, close, detection, execution, preview - so a
worker for another format gets them without writing any of this. Slots are
published from the heartbeat that already computes them, so a scrape and
the admin UI cannot disagree.

The pair worth having is objects_seen_total and objects_skipped_total. A
sweep that proposed nothing because there was nothing to do and a sweep
that proposed nothing because it could not read anything are the same
number of proposals; they are not the same event, and until now only a log
line told them apart.

The Lance jobs add what they reclaimed - fragments, rows brought under an
index, versions, bytes - on the same registry, so one endpoint serves both.

Claude-Session: https://claude.ai/code/session_01Rkp1Mw5E89Jp6dzJFYiMrm
2026-08-19 23:16:40 -07:00
165 changed files with 1399 additions and 13608 deletions

No files matched your search

+5 -39
View File
@@ -6,7 +6,6 @@ on:
paths:
- 'weed/**'
- 'seaweed-volume/**'
- 'seaweed-worker/**'
- 'docker/**'
- 'go.mod'
- 'go.sum'
@@ -17,7 +16,7 @@ permissions:
jobs:
# ── Pre-build the Rust binaries natively ────────────────────────────
# ── Pre-build Rust volume server binaries natively ──────────────────
build-rust-binaries:
runs-on: ubuntu-22.04
strategy:
@@ -56,26 +55,10 @@ jobs:
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
seaweed-worker/target/${{ matrix.target }}/release
key: rust-docker-dev-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/Cargo.lock') }}
key: rust-docker-dev-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
restore-keys: |
rust-docker-dev-${{ matrix.target }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
# own build already uses, so no job depends on a system package and every
# build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-worker
cargo fetch
# The version from the lock, not whatever else a restored cache holds.
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build normal variant
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -84,19 +67,11 @@ jobs:
cargo build --release --target ${{ matrix.target }} --no-default-features
cp target/${{ matrix.target }}/release/weed-volume ../weed-volume-normal-${{ matrix.arch }}
- name: Build the Rust maintenance worker
run: |
cd seaweed-worker
cargo build --release -p weed-lance-worker --target ${{ matrix.target }}
cp target/${{ matrix.target }}/release/weed-worker ../weed-worker-${{ matrix.arch }}
- name: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: rust-bins-${{ matrix.arch }}
path: |
weed-volume-normal-${{ matrix.arch }}
weed-worker-${{ matrix.arch }}
name: rust-volume-${{ matrix.arch }}
path: weed-volume-normal-${{ matrix.arch }}
build-dev-containers:
needs: [build-rust-binaries]
@@ -109,7 +84,7 @@ jobs:
- name: Download pre-built Rust binaries
uses: actions/download-artifact@v8
with:
pattern: rust-bins-*
pattern: rust-volume-*
merge-multiple: true
path: ./rust-bins
@@ -123,16 +98,7 @@ jobs:
echo "Placed pre-built Rust binary for ${arch}"
fi
done
mkdir -p docker/weed-worker-prebuilt
for arch in amd64 arm64; do
src="./rust-bins/weed-worker-${arch}"
if [ -f "$src" ]; then
cp "$src" "docker/weed-worker-prebuilt/weed-worker-${arch}"
echo "Placed pre-built Rust worker for ${arch}"
fi
done
ls -la docker/weed-volume-prebuilt/
ls -la docker/weed-worker-prebuilt/
- name: Docker meta
id: docker_meta
+5 -46
View File
@@ -59,7 +59,7 @@ jobs:
echo "publish=true" >> "$GITHUB_OUTPUT"
fi
# ── Pre-build the Rust binaries natively ────────────────────────────
# ── Pre-build Rust volume server binaries natively ──────────────────
build-rust-binaries:
runs-on: ubuntu-22.04
strategy:
@@ -100,26 +100,10 @@ jobs:
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
seaweed-worker/target/${{ matrix.target }}/release
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/Cargo.lock') }}
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
restore-keys: |
rust-docker-${{ matrix.target }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
# own build already uses, so no job depends on a system package and every
# build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-worker
cargo fetch
# The version from the lock, not whatever else a restored cache holds.
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build large-disk variant
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -136,20 +120,13 @@ jobs:
cargo build --release --target ${{ matrix.target }} --no-default-features
cp target/${{ matrix.target }}/release/weed-volume ../weed-volume-normal-${{ matrix.arch }}
- name: Build the Rust maintenance worker
run: |
cd seaweed-worker
cargo build --release -p weed-lance-worker --target ${{ matrix.target }}
cp target/${{ matrix.target }}/release/weed-worker ../weed-worker-${{ matrix.arch }}
- name: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: rust-bins-${{ matrix.arch }}
name: rust-volume-${{ matrix.arch }}
path: |
weed-volume-large-disk-${{ matrix.arch }}
weed-volume-normal-${{ matrix.arch }}
weed-worker-${{ matrix.arch }}
build:
needs: [setup, build-rust-binaries]
@@ -197,7 +174,7 @@ jobs:
- name: Download pre-built Rust binaries
uses: actions/download-artifact@v8
with:
pattern: rust-bins-*
pattern: rust-volume-*
merge-multiple: true
path: ./rust-bins
@@ -211,16 +188,7 @@ jobs:
echo "Placed pre-built Rust binary for ${arch}"
fi
done
mkdir -p docker/weed-worker-prebuilt
for arch in amd64 arm64; do
src="./rust-bins/weed-worker-${arch}"
if [ -f "$src" ]; then
cp "$src" "docker/weed-worker-prebuilt/weed-worker-${arch}"
echo "Placed pre-built Rust worker for ${arch}"
fi
done
ls -la docker/weed-volume-prebuilt/
ls -la docker/weed-worker-prebuilt/
- name: Docker meta
id: docker_meta
@@ -318,7 +286,7 @@ jobs:
if: needs.setup.outputs.publish != 'true'
uses: actions/download-artifact@v8
with:
pattern: rust-bins-*
pattern: rust-volume-*
merge-multiple: true
path: ./rust-bins
- name: Place Rust binaries in Docker context for local scan
@@ -336,16 +304,7 @@ jobs:
echo "Placed pre-built Rust binary for ${arch}"
fi
done
mkdir -p docker/weed-worker-prebuilt
for arch in amd64 arm64; do
src="./rust-bins/weed-worker-${arch}"
if [ -f "$src" ]; then
cp "$src" "docker/weed-worker-prebuilt/weed-worker-${arch}"
echo "Placed pre-built Rust worker for ${arch}"
fi
done
ls -la docker/weed-volume-prebuilt/
ls -la docker/weed-worker-prebuilt/
- name: Create BuildKit config for local scan build
if: needs.setup.outputs.publish != 'true'
run: |
@@ -42,10 +42,9 @@ concurrency:
jobs:
# ── Pre-build the Rust binaries natively ────────────────────────────
# The volume server and the Rust maintenance worker, cross-compiled for
# amd64 and arm64 without QEMU, turning a 5-hour emulated cargo build into
# ~15 minutes of native compilation.
# ── Pre-build Rust volume server binaries natively ──────────────────
# Cross-compiles for amd64 and arm64 without QEMU, turning a 5-hour
# emulated cargo build into ~15 minutes of native compilation.
build-rust-binaries:
runs-on: ubuntu-22.04
strategy:
@@ -84,26 +83,10 @@ jobs:
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
seaweed-worker/target/${{ matrix.target }}/release
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/Cargo.lock') }}
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
restore-keys: |
rust-docker-${{ matrix.target }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
# own build already uses, so no job depends on a system package and every
# build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-worker
cargo fetch
# The version from the lock, not whatever else a restored cache holds.
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build large-disk variant
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -120,20 +103,13 @@ jobs:
cargo build --release --target ${{ matrix.target }} --no-default-features
cp target/${{ matrix.target }}/release/weed-volume ../weed-volume-normal-${{ matrix.arch }}
- name: Build the Rust maintenance worker
run: |
cd seaweed-worker
cargo build --release -p weed-lance-worker --target ${{ matrix.target }}
cp target/${{ matrix.target }}/release/weed-worker ../weed-worker-${{ matrix.arch }}
- name: Upload artifacts
uses: actions/upload-artifact@v7
with:
name: rust-bins-${{ matrix.arch }}
name: rust-volume-${{ matrix.arch }}
path: |
weed-volume-large-disk-${{ matrix.arch }}
weed-volume-normal-${{ matrix.arch }}
weed-worker-${{ matrix.arch }}
# One job per (variant, platform) on a native runner, pushed by digest;
# the merge job stitches the digests into one multi-arch tag.
@@ -179,7 +155,7 @@ jobs:
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: actions/download-artifact@v8
with:
pattern: rust-bins-*
pattern: rust-volume-*
merge-multiple: true
path: ./rust-bins
@@ -194,16 +170,7 @@ jobs:
echo "Placed pre-built Rust binary for ${arch}"
fi
done
mkdir -p docker/weed-worker-prebuilt
for arch in amd64 arm64; do
src="./rust-bins/weed-worker-${arch}"
if [ -f "$src" ]; then
cp "$src" "docker/weed-worker-prebuilt/weed-worker-${arch}"
echo "Placed pre-built Rust worker for ${arch}"
fi
done
ls -la docker/weed-volume-prebuilt/
ls -la docker/weed-worker-prebuilt/
- name: Free Disk Space
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
+4 -108
View File
@@ -3,10 +3,10 @@ name: "helm: lint and test charts"
on:
push:
branches: [ master ]
paths: ['k8s/**', '.github/workflows/helm_ci.yml']
paths: ['k8s/**']
pull_request:
branches: [ master ]
paths: ['k8s/**', '.github/workflows/helm_ci.yml']
paths: ['k8s/**']
permissions:
contents: read
@@ -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
@@ -1549,37 +1472,11 @@ jobs:
echo "All template rendering tests passed!"
- name: Resolve an image tag that is published
run: |
set -e
# A release bumps appVersion on master ~40 minutes before the container
# build publishes that tag, and this workflow runs on the bump commit.
# Install the last released image for the length of that window instead
# of failing on ImagePullBackOff.
IMAGE=$(helm template test k8s/charts/seaweedfs \
-s templates/master/master-statefulset.yaml | awk '$1 == "image:" {print $2; exit}')
REPO=${IMAGE%:*}
TAG=${IMAGE##*:}
# Anything but a published tag installs latest, which between releases
# is the same digest as the chart's own appVersion, so a registry blip
# costs nothing while failing the job on one would cost a red build.
STATUS=$(curl -sSL --connect-timeout 5 --max-time 15 -o /dev/null \
-w '%{http_code}' "https://hub.docker.com/v2/repositories/$REPO/tags/$TAG" || true)
if [ "$STATUS" = 200 ]; then
echo "installing $IMAGE"
else
echo "$IMAGE is unavailable (HTTP ${STATUS:-none}), installing $REPO:latest"
TAG=latest
fi
echo "IMAGE_TAG=$TAG" >> $GITHUB_ENV
- name: Create kind cluster
uses: helm/kind-action@v1.14.0
- name: Run chart-testing (install)
run: |
ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts \
--helm-extra-set-args "--set=image.tag=$IMAGE_TAG"
run: ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts
- name: Verify SFTP host key secret lifecycle
run: |
@@ -1587,7 +1484,7 @@ jobs:
CHART_DIR="k8s/charts/seaweedfs"
NS="sftp-hostkey"
SECRET="hk-seaweedfs-sftp-ssh-secret"
SFTP_ARGS="--set image.tag=$IMAGE_TAG --set sftp.enabled=true --set master.enabled=false --set volume.enabled=false --set filer.enabled=false"
SFTP_ARGS="--set sftp.enabled=true --set master.enabled=false --set volume.enabled=false --set filer.enabled=false"
kubectl create namespace "$NS"
echo "=== install generates a host key, upgrade keeps it ==="
@@ -1664,7 +1561,6 @@ jobs:
# release if the hook Job does not finish, so a clean install is the
# assertion.
helm install np $CHART_DIR -n "$NS" --wait --timeout 8m \
--set image.tag=$IMAGE_TAG \
--set s3.enabled=true \
--set s3.createBuckets[0].name=testbucket \
--set networkPolicy.enabled=true \
+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
-82
View File
@@ -1,82 +0,0 @@
name: "Rust Plugin Worker Tests"
on:
pull_request:
branches: [ master ]
paths:
- 'seaweed-worker/**'
- 'weed/pb/plugin.proto'
- '.github/workflows/rust-worker-tests.yml'
push:
branches: [ master, main ]
paths:
- 'seaweed-worker/**'
- 'weed/pb/plugin.proto'
- '.github/workflows/rust-worker-tests.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
rust-worker-build:
name: Rust Plugin Worker Build and Unit Tests
runs-on: ubuntu-22.04
timeout-minutes: 45
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
# cargo tracks its own inputs but not the runner's C toolchain, so a cached
# target/ can carry C objects built against a different glibc than we link against.
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-worker/target/release
key: rust-worker-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-worker/Cargo.lock') }}
restore-keys: |
rust-worker-${{ steps.toolchain.outputs.fingerprint }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
# own build already uses, so no job depends on a system package and every
# build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-worker
cargo fetch
# The version from the lock, not whatever else a restored cache holds.
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
# The release profile is what ships, and it is where the release and the
# container builds would otherwise discover a break for the first time.
- name: Build the plugin workers
run: cd seaweed-worker && cargo build --release
# The tests that need a live gateway skip themselves without one, the way
# the Go integration tests skip without Docker; the lifecycle suite in
# test/s3tables/lifecycle is what runs them against a real cluster.
# Release, so this reuses the build above rather than compiling lance,
# arrow and datafusion a second time in another profile.
- name: Run unit tests
run: cd seaweed-worker && cargo test --release --workspace
+1 -97
View File
@@ -1,4 +1,4 @@
name: "rust: build versioned binaries"
name: "rust: build versioned volume server binaries"
on:
push:
@@ -113,102 +113,6 @@ jobs:
weed-volume_${{ matrix.asset_suffix }}.tar.gz
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
# The Rust maintenance worker: Linux only, because it runs beside the cluster
# it maintains rather than on a laptop, and its dependency tree (lance, arrow,
# datafusion) makes every extra target an expensive build.
build-rust-worker-linux:
permissions:
contents: write
runs-on: ubuntu-22.04
strategy:
matrix:
include:
- target: x86_64-unknown-linux-gnu
asset_suffix: linux_amd64
- target: aarch64-unknown-linux-gnu
asset_suffix: linux_arm64
cross: true
steps:
- uses: actions/checkout@v7
with:
# The upload step is handed a token explicitly; a cargo build script
# should not find another one sitting in the checkout's git config.
persist-credentials: false
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Install cross-compilation tools
if: matrix.cross
run: |
sudo dpkg --add-architecture arm64
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-worker/target/${{ matrix.target }}/release
key: rust-worker-release-${{ matrix.target }}-${{ hashFiles('seaweed-worker/Cargo.lock') }}
restore-keys: |
rust-worker-release-${{ matrix.target }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
# own build already uses, so no job depends on a system package and every
# build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-worker
cargo fetch
# The version from the lock, not whatever else a restored cache holds.
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build the Rust maintenance worker
run: |
cd seaweed-worker
cargo build --release -p weed-lance-worker --target ${{ matrix.target }}
- name: Package binary
run: |
cp seaweed-worker/target/${{ matrix.target }}/release/weed-worker weed-worker
tar czf weed-worker_${{ matrix.asset_suffix }}.tar.gz weed-worker
rm weed-worker
md5sum weed-worker_${{ matrix.asset_suffix }}.tar.gz > weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
- name: Upload release assets
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v3
with:
files: |
weed-worker_${{ matrix.asset_suffix }}.tar.gz
weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload artifacts
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
uses: actions/upload-artifact@v7
with:
name: rust-worker-${{ matrix.asset_suffix }}
path: |
weed-worker_${{ matrix.asset_suffix }}.tar.gz
weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
build-rust-volume-darwin:
permissions:
contents: write
-288
View File
@@ -6,7 +6,6 @@ on:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/worker/tasks/iceberg/**'
- 'test/s3tables/**'
- 'go.mod'
- 'go.sum'
@@ -875,293 +874,6 @@ jobs:
path: test/s3tables/unity_catalog/test-output.log
retention-days: 3
lancedb-namespace-tests:
name: LanceDB Namespace Integration Tests
runs-on: ubuntu-22.04
timeout-minutes: 30
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
- name: Run go mod tidy
run: go mod tidy
- name: Build SeaweedFS
run: |
cd weed && go build -buildvcs=false .
- name: Run LanceDB Namespace Integration Tests
timeout-minutes: 25
working-directory: test/s3tables/catalog_lancedb
run: |
set -x
set -o pipefail
echo "=== System Information ==="
uname -a
free -h
df -h
docker info
echo "=== Starting LanceDB Namespace Tests ==="
go test -v -timeout 20m . 2>&1 | tee test-output.log || {
echo "LanceDB namespace integration tests failed"
exit 1
}
- name: Show test output on failure
if: failure()
working-directory: test/s3tables/catalog_lancedb
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: lancedb-namespace-test-logs
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
timeout-minutes: 40
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 apache/spark:3.5.1
- name: Run go mod tidy
run: go mod tidy
- name: Build SeaweedFS
run: |
cd weed && go build -buildvcs=false .
- name: Run Spark Lance Namespace Integration Tests
timeout-minutes: 35
working-directory: test/s3tables/catalog_spark_lance
run: |
set -x
set -o pipefail
echo "=== System Information ==="
uname -a
free -h
df -h
docker info
echo "=== Starting Spark Lance Namespace Tests ==="
go test -v -timeout 30m . 2>&1 | tee test-output.log || {
echo "Spark Lance namespace integration tests failed"
exit 1
}
- name: Show test output on failure
if: failure()
working-directory: test/s3tables/catalog_spark_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|spark)" || true
- name: Upload test logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: spark-lance-namespace-test-logs
path: test/s3tables/catalog_spark_lance/test-output.log
retention-days: 3
s3-tables-build-verification:
name: S3 Tables Build Verification
runs-on: ubuntu-22.04
+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
+2 -17
View File
@@ -29,7 +29,6 @@ FROM alpine:3.23 as rust_builder
ARG TARGETARCH
ARG TAGS
COPY weed-volume-prebuilt/ /prebuilt/
COPY weed-worker-prebuilt/ /prebuilt-worker/
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/seaweed-volume /build/seaweed-volume
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/weed /build/weed
WORKDIR /build/seaweed-volume
@@ -48,30 +47,16 @@ RUN if [ -f "/prebuilt/weed-volume-${TARGETARCH}" ]; then \
echo "Skipping Rust build for $TARGETARCH (unsupported)" && \
touch /weed-volume; \
fi
# The Rust maintenance worker is taken pre-built or not at all: the lance jobs
# it carries pull in arrow and datafusion, a far larger dependency tree than
# the image build can carry, so an architecture CI did not build for gets the
# same empty placeholder the entrypoint refuses to exec.
RUN if [ -f "/prebuilt-worker/weed-worker-${TARGETARCH}" ]; then \
echo "Using pre-built Rust worker for ${TARGETARCH}" && \
cp "/prebuilt-worker/weed-worker-${TARGETARCH}" /weed-worker; \
else \
echo "No pre-built Rust worker for ${TARGETARCH}" && \
touch /weed-worker; \
fi
# Pre-built binaries arrive via GitHub Actions artifacts, which drop the
# executable bit, so the copied file is 0644 and exec fails with "Permission
# denied". Restore it (no-op for the empty placeholders, which stay size 0).
RUN chmod 0755 /weed-volume /weed-worker
# denied". Restore it (no-op for the empty placeholder, which stays size 0).
RUN chmod 0755 /weed-volume
FROM alpine AS final
LABEL author="Chris Lu"
COPY --from=builder /go/bin/weed /usr/bin/
# Copy Rust volume server binary (real binary on amd64/arm64, empty placeholder on other platforms)
COPY --from=rust_builder /weed-volume /usr/bin/weed-volume
# Same for the Rust maintenance worker, which serves Lance table buckets
COPY --from=rust_builder /weed-worker /usr/bin/weed-worker
RUN mkdir -p /etc/seaweedfs
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
-10
View File
@@ -90,16 +90,6 @@ case "$1" in
exec /usr/bin/weed-volume $ARGS $@
;;
'worker-rust')
shift
if [ ! -s /usr/bin/weed-worker ]; then
echo "Error: Rust maintenance worker is not available on this platform ($(uname -m))." >&2
echo "Use 'worker' for the Go maintenance worker instead." >&2
exit 1
fi
exec /usr/bin/weed-worker "$@"
;;
'server')
ARGS="-dir=/data -volume.max=0 -master.volumeSizeLimitMB=1024"
if isArgPassed "-volume.max" "$@"; then
Whitespace-only changes.
+4 -4
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
@@ -238,12 +238,12 @@ require (
github.com/lpar/calendar v0.2.0 // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.3.0 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/moby/api v1.54.2 // indirect
github.com/moby/moby/client v0.4.0 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.1 // indirect
github.com/moby/sys/sequential v0.6.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/oklog/ulid/v2 v2.1.1 // indirect
+8 -8
View File
@@ -1543,8 +1543,8 @@ github.com/moby/buildkit v0.29.0 h1:wxLEFbCOJntEDjSNNN2YWd8zxltZxT5muDQ0LzpbtpU=
github.com/moby/buildkit v0.29.0/go.mod h1:Dmv2FeDe34t75QuzeU87rBoZpAAkcpT5zeu4hXzmASc=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c=
github.com/moby/go-archive v0.3.0/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg=
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
@@ -1559,14 +1559,14 @@ github.com/moby/sys/capability v0.4.0 h1:4D4mI6KlNtWMCM1Z/K0i7RV1FkX+DBDHKVJpCnd
github.com/moby/sys/capability v0.4.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I=
github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg=
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
github.com/moby/sys/signal v0.7.1 h1:PrQxdvxcGijdo6UXXo/lU/TvHUWyPhj7UOpSo8tuvk0=
github.com/moby/sys/signal v0.7.1/go.mod h1:Se1VGehYokAkrSQwL4tDzHvETwUZlnY7S5XtQ50mQp8=
github.com/moby/sys/symlink v0.3.0 h1:GZX89mEZ9u53f97npBy4Rc3vJKj7JBDj/PN2I22GrNU=
github.com/moby/sys/symlink v0.3.0/go.mod h1:3eNdhduHmYPcgsJtZXW1W4XUJdZGBIkttZ8xKqPUJq0=
github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0=
github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y=
github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs=
github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
@@ -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 -84
View File
@@ -9,7 +9,7 @@
# curl -fsSL ... | bash -s -- --version 4.34 --dir /usr/local/bin
#
# Options:
# --component COMP Which binary to install: weed, volume-rust, worker-rust, all (default: weed)
# --component COMP Which binary to install: weed, volume-rust, all (default: weed)
# --version VER Release version tag (default: latest)
# --large-disk Use large disk variant (5-byte offset, 8TB max volume)
# --dir DIR Installation directory (default: /usr/local/bin)
@@ -22,7 +22,6 @@ COMPONENT="weed"
VERSION=""
LARGE_DISK=false
INSTALL_DIR="/usr/local/bin"
WORKER_INSTALLED=false
# Colors (if terminal supports them)
if [ -t 1 ]; then
@@ -129,33 +128,6 @@ rust_asset_name() {
fi
}
# Does a release carry this asset? Answers 0 for yes and 1 for a 404, and stops
# the installer on anything else: a rate limit or a network blip must not read
# as "this release predates the binary" and quietly skip it.
asset_exists() {
local url="$1" code=""
if command -v curl &>/dev/null; then
code="$(curl -sL -o /dev/null -I -w '%{http_code}' "$url" || true)"
elif command -v wget &>/dev/null; then
# --spider's exit status folds 404 in with every other server error, so
# read the status line itself; -S prints one per redirect hop.
code="$(wget -S --spider -q -O /dev/null "$url" 2>&1 | awk '/^ *HTTP\// {c=$2} END {print c}')"
fi
case "$code" in
200) return 0 ;;
404) return 1 ;;
*) error "Could not check ${url} (HTTP ${code:-none}). Retry, or install components one at a time." ;;
esac
}
# Build Rust maintenance worker asset name. No large-disk variant: the worker
# maintains tables through the namespace and never opens a volume file.
worker_asset_name() {
local os="$1" arch="$2"
echo "weed-worker_${os}_${arch}.tar.gz"
}
# Install a single component
install_component() {
local component="$1" os="$2" arch="$3"
@@ -232,48 +204,10 @@ install_component() {
ok "Installed weed-volume to ${INSTALL_DIR}/${dest_name}"
;;
worker-rust)
# Published for linux only: the worker runs beside the cluster it
# maintains, and its dependency tree makes every extra target an
# expensive build.
case "$os" in
linux) ;;
*) error "Rust maintenance worker is not available for ${os}. Supported: linux" ;;
esac
case "$arch" in
amd64|arm64) ;;
*) error "Rust maintenance worker is not available for ${arch}. Supported: amd64, arm64" ;;
esac
asset_name="$(worker_asset_name "$os" "$arch")"
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
download "$download_url" "${tmpdir}/${asset_name}"
info "Extracting ${asset_name}..."
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
local worker_bin
worker_bin="$(find "$tmpdir" -name 'weed-worker' -type f | head -1)"
if [ -z "$worker_bin" ]; then
error "Could not find weed-worker binary in archive"
fi
chmod +x "$worker_bin"
install_binary "$worker_bin" "weed-worker"
WORKER_INSTALLED=true
ok "Installed weed-worker to ${INSTALL_DIR}/weed-worker"
;;
*)
error "Unknown component: ${component}. Use: weed, volume-rust, worker-rust, all"
error "Unknown component: ${component}. Use: weed, volume-rust, all"
;;
esac
# The trap is per-process, so a later component's would replace this one and
# leave the earlier extraction behind. Clean up here and hand the trap back;
# the error paths above exit, which still fires it.
rm -rf "$tmpdir"
trap - EXIT
}
# Copy binary to install dir, using sudo if needed
@@ -317,16 +251,6 @@ main() {
all)
install_component "weed" "$os" "$arch"
install_component "volume-rust" "$os" "$arch"
# The worker is published for linux amd64/arm64 only, and only by
# releases new enough to carry it; skip either case rather than fail
# an install that has already put two binaries in place.
if [ "$os" != "linux" ] || { [ "$arch" != "amd64" ] && [ "$arch" != "arm64" ]; }; then
warn "Skipping the Rust maintenance worker: no build for ${os}/${arch}"
elif ! asset_exists "https://github.com/${REPO}/releases/download/${VERSION}/$(worker_asset_name "$os" "$arch")"; then
warn "Skipping the Rust maintenance worker: ${VERSION} does not carry one"
else
install_component "worker-rust" "$os" "$arch"
fi
;;
*)
install_component "$COMPONENT" "$os" "$arch"
@@ -341,17 +265,11 @@ main() {
if [ "$COMPONENT" = "volume-rust" ] || [ "$COMPONENT" = "all" ]; then
info " weed-volume: ${INSTALL_DIR}/weed-volume"
fi
if [ "$WORKER_INSTALLED" = true ]; then
info " weed-worker: ${INSTALL_DIR}/weed-worker"
fi
echo ""
info "Quick start:"
info " weed master # Start master server"
info " weed volume -mserver=localhost:9333 # Start Go volume server"
info " weed-volume -mserver localhost:9333 # Start Rust volume server"
if [ "$WORKER_INSTALLED" = true ]; then
info " weed-worker --admin localhost:23646 # Start the Rust maintenance worker"
fi
}
main
+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`
-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);
}
}
}
-65
View File
@@ -4666,70 +4666,6 @@ dependencies = [
"prost 0.14.4",
]
[[package]]
name = "protoc-bin-vendored"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa"
dependencies = [
"protoc-bin-vendored-linux-aarch_64",
"protoc-bin-vendored-linux-ppcle_64",
"protoc-bin-vendored-linux-s390_64",
"protoc-bin-vendored-linux-x86_32",
"protoc-bin-vendored-linux-x86_64",
"protoc-bin-vendored-macos-aarch_64",
"protoc-bin-vendored-macos-x86_64",
"protoc-bin-vendored-win32",
]
[[package]]
name = "protoc-bin-vendored-linux-aarch_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c"
[[package]]
name = "protoc-bin-vendored-linux-ppcle_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c"
[[package]]
name = "protoc-bin-vendored-linux-s390_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0"
[[package]]
name = "protoc-bin-vendored-linux-x86_32"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5"
[[package]]
name = "protoc-bin-vendored-linux-x86_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78"
[[package]]
name = "protoc-bin-vendored-macos-aarch_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092"
[[package]]
name = "protoc-bin-vendored-macos-x86_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756"
[[package]]
name = "protoc-bin-vendored-win32"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
[[package]]
name = "quick-xml"
version = "0.39.4"
@@ -5443,7 +5379,6 @@ dependencies = [
"prometheus",
"prost 0.13.5",
"prost-types 0.13.5",
"protoc-bin-vendored",
"tokio",
"tokio-stream",
"tonic",
-27
View File
@@ -12,17 +12,6 @@ one.
`core` knows nothing about any job. A second worker is a new crate beside
`lance` that depends on it, not a fork of the protocol.
## Building
`core` compiles `plugin.proto` with the protoc that protoc-bin-vendored ships,
the way seaweed-volume does, so it needs no system install.
The lance crates compile protos of their own, in their own build-script
processes, which nothing our build script sets can reach. They need a protoc of
their own: either one on PATH — `brew install protobuf`, `apt install
protobuf-compiler` — or `PROTOC` naming one. CI points it at the vendored
binary for the runner's platform, resolved from the version in `Cargo.lock`.
## Running
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646
@@ -31,22 +20,6 @@ The admin's *HTTP* address is what an operator has; the gRPC port is derived
from it the way the Go side does. Dialling the HTTP port fails as "frame with
invalid size", which reads like a protocol bug rather than a wrong port.
The binary is `weed-worker`, not `weed-lance-worker`: it is the Rust side of
`weed worker`, and lance is the first family of jobs it carries rather than the
only one it ever will.
Released builds do not need a toolchain. The worker ships inside the SeaweedFS
image, beside the Rust volume server, under the verb that mirrors
`volume-rust`:
docker run chrislusf/seaweedfs worker-rust --admin admin:23646
and as `weed-worker_linux_{amd64,arm64}.tar.gz` on each GitHub release. Both are
linux amd64/arm64 only — lance, arrow and datafusion make every extra target an
expensive build, and the worker runs beside the cluster it maintains. On an
architecture without a build the image carries an empty placeholder and the
entrypoint says so rather than failing as "not found".
## Metrics
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646 --metrics-port 9328
-4
View File
@@ -21,7 +21,3 @@ tracing.workspace = true
[build-dependencies]
tonic-build.workspace = true
# Ships protoc with the build so neither CI nor a developer needs a system
# install, and so the version is pinned rather than whatever the platform's
# package manager happens to carry. The same crate seaweed-volume uses.
protoc-bin-vendored = "3"
-8
View File
@@ -1,12 +1,4 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Use the protoc that ships with protoc-bin-vendored rather than a system
// one, so the build needs no package manager and always sees the same
// version. An explicit PROTOC still wins, for packagers supplying their own
// and for the lance crates, whose own build scripts read the same variable.
if std::env::var_os("PROTOC").is_none() {
std::env::set_var("PROTOC", protoc_bin_vendored::protoc_bin_path()?);
}
// Compiled straight out of the Go tree, the way seaweed-volume already reads
// filer.proto, so the contract cannot drift from a vendored copy.
tonic_build::configure()
+1 -4
View File
@@ -7,11 +7,8 @@ description = "SeaweedFS maintenance worker for Lance tables"
[lib]
name = "weed_lance_worker"
# The binary is not named for lance: it is the Rust side of `weed worker`, and
# the job families it registers will outgrow this crate. When a second one
# arrives the bin target moves to a crate of its own under the same name.
[[bin]]
name = "weed-worker"
name = "weed-lance-worker"
path = "src/main.rs"
[dependencies]
+2 -2
View File
@@ -13,8 +13,8 @@ use weed_lance_worker::metrics::LanceMetrics;
/// language and an operator should not have to learn a second set of names.
#[derive(Parser, Debug)]
#[command(
name = "weed-worker",
about = "SeaweedFS maintenance worker"
name = "weed-lance-worker",
about = "SeaweedFS maintenance worker for Lance tables"
)]
struct Args {
/// Admin server gRPC address.
@@ -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,22 +0,0 @@
# LanceDB client for the SeaweedFS Lance Namespace integration test.
#
# The Iceberg suites point Spark, Trino and ClickHouse at the catalog; this is
# the same idea for Lance. LanceDB connects with connect_namespace("rest", ...),
# which speaks the routes this catalog implements, so what it exercises is the
# protocol rather than requests we wrote ourselves.
FROM python:3.11-slim
WORKDIR /app
# Pinned to the versions this suite was verified against. An unrelated upstream
# release should not be able to change what an old commit reproduces, and this
# client is the thing under test as much as the server is.
RUN pip install --no-cache-dir \
"lancedb==0.37.1" \
"lance-namespace==0.8.6" \
"pylance==10.0.0" \
"pyarrow==25.0.1"
COPY lancedb_ops.py /app/
CMD ["python3", "/app/lancedb_ops.py", "--help"]
-56
View File
@@ -1,56 +0,0 @@
# LanceDB Integration Test
Drives the SeaweedFS Lance Namespace with [LanceDB](https://lancedb.com), the way
`catalog_spark`, `catalog_trino` and `catalog_clickhouse` drive the Iceberg REST
catalog with their engines.
## Why a real client
Every serious bug in this catalog so far looked correct to a request written by
hand: a deregister that deleted the dataset, an S3 door that refused every Lance
file, a namespace that listed tables it would then deny. A hand-built HTTP test
checks the shape of a response. A client checks whether the response is *usable* —
that the location it hands back, the storage options beside it and the layout
rules on the S3 door all line up at once.
LanceDB connects with `connect_namespace("rest", ...)`, which speaks the routes
this catalog implements, so what runs here is the protocol rather than our own
idea of it.
## What it does
`TestLanceDBNamespace`:
1. Starts a `weed mini` cluster with S3 and the Lance Namespace enabled.
2. Creates a table bucket declared `LANCE`, so the catalog refuses tables of any
other format in it.
3. Builds `Dockerfile.client` (LanceDB, pylance, lance-namespace) and runs
`lancedb_ops.py` against the namespace.
Inside the container:
| Step | What it proves |
| --- | --- |
| seed a table | the namespace's location and credentials are enough to write |
| `table_names` | the catalog is browsable through LanceDB |
| `open_table` | LanceDB resolves a table through the catalog and reads it |
| schema check | the vector column survived the round trip |
| `create_index` | an IVF_PQ index builds, and its files land through the S3 door's layout rules |
| `search(...)` | approximate search over that index, on data behind SeaweedFS |
| `where("id < 5")` | so does the scan path, not only the index |
| `create_table` | LanceDB declares through the namespace and writes the data itself |
| `create_table` with pushdown | either the client falls back and the table is complete, or the catalog refuses with the spec's Unsupported and leaves nothing behind |
| direct `lance.dataset(uri)` | the catalog stays optional; the dataset opens without it |
The seeding is pylance rather than LanceDB, because the namespace records where
a table lives and does not carry its data. That split is the design, not a
limitation of the test.
## Running it
cd test/s3tables/catalog_lancedb
(cd ../../../weed && go build .) # the harness runs this binary
go test -run TestLanceDBNamespace -v -timeout 30m .
Skipped without Docker, and in `-short` mode. The first run builds the client
image, which takes a few minutes; later runs reuse it.
@@ -1,291 +0,0 @@
// Package lancedb drives the SeaweedFS Lance Namespace with LanceDB, the way
// the catalog_spark, catalog_trino and catalog_clickhouse suites drive the
// Iceberg REST catalog with their engines.
//
// A catalog is only as good as what a real client can do with it. Every serious
// bug in this surface so far - a deregister that deleted the dataset, an S3 door
// that refused every Lance file, a namespace that listed tables it would then
// deny - looked correct to a request written by hand.
package lancedb
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/testutil"
)
const (
clientImage = "seaweedfs-lancedb-test"
startupTimeout = 60 * time.Second
clientTimeout = 15 * time.Minute
)
// TestLanceDBNamespace runs LanceDB against the namespace end to end: it lists
// what the catalog holds, opens a table through it, searches the vectors, and
// reads the same dataset straight off its URI to show the catalog stays
// optional.
func TestLanceDBNamespace(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !hasDocker() {
t.Skip("Docker not available, skipping LanceDB integration test")
}
env := newEnvironment(t)
defer env.cleanup()
env.start(t)
bucket := "lancedb-" + randomSuffix()
env.createTableBucket(t, bucket)
buildClientImage(t)
env.runClient(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-lancedb-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))
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("create table bucket %s: %v\n%s", bucket, err, out)
}
t.Logf("created LANCE table bucket %s", bucket)
}
func buildClientImage(t *testing.T) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", "build",
"-t", clientImage, "-f", "Dockerfile.client", ".")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build the LanceDB client image: %v\n%s", err, out)
}
}
func (env *environment) runClient(t *testing.T, bucket string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), clientTimeout)
defer cancel()
// The container reaches the gateway through the host gateway address, which
// is not the address the namespace advertises to its own clients.
namespaceURL := fmt.Sprintf("http://host.docker.internal:%d", env.lancePort)
s3Endpoint := fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
"--add-host", "host.docker.internal:host-gateway",
// Also in the environment, not only in storage_options: LanceDB takes
// some paths through the options the namespace vends, and a gateway
// without STS vends none, leaving lance's provider chain to find them.
"-e", "AWS_ACCESS_KEY_ID="+env.accessKey,
"-e", "AWS_SECRET_ACCESS_KEY="+env.secretKey,
"-e", "AWS_REGION=us-east-1",
"-e", "AWS_ENDPOINT_URL="+s3Endpoint,
"-e", "AWS_ALLOW_HTTP=true",
clientImage,
"python3", "/app/lancedb_ops.py",
"--namespace-url", namespaceURL,
"--s3-endpoint", s3Endpoint,
"--bucket", bucket,
"--access-key", env.accessKey,
"--secret-key", env.secretKey,
)
out, err := cmd.CombinedOutput()
t.Logf("LanceDB client output:\n%s", out)
if err != nil {
t.Fatalf("the LanceDB client failed: %v", err)
}
if !strings.Contains(string(out), "PASS") {
t.Fatalf("the LanceDB client did not report PASS")
}
}
func hasDocker() bool {
return exec.Command("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,244 +0,0 @@
#!/usr/bin/env python3
"""Drive the SeaweedFS Lance Namespace with LanceDB.
The existing client test uses `lance_namespace` and `pylance` directly, which is
the protocol's reference client. LanceDB is what people actually point at a
catalog: it connects with `connect_namespace("rest", ...)`, lists what is there,
opens a table and searches it. This checks the catalog against that path, the
way the Spark, Trino and ClickHouse suites check the Iceberg one.
Everything it prints is either "PASS" or a line starting with FAIL, so the Go
harness can report the first real failure rather than a stack trace.
"""
import argparse
import sys
import warnings
warnings.filterwarnings("ignore")
import lance
import lance_namespace as ln
import lancedb
import pyarrow as pa
DIM = 8
def sample_rows(count):
"""A vector table, which is the only kind worth putting in Lance."""
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 seed_table(namespace_url, storage, bucket, namespace, table, rows):
"""Declares a table through the namespace and writes a dataset into it.
LanceDB reads through the catalog; the writing half is pylance, because the
namespace records where a table lives and does not carry its data.
"""
ns = ln.connect("rest", {"uri": namespace_url})
ns.create_namespace(
ln.CreateNamespaceRequest(id=[bucket], mode="EXIST_OK")
)
ns.create_namespace(
ln.CreateNamespaceRequest(id=[bucket, namespace], mode="EXIST_OK")
)
table_id = [bucket, namespace, table]
declared = ns.declare_table(ln.DeclareTableRequest(id=table_id))
lance.write_dataset(
sample_rows(rows), declared.location, storage_options=storage, mode="overwrite"
)
print(f"seeded {rows} rows at {declared.location}")
return declared.location
def check(condition, message):
if not condition:
print(f"FAIL: {message}", file=sys.stderr)
raise SystemExit(1)
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")
# Enough rows for an IVF_PQ index to be worth building, which is the point
# of step 4: without one, a search is a brute-force scan.
parser.add_argument("--rows", type=int, default=1024)
parser.add_argument("--access-key", default="any")
parser.add_argument("--secret-key", default="any")
args = parser.parse_args()
# The namespace vends an endpoint correct for its own host; a container
# reaches the same gateway by another name, so the endpoint is overridden
# here and the credentials filled in for a deployment without STS.
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",
}
location = seed_table(
args.namespace_url, storage, args.bucket, args.namespace, args.table, args.rows
)
print(f"lancedb {lancedb.__version__} connecting to {args.namespace_url}")
db = lancedb.connect_namespace(
"rest", {"uri": args.namespace_url}, storage_options=storage
)
# 1. The catalog is browsable: the bucket is a namespace, and the table is
# in it under the name the namespace gave it.
tables = list(db.table_names(namespace_path=[args.bucket, args.namespace], limit=100))
print(f"table_names -> {tables}")
check(
any(args.table in name for name in tables),
f"{args.table} is not listed in {tables}",
)
# 2. Opening it goes through the catalog: LanceDB asks the namespace where
# the table is and reads it from there.
# storage_options is passed per call as well as on the connection: what the
# namespace vends for a table is merged in, and a deployment without STS
# vends no credentials, which is what the client would otherwise be left with.
table = db.open_table(
args.table,
namespace_path=[args.bucket, args.namespace],
storage_options=storage,
)
count = table.count_rows()
print(f"open_table -> {count} rows")
check(count == args.rows, f"read {count} rows, want {args.rows}")
# 3. The schema survived the round trip, vector column included. This is the
# part a catalog that only records a location cannot fake.
names = table.schema.names
print(f"schema -> {names}")
check("vector" in names and "title" in names, f"schema lost columns: {names}")
# 4. Build a vector index, then search it. Both halves matter: an index
# writes files into a directory of the table the S3 door has to admit -
# the layout guard has refused a Lance directory before - and without one
# a search is a brute-force scan that proves nothing about the index path
# the maintenance worker exists to keep in shape.
table.create_index(
metric="l2",
vector_column_name="vector",
index_type="IVF_PQ",
num_partitions=1,
num_sub_vectors=4,
)
indices = table.list_indices()
print(f"create_index -> {indices}")
check(len(indices) >= 1, "no index was created")
# Vectors are laid out so that id N sits near id N+1, so a query built from
# id 1 should come back with its neighbourhood. The assertion is a
# neighbourhood and not an exact id: an IVF_PQ index quantizes, so the
# nearest hit is approximate by construction - with this data it answers 0
# as readily as 1, and both are right.
query = [float(1) + d for d in range(DIM)]
hits = table.search(query).limit(3).to_list()
ids = [hit["id"] for hit in hits]
print(f"search -> {ids}")
check(len(hits) == 3, f"search returned {len(hits)} hits, want 3")
check(
all(i <= 5 for i in ids),
f"search returned {ids}, which is not the neighbourhood of the query",
)
# 5. A filtered scan, so it is not only the ANN path that works.
filtered = table.search().where("id < 5").limit(10).to_list()
print(f"filtered scan -> {len(filtered)} rows")
check(len(filtered) == 5, f"filter returned {len(filtered)} rows, want 5")
# 6. Creating a table. By default LanceDB declares it through the namespace
# and writes the data itself, which is exactly the split this catalog
# serves, so this has to work.
created = db.create_table(
"created_by_lancedb",
data=sample_rows(4),
namespace_path=[args.bucket, args.namespace],
storage_options=storage,
)
check(created.count_rows() == 4, "create_table wrote the wrong number of rows")
listed = list(db.table_names(namespace_path=[args.bucket, args.namespace], limit=100))
check(
any("created_by_lancedb" in name for name in listed),
f"a table created through LanceDB is not listed: {listed}",
)
print(f"create_table -> {created.count_rows()} rows, listed by the catalog")
# 7. The same creation with server-side pushdown, which asks the namespace
# to run CreateTable itself. That operation carries Arrow data and this
# catalog answers the spec's Unsupported for it. What matters is that the
# client is left with something coherent either way - it falls back to
# declare-and-write - rather than a hang, a 404, or a half-made table.
pushdown = lancedb.connect_namespace(
"rest",
{"uri": args.namespace_url},
storage_options=storage,
namespace_client_pushdown_operations=["CreateTable"],
)
pushed_error = None
try:
pushdown.create_table(
"pushed_by_lancedb",
data=sample_rows(2),
namespace_path=[args.bucket, args.namespace],
storage_options=storage,
)
except Exception as err: # noqa: BLE001 - the point is what the client sees
pushed_error = err
after = list(db.table_names(namespace_path=[args.bucket, args.namespace], limit=100))
landed = any("pushed_by_lancedb" in name for name in after)
print(f"create_table with pushdown: error={pushed_error!r}, catalog has it={landed}")
if pushed_error is None:
# The client fell back to declare-and-write, so the table is real and
# has to be readable and complete.
check(landed, "create_table reported success but the catalog has no table")
rows = db.open_table(
"pushed_by_lancedb",
namespace_path=[args.bucket, args.namespace],
storage_options=storage,
).count_rows()
check(rows == 2, f"the pushed table holds {rows} rows, want 2")
else:
# Refused, which is what this catalog answers for a data-plane
# operation. It has to be that refusal and not some other failure, and
# it must not have left a half-made table behind.
message = str(pushed_error).lower()
check(
"unsupported" in message or "501" in message or "not implemented" in message,
f"pushdown failed for an unexpected reason: {pushed_error}",
)
check(not landed, "a refused create left a table behind in the catalog")
# 8. And the dataset is still readable straight off its URI, which is what
# keeps the catalog optional.
direct = lance.dataset(location, storage_options=storage).count_rows()
check(direct == args.rows, f"direct read got {direct} rows, want {args.rows}")
print(f"direct read without the catalog -> {direct} rows")
print("PASS")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,63 +0,0 @@
# Spark Lance Integration Test
Drives the SeaweedFS Lance Namespace with Spark, through the Lance Spark
connector's DSV2 catalog. The Lance counterpart of `catalog_spark`, which does
the same for the Iceberg REST catalog.
## Why Spark
Spark is the engine most likely to be pointed at a lakehouse, and it reaches the
catalog over the same Lance Namespace routes as every other client. Between this
and `catalog_lancedb`, the catalog is exercised by the two clients people
actually use, rather than only by the protocol's reference implementation.
## What it does
`TestSparkLanceNamespace`:
1. Starts a `weed mini` cluster with S3 and the Lance Namespace enabled.
2. Creates a table bucket declared `LANCE`.
3. Runs `spark_lance_ops.py` inside the stock `apache/spark:3.5.1` image, with
the connector pulled from Maven at submit time.
Inside Spark:
| Step | What it proves |
| --- | --- |
| `CREATE NAMESPACE` / `SHOW NAMESPACES` | the bucket is the first level of the path, and the catalog is writable |
| `CREATE TABLE ... USING lance` | the connector declares through the namespace and writes the data itself |
| `INSERT` / `SELECT count(*)` | a write lands and reads back through the catalog |
| schema check | the vector column survived the round trip |
| `WHERE id >= 2` | the filter path, not only a full scan |
| a second `INSERT` | the commit a store that cannot order commits fails on |
## 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:
```
spark.sql.catalog.lance org.lance.spark.LanceNamespaceSparkCatalog
spark.sql.catalog.lance.impl rest
spark.sql.catalog.lance.uri http://seaweed:9101
spark.sql.catalog.lance.storage.aws_endpoint http://seaweed:8333
spark.sql.catalog.lance.storage.allow_http true
spark.sql.catalog.lance.storage.aws_access_key_id …
spark.sql.catalog.lance.storage.aws_secret_access_key …
```
Anything under `storage.` is handed to lance as object_store options, so those
are object_store's key names rather than Spark's `s3a` ones. Credentials belong
there because a gateway without STS vends none — see the note in
`../catalog_lancedb/README.md`.
## Running it
cd test/s3tables/catalog_spark_lance
(cd ../../../weed && go build .) # the harness runs this binary
go test -run TestSparkLanceNamespace -v -timeout 40m .
Skipped without Docker, and in `-short` mode. The first run downloads the Spark
image and the connector bundle, which is a few hundred megabytes; later runs
reuse both.
@@ -1,153 +0,0 @@
#!/usr/bin/env python3
"""Drive the SeaweedFS Lance Namespace with Spark.
Spark reaches the catalog through the Lance Spark connector's DSV2 catalog,
`org.lance.spark.LanceNamespaceSparkCatalog` with `impl=rest`, which speaks the
same routes this catalog implements. It is the Lance counterpart of the Spark
Iceberg suite next door.
Every step prints what happened. The last line is PASS, or a line starting with
FAIL that names the step, so the Go harness can report something useful rather
than a stack trace.
"""
import argparse
import sys
from pyspark.sql import SparkSession
from pyspark.sql.types import ArrayType, FloatType
def check(condition, message):
if not condition:
print(f"FAIL: {message}", file=sys.stderr)
raise SystemExit(1)
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("--access-key", default="any")
parser.add_argument("--secret-key", default="any")
parser.add_argument("--packages", required=True)
parser.add_argument("--ivy-dir", default="/tmp/ivy")
args = parser.parse_args()
# storage.* is handed to lance as its object_store options, so these are
# object_store's own key names rather than Spark's s3a ones.
spark = (
SparkSession.builder.appName("SeaweedFS Lance Namespace Test")
.config("spark.jars.ivy", args.ivy_dir)
.config("spark.jars.packages", args.packages)
.config("spark.sql.catalog.lance", "org.lance.spark.LanceNamespaceSparkCatalog")
.config("spark.sql.catalog.lance.impl", "rest")
.config("spark.sql.catalog.lance.uri", args.namespace_url)
.config("spark.sql.catalog.lance.storage.aws_endpoint", args.s3_endpoint)
.config("spark.sql.catalog.lance.storage.allow_http", "true")
.config("spark.sql.catalog.lance.storage.aws_access_key_id", args.access_key)
.config("spark.sql.catalog.lance.storage.aws_secret_access_key", args.secret_key)
.config("spark.sql.catalog.lance.storage.aws_region", "us-east-1")
.config("spark.sql.catalog.lance.storage.virtual_hosted_style_request", "false")
.getOrCreate()
)
spark.sparkContext.setLogLevel("WARN")
print(f"spark {spark.version} connected to {args.namespace_url}")
ns = f"lance.`{args.bucket}`.{args.namespace}"
table = f"{ns}.{args.table}"
# 1. A table bucket is the first level of the namespace path, so the
# namespace below it is created through the catalog like any other.
spark.sql(f"CREATE NAMESPACE IF NOT EXISTS {ns}")
namespaces = [row[0] for row in spark.sql(f"SHOW NAMESPACES IN lance.`{args.bucket}`").collect()]
print(f"SHOW NAMESPACES -> {namespaces}")
check(
any(args.namespace in name for name in namespaces),
f"{args.namespace} is not listed in {namespaces}",
)
# 2. Creating a table. The connector declares it through the namespace and
# writes the data itself, which is the split this catalog serves.
spark.sql(f"DROP TABLE IF EXISTS {table}")
spark.sql(
f"CREATE TABLE {table} (id BIGINT, title STRING, vector ARRAY<FLOAT>) USING lance"
)
# SHOW TABLES gives back the namespace's own identifiers - bucket, namespace
# and name joined by the delimiter - rather than a bare Spark table name.
tables = [row[1] for row in spark.sql(f"SHOW TABLES IN {ns}").collect()]
print(f"SHOW TABLES -> {tables}")
check(
any(args.table in name for name in tables),
f"{args.table} is not listed in {tables}",
)
# 3. Write, and read back through the catalog.
spark.sql(
f"""INSERT INTO {table} VALUES
(1, 'one', array(1.0f, 2.0f, 3.0f)),
(2, 'two', array(2.0f, 3.0f, 4.0f)),
(3, 'three', array(3.0f, 4.0f, 5.0f))"""
)
count = spark.sql(f"SELECT count(*) FROM {table}").collect()[0][0]
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",
)
# 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()
print(f"filtered -> {[(r[0], r[1]) for r in rows]}")
check(len(rows) == 2, f"filter returned {len(rows)} rows, want 2")
check(rows[0][0] == 2, f"filter returned {rows[0][0]} first, want 2")
# 6. Appending again, because a second commit is the one that fails when a
# store cannot order commits - this store can, so it must not.
spark.sql(f"INSERT INTO {table} VALUES (4, 'four', array(4.0f, 5.0f, 6.0f))")
count = spark.sql(f"SELECT count(*) FROM {table}").collect()[0][0]
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.
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")
spark.stop()
print("PASS")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,339 +0,0 @@
// Package sparklance drives the SeaweedFS Lance Namespace with Spark, through
// the Lance Spark connector's DSV2 catalog. It is the Lance counterpart of the
// catalog_spark suite, which does the same for the Iceberg REST catalog.
//
// Spark is the engine most likely to be pointed at a lakehouse, and it reaches
// the catalog over the same routes as every other client - so what this proves
// is the protocol, not our idea of it.
package sparklance
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/test/testutil"
)
const (
sparkImage = "apache/spark:3.5.1"
// Pinned: the connector is as much the thing under test as the server, and
// an unrelated release should not change what an old commit reproduces.
lancePackages = "org.lance:lance-spark-bundle-3.5_2.12:0.7.1"
startupTimeout = 60 * time.Second
clientTimeout = 25 * time.Minute
)
// TestSparkLanceNamespace runs Spark SQL against the namespace end to end:
// create a namespace and a table through the catalog, write, read back, filter,
// and append a second time.
func TestSparkLanceNamespace(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !hasDocker() {
t.Skip("Docker not available, skipping Spark Lance integration test")
}
env := newEnvironment(t)
defer env.cleanup()
env.start(t)
bucket := "sparklance-" + randomSuffix()
env.createTableBucket(t, bucket)
env.runSpark(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-spark-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.
func (env *environment) runSpark(t *testing.T, bucket string) {
t.Helper()
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)
}
// 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 {
t.Fatalf("create the ivy directory: %v", err)
}
// The container reaches the gateway through the host gateway address, which
// is not the address the namespace advertises to its own clients.
namespaceURL := fmt.Sprintf("http://host.docker.internal:%d", env.lancePort)
s3Endpoint := fmt.Sprintf("http://host.docker.internal:%d", env.s3Port)
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
"--add-host", "host.docker.internal:host-gateway",
"-v", script+":/opt/spark/work-dir/spark_lance_ops.py:ro",
"-v", ivyDir+":/tmp/ivy",
"-e", "HOME=/tmp",
"-e", "SPARK_LOCAL_IP=127.0.0.1",
"-u", "root",
sparkImage,
"/opt/spark/bin/spark-submit",
"--packages", lancePackages,
"--conf", "spark.jars.ivy=/tmp/ivy",
"/opt/spark/work-dir/spark_lance_ops.py",
"--namespace-url", namespaceURL,
"--s3-endpoint", s3Endpoint,
"--bucket", bucket,
"--access-key", env.accessKey,
"--secret-key", env.secretKey,
"--packages", lancePackages,
"--ivy-dir", "/tmp/ivy",
)
out, err := cmd.CombinedOutput()
t.Logf("Spark output:\n%s", tailLines(string(out), 60))
if err != nil {
t.Fatalf("the Spark driver failed: %v", err)
}
if !strings.Contains(string(out), "PASS") {
t.Fatalf("the Spark driver did not report PASS")
}
}
// tailLines keeps the end of Spark's very chatty output, which is where the
// driver's own lines and any failure are.
func tailLines(out string, n int) string {
lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
if len(lines) <= n {
return out
}
return "... " + fmt.Sprintf("%d earlier lines omitted", len(lines)-n) + "\n" +
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
}
func randomSuffix() string {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
suffix := make([]byte, 8)
for i := range suffix {
suffix[i] = charset[rand.Intn(len(charset))]
}
return string(suffix)
}
-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
+4 -145
View File
@@ -278,17 +278,12 @@ func NewAdminServer(masters string, filerGroup string, templateFS http.FileSyste
glog.V(1).Infof("No data directory configured, maintenance system will run in memory-only mode (enabled: %v)", maintenanceConfig.Enabled)
}
// Load saved task configurations from persistence. This has to run before the maintenance
// manager is created: creating it applies the maintenance policy to the registered
// detectors and schedulers, while this call replaces each task's whole config object, so
// running it afterwards would discard what the policy just applied. Both read the same
// persisted task config files, so the policy ends up as the last writer and stays
// authoritative for the task types it covers.
server.loadTaskConfigurationsFromPersistence()
// Always initialize maintenance manager
server.InitMaintenanceManager(maintenanceConfig)
// Load saved task configurations from persistence
server.loadTaskConfigurationsFromPersistence()
// Start maintenance manager if enabled
if maintenanceConfig.Enabled {
go func() {
@@ -1006,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)
@@ -1784,16 +1652,7 @@ func (s *AdminServer) ListPluginSchedulerStates() ([]adminplugin.SchedulerJobTyp
// InitMaintenanceManager initializes the maintenance manager
func (s *AdminServer) InitMaintenanceManager(config *maintenance.MaintenanceConfig) {
// Hand the real config store to the manager so that, if it has to build the maintenance policy
// itself, it reads the persisted task configs instead of compiled-in defaults. Only pass it when
// a data directory is actually configured: an unconfigured store has nothing to read, and a typed
// nil pointer would satisfy the loaders' type assertion and then panic on use.
var configPersistence interface{}
if s.configPersistence != nil && s.configPersistence.IsConfigured() {
configPersistence = s.configPersistence
}
s.maintenanceManager = maintenance.NewMaintenanceManager(s, config, configPersistence)
s.maintenanceManager = maintenance.NewMaintenanceManager(s, config)
// Set up task persistence if config persistence is available
if s.configPersistence != nil {
-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
+152 -99
View File
@@ -14,7 +14,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
"google.golang.org/protobuf/encoding/protojson"
@@ -30,7 +29,6 @@ const (
VacuumTaskConfigFile = "task_vacuum.pb"
ECTaskConfigFile = "task_erasure_coding.pb"
BalanceTaskConfigFile = "task_balance.pb"
EcBalanceTaskConfigFile = "task_ec_balance.pb"
ReplicationTaskConfigFile = "task_replication.pb"
// JSON reference files
@@ -38,7 +36,6 @@ const (
VacuumTaskConfigJSONFile = "task_vacuum.json"
ECTaskConfigJSONFile = "task_erasure_coding.json"
BalanceTaskConfigJSONFile = "task_balance.json"
EcBalanceTaskConfigJSONFile = "task_ec_balance.json"
ReplicationTaskConfigJSONFile = "task_replication.json"
// Task persistence subdirectories and settings
@@ -56,7 +53,6 @@ type (
VacuumTaskConfig = worker_pb.VacuumTaskConfig
ErasureCodingTaskConfig = worker_pb.ErasureCodingTaskConfig
BalanceTaskConfig = worker_pb.BalanceTaskConfig
EcBalanceTaskConfig = worker_pb.EcBalanceTaskConfig
ReplicationTaskConfig = worker_pb.ReplicationTaskConfig
)
@@ -160,7 +156,7 @@ func (cp *ConfigPersistence) LoadMaintenanceConfig() (*MaintenanceConfig, error)
var config MaintenanceConfig
if err := proto.Unmarshal(configData, &config); err == nil {
// Always populate policy from separate task configuration files
config.Policy = cp.buildPolicyFromTaskConfigs()
config.Policy = buildPolicyFromTaskConfigs()
return &config, nil
}
}
@@ -272,28 +268,6 @@ func (cp *ConfigPersistence) RestoreConfig(filename, backupName string) error {
return nil
}
// Default task policies. These derive from each task's own NewDefaultConfig() so that a
// task type has exactly one definition of its defaults. They used to be hand-written copies
// here, and had drifted from the values the tasks themselves and the admin UI schema use:
// vacuum scanned every 24h instead of 2h, balance every 6h instead of 30m with a 0.1 instead
// of 0.2 imbalance threshold, and erasure coding every 168h instead of 1h with a 0.90 instead
// of 0.95 fullness ratio and a 1024MB instead of 30MB minimum volume size.
func defaultVacuumTaskPolicy() *worker_pb.TaskPolicy {
return vacuum.NewDefaultConfig().ToTaskPolicy()
}
func defaultErasureCodingTaskPolicy() *worker_pb.TaskPolicy {
return erasure_coding.NewDefaultConfig().ToTaskPolicy()
}
func defaultBalanceTaskPolicy() *worker_pb.TaskPolicy {
return balance.NewDefaultConfig().ToTaskPolicy()
}
func defaultEcBalanceTaskPolicy() *worker_pb.TaskPolicy {
return ec_balance.NewDefaultConfig().ToTaskPolicy()
}
// SaveVacuumTaskConfig saves vacuum task configuration to protobuf file
func (cp *ConfigPersistence) SaveVacuumTaskConfig(config *VacuumTaskConfig) error {
return cp.saveTaskConfig(VacuumTaskConfigFile, config)
@@ -314,14 +288,28 @@ func (cp *ConfigPersistence) LoadVacuumTaskConfig() (*VacuumTaskConfig, error) {
}
// Return default config if no valid config found
return defaultVacuumTaskPolicy().GetVacuumConfig(), nil
return &VacuumTaskConfig{
GarbageThreshold: 0.3,
MinVolumeAgeHours: 24,
}, nil
}
// LoadVacuumTaskPolicy loads complete vacuum task policy from protobuf file
func (cp *ConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error) {
if cp.dataDir == "" {
// Return default policy if no data directory
return defaultVacuumTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 2,
RepeatIntervalSeconds: 24 * 3600, // 24 hours in seconds
CheckIntervalSeconds: 6 * 3600, // 6 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
VacuumConfig: &worker_pb.VacuumTaskConfig{
GarbageThreshold: 0.3,
MinVolumeAgeHours: 24,
},
},
}, nil
}
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
@@ -330,7 +318,18 @@ func (cp *ConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, erro
// Check if file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// Return default policy if file doesn't exist
return defaultVacuumTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 2,
RepeatIntervalSeconds: 24 * 3600, // 24 hours in seconds
CheckIntervalSeconds: 6 * 3600, // 6 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
VacuumConfig: &worker_pb.VacuumTaskConfig{
GarbageThreshold: 0.3,
MinVolumeAgeHours: 24,
},
},
}, nil
}
// Read file
@@ -372,14 +371,32 @@ func (cp *ConfigPersistence) LoadErasureCodingTaskConfig() (*ErasureCodingTaskCo
}
// Return default config if no valid config found
return defaultErasureCodingTaskPolicy().GetErasureCodingConfig(), nil
return &ErasureCodingTaskConfig{
FullnessRatio: 0.9,
QuietForSeconds: 3600,
MinVolumeSizeMb: 1024,
CollectionFilter: "",
}, nil
}
// LoadErasureCodingTaskPolicy loads complete EC task policy from protobuf file
func (cp *ConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolicy, error) {
if cp.dataDir == "" {
// Return default policy if no data directory
return defaultErasureCodingTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 1,
RepeatIntervalSeconds: 168 * 3600, // 1 week in seconds
CheckIntervalSeconds: 24 * 3600, // 24 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
FullnessRatio: 0.9,
QuietForSeconds: 3600,
MinVolumeSizeMb: 1024,
CollectionFilter: "",
},
},
}, nil
}
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
@@ -388,7 +405,20 @@ func (cp *ConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolic
// Check if file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// Return default policy if file doesn't exist
return defaultErasureCodingTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 1,
RepeatIntervalSeconds: 168 * 3600, // 1 week in seconds
CheckIntervalSeconds: 24 * 3600, // 24 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
FullnessRatio: 0.9,
QuietForSeconds: 3600,
MinVolumeSizeMb: 1024,
CollectionFilter: "",
},
},
}, nil
}
// Read file
@@ -430,14 +460,28 @@ func (cp *ConfigPersistence) LoadBalanceTaskConfig() (*BalanceTaskConfig, error)
}
// Return default config if no valid config found
return defaultBalanceTaskPolicy().GetBalanceConfig(), nil
return &BalanceTaskConfig{
ImbalanceThreshold: 0.1,
MinServerCount: 2,
}, nil
}
// LoadBalanceTaskPolicy loads complete balance task policy from protobuf file
func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
if cp.dataDir == "" {
// Return default policy if no data directory
return defaultBalanceTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 1,
RepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
CheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
BalanceConfig: &worker_pb.BalanceTaskConfig{
ImbalanceThreshold: 0.1,
MinServerCount: 2,
},
},
}, nil
}
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
@@ -446,7 +490,18 @@ func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, err
// Check if file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// Return default policy if file doesn't exist
return defaultBalanceTaskPolicy(), nil
return &worker_pb.TaskPolicy{
Enabled: true,
MaxConcurrent: 1,
RepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
CheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
BalanceConfig: &worker_pb.BalanceTaskConfig{
ImbalanceThreshold: 0.1,
MinServerCount: 2,
},
},
}, nil
}
// Read file
@@ -468,60 +523,6 @@ func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, err
return nil, fmt.Errorf("failed to unmarshal balance task configuration")
}
// SaveEcBalanceTaskPolicy saves complete EC balance task policy to protobuf file
func (cp *ConfigPersistence) SaveEcBalanceTaskPolicy(policy *worker_pb.TaskPolicy) error {
return cp.saveTaskConfig(EcBalanceTaskConfigFile, policy)
}
// LoadEcBalanceTaskConfig loads EC balance task configuration from protobuf file
func (cp *ConfigPersistence) LoadEcBalanceTaskConfig() (*EcBalanceTaskConfig, error) {
if taskPolicy, err := cp.LoadEcBalanceTaskPolicy(); err == nil && taskPolicy != nil {
if ecBalanceConfig := taskPolicy.GetEcBalanceConfig(); ecBalanceConfig != nil {
return ecBalanceConfig, nil
}
}
// Return default config if no valid config found
return defaultEcBalanceTaskPolicy().GetEcBalanceConfig(), nil
}
// LoadEcBalanceTaskPolicy loads complete EC balance task policy from protobuf file.
// ec_balance is registered like the other maintenance tasks and ec_balance.LoadConfigFromPersistence
// asserts on this accessor, so without it the task could never be configured at all.
func (cp *ConfigPersistence) LoadEcBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
if cp.dataDir == "" {
// Return default policy if no data directory
return defaultEcBalanceTaskPolicy(), nil
}
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
configPath := filepath.Join(confDir, EcBalanceTaskConfigFile)
// Check if file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// Return default policy if file doesn't exist
return defaultEcBalanceTaskPolicy(), nil
}
// Read file
configData, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read EC balance task config file: %w", err)
}
// Try to unmarshal as TaskPolicy
var policy worker_pb.TaskPolicy
if err := proto.Unmarshal(configData, &policy); err == nil {
// Validate that it's actually a TaskPolicy with EC balance config
if policy.GetEcBalanceConfig() != nil {
glog.V(1).Infof("Loaded EC balance task policy from %s", configPath)
return &policy, nil
}
}
return nil, fmt.Errorf("failed to unmarshal EC balance task configuration")
}
// SaveReplicationTaskConfig saves replication task configuration to protobuf file
func (cp *ConfigPersistence) SaveReplicationTaskConfig(config *ReplicationTaskConfig) error {
return cp.saveTaskConfig(ReplicationTaskConfigFile, config)
@@ -631,8 +632,6 @@ func (cp *ConfigPersistence) SaveTaskPolicy(taskType string, policy *worker_pb.T
return cp.SaveErasureCodingTaskPolicy(policy)
case "balance":
return cp.SaveBalanceTaskPolicy(policy)
case "ec_balance":
return cp.SaveEcBalanceTaskPolicy(policy)
case "replication":
return cp.SaveReplicationTaskPolicy(policy)
}
@@ -688,13 +687,67 @@ func (cp *ConfigPersistence) GetConfigInfo() map[string]interface{} {
return info
}
// buildPolicyFromTaskConfigs builds the maintenance policy from the persisted task configs.
//
// The body lives in weed/admin/maintenance because the maintenance manager needs the same
// policy when it has to build one itself, and this package already imports that one. Keeping
// a second copy here is what let the two drift apart in the first place.
func (cp *ConfigPersistence) buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
return maintenance.BuildPolicyFromTaskConfigs(cp)
// buildPolicyFromTaskConfigs loads task configurations from separate files and builds a MaintenancePolicy
func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
policy := &worker_pb.MaintenancePolicy{
GlobalMaxConcurrent: 4,
DefaultRepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
DefaultCheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
}
// Load vacuum task configuration
if vacuumConfig := vacuum.LoadConfigFromPersistence(nil); vacuumConfig != nil {
policy.TaskPolicies["vacuum"] = &worker_pb.TaskPolicy{
Enabled: vacuumConfig.Enabled,
MaxConcurrent: int32(vacuumConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
VacuumConfig: &worker_pb.VacuumTaskConfig{
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
},
},
}
}
// Load erasure coding task configuration
if ecConfig := erasure_coding.LoadConfigFromPersistence(nil); ecConfig != nil {
policy.TaskPolicies["erasure_coding"] = &worker_pb.TaskPolicy{
Enabled: ecConfig.Enabled,
MaxConcurrent: int32(ecConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
FullnessRatio: float64(ecConfig.FullnessRatio),
QuietForSeconds: int32(ecConfig.QuietForSeconds),
MinVolumeSizeMb: int32(ecConfig.MinSizeMB),
CollectionFilter: ecConfig.CollectionFilter,
},
},
}
}
// Load balance task configuration
if balanceConfig := balance.LoadConfigFromPersistence(nil); balanceConfig != nil {
policy.TaskPolicies["balance"] = &worker_pb.TaskPolicy{
Enabled: balanceConfig.Enabled,
MaxConcurrent: int32(balanceConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
BalanceConfig: &worker_pb.BalanceTaskConfig{
ImbalanceThreshold: float64(balanceConfig.ImbalanceThreshold),
MinServerCount: int32(balanceConfig.MinServerCount),
},
},
}
}
glog.V(1).Infof("Built maintenance policy from separate task configs - %d task policies loaded", len(policy.TaskPolicies))
return policy
}
// SaveTaskDetail saves detailed task information to disk
+3 -6
View File
@@ -53,11 +53,8 @@ type FileBrowserData struct {
CurrentLastFileName string `json:"current_last_file_name"` // Cursor from current request (for page size changes)
}
// GetFileBrowser retrieves file browser data for a given path with cursor-based
// pagination. A non-empty prefix limits the listing to entries whose name starts
// with it, so callers that only want part of a large directory don't have to page
// through all of it.
func (s *AdminServer) GetFileBrowser(dir string, prefix string, lastFileName string, pageSize int) (*FileBrowserData, error) {
// GetFileBrowser retrieves file browser data for a given path with cursor-based pagination
func (s *AdminServer) GetFileBrowser(dir string, lastFileName string, pageSize int) (*FileBrowserData, error) {
if dir == "" {
dir = "/"
}
@@ -79,7 +76,7 @@ func (s *AdminServer) GetFileBrowser(dir string, prefix string, lastFileName str
// Fetch entries starting from the cursor (lastFileName)
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
Directory: dir,
Prefix: prefix,
Prefix: "",
Limit: uint32(fetchLimit),
StartFromFileName: lastFileName,
InclusiveStartFrom: false, // Don't include the cursor file itself
@@ -1,73 +0,0 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
)
// TestLoadMaintenanceConfigHonoursPersistedTaskConfigs guards against a regression: buildPolicyFromTaskConfigs used to call
// LoadConfigFromPersistence(nil), which can never satisfy the loaders' type assertion, so every
// task silently fell back to its compiled-in defaults (Enabled: true) and a task disabled in the
// admin UI kept being scheduled.
func TestLoadMaintenanceConfigHonoursPersistedTaskConfigs(t *testing.T) {
dir := t.TempDir()
cp := NewConfigPersistence(dir)
// A maintenance.pb must exist, otherwise LoadMaintenanceConfig returns early with defaults.
if err := cp.SaveMaintenanceConfig(DefaultMaintenanceConfig()); err != nil {
t.Fatalf("save maintenance config: %v", err)
}
// Disable balance and vacuum the way the admin UI does, and change a value that is not a bool
// so a fallback to defaults cannot pass by coincidence.
disabledBalance := balance.NewDefaultConfig()
disabledBalance.Enabled = false
disabledBalance.MinServerCount = 7
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
t.Fatalf("save balance policy: %v", err)
}
disabledVacuum := vacuum.NewDefaultConfig()
disabledVacuum.Enabled = false
if err := cp.SaveVacuumTaskPolicy(disabledVacuum.ToTaskPolicy()); err != nil {
t.Fatalf("save vacuum policy: %v", err)
}
config, err := cp.LoadMaintenanceConfig()
if err != nil {
t.Fatalf("load maintenance config: %v", err)
}
if config.Policy == nil {
t.Fatal("policy is nil, want it populated from the persisted task configs")
}
balancePolicy := config.Policy.TaskPolicies["balance"]
if balancePolicy == nil {
t.Fatal("no balance task policy in the built maintenance policy")
}
if balancePolicy.Enabled {
t.Error("balance enabled = true, want false from the persisted config")
}
if got := balancePolicy.GetBalanceConfig().GetMinServerCount(); got != 7 {
t.Errorf("balance min server count = %d, want persisted 7", got)
}
vacuumPolicy := config.Policy.TaskPolicies["vacuum"]
if vacuumPolicy == nil {
t.Fatal("no vacuum task policy in the built maintenance policy")
}
if vacuumPolicy.Enabled {
t.Error("vacuum enabled = true, want false from the persisted config")
}
// erasure_coding was never saved, so it keeps the loader's default of enabled.
ecPolicy := config.Policy.TaskPolicies["erasure_coding"]
if ecPolicy == nil {
t.Fatal("no erasure_coding task policy in the built maintenance policy")
}
if !ecPolicy.Enabled {
t.Error("erasure_coding enabled = false, want the default true for a config never saved")
}
}
-123
View File
@@ -1,123 +0,0 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
// The task definitions these tests configure are process-global, so put them back the way a
// fresh process would have them. Passing no config store makes every task fall back to its
// own NewDefaultConfig, which is exactly the state package init left them in.
func restoreGlobalTaskState(t *testing.T) {
t.Helper()
t.Cleanup(func() {
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(nil)
})
}
// TestDisabledTaskIsNotScannedAfterStartup walks the admin server's startup sequence over a
// data directory that has a disabled balance task saved in it, and checks the end state that
// actually matters: the balance detector reports disabled, so ScanWithTaskDetectors skips it.
//
// This is the whole reported bug in one test. The reporter disabled balance, and the
// scanner kept detecting balance tasks, cancelling them and re-detecting them. Two separate
// defects had to line up for the disabled flag to survive to here: the policy had to be built
// from the persisted configs rather than from a nil store, and the policy had to reach
// detector.IsEnabled() rather than dying in a failed type assertion.
func TestDisabledTaskIsNotScannedAfterStartup(t *testing.T) {
restoreGlobalTaskState(t)
dir := t.TempDir()
cp := NewConfigPersistence(dir)
// What the admin writes when a user turns balance off, and leaves vacuum on.
disabledBalance := balance.NewDefaultConfig()
disabledBalance.Enabled = false
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
t.Fatalf("save balance policy: %v", err)
}
enabledVacuum := vacuum.NewDefaultConfig()
enabledVacuum.Enabled = true
if err := cp.SaveVacuumTaskPolicy(enabledVacuum.ToTaskPolicy()); err != nil {
t.Fatalf("save vacuum policy: %v", err)
}
// The admin server's startup sequence, in order:
// loadTaskConfigurationsFromPersistence, then InitMaintenanceManager.
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(cp)
maintenanceConfig, err := cp.LoadMaintenanceConfig()
if err != nil {
t.Fatalf("load maintenance config: %v", err)
}
manager := maintenance.NewMaintenanceManager(nil, maintenanceConfig, cp)
if manager == nil {
t.Fatal("NewMaintenanceManager returned nil")
}
registry := tasks.GetGlobalTypesRegistry()
balanceDetector := registry.GetDetector(types.TaskTypeBalance)
if balanceDetector == nil {
t.Fatal("no balance detector registered")
}
if balanceDetector.IsEnabled() {
t.Error("balance detector reports enabled after startup over a data directory where " +
"balance is saved as disabled; the scanner will keep detecting and cancelling balance tasks")
}
vacuumDetector := registry.GetDetector(types.TaskTypeVacuum)
if vacuumDetector == nil {
t.Fatal("no vacuum detector registered")
}
if !vacuumDetector.IsEnabled() {
t.Error("vacuum detector reports disabled although vacuum is saved as enabled; " +
"the fix must not switch off tasks the user left on")
}
// Tasks the user never touched keep their compiled-in default of enabled rather than
// being switched off by a policy entry built from a config that was never saved.
for _, taskType := range []types.TaskType{types.TaskTypeErasureCoding, types.TaskTypeECBalance} {
detector := registry.GetDetector(taskType)
if detector == nil {
t.Fatalf("no %s detector registered", taskType)
}
if !detector.IsEnabled() {
t.Errorf("%s detector reports disabled although its config was never saved", taskType)
}
}
}
// TestPolicyMirrorsWhatTheDetectorsReport checks that the maintenance policy the queue and
// the scanner run on agrees with the detectors. A disagreement means one of the two paths
// into the task configs has gone stale again.
func TestPolicyMirrorsWhatTheDetectorsReport(t *testing.T) {
restoreGlobalTaskState(t)
dir := t.TempDir()
cp := NewConfigPersistence(dir)
disabledBalance := balance.NewDefaultConfig()
disabledBalance.Enabled = false
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
t.Fatalf("save balance policy: %v", err)
}
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(cp)
policy := cp.buildPolicyFromTaskConfigs()
for taskType, detector := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
policyEnabled := maintenance.IsTaskEnabled(policy, maintenance.MaintenanceTaskType(taskType))
if policyEnabled != detector.IsEnabled() {
t.Errorf("%s: policy says enabled=%v but the detector says enabled=%v",
taskType, policyEnabled, detector.IsEnabled())
}
}
}
-57
View File
@@ -1,57 +0,0 @@
package dash
import (
"context"
weediam "github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
// principalRoleArn builds the ARN SeaweedFS assigns a role by default (when
// its RoleDefinition.RoleArn isn't explicitly set) - see
// weed/iam/integration/iam_manager.go's CreateRole. ListRoles only returns
// role names, so this reconstructs the well-known default rather than
// fetching every role's stored definition just to populate a suggestion list.
func principalRoleArn(roleName string) string {
return "arn:aws:iam::role/" + roleName
}
// GetPrincipalSuggestions returns candidate ARNs for the policy editor's
// Principal/NotPrincipal autocomplete: one per S3 user, plus one per IAM
// role. Service accounts are deliberately not listed separately - a service
// account is just an additional credential for its parent user, so its ARN
// is identical to the one already suggested for that user.
//
// Role listing is best-effort: if the filer or role store is unavailable,
// the error is logged and suggestions fall back to users only, since an
// incomplete autocomplete list is far less disruptive than blocking policy
// editing over a suggestions-only feature.
func (s *AdminServer) GetPrincipalSuggestions(ctx context.Context) ([]string, error) {
var suggestions []string
users, err := s.GetObjectStoreUsers(ctx)
if err != nil {
return nil, err
}
for _, u := range users {
suggestions = append(suggestions, weediam.UserArn(u.Username))
}
roleStore, err := integration.NewFilerRoleStore(nil, func() string { return s.GetFilerAddress() })
if err != nil {
glog.Warningf("GetPrincipalSuggestions: failed to create role store: %v", err)
return suggestions, nil
}
roleNames, err := roleStore.ListRoles(ctx, s.GetFilerAddress())
if err != nil {
glog.Warningf("GetPrincipalSuggestions: failed to list roles: %v", err)
return suggestions, nil
}
for _, roleName := range roleNames {
suggestions = append(suggestions, principalRoleArn(roleName))
}
return suggestions, nil
}
@@ -1,11 +0,0 @@
package dash
import "testing"
func TestPrincipalRoleArn(t *testing.T) {
got := principalRoleArn("S3ReadOnlyRole")
want := "arn:aws:iam::role/S3ReadOnlyRole"
if got != want {
t.Fatalf("principalRoleArn() = %q, want %q", got, want)
}
}
@@ -1,184 +0,0 @@
package dash
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
"google.golang.org/protobuf/proto"
)
// TestLoadTaskPolicyDefaultsMatchTaskDefaults pins the persistence layer's "nothing saved
// yet" defaults to each task's own NewDefaultConfig(). They used to be a second, hand-written
// copy and had drifted: with a data directory but no config file on disk, vacuum ran on a 24h
// scan interval instead of 2h, balance on 6h with a 0.1 imbalance threshold instead of 30m
// with 0.2, and erasure coding on 168h with a 0.90 fullness ratio and a 1024MB minimum volume
// size instead of 1h with 0.95 and 30MB - none of which is what the admin UI shows as the
// default for those fields.
func TestLoadTaskPolicyDefaultsMatchTaskDefaults(t *testing.T) {
cases := []struct {
name string
want *worker_pb.TaskPolicy
load func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error)
}{
{
name: "vacuum",
want: vacuum.NewDefaultConfig().ToTaskPolicy(),
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadVacuumTaskPolicy() },
},
{
name: "erasure_coding",
want: erasure_coding.NewDefaultConfig().ToTaskPolicy(),
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) {
return cp.LoadErasureCodingTaskPolicy()
},
},
{
name: "balance",
want: balance.NewDefaultConfig().ToTaskPolicy(),
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadBalanceTaskPolicy() },
},
{
name: "ec_balance",
want: ec_balance.NewDefaultConfig().ToTaskPolicy(),
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadEcBalanceTaskPolicy() },
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Both no-file branches have to agree with the task's own defaults: no data
// directory at all, and a data directory that has never been written to.
for _, cp := range []*ConfigPersistence{NewConfigPersistence(""), NewConfigPersistence(t.TempDir())} {
got, err := tc.load(cp)
if err != nil {
t.Fatalf("load %s policy: %v", tc.name, err)
}
if !proto.Equal(got, tc.want) {
t.Errorf("%s default policy (dataDir=%q) =\n %v\nwant NewDefaultConfig().ToTaskPolicy() =\n %v",
tc.name, cp.GetDataDir(), got, tc.want)
}
}
})
}
}
// TestLoadTaskConfigDefaultsMatchTaskDefaults covers the narrower Load*TaskConfig accessors,
// which carried a third copy of the same defaults.
func TestLoadTaskConfigDefaultsMatchTaskDefaults(t *testing.T) {
cp := NewConfigPersistence(t.TempDir())
vacuumConfig, err := cp.LoadVacuumTaskConfig()
if err != nil {
t.Fatalf("load vacuum config: %v", err)
}
if want := vacuum.NewDefaultConfig().ToTaskPolicy().GetVacuumConfig(); !proto.Equal(vacuumConfig, want) {
t.Errorf("vacuum default config = %v, want %v", vacuumConfig, want)
}
ecConfig, err := cp.LoadErasureCodingTaskConfig()
if err != nil {
t.Fatalf("load erasure coding config: %v", err)
}
if want := erasure_coding.NewDefaultConfig().ToTaskPolicy().GetErasureCodingConfig(); !proto.Equal(ecConfig, want) {
t.Errorf("erasure coding default config = %v, want %v", ecConfig, want)
}
balanceConfig, err := cp.LoadBalanceTaskConfig()
if err != nil {
t.Fatalf("load balance config: %v", err)
}
if want := balance.NewDefaultConfig().ToTaskPolicy().GetBalanceConfig(); !proto.Equal(balanceConfig, want) {
t.Errorf("balance default config = %v, want %v", balanceConfig, want)
}
}
// TestEcBalanceTaskPolicyRoundTrip checks the accessor ec_balance.LoadConfigFromPersistence
// asserts on. Before it existed, ec_balance was the one registered maintenance task whose
// configuration could not be persisted at all.
func TestEcBalanceTaskPolicyRoundTrip(t *testing.T) {
cp := NewConfigPersistence(t.TempDir())
saved := ec_balance.NewDefaultConfig()
saved.Enabled = false
saved.MinServerCount = 9
saved.ImbalanceThreshold = 0.42
saved.CollectionFilter = "pictures"
if err := cp.SaveEcBalanceTaskPolicy(saved.ToTaskPolicy()); err != nil {
t.Fatalf("save ec_balance policy: %v", err)
}
loaded := ec_balance.LoadConfigFromPersistence(cp)
if loaded == nil {
t.Fatal("ec_balance.LoadConfigFromPersistence returned nil")
}
if loaded.Enabled {
t.Error("ec_balance enabled = true, want the persisted false")
}
if loaded.MinServerCount != 9 {
t.Errorf("ec_balance min server count = %d, want the persisted 9", loaded.MinServerCount)
}
if loaded.ImbalanceThreshold != 0.42 {
t.Errorf("ec_balance imbalance threshold = %v, want the persisted 0.42", loaded.ImbalanceThreshold)
}
if loaded.CollectionFilter != "pictures" {
t.Errorf("ec_balance collection filter = %q, want the persisted %q", loaded.CollectionFilter, "pictures")
}
// The generic dispatcher the maintenance manager uses has to know the type too, and
// has to write the same file the dedicated loader reads.
dispatched := NewConfigPersistence(t.TempDir())
if err := dispatched.SaveTaskPolicy("ec_balance", saved.ToTaskPolicy()); err != nil {
t.Fatalf("SaveTaskPolicy(ec_balance): %v", err)
}
roundTripped := ec_balance.LoadConfigFromPersistence(dispatched)
if roundTripped == nil || roundTripped.MinServerCount != 9 {
t.Errorf("SaveTaskPolicy(ec_balance) did not round-trip through the ec_balance store: %+v", roundTripped)
}
}
// TestBuildPolicyKeepsTaskSpecificFields guards the fields the hand-written policy builder
// used to drop on the floor: the erasure coding preferred tags and replica placement, and
// the balance IO rate limit. Building each entry from the task's own ToTaskPolicy() keeps
// them, so a value set in admin.toml survives into the maintenance policy.
func TestBuildPolicyKeepsTaskSpecificFields(t *testing.T) {
cp := NewConfigPersistence(t.TempDir())
ecConfig := erasure_coding.NewDefaultConfig()
ecConfig.PreferredTags = []string{"ssd", "archive"}
ecConfig.ReplicaPlacement = "020"
if err := cp.SaveErasureCodingTaskPolicy(ecConfig.ToTaskPolicy()); err != nil {
t.Fatalf("save erasure coding policy: %v", err)
}
balanceConfig := balance.NewDefaultConfig()
balanceConfig.IoBytePerSecond = 5 << 20
if err := cp.SaveBalanceTaskPolicy(balanceConfig.ToTaskPolicy()); err != nil {
t.Fatalf("save balance policy: %v", err)
}
policy := cp.buildPolicyFromTaskConfigs()
ecPolicy := policy.TaskPolicies["erasure_coding"].GetErasureCodingConfig()
if ecPolicy == nil {
t.Fatal("no erasure coding config in the built policy")
}
if got := ecPolicy.GetReplicaPlacement(); got != "020" {
t.Errorf("erasure coding replica placement = %q, want the persisted %q", got, "020")
}
if got := ecPolicy.GetPreferredTags(); len(got) != 2 || got[0] != "ssd" || got[1] != "archive" {
t.Errorf("erasure coding preferred tags = %v, want the persisted [ssd archive]", got)
}
balancePolicy := policy.TaskPolicies["balance"].GetBalanceConfig()
if balancePolicy == nil {
t.Fatal("no balance config in the built policy")
}
if got := balancePolicy.GetIoBytePerSecond(); got != 5<<20 {
t.Errorf("balance IO limit = %d, want the persisted %d", got, 5<<20)
}
}
-7
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)
@@ -224,10 +222,6 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
policyApi.Handle("/{name}", wrapWrite(h.policyHandlers.DeletePolicy)).Methods(http.MethodDelete)
policyApi.HandleFunc("/validate", h.policyHandlers.ValidatePolicy).Methods(http.MethodPost)
// Registered at the API root, not under policyApi: policyApi's "/{name}"
// GET route would shadow any single-segment GET route registered after it.
api.HandleFunc("/principals", h.policyHandlers.GetPrincipalSuggestions).Methods(http.MethodGet)
s3TablesApi := api.PathPrefix("/s3tables").Subrouter()
s3TablesApi.HandleFunc("/buckets", h.adminServer.ListS3TablesBucketsAPI).Methods(http.MethodGet)
s3TablesApi.Handle("/buckets", wrapWrite(h.adminServer.CreateS3TablesBucket)).Methods(http.MethodPost)
@@ -257,7 +251,6 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
filesApi.HandleFunc("/view", h.fileBrowserHandlers.ViewFile).Methods(http.MethodGet)
filesApi.HandleFunc("/properties", h.fileBrowserHandlers.GetFileProperties).Methods(http.MethodGet)
filesApi.HandleFunc("/metadata", h.fileBrowserHandlers.ExportMetadata).Methods(http.MethodGet)
filesApi.HandleFunc("/list-folders", h.fileBrowserHandlers.ListFolders).Methods(http.MethodGet)
volumeApi := api.PathPrefix("/volumes").Subrouter()
volumeApi.HandleFunc("/export", h.clusterHandlers.ExportClusterVolumes).Methods(http.MethodGet)
@@ -42,68 +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_RegistersPolicyAPI_NoAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")
}
func TestSetupRoutes_RegistersPolicyAPI_WithAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")
}
func TestSetupRoutes_RegistersPrincipalsAPI_NoAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/principals")
}
func TestSetupRoutes_RegistersFilesListFoldersAPI_NoAuth(t *testing.T) {
router := mux.NewRouter()
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
assertHasRoute(t, router, http.MethodGet, "/api/files/list-folders")
}
func TestSetupRoutes_RegistersPluginPages_NoAuth(t *testing.T) {
router := mux.NewRouter()
+1 -61
View File
@@ -66,7 +66,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req
}
// Get file browser data with cursor-based pagination
browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)
browserData, err := h.adminServer.GetFileBrowser(path, lastFileName, pageSize)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())
return
@@ -778,63 +778,3 @@ func min(a, b int64) int64 {
}
return b
}
// maxListFoldersEntries caps how many subfolder names ListFolders will
// collect for a single request, so a directory with an unusually large
// number of children can't turn one autocomplete keystroke into an
// unbounded, slow full-directory walk.
const maxListFoldersEntries = 2000
// maxListFoldersScanned caps how many entries ListFolders will page through
// looking for those subfolders. The folder cap alone doesn't bound the work:
// a bucket holding nothing but flat object keys has no subfolders to count,
// so the walk runs to the end of the directory - a million keys is a million
// entries read, 200 per round trip, behind a single keystroke.
const maxListFoldersScanned = 10000
// ListFolders returns, as JSON, the names of the subdirectories directly
// under the given path. It exists to back progressive autocomplete (e.g. the
// policy editor's Resource ARN field building up "bucket/folder/subfolder"
// one path segment at a time) rather than to be a general directory listing
// API, so it's restricted to paths under /buckets. The optional prefix is the
// segment the caller is still typing, and narrows the listing to it.
func (h *FileBrowserHandlers) ListFolders(w http.ResponseWriter, r *http.Request) {
dirPath := defaultQuery(r.URL.Query().Get("path"), "/buckets")
// Clean before the scope check: CleanWindowsPath only rewrites backslashes,
// so "/buckets/../etc" would otherwise satisfy the prefix test below.
dirPath = path.Clean(util.CleanWindowsPath(dirPath))
if dirPath != "/buckets" && !strings.HasPrefix(dirPath, "/buckets/") {
writeJSONError(w, http.StatusBadRequest, "path must be under /buckets")
return
}
prefix := r.URL.Query().Get("prefix")
folders := []string{}
lastFileName := ""
scanned := 0
for {
browserData, err := h.adminServer.GetFileBrowser(dirPath, prefix, lastFileName, 200)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to list directory: "+err.Error())
return
}
scanned += len(browserData.Entries)
for _, entry := range browserData.Entries {
if entry.IsDirectory {
folders = append(folders, entry.Name)
if len(folders) >= maxListFoldersEntries {
break
}
}
}
if len(browserData.Entries) == 0 || !browserData.HasNextPage ||
len(folders) >= maxListFoldersEntries || scanned >= maxListFoldersScanned {
break
}
lastFileName = browserData.Entries[len(browserData.Entries)-1].Name
}
writeJSON(w, http.StatusOK, map[string]interface{}{"folders": folders})
}
@@ -1,11 +1,7 @@
package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
)
func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
@@ -46,20 +42,3 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {
}
}
func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}
cases := []string{"/etc/seaweedfs", "/", "/notbuckets/foo", "/buckets-not-really/foo",
"/buckets/../etc", "/buckets/..", "/buckets/foo/../../etc", `/buckets\..\etc`}
for _, path := range cases {
req := httptest.NewRequest(http.MethodGet, "/api/files/list-folders?path="+path, nil)
w := httptest.NewRecorder()
h.ListFolders(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("path %q: expected 400, got %d (body: %s)", path, w.Code, w.Body.String())
}
}
}
+2 -23
View File
@@ -51,17 +51,6 @@ func (h *PolicyHandlers) GetPolicies(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]interface{}{"policies": policies})
}
// GetPrincipalSuggestions returns candidate ARNs (existing users and IAM
// roles) for the policy editor's Principal/NotPrincipal autocomplete.
func (h *PolicyHandlers) GetPrincipalSuggestions(w http.ResponseWriter, r *http.Request) {
suggestions, err := h.adminServer.GetPrincipalSuggestions(r.Context())
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to get principal suggestions: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{"principals": suggestions})
}
// CreatePolicy handles policy creation
func (h *PolicyHandlers) CreatePolicy(w http.ResponseWriter, r *http.Request) {
var req dash.CreatePolicyRequest
@@ -232,18 +221,8 @@ func (h *PolicyHandlers) ValidatePolicy(w http.ResponseWriter, r *http.Request)
return
}
if len(statement.Resource.Strings()) == 0 && len(statement.NotResource.Strings()) == 0 {
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource or NotResource is required", i+1))
return
}
if statement.Resource != nil && statement.NotResource != nil {
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Resource and NotResource", i+1))
return
}
if statement.Principal != nil && statement.NotPrincipal != nil {
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Principal and NotPrincipal", i+1))
if len(statement.Resource.Strings()) == 0 {
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource is required", i+1))
return
}
}
-161
View File
@@ -1,161 +0,0 @@
package handlers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
)
func newValidatePolicyRequest(t *testing.T, document map[string]interface{}) *http.Request {
t.Helper()
body, err := json.Marshal(map[string]interface{}{"document": document})
if err != nil {
t.Fatalf("failed to marshal request body: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/object-store/policies/validate", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
return req
}
func TestValidatePolicy(t *testing.T) {
handlers := &PolicyHandlers{adminServer: &dash.AdminServer{}}
tests := []struct {
name string
document map[string]interface{}
wantStatus int
}{
{
name: "valid document with Resource",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
},
},
wantStatus: http.StatusOK,
},
{
name: "valid document with NotResource only",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "NotResource": "arn:aws:s3:::secret-bucket/*"},
},
},
wantStatus: http.StatusOK,
},
{
name: "missing version",
document: map[string]interface{}{
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "no statements",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{},
},
wantStatus: http.StatusBadRequest,
},
{
name: "invalid effect",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Maybe", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "missing action",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Resource": "arn:aws:s3:::my-bucket/*"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "neither Resource nor NotResource",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "both Resource and NotResource",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "NotResource": "arn:aws:s3:::secret-bucket/*"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "empty Resource alongside non-empty NotResource is still a conflict",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": []string{}, "NotResource": "arn:aws:s3:::secret-bucket/*"},
},
},
wantStatus: http.StatusBadRequest,
},
{
name: "both Principal and NotPrincipal",
document: map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Principal": "*", "NotPrincipal": "arn:aws:iam::123456789012:user/bob"},
},
},
wantStatus: http.StatusBadRequest,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := newValidatePolicyRequest(t, tt.document)
w := httptest.NewRecorder()
handlers.ValidatePolicy(w, req)
if w.Code != tt.wantStatus {
t.Fatalf("expected status %d, got %d (body: %s)", tt.wantStatus, w.Code, w.Body.String())
}
})
}
}
// Sanity check that policy_engine.PolicyStatement (the type ValidatePolicy
// actually decodes into) round-trips NotResource-only statements the way the
// test above assumes.
func TestValidatePolicy_NotResourceOnlyDecodes(t *testing.T) {
raw := []byte(`{"Effect":"Allow","Action":"s3:GetObject","NotResource":"arn:aws:s3:::secret/*"}`)
var stmt policy_engine.PolicyStatement
if err := json.Unmarshal(raw, &stmt); err != nil {
t.Fatalf("failed to unmarshal statement: %v", err)
}
if len(stmt.Resource.Strings()) != 0 {
t.Fatalf("expected no Resource, got %v", stmt.Resource.Strings())
}
if len(stmt.NotResource.Strings()) != 1 {
t.Fatalf("expected exactly one NotResource entry, got %v", stmt.NotResource.Strings())
}
}
@@ -122,22 +122,6 @@ func (s *MaintenanceIntegration) registerAllTasks() {
glog.V(1).Infof("Registered tasks: %v", registeredTaskTypes)
}
// SetPolicy replaces the maintenance policy the integration configures tasks from and
// applies it immediately. Without this the integration kept the policy it was built with,
// so a policy updated at runtime reached the queue but never the detectors that decide
// which task types are scanned for.
//
// Not safe to call concurrently with a running scan. ConfigureTasksFromPolicy writes
// TaskDefinition.Config and TaskDefinition.MaxConcurrent, which ScanWithTaskDetectors reads
// through detector.IsEnabled(); nothing synchronises the two. Today every caller runs during
// admin server startup, before the scan loop exists. Anything that wires this to an HTTP
// handler has to add that synchronisation first - the same applies to
// tasks.ConfigUpdateRegistry.UpdateAllConfigs, which replaces TaskDefinition.Config outright.
func (s *MaintenanceIntegration) SetPolicy(policy *MaintenancePolicy) {
s.maintenancePolicy = policy
s.ConfigureTasksFromPolicy()
}
// ConfigureTasksFromPolicy dynamically configures all registered tasks based on the maintenance policy
func (s *MaintenanceIntegration) ConfigureTasksFromPolicy() {
if s.maintenancePolicy == nil {
@@ -171,32 +155,20 @@ func (s *MaintenanceIntegration) configureDetectorFromPolicy(taskType types.Task
return
}
// Convert task system type to maintenance task type for policy lookup
maintenanceTaskType, exists := s.taskTypeMap[taskType]
if !exists {
glog.V(3).Infof("No maintenance task type mapping for %s, skipping configuration", taskType)
return
}
// A task type the policy says nothing about is left alone. IsTaskEnabled reports
// false for a missing entry, so applying it unconditionally would silently disable
// every task the policy does not list - which is how ec_balance would have been
// switched off the moment SetEnabled started working.
if GetTaskPolicy(s.maintenancePolicy, maintenanceTaskType) == nil {
glog.V(2).Infof("Maintenance policy has no entry for %s, leaving its detector configuration untouched", taskType)
return
}
// Apply basic configuration that all detectors should support
if basicDetector, ok := detector.(interface{ SetEnabled(bool) }); ok {
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
basicDetector.SetEnabled(enabled)
glog.V(3).Infof("Set enabled=%v for detector %s", enabled, taskType)
} else {
// For detectors that don't implement PolicyConfigurableDetector interface,
// they should be updated to implement it for full policy-based configuration
glog.V(2).Infof("Detector %s supports neither PolicyConfigurableDetector nor SetEnabled, its policy is ignored", taskType)
// Convert task system type to maintenance task type for policy lookup
maintenanceTaskType, exists := s.taskTypeMap[taskType]
if exists {
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
basicDetector.SetEnabled(enabled)
glog.V(3).Infof("Set enabled=%v for detector %s", enabled, taskType)
}
}
// For detectors that don't implement PolicyConfigurableDetector interface,
// they should be updated to implement it for full policy-based configuration
glog.V(2).Infof("Detector %s should implement PolicyConfigurableDetector interface for full policy support", taskType)
}
// configureSchedulerFromPolicy configures a scheduler using policy-based configuration
@@ -215,21 +187,11 @@ func (s *MaintenanceIntegration) configureSchedulerFromPolicy(taskType types.Tas
return
}
// Same guard as on the detector side: no policy entry means no opinion, not disabled.
if GetTaskPolicy(s.maintenancePolicy, maintenanceTaskType) == nil {
glog.V(2).Infof("Maintenance policy has no entry for %s, leaving its scheduler configuration untouched", taskType)
return
}
// Set enabled status if scheduler supports it
if enableableScheduler, ok := scheduler.(interface{ SetEnabled(bool) }); ok {
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
enableableScheduler.SetEnabled(enabled)
glog.V(3).Infof("Set enabled=%v for scheduler %s", enabled, taskType)
} else {
// For schedulers that don't implement PolicyConfigurableScheduler interface,
// they should be updated to implement it for full policy-based configuration
glog.V(2).Infof("Scheduler %s supports neither PolicyConfigurableScheduler nor SetEnabled, its policy is ignored", taskType)
}
// Set max concurrent if scheduler supports it
@@ -240,6 +202,10 @@ func (s *MaintenanceIntegration) configureSchedulerFromPolicy(taskType types.Tas
glog.V(3).Infof("Set max concurrent=%d for scheduler %s", maxConcurrent, taskType)
}
}
// For schedulers that don't implement PolicyConfigurableScheduler interface,
// they should be updated to implement it for full policy-based configuration
glog.V(2).Infof("Scheduler %s should implement PolicyConfigurableScheduler interface for full policy support", taskType)
}
// ScanWithTaskDetectors performs a scan using the task system
+60 -86
View File
@@ -10,29 +10,12 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
// BuildPolicyFromTaskConfigs loads each registered task's configuration and builds the
// MaintenancePolicy the maintenance system runs on.
//
// Every entry is produced by the task's own ToTaskPolicy(), so a policy entry always carries
// exactly what that task's config holds. Hand-copying the fields here instead made this a
// second, silently diverging definition of every task's policy: it dropped the erasure
// coding preferred tags and replica placement and the balance IO rate limit outright.
//
// Every task registered through base.RegisterTask needs an entry, because a task type the
// policy does not list has no enabled flag and no concurrency limit of its own -
// IsTaskEnabled reports false for a missing entry.
//
// configPersistence is duck-typed as interface{} because weed/admin/dash already imports this
// package, so importing *dash.ConfigPersistence back here would create an import cycle. It must be
// a value implementing the LoadXTaskPolicy() accessors the task loaders assert on; passing nil (or
// anything else) makes every task fall back to its compiled-in defaults.
func BuildPolicyFromTaskConfigs(configPersistence interface{}) *worker_pb.MaintenancePolicy {
// buildPolicyFromTaskConfigs loads task configurations from separate files and builds a MaintenancePolicy
func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
policy := &worker_pb.MaintenancePolicy{
GlobalMaxConcurrent: 4,
DefaultRepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
@@ -40,20 +23,54 @@ func BuildPolicyFromTaskConfigs(configPersistence interface{}) *worker_pb.Mainte
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
}
if vacuumConfig := vacuum.LoadConfigFromPersistence(configPersistence); vacuumConfig != nil {
policy.TaskPolicies[string(types.TaskTypeVacuum)] = vacuumConfig.ToTaskPolicy()
// Load vacuum task configuration
if vacuumConfig := vacuum.LoadConfigFromPersistence(nil); vacuumConfig != nil {
policy.TaskPolicies["vacuum"] = &worker_pb.TaskPolicy{
Enabled: vacuumConfig.Enabled,
MaxConcurrent: int32(vacuumConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
VacuumConfig: &worker_pb.VacuumTaskConfig{
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
},
},
}
}
if ecConfig := erasure_coding.LoadConfigFromPersistence(configPersistence); ecConfig != nil {
policy.TaskPolicies[string(types.TaskTypeErasureCoding)] = ecConfig.ToTaskPolicy()
// Load erasure coding task configuration
if ecConfig := erasure_coding.LoadConfigFromPersistence(nil); ecConfig != nil {
policy.TaskPolicies["erasure_coding"] = &worker_pb.TaskPolicy{
Enabled: ecConfig.Enabled,
MaxConcurrent: int32(ecConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
FullnessRatio: float64(ecConfig.FullnessRatio),
QuietForSeconds: int32(ecConfig.QuietForSeconds),
MinVolumeSizeMb: int32(ecConfig.MinSizeMB),
CollectionFilter: ecConfig.CollectionFilter,
},
},
}
}
if balanceConfig := balance.LoadConfigFromPersistence(configPersistence); balanceConfig != nil {
policy.TaskPolicies[string(types.TaskTypeBalance)] = balanceConfig.ToTaskPolicy()
}
if ecBalanceConfig := ec_balance.LoadConfigFromPersistence(configPersistence); ecBalanceConfig != nil {
policy.TaskPolicies[string(types.TaskTypeECBalance)] = ecBalanceConfig.ToTaskPolicy()
// Load balance task configuration
if balanceConfig := balance.LoadConfigFromPersistence(nil); balanceConfig != nil {
policy.TaskPolicies["balance"] = &worker_pb.TaskPolicy{
Enabled: balanceConfig.Enabled,
MaxConcurrent: int32(balanceConfig.MaxConcurrent),
RepeatIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
CheckIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
BalanceConfig: &worker_pb.BalanceTaskConfig{
ImbalanceThreshold: float64(balanceConfig.ImbalanceThreshold),
MinServerCount: int32(balanceConfig.MinServerCount),
},
},
}
}
glog.V(1).Infof("Built maintenance policy from separate task configs - %d task policies loaded", len(policy.TaskPolicies))
@@ -77,12 +94,8 @@ type MaintenanceManager struct {
scanInProgress bool
}
// NewMaintenanceManager creates a new maintenance manager.
//
// configPersistence is the config store to read persisted task configs from when the policy has to
// be built here. See BuildPolicyFromTaskConfigs for why it is duck-typed; pass nil when no config
// store is available.
func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig, configPersistence interface{}) *MaintenanceManager {
// NewMaintenanceManager creates a new maintenance manager
func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig) *MaintenanceManager {
if config == nil {
config = DefaultMaintenanceConfig()
}
@@ -91,7 +104,7 @@ func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig, c
policy := config.Policy
if policy == nil {
// Fallback: build policy from separate task configuration files if not already populated
policy = BuildPolicyFromTaskConfigs(configPersistence)
policy = buildPolicyFromTaskConfigs()
}
queue := NewMaintenanceQueue(policy)
@@ -119,9 +132,7 @@ func (mm *MaintenanceManager) Start() error {
return fmt.Errorf("invalid maintenance configuration: %w", err)
}
mm.mutex.Lock()
mm.running = true
mm.mutex.Unlock()
// Start background processes
go mm.scanLoop()
@@ -167,53 +178,30 @@ func (mm *MaintenanceManager) validateConfig() error {
return nil
}
// IsRunning returns whether the maintenance manager is currently running.
// running is guarded by mm.mutex because the background loops read it on every
// iteration while Start and Stop are called from the admin server's goroutines.
// IsRunning returns whether the maintenance manager is currently running
func (mm *MaintenanceManager) IsRunning() bool {
mm.mutex.RLock()
defer mm.mutex.RUnlock()
return mm.running
}
// Stop terminates the maintenance manager. It is a no-op when the manager is not
// running, so a second call cannot close the already closed stop channel.
// Stop terminates the maintenance manager
func (mm *MaintenanceManager) Stop() {
mm.mutex.Lock()
if !mm.running {
mm.mutex.Unlock()
return
}
mm.running = false
close(mm.stopChan)
mm.mutex.Unlock()
glog.Infof("Maintenance manager stopped")
}
// scanLoop periodically scans for maintenance tasks with adaptive timing
func (mm *MaintenanceManager) scanLoop() {
scanInterval := time.Duration(mm.config.ScanIntervalSeconds) * time.Second
ticker := time.NewTicker(scanInterval)
defer ticker.Stop()
// activeInterval is the interval the ticker is actually running at right now. It has
// to be tracked separately from the configured scanInterval, because the error backoff
// replaces the ticker with a much shorter one. Comparing the target against the
// configured interval instead never restores the normal cadence: once the errors stop,
// getScanInterval returns scanInterval again, the comparison comes out false, and the
// ticker is left at the backoff delay. A single transient scan failure therefore pinned
// the scanner to one scan per second forever.
activeInterval := scanInterval
ticker := time.NewTicker(activeInterval)
// Wrapped in a closure so the replacement ticker is stopped, not the one that happened
// to be current when the defer was registered.
defer func() { ticker.Stop() }()
for mm.IsRunning() {
for mm.running {
select {
case <-mm.stopChan:
return
case <-ticker.C:
glog.V(1).Infof("Performing maintenance scan every %v", activeInterval)
glog.V(1).Infof("Performing maintenance scan every %v", scanInterval)
// Use the same synchronization as TriggerScan to prevent concurrent scans
if err := mm.triggerScanInternal(false); err != nil {
@@ -223,13 +211,10 @@ func (mm *MaintenanceManager) scanLoop() {
// Adjust ticker interval based on error state (read error state safely)
currentInterval := mm.getScanInterval(scanInterval)
// Reset ticker whenever the target differs from what the ticker is running at,
// which covers both entering the backoff and returning to the normal cadence.
if currentInterval != activeInterval {
// Reset ticker with new interval if needed
if currentInterval != scanInterval {
ticker.Stop()
ticker = time.NewTicker(currentInterval)
glog.V(1).Infof("Maintenance scan cadence changed from %v to %v", activeInterval, currentInterval)
activeInterval = currentInterval
}
}
}
@@ -261,7 +246,7 @@ func (mm *MaintenanceManager) cleanupLoop() {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for mm.IsRunning() {
for mm.running {
select {
case <-mm.stopChan:
return
@@ -278,7 +263,7 @@ func (mm *MaintenanceManager) topologyStatusLoop() {
ticker := time.NewTicker(statusInterval)
defer ticker.Stop()
for mm.IsRunning() {
for mm.running {
select {
case <-mm.stopChan:
return
@@ -547,15 +532,12 @@ func (mm *MaintenanceManager) TriggerScan() error {
// triggerScanInternal handles both manual and automatic scan triggers
func (mm *MaintenanceManager) triggerScanInternal(isManual bool) error {
// running and scanInProgress are checked under one lock so a Stop that lands
// between the two checks cannot leave a scan running after shutdown.
mm.mutex.Lock()
if !mm.running {
mm.mutex.Unlock()
return fmt.Errorf("maintenance manager is not running")
}
// Prevent multiple concurrent scans
mm.mutex.Lock()
if mm.scanInProgress {
mm.mutex.Unlock()
if isManual {
@@ -587,14 +569,6 @@ func (mm *MaintenanceManager) UpdateConfig(config *MaintenanceConfig) error {
mm.saveTaskConfigsFromPolicy(config.Policy)
}
// The integration holds its own reference to the policy and is what pushes the
// enabled flag and the concurrency limit into the registered detectors and
// schedulers. Without this the queue and the scanner saw the new policy while the
// detectors kept scanning under the old one until the next restart.
if mm.scanner != nil && mm.scanner.integration != nil {
mm.scanner.integration.SetPolicy(config.Policy)
}
glog.V(1).Infof("Maintenance configuration updated")
return nil
}
@@ -10,7 +10,7 @@ func TestMaintenanceManager_ErrorHandling(t *testing.T) {
config := DefaultMaintenanceConfig()
config.ScanIntervalSeconds = 1 // Short interval for testing (1 second)
manager := NewMaintenanceManager(nil, config, nil)
manager := NewMaintenanceManager(nil, config)
// Test initial state
if manager.errorCount != 0 {
@@ -96,7 +96,7 @@ func TestIsConnectionError(t *testing.T) {
func TestMaintenanceManager_GetErrorState(t *testing.T) {
config := DefaultMaintenanceConfig()
manager := NewMaintenanceManager(nil, config, nil)
manager := NewMaintenanceManager(nil, config)
// Test initial state
errorCount, lastError, backoffDelay := manager.GetErrorState()
@@ -118,7 +118,7 @@ func TestMaintenanceManager_GetErrorState(t *testing.T) {
func TestMaintenanceManager_LogThrottling(t *testing.T) {
config := DefaultMaintenanceConfig()
manager := NewMaintenanceManager(nil, config, nil)
manager := NewMaintenanceManager(nil, config)
// This is a basic test to ensure the error handling doesn't panic
// In practice, you'd want to capture log output to verify throttling
@@ -1,133 +0,0 @@
package maintenance
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
)
// stubConfigPersistence implements the LoadXTaskPolicy accessors that the task config loaders
// type-assert on. The real implementation is *dash.ConfigPersistence, which this package cannot
// import: weed/admin/dash already imports weed/admin/maintenance, so the dependency only runs one
// way and the persistence argument has to stay duck-typed.
type stubConfigPersistence struct {
vacuum *worker_pb.TaskPolicy
ec *worker_pb.TaskPolicy
balance *worker_pb.TaskPolicy
ecBalance *worker_pb.TaskPolicy
}
func (s *stubConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error) {
return s.vacuum, nil
}
func (s *stubConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolicy, error) {
return s.ec, nil
}
func (s *stubConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
return s.balance, nil
}
func (s *stubConfigPersistence) LoadEcBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
return s.ecBalance, nil
}
func disabledStub() *stubConfigPersistence {
return &stubConfigPersistence{
vacuum: &worker_pb.TaskPolicy{
Enabled: false,
MaxConcurrent: 2,
RepeatIntervalSeconds: 2 * 3600,
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
VacuumConfig: &worker_pb.VacuumTaskConfig{GarbageThreshold: 0.3, MinVolumeAgeHours: 24},
},
},
ec: &worker_pb.TaskPolicy{
Enabled: false,
MaxConcurrent: 1,
RepeatIntervalSeconds: 3600,
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{FullnessRatio: 0.95, QuietForSeconds: 3600, MinVolumeSizeMb: 30},
},
},
balance: &worker_pb.TaskPolicy{
Enabled: false,
MaxConcurrent: 1,
RepeatIntervalSeconds: 30 * 60,
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
BalanceConfig: &worker_pb.BalanceTaskConfig{ImbalanceThreshold: 0.2, MinServerCount: 7},
},
},
ecBalance: &worker_pb.TaskPolicy{
Enabled: false,
MaxConcurrent: 1,
RepeatIntervalSeconds: 60 * 60,
TaskConfig: &worker_pb.TaskPolicy_EcBalanceConfig{
EcBalanceConfig: &worker_pb.EcBalanceTaskConfig{ImbalanceThreshold: 0.2, MinServerCount: 5},
},
},
}
}
// TestBuildPolicyFromTaskConfigsUsesPersistence covers a reported bug: the persistence argument used to be a
// literal nil, which no type assertion can satisfy, so a task disabled on disk came back enabled.
func TestBuildPolicyFromTaskConfigsUsesPersistence(t *testing.T) {
policy := BuildPolicyFromTaskConfigs(disabledStub())
for _, taskType := range []string{"vacuum", "erasure_coding", "balance", "ec_balance"} {
taskPolicy := policy.TaskPolicies[taskType]
if taskPolicy == nil {
t.Fatalf("no %s task policy built", taskType)
}
if taskPolicy.Enabled {
t.Errorf("%s enabled = true, want false from the persisted config", taskType)
}
}
if got := policy.TaskPolicies["balance"].GetBalanceConfig().GetMinServerCount(); got != 7 {
t.Errorf("balance min server count = %d, want persisted 7", got)
}
}
// TestBuildPolicyFromTaskConfigsWithoutPersistence keeps the documented fallback: with no config
// store there is nothing to read, so the compiled-in defaults apply.
func TestBuildPolicyFromTaskConfigsWithoutPersistence(t *testing.T) {
policy := BuildPolicyFromTaskConfigs(nil)
for _, taskType := range []string{"vacuum", "erasure_coding", "balance", "ec_balance"} {
taskPolicy := policy.TaskPolicies[taskType]
if taskPolicy == nil {
t.Fatalf("no %s task policy built", taskType)
}
if !taskPolicy.Enabled {
t.Errorf("%s enabled = false, want the compiled-in default true", taskType)
}
}
}
// TestNewMaintenanceManagerUsesPersistenceForPolicyFallback covers the path the admin server takes
// when no maintenance.pb has been written yet: the config carries no policy, so the manager builds
// one itself and must read the persisted task configs to do it.
func TestNewMaintenanceManagerUsesPersistenceForPolicyFallback(t *testing.T) {
config := DefaultMaintenanceConfig()
if config.Policy != nil {
t.Fatal("default config unexpectedly carries a policy, test no longer covers the fallback")
}
manager := NewMaintenanceManager(nil, config, disabledStub())
policy := manager.queue.policy
if policy == nil {
t.Fatal("queue policy is nil")
}
if IsTaskEnabled(policy, MaintenanceTaskType("balance")) {
t.Error("balance enabled = true, want false from the persisted config")
}
if IsTaskEnabled(policy, MaintenanceTaskType("vacuum")) {
t.Error("vacuum enabled = true, want false from the persisted config")
}
if manager.scanner.policy != policy {
t.Error("scanner and queue disagree on the policy")
}
}
@@ -1,209 +0,0 @@
package maintenance
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
)
// The detectors and schedulers live in a process-global registry, so these tests restore
// whatever they change. Otherwise a test that disables a task leaks that state into every
// later test in the package.
func snapshotDetectorState(t *testing.T) {
t.Helper()
registry := tasks.GetGlobalTypesRegistry()
enabled := make(map[types.TaskType]bool)
maxConcurrent := make(map[types.TaskType]int)
for taskType, detector := range registry.GetAllDetectors() {
enabled[taskType] = detector.IsEnabled()
}
for taskType, scheduler := range registry.GetAllSchedulers() {
maxConcurrent[taskType] = scheduler.GetMaxConcurrent()
}
t.Cleanup(func() {
for taskType, detector := range registry.GetAllDetectors() {
if setter, ok := detector.(interface{ SetEnabled(bool) }); ok {
setter.SetEnabled(enabled[taskType])
}
}
for taskType, scheduler := range registry.GetAllSchedulers() {
if setter, ok := scheduler.(interface{ SetMaxConcurrent(int) }); ok {
setter.SetMaxConcurrent(maxConcurrent[taskType])
}
}
})
}
// TestPolicyReachesRegisteredDetectors is the regression test for the half of the scan-flood bug
// that a corrected policy alone did not fix: MaintenanceIntegration pushes the policy into
// detectors and schedulers through interface{ SetEnabled(bool) } and
// interface{ SetMaxConcurrent(int) } type assertions, but every task is backed by
// base.GenericDetector/base.GenericScheduler, which implemented neither. The assertions
// failed silently for every task on every startup, so the policy never reached
// detector.IsEnabled() - which is what ScanWithTaskDetectors gates scanning on.
func TestPolicyReachesRegisteredDetectors(t *testing.T) {
snapshotDetectorState(t)
registry := tasks.GetGlobalTypesRegistry()
if len(registry.GetAllDetectors()) == 0 {
t.Fatal("no detectors registered, the test cannot prove anything")
}
// Enable everything first so the disabling below cannot pass by accident.
policy := policyWithAllTasks(t, true)
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
for taskType, detector := range registry.GetAllDetectors() {
if !detector.IsEnabled() {
t.Fatalf("detector %s is disabled after an all-enabled policy was applied", taskType)
}
}
// Now disable everything through the policy and check it lands on the detectors.
policy = policyWithAllTasks(t, false)
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
for taskType, detector := range registry.GetAllDetectors() {
if detector.IsEnabled() {
t.Errorf("detector %s still reports enabled after the policy disabled it; "+
"the policy is not reaching the flag ScanWithTaskDetectors gates on", taskType)
}
}
for taskType, scheduler := range registry.GetAllSchedulers() {
if scheduler.IsEnabled() {
t.Errorf("scheduler %s still reports enabled after the policy disabled it", taskType)
}
}
}
// TestPolicyMaxConcurrentReachesSchedulers covers the SetMaxConcurrent half of the same
// wiring. GetMaxConcurrent is what MaintenanceQueue.getMaxConcurrentForTaskType asks before
// starting another task of a type.
func TestPolicyMaxConcurrentReachesSchedulers(t *testing.T) {
snapshotDetectorState(t)
const wantMaxConcurrent = 7
policy := policyWithAllTasks(t, true)
for _, taskPolicy := range policy.TaskPolicies {
taskPolicy.MaxConcurrent = wantMaxConcurrent
}
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
registry := tasks.GetGlobalTypesRegistry()
for taskType, scheduler := range registry.GetAllSchedulers() {
if _, covered := policy.TaskPolicies[string(taskType)]; !covered {
continue
}
if got := scheduler.GetMaxConcurrent(); got != wantMaxConcurrent {
t.Errorf("scheduler %s max concurrent = %d, want %d from the policy", taskType, got, wantMaxConcurrent)
}
}
}
// TestPolicyWithoutEntryLeavesTaskAlone guards the direction that would have been a silent
// outage: IsTaskEnabled reports false for a task type the policy does not list, so applying
// it unconditionally would disable every task the policy has no entry for.
func TestPolicyWithoutEntryLeavesTaskAlone(t *testing.T) {
snapshotDetectorState(t)
registry := tasks.GetGlobalTypesRegistry()
// Start from a policy that enables everything.
enabling := policyWithAllTasks(t, true)
NewMaintenanceIntegration(NewMaintenanceQueue(enabling), enabling)
// An empty policy has an entry for nothing at all.
empty := &MaintenancePolicy{TaskPolicies: make(map[string]*worker_pb.TaskPolicy)}
NewMaintenanceIntegration(NewMaintenanceQueue(empty), empty)
for taskType, detector := range registry.GetAllDetectors() {
if !detector.IsEnabled() {
t.Errorf("detector %s was disabled by a policy that has no entry for it; "+
"a missing entry means no opinion, not disabled", taskType)
}
}
}
// TestBuildPolicyCoversEveryRegisteredTask keeps BuildPolicyFromTaskConfigs and the task
// registry in step. A registered task with no policy entry has no enabled flag and no
// concurrency limit of its own, which is the state ec_balance was in.
func TestBuildPolicyCoversEveryRegisteredTask(t *testing.T) {
policy := BuildPolicyFromTaskConfigs(nil)
for taskType := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
if _, ok := policy.TaskPolicies[string(taskType)]; !ok {
t.Errorf("task %s is registered as a detector but BuildPolicyFromTaskConfigs "+
"builds no policy entry for it, so IsTaskEnabled reports false for it", taskType)
}
}
}
// TestBuildPolicyIncludesEcBalance pins the specific gap above.
func TestBuildPolicyIncludesEcBalance(t *testing.T) {
policy := BuildPolicyFromTaskConfigs(nil)
ecBalance := policy.TaskPolicies[string(types.TaskTypeECBalance)]
if ecBalance == nil {
t.Fatal("no ec_balance entry in the built maintenance policy")
}
if !IsTaskEnabled(policy, MaintenanceTaskType(types.TaskTypeECBalance)) {
t.Error("ec_balance reports disabled with no persisted config, want the compiled-in default of enabled")
}
if ecBalance.GetEcBalanceConfig() == nil {
t.Error("ec_balance policy entry carries no EcBalanceConfig")
}
}
// policyWithAllTasks builds a policy that has an entry for every registered task type,
// all sharing the same enabled flag.
func policyWithAllTasks(t *testing.T, enabled bool) *MaintenancePolicy {
t.Helper()
policy := &MaintenancePolicy{
GlobalMaxConcurrent: 4,
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
}
for taskType := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
policy.TaskPolicies[string(taskType)] = &worker_pb.TaskPolicy{
Enabled: enabled,
MaxConcurrent: 1,
RepeatIntervalSeconds: 3600,
}
}
return policy
}
// TestPolicyHelpersTolerateNilPolicy pins the nil handling in the exported policy helpers.
// MaintenanceConfig.Policy is nil until something builds one, and UpdateConfig accepts a
// config that has none, so these are reachable with a nil policy - GetTaskPolicy used to
// dereference it and take the admin process down.
func TestPolicyHelpersTolerateNilPolicy(t *testing.T) {
const taskType = MaintenanceTaskType("balance")
if got := GetTaskPolicy(nil, taskType); got != nil {
t.Errorf("GetTaskPolicy(nil) = %v, want nil", got)
}
if IsTaskEnabled(nil, taskType) {
t.Error("IsTaskEnabled(nil) = true, want false")
}
if got := GetMaxConcurrent(nil, taskType); got != 1 {
t.Errorf("GetMaxConcurrent(nil) = %d, want the safe default 1", got)
}
if got := GetRepeatInterval(nil, taskType); got != 0 {
t.Errorf("GetRepeatInterval(nil) = %d, want 0 so callers fall back to their own default", got)
}
// A policy that exists but lists nothing must behave the same way.
empty := &MaintenancePolicy{}
if got := GetTaskPolicy(empty, taskType); got != nil {
t.Errorf("GetTaskPolicy(empty) = %v, want nil", got)
}
if IsTaskEnabled(empty, taskType) {
t.Error("IsTaskEnabled(empty) = true, want false")
}
}
@@ -618,7 +618,7 @@ func TestMaintenanceQueue_StaleWorkerCapacityRelease(t *testing.T) {
func TestMaintenanceManager_CancelTaskCapacityRelease(t *testing.T) {
// Setup Manager
config := DefaultMaintenanceConfig()
mm := NewMaintenanceManager(nil, config, nil)
mm := NewMaintenanceManager(nil, config)
integration := mm.scanner.integration
mq := mm.queue
at := integration.GetActiveTopology()
@@ -1,168 +0,0 @@
package maintenance
import (
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
)
// scanCadenceClient is a minimal AdminClient whose first call blocks until the test
// releases it. Blocking the first scan is what makes the cadence test deterministic:
// the scan loop evaluates the error state right after triggering a scan, and that scan
// runs in its own goroutine, so without the block the loop could observe the error
// counter either before or after the scan finished.
type scanCadenceClient struct {
mu sync.Mutex
calls int
release chan struct{}
}
func (c *scanCadenceClient) WithMasterClient(fn func(client master_pb.SeaweedClient) error) error {
c.mu.Lock()
c.calls++
first := c.calls == 1
c.mu.Unlock()
if first {
<-c.release
}
// Returning nil without invoking fn yields an empty, successful scan.
return nil
}
func (c *scanCadenceClient) callCount() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.calls
}
// TestScanLoopRestoresIntervalAfterBackoff is the regression test for the scan flood. The loop shortens its ticker to the
// error backoff delay after a failed scan. It used to compare the target interval against
// the *configured* scan interval rather than against the interval the ticker was actually
// running at, so once the errors stopped the comparison came out false and the ticker was
// never restored: one transient failure pinned the scanner to one scan per second for as
// long as the process lived.
//
// The test seeds the error state, lets the loop drop into the 1s backoff, then lets a scan
// succeed and asserts the loop goes back to the configured 3s cadence instead of keeping
// the 1s one.
func TestScanLoopRestoresIntervalAfterBackoff(t *testing.T) {
const baseInterval = 3 * time.Second
client := &scanCadenceClient{release: make(chan struct{})}
config := DefaultMaintenanceConfig()
config.ScanIntervalSeconds = int32(baseInterval / time.Second)
manager := NewMaintenanceManager(client, config, nil)
// Seed a failed scan so the very first cadence decision drops to the backoff delay.
// backoffDelay is what getScanInterval returns while errorCount > 0.
manager.mutex.Lock()
manager.errorCount = 1
manager.backoffDelay = time.Second
manager.running = true
manager.mutex.Unlock()
go manager.scanLoop()
defer manager.Stop()
// First tick at ~3s: the scan blocks in the client, so the loop still sees errorCount == 1
// and switches the ticker to the 1s backoff.
deadline := time.Now().Add(baseInterval + 2*time.Second)
for client.callCount() == 0 {
if time.Now().After(deadline) {
t.Fatal("scan loop never triggered its first scan")
}
time.Sleep(20 * time.Millisecond)
}
// Let the blocked scan complete successfully, which clears the error state.
close(client.release)
// Wait for the error state to clear so the next cadence decision is unambiguous.
deadline = time.Now().Add(2 * time.Second)
for {
errorCount, _, _ := manager.GetErrorState()
if errorCount == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("error tracking never reset, errorCount=%d", errorCount)
}
time.Sleep(20 * time.Millisecond)
}
// The ticker is at 1s now. Wait for the next tick, where the loop must notice the
// recovery and restore the 3s cadence.
time.Sleep(1500 * time.Millisecond)
before := client.callCount()
// Observe a window that a 1s cadence would fill with scans and a 3s cadence would not.
const window = 5 * time.Second
time.Sleep(window)
callsInWindow := client.callCount() - before
// One scan makes two master-client calls. 3s cadence: at most 2 scans (4 calls) in 5s,
// even if a stall shifts the window. 1s cadence: about 5 scans (10 calls).
if callsInWindow > 4 {
t.Errorf("scan loop made %d master-client calls in %v after recovering from a failed scan; "+
"the ticker was left at the %v backoff instead of returning to the configured %v",
callsInWindow, window, time.Second, baseInterval)
}
if callsInWindow == 0 {
t.Errorf("scan loop ran no scans in %v, expected the %v cadence to fire at least once", window, baseInterval)
}
}
// TestScanLoopEntersBackoffOnError checks the other half of the cadence logic: a failing
// scan still has to shorten the ticker, so the fix above did not simply pin the loop to
// the configured interval.
func TestScanLoopEntersBackoffOnError(t *testing.T) {
config := DefaultMaintenanceConfig()
config.ScanIntervalSeconds = 600
manager := NewMaintenanceManager(nil, config, nil)
baseInterval := time.Duration(config.ScanIntervalSeconds) * time.Second
if got := manager.getScanInterval(baseInterval); got != baseInterval {
t.Errorf("healthy scan interval = %v, want the configured %v", got, baseInterval)
}
manager.mutex.Lock()
manager.errorCount = 1
manager.backoffDelay = time.Second
manager.mutex.Unlock()
if got := manager.getScanInterval(baseInterval); got != time.Second {
t.Errorf("scan interval while failing = %v, want the %v backoff", got, time.Second)
}
manager.mutex.Lock()
manager.resetErrorTracking()
manager.mutex.Unlock()
if got := manager.getScanInterval(baseInterval); got != baseInterval {
t.Errorf("scan interval after recovery = %v, want the configured %v", got, baseInterval)
}
}
// TestStopIsIdempotent guards the stop channel against a double close, which used to panic
// when StopMaintenanceManager ran twice (for example on a shutdown path that also runs on
// a signal handler).
func TestStopIsIdempotent(t *testing.T) {
manager := NewMaintenanceManager(nil, DefaultMaintenanceConfig(), nil)
manager.mutex.Lock()
manager.running = true
manager.mutex.Unlock()
manager.Stop()
manager.Stop()
if manager.IsRunning() {
t.Error("manager still reports running after Stop")
}
}
+2 -10
View File
@@ -144,14 +144,9 @@ func DefaultMaintenanceConfig() *MaintenanceConfig {
// Policy helper functions (since we can't add methods to type aliases)
// GetTaskPolicy returns the policy for a specific task type, or nil when the maintenance
// policy has no entry for it.
//
// A nil maintenance policy is a legitimate state, not a programming error:
// MaintenanceConfig.Policy is unset until something builds one, and UpdateConfig accepts a
// config that carries none. Dereferencing it here panicked the whole admin process.
// GetTaskPolicy returns the policy for a specific task type
func GetTaskPolicy(mp *MaintenancePolicy, taskType MaintenanceTaskType) *TaskPolicy {
if mp == nil || mp.TaskPolicies == nil {
if mp.TaskPolicies == nil {
return nil
}
return mp.TaskPolicies[string(taskType)]
@@ -179,9 +174,6 @@ func GetMaxConcurrent(mp *MaintenancePolicy, taskType MaintenanceTaskType) int {
func GetRepeatInterval(mp *MaintenancePolicy, taskType MaintenanceTaskType) int {
policy := GetTaskPolicy(mp, taskType)
if policy == nil {
if mp == nil {
return 0
}
return int(mp.DefaultRepeatIntervalSeconds)
}
return int(policy.RepeatIntervalSeconds)
+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.
File diff suppressed because it is too large. Load diff
+19 -42
View File
@@ -1,6 +1,6 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1020
// templ: version: v0.3.1001
package app
//lint:file-ignore SA4006 This context is only used if a nested component is present.
@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
if templ_7745c5c3_Err != nil {
@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
@@ -148,11 +148,11 @@ func Policies(data dash.PoliciesData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -161,11 +161,11 @@ func Policies(data dash.PoliciesData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -174,11 +174,11 @@ func Policies(data dash.PoliciesData) templ.Component {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -193,30 +193,7 @@ func Policies(data dash.PoliciesData) templ.Component {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><style>\n /* Groups a statement's Sid/Effect and its Action/Resource/Principal\n sections in the structured policy editor. Plain <fieldset>/<legend>\n render fine natively, but Bootstrap's form reset stretches <legend> to\n the fieldset's full width (float: left; width: 100%), which loses the\n usual \"notch in the border\" look and makes the label bar as wide as\n the card. Undo just that here so the legend hugs its content instead.\n */\n .policy-stmt-fieldset {\n border: 1px solid var(--bs-border-color, #dee2e6);\n border-radius: 0.375rem;\n padding: 0 0.75rem 0.75rem;\n margin: 0.75rem 0 0;\n }\n .policy-stmt-legend {\n float: none;\n width: auto;\n max-width: 100%;\n padding: 0 0.5rem;\n margin: 0 0 0.25rem;\n font-size: 0.8125rem;\n font-weight: 600;\n color: var(--bs-secondary-color, #6c757d);\n }\n </style><!-- Datalist of suggested action names, shared by the create/edit editors --><datalist id=\"policyActionSuggestions\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, action := range PolicyActionSuggestions {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<option value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.ResolveAttributeValue(action)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 204, Col: 33}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\"></option>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</datalist><!-- Populated dynamically as the user types in a Resource field: bucket\n names first, then subfolders one path segment at a time. See\n updatePolicyResourceSuggestions() below. --><datalist id=\"policyResourceSuggestions\"></datalist><!-- Populated dynamically as the user types/focuses a Principal field:\n existing users and IAM roles, fetched once from /api/principals. See\n updatePolicyPrincipalSuggestions() below. --><datalist id=\"policyPrincipalSuggestions\"></datalist><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"createPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyEditorTab\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"createPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyJsonTab\">JSON</button></li></ul><div class=\"tab-content border border-top-0 rounded-bottom p-3 mb-3\"><div class=\"tab-pane fade show active\" id=\"createPolicyEditorTab\"><div id=\"createPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"createPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"createPolicyJsonTab\"><textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div></div><div class=\"mb-3 d-flex justify-content-between\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy('create')\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument('create')\"><i class=\"fas fa-check me-1\"></i>Validate</button></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><ul class=\"nav nav-tabs\" role=\Line truncated
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -1,107 +0,0 @@
package app
import "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
// PolicyActionSuggestions feeds the <datalist> used by the structured policy
// editor's Action inputs. This is an input-assistance aid, NOT a validation
// list: the editor accepts any action string typed by hand, since IAM policy
// actions are not restricted to this set (custom/future actions, wildcards
// like "s3:Get*", etc.).
var PolicyActionSuggestions = buildPolicyActionSuggestions()
func buildPolicyActionSuggestions() []string {
return []string{
// s3: actions, sourced from the constants used elsewhere for policy
// evaluation (weed/s3api/s3_constants/s3_action_strings.go) so the
// suggestion list can't drift from the strings the engine actually
// understands.
s3_constants.S3_ACTION_ALL,
s3_constants.S3_ACTION_GET_OBJECT,
s3_constants.S3_ACTION_PUT_OBJECT,
s3_constants.S3_ACTION_DELETE_OBJECT,
s3_constants.S3_ACTION_DELETE_OBJECT_VERSION,
s3_constants.S3_ACTION_GET_OBJECT_VERSION,
s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES,
s3_constants.S3_ACTION_GET_OBJECT_ACL,
s3_constants.S3_ACTION_PUT_OBJECT_ACL,
s3_constants.S3_ACTION_GET_OBJECT_TAGGING,
s3_constants.S3_ACTION_PUT_OBJECT_TAGGING,
s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING,
s3_constants.S3_ACTION_GET_OBJECT_RETENTION,
s3_constants.S3_ACTION_PUT_OBJECT_RETENTION,
s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD,
s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD,
s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
s3_constants.S3_ACTION_CREATE_MULTIPART,
s3_constants.S3_ACTION_UPLOAD_PART,
s3_constants.S3_ACTION_COMPLETE_MULTIPART,
s3_constants.S3_ACTION_ABORT_MULTIPART,
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
s3_constants.S3_ACTION_LIST_PARTS,
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
s3_constants.S3_ACTION_CREATE_BUCKET,
s3_constants.S3_ACTION_DELETE_BUCKET,
s3_constants.S3_ACTION_LIST_BUCKET,
s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS,
s3_constants.S3_ACTION_GET_BUCKET_ACL,
s3_constants.S3_ACTION_PUT_BUCKET_ACL,
s3_constants.S3_ACTION_GET_BUCKET_POLICY,
s3_constants.S3_ACTION_PUT_BUCKET_POLICY,
s3_constants.S3_ACTION_DELETE_BUCKET_POLICY,
s3_constants.S3_ACTION_GET_BUCKET_TAGGING,
s3_constants.S3_ACTION_PUT_BUCKET_TAGGING,
s3_constants.S3_ACTION_DELETE_BUCKET_TAGGING,
s3_constants.S3_ACTION_GET_BUCKET_CORS,
s3_constants.S3_ACTION_PUT_BUCKET_CORS,
s3_constants.S3_ACTION_DELETE_BUCKET_CORS,
s3_constants.S3_ACTION_GET_BUCKET_LIFECYCLE,
s3_constants.S3_ACTION_PUT_BUCKET_LIFECYCLE,
s3_constants.S3_ACTION_GET_BUCKET_VERSIONING,
s3_constants.S3_ACTION_PUT_BUCKET_VERSIONING,
s3_constants.S3_ACTION_GET_BUCKET_LOCATION,
s3_constants.S3_ACTION_GET_BUCKET_NOTIFICATION,
s3_constants.S3_ACTION_PUT_BUCKET_NOTIFICATION,
s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK,
s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK,
// s3tables: actions, sourced from weed/s3api/s3_constants so this list
// can't drift from the strings the s3tables engine actually understands.
s3_constants.S3TABLES_ACTION_ALL,
s3_constants.S3TABLES_ACTION_CREATE_TABLE_BUCKET,
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET,
s3_constants.S3TABLES_ACTION_LIST_TABLE_BUCKETS,
s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET,
s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_POLICY,
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_POLICY,
s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET_POLICY,
s3_constants.S3TABLES_ACTION_CREATE_NAMESPACE,
s3_constants.S3TABLES_ACTION_GET_NAMESPACE,
s3_constants.S3TABLES_ACTION_UPDATE_NAMESPACE,
s3_constants.S3TABLES_ACTION_LIST_NAMESPACES,
s3_constants.S3TABLES_ACTION_DELETE_NAMESPACE,
s3_constants.S3TABLES_ACTION_CREATE_TABLE,
s3_constants.S3TABLES_ACTION_REGISTER_TABLE,
s3_constants.S3TABLES_ACTION_GET_TABLE,
s3_constants.S3TABLES_ACTION_LIST_TABLES,
s3_constants.S3TABLES_ACTION_UPDATE_TABLE,
s3_constants.S3TABLES_ACTION_DELETE_TABLE,
s3_constants.S3TABLES_ACTION_RENAME_TABLE,
s3_constants.S3TABLES_ACTION_CREATE_VIEW,
s3_constants.S3TABLES_ACTION_GET_VIEW,
s3_constants.S3TABLES_ACTION_LIST_VIEWS,
s3_constants.S3TABLES_ACTION_UPDATE_VIEW,
s3_constants.S3TABLES_ACTION_DELETE_VIEW,
s3_constants.S3TABLES_ACTION_RENAME_VIEW,
s3_constants.S3TABLES_ACTION_PUT_TABLE_POLICY,
s3_constants.S3TABLES_ACTION_GET_TABLE_POLICY,
s3_constants.S3TABLES_ACTION_DELETE_TABLE_POLICY,
s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,
s3_constants.S3TABLES_ACTION_PUT_TABLE_MAINTENANCE_CONFIGURATION,
s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_CONFIGURATION,
s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_JOB_STATUS,
s3_constants.S3TABLES_ACTION_TAG_RESOURCE,
s3_constants.S3TABLES_ACTION_LIST_TAGS_FOR_RESOURCE,
s3_constants.S3TABLES_ACTION_UNTAG_RESOURCE,
}
}
@@ -1,38 +0,0 @@
package app
import (
"strings"
"testing"
)
func TestPolicyActionSuggestions_NotEmpty(t *testing.T) {
if len(PolicyActionSuggestions) == 0 {
t.Fatal("expected at least one suggestion")
}
}
func TestPolicyActionSuggestions_NoDuplicates(t *testing.T) {
seen := make(map[string]bool, len(PolicyActionSuggestions))
for _, action := range PolicyActionSuggestions {
if seen[action] {
t.Errorf("duplicate action suggestion: %q", action)
}
seen[action] = true
}
}
func TestPolicyActionSuggestions_AllPrefixed(t *testing.T) {
for _, action := range PolicyActionSuggestions {
if !strings.HasPrefix(action, "s3:") && !strings.HasPrefix(action, "s3tables:") {
t.Errorf("action suggestion %q is not prefixed with a known service", action)
}
}
}
func TestPolicyActionSuggestions_NoEmptyStrings(t *testing.T) {
for i, action := range PolicyActionSuggestions {
if strings.TrimSpace(action) == "" {
t.Errorf("suggestion at index %d is empty", i)
}
}
}
+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
}
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more