mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-29 07:37:05 +01:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65f9d611a2 | ||
|
|
0a11b589e5 | ||
|
|
76f3233157 | ||
|
|
2dec17b19c | ||
|
|
9b4a15bee0 | ||
|
|
66ab209971 | ||
|
|
7befb9da4f | ||
|
|
5b44837701 | ||
|
|
2376f63a49 | ||
|
|
50f8366a11 | ||
|
|
414d80aa52 | ||
|
|
3563738699 | ||
|
|
c1a993bc3b | ||
|
|
34bb444f33 | ||
|
|
4af6798639 | ||
|
|
df93d01c06 | ||
|
|
301d83cc7a | ||
|
|
c0a9b110dd | ||
|
|
96304b6870 | ||
|
|
480795d40d | ||
|
|
5e7ab43ddd | ||
|
|
35d53a20f6 | ||
|
|
0c95137528 | ||
|
|
0dfaa103d0 | ||
|
|
3bd218e030 | ||
|
|
930603eb74 | ||
|
|
6faa9d20e8 | ||
|
|
813c439af6 | ||
|
|
bd34565e56 | ||
|
|
6c7f184381 | ||
|
|
8a532cc0cf | ||
|
|
83753ccdad | ||
|
|
6f3b5a4f4d | ||
|
|
f56a7a1557 | ||
|
|
fc97f8ea8f | ||
|
|
f7c4636d22 |
No files matched your search
@@ -6,6 +6,7 @@ on:
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'seaweed-volume/**'
|
||||
- 'seaweed-worker/**'
|
||||
- 'docker/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
@@ -16,7 +17,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
|
||||
# ── Pre-build Rust volume server binaries natively ──────────────────
|
||||
# ── Pre-build the Rust binaries natively ────────────────────────────
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
@@ -55,10 +56,23 @@ jobs:
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
seaweed-volume/target
|
||||
key: rust-docker-dev-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
|
||||
seaweed-worker/target/${{ matrix.target }}/release
|
||||
key: rust-docker-dev-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/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
|
||||
protoc=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-linux-x86_64*/bin/protoc' | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build normal variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -67,11 +81,19 @@ 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-volume-${{ matrix.arch }}
|
||||
path: weed-volume-normal-${{ matrix.arch }}
|
||||
name: rust-bins-${{ matrix.arch }}
|
||||
path: |
|
||||
weed-volume-normal-${{ matrix.arch }}
|
||||
weed-worker-${{ matrix.arch }}
|
||||
|
||||
build-dev-containers:
|
||||
needs: [build-rust-binaries]
|
||||
@@ -84,7 +106,7 @@ jobs:
|
||||
- name: Download pre-built Rust binaries
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: rust-volume-*
|
||||
pattern: rust-bins-*
|
||||
merge-multiple: true
|
||||
path: ./rust-bins
|
||||
|
||||
@@ -98,7 +120,16 @@ 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
|
||||
|
||||
@@ -59,7 +59,7 @@ jobs:
|
||||
echo "publish=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# ── Pre-build Rust volume server binaries natively ──────────────────
|
||||
# ── Pre-build the Rust binaries natively ────────────────────────────
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
@@ -100,10 +100,23 @@ jobs:
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
seaweed-volume/target
|
||||
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
|
||||
seaweed-worker/target/${{ matrix.target }}/release
|
||||
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/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
|
||||
protoc=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-linux-x86_64*/bin/protoc' | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build large-disk variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -120,13 +133,20 @@ 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-volume-${{ matrix.arch }}
|
||||
name: rust-bins-${{ matrix.arch }}
|
||||
path: |
|
||||
weed-volume-large-disk-${{ matrix.arch }}
|
||||
weed-volume-normal-${{ matrix.arch }}
|
||||
weed-worker-${{ matrix.arch }}
|
||||
|
||||
build:
|
||||
needs: [setup, build-rust-binaries]
|
||||
@@ -174,7 +194,7 @@ jobs:
|
||||
- name: Download pre-built Rust binaries
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: rust-volume-*
|
||||
pattern: rust-bins-*
|
||||
merge-multiple: true
|
||||
path: ./rust-bins
|
||||
|
||||
@@ -188,7 +208,16 @@ 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
|
||||
@@ -286,7 +315,7 @@ jobs:
|
||||
if: needs.setup.outputs.publish != 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: rust-volume-*
|
||||
pattern: rust-bins-*
|
||||
merge-multiple: true
|
||||
path: ./rust-bins
|
||||
- name: Place Rust binaries in Docker context for local scan
|
||||
@@ -304,7 +333,16 @@ 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,9 +42,10 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
|
||||
# ── 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.
|
||||
# ── 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.
|
||||
build-rust-binaries:
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
@@ -83,10 +84,23 @@ jobs:
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
seaweed-volume/target
|
||||
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock') }}
|
||||
seaweed-worker/target/${{ matrix.target }}/release
|
||||
key: rust-docker-${{ matrix.target }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-worker/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
|
||||
protoc=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-linux-x86_64*/bin/protoc' | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build large-disk variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -103,13 +117,20 @@ 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-volume-${{ matrix.arch }}
|
||||
name: rust-bins-${{ 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.
|
||||
@@ -155,7 +176,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-volume-*
|
||||
pattern: rust-bins-*
|
||||
merge-multiple: true
|
||||
path: ./rust-bins
|
||||
|
||||
@@ -170,7 +191,16 @@ 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
|
||||
|
||||
@@ -58,10 +58,52 @@ 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
|
||||
@@ -440,6 +482,41 @@ 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
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
name: "release: bump version"
|
||||
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.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -14,15 +27,37 @@ on:
|
||||
description: "Explicit MAJOR.MINOR to set, e.g. 4.36 (overrides 'bump')"
|
||||
type: string
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
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
|
||||
|
||||
jobs:
|
||||
bump-version:
|
||||
release:
|
||||
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
|
||||
@@ -99,17 +134,103 @@ jobs:
|
||||
sed -i -E "s/^version:.*/version: ${CHART_VERSION}/" "$CHART"
|
||||
cat "$CHART"
|
||||
|
||||
- name: Commit and push
|
||||
- name: Commit, and push the tag
|
||||
id: tag
|
||||
env:
|
||||
APP_VERSION: ${{ steps.compute.outputs.app_version }}
|
||||
TAG: ${{ steps.compute.outputs.app_version }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if git diff --quiet; then
|
||||
echo "No version change to commit."
|
||||
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"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add weed/util/version/constants.go k8s/charts/seaweedfs/Chart.yaml
|
||||
git commit -m "${APP_VERSION}"
|
||||
git push
|
||||
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")"
|
||||
@@ -0,0 +1,79 @@
|
||||
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
|
||||
protoc=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-linux-x86_64*/bin/protoc' | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc 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,4 +1,4 @@
|
||||
name: "rust: build versioned volume server binaries"
|
||||
name: "rust: build versioned binaries"
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -113,6 +113,99 @@ 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
|
||||
protoc=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-linux-x86_64*/bin/protoc' | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc 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
|
||||
|
||||
@@ -6,6 +6,7 @@ on:
|
||||
- 'weed/s3api/**'
|
||||
- 'weed/filer/**'
|
||||
- 'weed/server/**'
|
||||
- 'weed/worker/tasks/iceberg/**'
|
||||
- 'test/s3tables/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
@@ -874,6 +875,293 @@ 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
|
||||
|
||||
@@ -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 (Iceberg) buckets. 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 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).
|
||||
|
||||
The same command starts everything else too:
|
||||
- **S3 Endpoint**: http://localhost:8333
|
||||
|
||||
@@ -29,6 +29,7 @@ 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
|
||||
@@ -47,16 +48,30 @@ 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 placeholder, which stays size 0).
|
||||
RUN chmod 0755 /weed-volume
|
||||
# denied". Restore it (no-op for the empty placeholders, which stay size 0).
|
||||
RUN chmod 0755 /weed-volume /weed-worker
|
||||
|
||||
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
|
||||
|
||||
@@ -90,6 +90,16 @@ 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
|
||||
|
||||
@@ -11,4 +11,8 @@ scrape_configs:
|
||||
- 'master:9324'
|
||||
- 'volume:9325'
|
||||
- 'filer:9326'
|
||||
- 's3:9327'
|
||||
- 's3:9327'
|
||||
# A plugin worker publishes its own metrics when started with
|
||||
# -metricsPort (Go) or --metrics-port (Rust). 9328 continues the
|
||||
# series, since 9327 is already the S3 gateway's.
|
||||
# - 'worker:9328'
|
||||
Whitespace-only changes.
@@ -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.30.1
|
||||
github.com/parquet-go/parquet-go v0.32.0
|
||||
github.com/pkg/sftp v1.13.11
|
||||
github.com/rabbitmq/amqp091-go v1.13.0
|
||||
github.com/rclone/rclone v1.75.0
|
||||
|
||||
@@ -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.30.1 h1:Oy6ganNrAdFiVwy7wNmWagfPTWA2X9Z3tVHBc7JtuX8=
|
||||
github.com/parquet-go/parquet-go v0.30.1/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
|
||||
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
|
||||
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
|
||||
github.com/pascaldekloe/goe v0.1.0 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=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.42"
|
||||
appVersion: "4.44"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.42.0
|
||||
version: 4.44.0
|
||||
@@ -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.
|
||||
* 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.
|
||||
* 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.
|
||||
* cert config exists and can be enabled, but not been tested, requires cert-manager to be installed.
|
||||
|
||||
## Prerequisites
|
||||
@@ -289,6 +289,32 @@ 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,6 +84,9 @@ 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,6 +92,7 @@ spec:
|
||||
image: {{ template "seaweedfs.filer.image" . }}
|
||||
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
|
||||
env:
|
||||
{{- $mysqlEnabled := include "seaweedfs.filer.mysqlEnabled" . }}
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
@@ -104,6 +105,7 @@ spec:
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
{{- if $mysqlEnabled }}
|
||||
- name: WEED_MYSQL_USERNAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
@@ -116,10 +118,21 @@ 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 }}
|
||||
@@ -132,10 +145,12 @@ 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,6 +94,9 @@ 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,4 +1,7 @@
|
||||
{{- 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)) }}
|
||||
{{- /* 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 }}
|
||||
{{- $secretName := printf "%s-s3-secret" (include "seaweedfs.fullname" .) }}
|
||||
{{- $legacySecretName := "seaweedfs-s3-secret" }}
|
||||
{{- $lookupName := $secretName }}
|
||||
@@ -14,14 +17,20 @@
|
||||
{{- $adminCreds := $creds.admin | default dict -}}
|
||||
{{- $access_key_admin := $adminCreds.accessKey -}}
|
||||
{{- $secret_key_admin := $adminCreds.secretKey -}}
|
||||
{{- if not (and $access_key_admin $secret_key_admin) -}}
|
||||
{{- 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) -}}
|
||||
{{- $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 not (and $access_key_read $secret_key_read) -}}
|
||||
{{- 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) -}}
|
||||
{{- $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 -}}
|
||||
@@ -41,10 +50,16 @@ 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,6 +76,18 @@ 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 -}}
|
||||
@@ -496,6 +508,39 @@ 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 .Values.filer.enabled }}
|
||||
{{- if and .Values.filer.enabled (include "seaweedfs.filer.mysqlEnabled" .) }}
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
type: Opaque
|
||||
|
||||
@@ -897,6 +897,7 @@ 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"
|
||||
@@ -1014,13 +1015,24 @@ 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`
|
||||
|
||||
@@ -9263,6 +9263,959 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Plugin Workers",
|
||||
"collapsed": true,
|
||||
"id": 229,
|
||||
"gridPos": {
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 27
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Plugin Workers Connected",
|
||||
"description": "Workers with a live control stream. Unlike the Admin/Maintenance row, this counts plugin workers, which is what a Rust or Go plugin worker actually is.",
|
||||
"type": "stat",
|
||||
"id": 219,
|
||||
"gridPos": {
|
||||
"h": 4,
|
||||
"w": 6,
|
||||
"x": 0,
|
||||
"y": 28
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"colorMode": "value",
|
||||
"graphMode": "area",
|
||||
"justifyMode": "auto",
|
||||
"orientation": "auto",
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "count(SeaweedFS_worker_connected{cluster=~\"$cluster\"} == 1) or vector(0)",
|
||||
"instant": true,
|
||||
"range": false,
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Worker Job Failures (1h)",
|
||||
"description": "Jobs that ended in failure across all workers in the last hour.",
|
||||
"type": "stat",
|
||||
"id": 220,
|
||||
"gridPos": {
|
||||
"h": 4,
|
||||
"w": 6,
|
||||
"x": 6,
|
||||
"y": 28
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"colorMode": "value",
|
||||
"graphMode": "area",
|
||||
"justifyMode": "auto",
|
||||
"orientation": "auto",
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(increase(SeaweedFS_worker_jobs_total{cluster=~\"$cluster\",result=\"failed\"}[1h])) or vector(0)",
|
||||
"instant": true,
|
||||
"range": false,
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Objects Seen vs Skipped",
|
||||
"description": "A sweep that proposes nothing because there was nothing to do and one that proposes nothing because it could read nothing produce the same proposal count. Skips are the difference, and are the thing to alert on.",
|
||||
"type": "timeseries",
|
||||
"id": 221,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 32
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (job_type) (rate(SeaweedFS_worker_objects_seen_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "seen {{job_type}}"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (job_type, reason) (rate(SeaweedFS_worker_objects_skipped_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "B",
|
||||
"legendFormat": "skipped {{job_type}} ({{reason}})"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Detections and Proposals",
|
||||
"description": "Detection sweeps by outcome, and the work they handed to admin.",
|
||||
"type": "timeseries",
|
||||
"id": 222,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 32
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (job_type, result) (rate(SeaweedFS_worker_detections_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "detections {{job_type}} ({{result}})"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (job_type) (rate(SeaweedFS_worker_proposals_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "B",
|
||||
"legendFormat": "proposals {{job_type}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Jobs Executed",
|
||||
"description": "Jobs run by these workers, by outcome.",
|
||||
"type": "timeseries",
|
||||
"id": 223,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 40
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (job_type, result) (rate(SeaweedFS_worker_jobs_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{job_type}} ({{result}})"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Job Duration p99",
|
||||
"description": "How long a job takes, per job type.",
|
||||
"type": "timeseries",
|
||||
"id": 224,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 40
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_worker_job_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, job_type))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{job_type}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Worker Slots",
|
||||
"description": "Capacity a worker advertised and how much of it is in use. Held slots are what admin schedules against.",
|
||||
"type": "timeseries",
|
||||
"id": 225,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 48
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (lane) (SeaweedFS_worker_slots_used{cluster=~\"$cluster\"})",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "used {{lane}}"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (lane) (SeaweedFS_worker_slots_total{cluster=~\"$cluster\"})",
|
||||
"range": true,
|
||||
"refId": "B",
|
||||
"legendFormat": "total {{lane}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Control Stream Events",
|
||||
"description": "Connects, closes and failures. A worker that reconnects steadily is usually two workers sharing one id, evicting each other.",
|
||||
"type": "timeseries",
|
||||
"id": 226,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 48
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (event) (rate(SeaweedFS_worker_stream_events_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{event}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Lance Maintenance Reclaimed",
|
||||
"description": "What the Lance jobs actually removed. A job that runs every minute and reclaims nothing is a different thing from a job that never runs.",
|
||||
"type": "timeseries",
|
||||
"id": 227,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 56
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(rate(SeaweedFS_worker_lance_fragments_removed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "fragments merged"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(rate(SeaweedFS_worker_lance_rows_indexed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "B",
|
||||
"legendFormat": "rows indexed"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(rate(SeaweedFS_worker_lance_versions_removed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "C",
|
||||
"legendFormat": "versions removed"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Storage Reclaimed",
|
||||
"description": "Bytes freed by version cleanup. Its own panel because bytes and counts do not belong on one axis.",
|
||||
"type": "timeseries",
|
||||
"id": 228,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 56
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "Bps",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum(rate(SeaweedFS_worker_lance_bytes_reclaimed_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "reclaimed"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Go Runtime",
|
||||
@@ -9272,7 +10225,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 27
|
||||
"y": 28
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
|
||||
@@ -330,6 +330,16 @@ 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) {
|
||||
|
||||
@@ -842,8 +842,7 @@ 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) = store.volume_report.begin();
|
||||
let mut reported_hashes: HashMap<VolumeReportKey, u64> = HashMap::new();
|
||||
let (send_full_list, report_generation, report_pass) = store.volume_report.begin();
|
||||
let mut changed_volumes = Vec::new();
|
||||
let mut max_file_key = NeedleId(0);
|
||||
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
|
||||
@@ -941,8 +940,14 @@ 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);
|
||||
reported_hashes.insert(key, hash);
|
||||
if send_full_list || store.volume_report.changed(key, hash) {
|
||||
// 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 {
|
||||
changed_volumes.push(volume_message.clone());
|
||||
}
|
||||
volumes.push(volume_message);
|
||||
@@ -951,24 +956,30 @@ fn build_heartbeat_with_ec_status(
|
||||
should_delete_volume = true;
|
||||
}
|
||||
|
||||
// Track disk size by collection
|
||||
let entry = disk_sizes.entry(vol.collection.clone()).or_insert((0, 0));
|
||||
// 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.
|
||||
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();
|
||||
}
|
||||
|
||||
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;
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1002,6 +1013,17 @@ 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);
|
||||
@@ -1009,7 +1031,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(reported_hashes, report_generation);
|
||||
store.volume_report.commit(report_pass, report_generation);
|
||||
}
|
||||
|
||||
// has_no_volumes says the server holds nothing, so it may only be derived
|
||||
@@ -1077,6 +1099,14 @@ 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
|
||||
@@ -1428,10 +1458,10 @@ mod tests {
|
||||
store.volume_report.accept_deltas();
|
||||
build_heartbeat(&test_config(), &mut store);
|
||||
|
||||
let (full, generation) = store.volume_report.begin();
|
||||
let (full, generation, pass) = store.volume_report.begin();
|
||||
assert!(!full);
|
||||
store.volume_report.request_full_list();
|
||||
store.volume_report.commit(HashMap::new(), generation);
|
||||
store.volume_report.commit(pass, generation);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.volumes.len(), 2);
|
||||
@@ -1596,6 +1626,82 @@ 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();
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//! 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;
|
||||
@@ -32,6 +34,12 @@ 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 {
|
||||
@@ -49,6 +57,8 @@ 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()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! 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
|
||||
@@ -9,6 +8,34 @@ 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.
|
||||
///
|
||||
@@ -18,56 +45,86 @@ pub type VolumeReportKey = (u32, u32);
|
||||
/// until one accepts changes.
|
||||
#[derive(Default)]
|
||||
pub struct VolumeReportState {
|
||||
/// 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>>,
|
||||
state: Mutex<ReportState>,
|
||||
}
|
||||
|
||||
impl VolumeReportState {
|
||||
/// Drops everything known about the master's view.
|
||||
pub fn reset(&self) {
|
||||
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();
|
||||
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();
|
||||
}
|
||||
|
||||
pub fn accept_deltas(&self) {
|
||||
self.deltas_accepted.store(true, Ordering::Relaxed);
|
||||
self.state.lock().unwrap().deltas_accepted = true;
|
||||
}
|
||||
|
||||
pub fn request_full_list(&self) {
|
||||
self.full_list_needed.store(true, Ordering::Relaxed);
|
||||
self.full_list_generation.fetch_add(1, Ordering::Relaxed);
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.full_list_needed = true;
|
||||
state.full_list_generation += 1;
|
||||
}
|
||||
|
||||
/// 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))
|
||||
/// 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 the master needs telling about this volume, given what
|
||||
/// it was last told.
|
||||
/// 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`.
|
||||
pub fn changed(&self, key: VolumeReportKey, hash: u64) -> bool {
|
||||
self.last_reported.lock().unwrap().get(&key) != Some(&hash)
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.last_reported
|
||||
.get(&key)
|
||||
.is_none_or(|previous| previous.hash != hash)
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// 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);
|
||||
// A request that arrived while this heartbeat was being built asked
|
||||
// about a later state than it carries, so it stands.
|
||||
if self.full_list_generation.load(Ordering::Relaxed) == generation {
|
||||
self.full_list_needed.store(false, Ordering::Relaxed);
|
||||
if state.full_list_generation == generation {
|
||||
state.full_list_needed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+130
-7
@@ -867,6 +867,8 @@ dependencies = [
|
||||
"http 1.5.0",
|
||||
"http-body 1.1.0",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
@@ -875,10 +877,15 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"rustversion",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower 0.5.3",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -899,6 +906,7 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2120,7 +2128,7 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
|
||||
dependencies = [
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3107,7 +3115,7 @@ dependencies = [
|
||||
"jni-sys",
|
||||
"log",
|
||||
"simd_cesu8",
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
"walkdir",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -4162,7 +4170,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
@@ -4541,6 +4549,20 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prometheus"
|
||||
version = "0.13.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fnv",
|
||||
"lazy_static",
|
||||
"memchr",
|
||||
"parking_lot",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost"
|
||||
version = "0.13.5"
|
||||
@@ -4644,6 +4666,70 @@ 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"
|
||||
@@ -4690,7 +4776,7 @@ dependencies = [
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.6.5",
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
@@ -4713,7 +4799,7 @@ dependencies = [
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
@@ -4913,7 +4999,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"libredox",
|
||||
"thiserror",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5353,8 +5439,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"prometheus",
|
||||
"prost 0.13.5",
|
||||
"prost-types 0.13.5",
|
||||
"protoc-bin-vendored",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
@@ -5440,6 +5529,17 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_repr"
|
||||
version = "0.1.21"
|
||||
@@ -5784,13 +5884,33 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
||||
dependencies = [
|
||||
"thiserror-impl 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
"thiserror-impl 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6030,6 +6150,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6073,6 +6194,7 @@ version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
@@ -6422,6 +6544,7 @@ dependencies = [
|
||||
"lance",
|
||||
"lance-index",
|
||||
"lance-linalg",
|
||||
"prometheus",
|
||||
"reqwest 0.12.28",
|
||||
"seaweed-worker-core",
|
||||
"serde",
|
||||
|
||||
@@ -19,6 +19,9 @@ prost-types = "0.13"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-stream = "0.1"
|
||||
tonic = { version = "0.12", features = ["tls"] }
|
||||
# Already in the tree via tonic; named here so the metrics server can use them.
|
||||
axum = "0.7"
|
||||
prometheus = { version = "0.13", default-features = false }
|
||||
tonic-build = "0.12"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
@@ -12,6 +12,18 @@ 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 and look for a protoc on PATH or in `PROTOC`, and
|
||||
they honour the same vendored one:
|
||||
|
||||
PROTOC=$(find ~/.cargo/registry/src -path '*protoc-bin-vendored-*/bin/protoc' | head -1) \
|
||||
cargo build --release
|
||||
|
||||
which is what CI does. A protoc from the platform's package manager works too.
|
||||
|
||||
## Running
|
||||
|
||||
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646
|
||||
@@ -20,6 +32,52 @@ 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
|
||||
|
||||
Serves `/health`, `/ready` and `/metrics` on that port, the same three the Go
|
||||
worker serves under `weed worker -metricsPort`, so one scrape config covers
|
||||
workers in either language. Off by default, and bound to loopback unless
|
||||
`--metrics-ip` says otherwise, because the endpoint is unauthenticated. 9328
|
||||
continues the series the other components use (master 9324, volume 9325, filer
|
||||
9326, s3 9327); an IPv6 address works with or without brackets.
|
||||
|
||||
Grafana: the "Plugin Workers" row of `other/metrics/grafana_seaweedfs.json`
|
||||
graphs these. Its panels filter on `$cluster`, which comes from the scrape job's
|
||||
labels, so scrape the worker the way the rest of the cluster is scraped or the
|
||||
row stays empty.
|
||||
|
||||
Names are `SeaweedFS_worker_*`, matching the Go side's convention. The pair
|
||||
worth alerting on is `objects_seen_total` and `objects_skipped_total`: a sweep
|
||||
that proposes nothing and a sweep that could read nothing look identical from
|
||||
`proposals_total` alone.
|
||||
|
||||
SeaweedFS_worker_connected 1
|
||||
SeaweedFS_worker_objects_seen_total{job_type="lance_compact"} 7
|
||||
SeaweedFS_worker_proposals_total{job_type="lance_compact"} 2
|
||||
SeaweedFS_worker_jobs_total{job_type="lance_compact",result="ok"} 2
|
||||
SeaweedFS_worker_lance_fragments_removed_total 25
|
||||
|
||||
`/ready` follows the control stream: a worker whose admin has gone away is
|
||||
running but is not going to do anything.
|
||||
|
||||
## Credentials
|
||||
|
||||
The worker holds none. It asks the namespace to describe a table with
|
||||
|
||||
@@ -15,7 +15,13 @@ prost-types.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
tonic.workspace = true
|
||||
axum.workspace = true
|
||||
prometheus.workspace = true
|
||||
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"
|
||||
@@ -1,4 +1,12 @@
|
||||
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()
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
pub mod address;
|
||||
pub mod config;
|
||||
pub mod config_form;
|
||||
pub mod metrics;
|
||||
pub mod registry;
|
||||
pub mod senders;
|
||||
pub mod stream;
|
||||
@@ -19,6 +20,7 @@ pub mod pb {
|
||||
}
|
||||
|
||||
pub use config::{TlsOptions, WorkerOptions};
|
||||
pub use metrics::Metrics;
|
||||
pub use registry::{JobHandler, Preview, PreviewProvider, Registry};
|
||||
pub use senders::{DetectionSender, ExecutionSender};
|
||||
pub use stream::run;
|
||||
@@ -0,0 +1,395 @@
|
||||
//! What a worker will say about itself when nobody is watching the logs.
|
||||
//!
|
||||
//! The Go plugin worker serves `/health`, `/ready` and `/metrics` on an optional
|
||||
//! port (`weed worker -metricsPort`); this is the same contract, so one scrape
|
||||
//! config covers workers in either language. Names follow the Go side's
|
||||
//! convention, `SeaweedFS_<subsystem>_<name>`, under a `worker` subsystem that
|
||||
//! nothing else uses.
|
||||
//!
|
||||
//! Nothing here is Lance-specific. A worker for another format registers its own
|
||||
//! collectors on the same registry and gets the same endpoint.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use prometheus::{
|
||||
Encoder, HistogramOpts, HistogramVec, IntCounter, IntCounterVec, IntGauge, IntGaugeVec, Opts,
|
||||
Registry, TextEncoder,
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tracing::{info, warn};
|
||||
|
||||
const NAMESPACE: &str = "SeaweedFS";
|
||||
const SUBSYSTEM: &str = "worker";
|
||||
|
||||
/// The metrics one worker process publishes, and the registry they live on.
|
||||
///
|
||||
/// Cloneable because the stream loop, the job handlers and the HTTP server all
|
||||
/// hold it; everything inside is already shared.
|
||||
#[derive(Clone)]
|
||||
pub struct Metrics {
|
||||
registry: Registry,
|
||||
connected: IntGauge,
|
||||
connects: IntCounterVec,
|
||||
slots_used: IntGaugeVec,
|
||||
slots_total: IntGaugeVec,
|
||||
detections: IntCounterVec,
|
||||
detection_seconds: HistogramVec,
|
||||
proposals: IntCounterVec,
|
||||
objects_seen: IntCounterVec,
|
||||
objects_skipped: IntCounterVec,
|
||||
jobs: IntCounterVec,
|
||||
job_seconds: HistogramVec,
|
||||
previews: IntCounterVec,
|
||||
ready: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
pub fn new(worker_id: &str, worker_version: &str) -> Result<Self> {
|
||||
let registry = Registry::new();
|
||||
|
||||
// Build info as a constant 1, the way the Go side does it, so a scrape
|
||||
// can tell which worker and which build answered.
|
||||
let build = IntGaugeVec::new(
|
||||
Opts::new("build_info", "Worker build information.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["worker_id", "version"],
|
||||
)?;
|
||||
build.with_label_values(&[worker_id, worker_version]).set(1);
|
||||
registry.register(Box::new(build))?;
|
||||
|
||||
let connected = IntGauge::with_opts(
|
||||
Opts::new("connected", "1 while the admin control stream is up.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
)?;
|
||||
let connects = IntCounterVec::new(
|
||||
Opts::new(
|
||||
"stream_events_total",
|
||||
"Control stream lifecycle events by outcome (connected, closed, failed, shutdown).",
|
||||
)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["event"],
|
||||
)?;
|
||||
let slots_used = IntGaugeVec::new(
|
||||
Opts::new("slots_used", "Slots currently held, by lane.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["lane"],
|
||||
)?;
|
||||
let slots_total = IntGaugeVec::new(
|
||||
Opts::new("slots_total", "Slots this worker advertises, by lane.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["lane"],
|
||||
)?;
|
||||
let detections = IntCounterVec::new(
|
||||
Opts::new(
|
||||
"detections_total",
|
||||
"Detection sweeps by job type and outcome.",
|
||||
)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["job_type", "result"],
|
||||
)?;
|
||||
let detection_seconds = HistogramVec::new(
|
||||
HistogramOpts::new("detection_seconds", "How long a detection sweep took.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM)
|
||||
.buckets(prometheus::exponential_buckets(0.01, 2.0, 14)?),
|
||||
&["job_type"],
|
||||
)?;
|
||||
let proposals = IntCounterVec::new(
|
||||
Opts::new("proposals_total", "Jobs proposed to admin, by job type.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["job_type"],
|
||||
)?;
|
||||
let objects_seen = IntCounterVec::new(
|
||||
Opts::new(
|
||||
"objects_seen_total",
|
||||
"Objects a detection sweep read, by job type.",
|
||||
)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["job_type"],
|
||||
)?;
|
||||
let objects_skipped = IntCounterVec::new(
|
||||
Opts::new(
|
||||
"objects_skipped_total",
|
||||
"Objects a sweep could not read, by job type and reason. A sweep that \
|
||||
proposes nothing looks the same as one that could read nothing; this is \
|
||||
what tells them apart.",
|
||||
)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["job_type", "reason"],
|
||||
)?;
|
||||
let jobs = IntCounterVec::new(
|
||||
Opts::new("jobs_total", "Jobs executed by job type and outcome.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["job_type", "result"],
|
||||
)?;
|
||||
let job_seconds = HistogramVec::new(
|
||||
HistogramOpts::new("job_seconds", "How long a job took to run.")
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM)
|
||||
.buckets(prometheus::exponential_buckets(0.05, 2.0, 16)?),
|
||||
&["job_type"],
|
||||
)?;
|
||||
let previews = IntCounterVec::new(
|
||||
Opts::new(
|
||||
"previews_total",
|
||||
"Object previews served to admin, by outcome.",
|
||||
)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
&["result"],
|
||||
)?;
|
||||
|
||||
for collector in [
|
||||
Box::new(connected.clone()) as Box<dyn prometheus::core::Collector>,
|
||||
Box::new(connects.clone()),
|
||||
Box::new(slots_used.clone()),
|
||||
Box::new(slots_total.clone()),
|
||||
Box::new(detections.clone()),
|
||||
Box::new(detection_seconds.clone()),
|
||||
Box::new(proposals.clone()),
|
||||
Box::new(objects_seen.clone()),
|
||||
Box::new(objects_skipped.clone()),
|
||||
Box::new(jobs.clone()),
|
||||
Box::new(job_seconds.clone()),
|
||||
Box::new(previews.clone()),
|
||||
] {
|
||||
registry.register(collector)?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
registry,
|
||||
connected,
|
||||
connects,
|
||||
slots_used,
|
||||
slots_total,
|
||||
detections,
|
||||
detection_seconds,
|
||||
proposals,
|
||||
objects_seen,
|
||||
objects_skipped,
|
||||
jobs,
|
||||
job_seconds,
|
||||
previews,
|
||||
ready: Arc::new(AtomicBool::new(false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The registry, so a worker can add collectors of its own.
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.registry
|
||||
}
|
||||
|
||||
pub fn stream_connected(&self) {
|
||||
self.connected.set(1);
|
||||
self.ready.store(true, Ordering::Relaxed);
|
||||
self.connects.with_label_values(&["connected"]).inc();
|
||||
}
|
||||
|
||||
/// `event` is why the stream ended: closed, failed, or shutdown.
|
||||
pub fn stream_ended(&self, event: &str) {
|
||||
self.connected.set(0);
|
||||
self.ready.store(false, Ordering::Relaxed);
|
||||
self.connects.with_label_values(&[event]).inc();
|
||||
}
|
||||
|
||||
pub fn set_slots(&self, lane: &str, used: i64, total: i64) {
|
||||
self.slots_used.with_label_values(&[lane]).set(used);
|
||||
self.slots_total.with_label_values(&[lane]).set(total);
|
||||
}
|
||||
|
||||
pub fn detection_finished(&self, job_type: &str, result: &str, seconds: f64, proposals: usize) {
|
||||
self.detections
|
||||
.with_label_values(&[job_type, result])
|
||||
.inc_by(1);
|
||||
self.detection_seconds
|
||||
.with_label_values(&[job_type])
|
||||
.observe(seconds);
|
||||
self.proposals
|
||||
.with_label_values(&[job_type])
|
||||
.inc_by(proposals as u64);
|
||||
}
|
||||
|
||||
pub fn object_seen(&self, job_type: &str) {
|
||||
self.objects_seen.with_label_values(&[job_type]).inc();
|
||||
}
|
||||
|
||||
pub fn object_skipped(&self, job_type: &str, reason: &str) {
|
||||
self.objects_skipped
|
||||
.with_label_values(&[job_type, reason])
|
||||
.inc();
|
||||
}
|
||||
|
||||
pub fn job_finished(&self, job_type: &str, result: &str, seconds: f64) {
|
||||
self.jobs.with_label_values(&[job_type, result]).inc();
|
||||
self.job_seconds
|
||||
.with_label_values(&[job_type])
|
||||
.observe(seconds);
|
||||
}
|
||||
|
||||
pub fn preview_finished(&self, result: &str) {
|
||||
self.previews.with_label_values(&[result]).inc();
|
||||
}
|
||||
|
||||
/// A counter this worker's own jobs can raise, e.g. fragments removed.
|
||||
/// Registered lazily so a format's numbers live beside the generic ones
|
||||
/// without core having to know what they are.
|
||||
pub fn counter(&self, name: &str, help: &str) -> Result<IntCounter> {
|
||||
let counter = IntCounter::with_opts(
|
||||
Opts::new(name, help)
|
||||
.namespace(NAMESPACE)
|
||||
.subsystem(SUBSYSTEM),
|
||||
)?;
|
||||
self.registry.register(Box::new(counter.clone()))?;
|
||||
Ok(counter)
|
||||
}
|
||||
|
||||
fn gather(&self) -> Result<String> {
|
||||
let mut buffer = Vec::new();
|
||||
TextEncoder::new().encode(&self.registry.gather(), &mut buffer)?;
|
||||
Ok(String::from_utf8(buffer)?)
|
||||
}
|
||||
|
||||
fn is_ready(&self) -> bool {
|
||||
self.ready.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serves the metrics endpoints until the process stops. Failing to bind is
|
||||
/// logged rather than fatal: a worker that cannot publish metrics should still
|
||||
/// do its work.
|
||||
pub async fn serve(metrics: Metrics, addr: SocketAddr) -> Result<()> {
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
|
||||
let app = Router::new()
|
||||
.route("/health", get(|| async { StatusCode::OK }))
|
||||
.route(
|
||||
"/ready",
|
||||
get(|State(metrics): State<Metrics>| async move {
|
||||
if metrics.is_ready() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/metrics",
|
||||
get(|State(metrics): State<Metrics>| async move {
|
||||
match metrics.gather() {
|
||||
Ok(body) => (StatusCode::OK, body),
|
||||
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{err:#}")),
|
||||
}
|
||||
}),
|
||||
)
|
||||
.with_state(metrics);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
.await
|
||||
.with_context(|| format!("bind the metrics server to {addr}"))?;
|
||||
info!("serving worker metrics on http://{addr}/metrics");
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.context("metrics server stopped")
|
||||
}
|
||||
|
||||
/// Starts the metrics server in the background, warning rather than failing when
|
||||
/// it cannot start.
|
||||
pub fn spawn(metrics: Metrics, addr: SocketAddr) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = serve(metrics, addr).await {
|
||||
warn!("worker metrics server: {err:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn metrics() -> Metrics {
|
||||
Metrics::new("worker-1", "0.1.0").expect("build metrics")
|
||||
}
|
||||
|
||||
// A scrape has to be able to tell these apart: a worker that swept and found
|
||||
// nothing to do, and one that could not read anything it swept.
|
||||
#[test]
|
||||
fn a_sweep_reports_what_it_read_and_what_it_could_not() {
|
||||
let metrics = metrics();
|
||||
metrics.object_seen("lance_compact");
|
||||
metrics.object_seen("lance_compact");
|
||||
metrics.object_skipped("lance_compact", "open");
|
||||
metrics.detection_finished("lance_compact", "ok", 0.5, 0);
|
||||
|
||||
let text = metrics.gather().expect("gather");
|
||||
assert!(text.contains("SeaweedFS_worker_objects_seen_total{job_type=\"lance_compact\"} 2"));
|
||||
assert!(text.contains(
|
||||
"SeaweedFS_worker_objects_skipped_total{job_type=\"lance_compact\",reason=\"open\"} 1"
|
||||
));
|
||||
assert!(text.contains(
|
||||
"SeaweedFS_worker_detections_total{job_type=\"lance_compact\",result=\"ok\"} 1"
|
||||
));
|
||||
assert!(text.contains("SeaweedFS_worker_proposals_total{job_type=\"lance_compact\"} 0"));
|
||||
}
|
||||
|
||||
// /ready follows the stream, because a worker with no admin behind it is
|
||||
// running but not doing anything.
|
||||
#[test]
|
||||
fn readiness_follows_the_stream() {
|
||||
let metrics = metrics();
|
||||
assert!(!metrics.is_ready(), "not ready before the stream is up");
|
||||
|
||||
metrics.stream_connected();
|
||||
assert!(metrics.is_ready());
|
||||
assert!(metrics
|
||||
.gather()
|
||||
.unwrap()
|
||||
.contains("SeaweedFS_worker_connected 1"));
|
||||
|
||||
metrics.stream_ended("closed");
|
||||
assert!(!metrics.is_ready());
|
||||
assert!(metrics
|
||||
.gather()
|
||||
.unwrap()
|
||||
.contains("SeaweedFS_worker_connected 0"));
|
||||
assert!(metrics
|
||||
.gather()
|
||||
.unwrap()
|
||||
.contains("SeaweedFS_worker_stream_events_total{event=\"closed\"} 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_info_names_the_worker() {
|
||||
let text = metrics().gather().expect("gather");
|
||||
assert!(text
|
||||
.contains("SeaweedFS_worker_build_info{version=\"0.1.0\",worker_id=\"worker-1\"} 1"));
|
||||
}
|
||||
|
||||
// A format's own numbers land on the same registry, so one endpoint serves
|
||||
// both and a second worker implementation needs no new plumbing.
|
||||
#[test]
|
||||
fn a_worker_can_add_counters_of_its_own() {
|
||||
let metrics = metrics();
|
||||
let counter = metrics
|
||||
.counter("lance_fragments_removed_total", "Fragments merged away.")
|
||||
.expect("register");
|
||||
counter.inc_by(16);
|
||||
|
||||
let text = metrics.gather().expect("gather");
|
||||
assert!(text.contains("SeaweedFS_worker_lance_fragments_removed_total 16"));
|
||||
}
|
||||
}
|
||||
@@ -73,3 +73,131 @@ impl ExecutionSender for StreamSender {
|
||||
self.send(Body::JobCompleted(completed))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a sender so what passes through it is counted. The handlers report
|
||||
/// their results to admin and nowhere else, so this is where a scrape can learn
|
||||
/// what happened without every handler having to know about metrics.
|
||||
pub struct MeteredSender<'a> {
|
||||
inner: &'a StreamSender,
|
||||
proposals: std::sync::atomic::AtomicUsize,
|
||||
failed: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl<'a> MeteredSender<'a> {
|
||||
pub fn new(inner: &'a StreamSender) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
proposals: std::sync::atomic::AtomicUsize::new(0),
|
||||
failed: std::sync::atomic::AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many proposals went out, for the detection counter.
|
||||
pub fn proposals(&self) -> usize {
|
||||
self.proposals.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether the handler reported a failure of its own. A handler that fails
|
||||
/// by returning an error is counted by the caller; this catches the one that
|
||||
/// reports failure and returns Ok.
|
||||
pub fn reported_failure(&self) -> bool {
|
||||
self.failed.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl DetectionSender for MeteredSender<'_> {
|
||||
fn send_proposals(&self, proposals: DetectionProposals) -> Result<()> {
|
||||
// Counted after the send, not before: a stream that closed mid-sweep
|
||||
// would otherwise leave proposals_total claiming work admin never saw.
|
||||
let count = proposals.proposals.len();
|
||||
self.inner.send_proposals(proposals)?;
|
||||
self.proposals
|
||||
.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_complete(&self, complete: DetectionComplete) -> Result<()> {
|
||||
if !complete.success {
|
||||
self.failed
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
self.inner.send_complete(complete)
|
||||
}
|
||||
|
||||
fn send_activity(&self, activity: ActivityEvent) -> Result<()> {
|
||||
self.inner.send_activity(activity)
|
||||
}
|
||||
|
||||
fn send_observations(&self, observations: WorkerObservations) -> Result<()> {
|
||||
self.inner.send_observations(observations)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutionSender for MeteredSender<'_> {
|
||||
fn send_progress(&self, progress: JobProgressUpdate) -> Result<()> {
|
||||
self.inner.send_progress(progress)
|
||||
}
|
||||
|
||||
fn send_completed(&self, completed: JobCompleted) -> Result<()> {
|
||||
if !completed.success {
|
||||
self.failed
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
self.inner.send_completed(completed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pb::JobProposal;
|
||||
|
||||
fn proposals(n: usize) -> DetectionProposals {
|
||||
DetectionProposals {
|
||||
proposals: (0..n).map(|_| JobProposal::default()).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proposals_are_counted_once_they_are_sent() {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
let stream = StreamSender::new("worker-1".to_string(), tx);
|
||||
let metered = MeteredSender::new(&stream);
|
||||
|
||||
metered.send_proposals(proposals(3)).expect("send");
|
||||
assert_eq!(metered.proposals(), 3);
|
||||
assert!(rx.try_recv().is_ok(), "the proposals reached the stream");
|
||||
}
|
||||
|
||||
// Admin never saw these, so counting them would report work that was not
|
||||
// handed over.
|
||||
#[test]
|
||||
fn proposals_are_not_counted_when_the_stream_is_gone() {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let stream = StreamSender::new("worker-1".to_string(), tx);
|
||||
let metered = MeteredSender::new(&stream);
|
||||
drop(rx);
|
||||
|
||||
assert!(metered.send_proposals(proposals(3)).is_err());
|
||||
assert_eq!(metered.proposals(), 0);
|
||||
}
|
||||
|
||||
// A handler can report failure and still return Ok; the outcome has to come
|
||||
// from what it said, not only from what it returned.
|
||||
#[test]
|
||||
fn a_reported_failure_is_remembered() {
|
||||
let (tx, _rx) = mpsc::unbounded_channel();
|
||||
let stream = StreamSender::new("worker-1".to_string(), tx);
|
||||
let metered = MeteredSender::new(&stream);
|
||||
assert!(!metered.reported_failure());
|
||||
|
||||
metered
|
||||
.send_complete(DetectionComplete {
|
||||
success: false,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("send");
|
||||
assert!(metered.reported_failure());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use tokio::sync::{mpsc, Semaphore};
|
||||
@@ -8,6 +8,7 @@ use tonic::transport::{Certificate, Channel, ClientTlsConfig, Identity};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::config::WorkerOptions;
|
||||
use crate::metrics::Metrics;
|
||||
use crate::pb::{
|
||||
admin_to_worker_message::Body as AdminBody,
|
||||
plugin_control_service_client::PluginControlServiceClient,
|
||||
@@ -16,7 +17,7 @@ use crate::pb::{
|
||||
RunningWork, WorkerHeartbeat, WorkerHello,
|
||||
};
|
||||
use crate::registry::Registry;
|
||||
use crate::senders::StreamSender;
|
||||
use crate::senders::{MeteredSender, StreamSender};
|
||||
|
||||
/// The protocol version this worker speaks, sent in WorkerHello.
|
||||
const PROTOCOL_VERSION: &str = "1";
|
||||
@@ -25,6 +26,17 @@ const PROTOCOL_VERSION: &str = "1";
|
||||
/// reconnecting on failure. The stream is the only channel: everything admin
|
||||
/// asks for and everything the worker reports flows through it.
|
||||
pub async fn run(options: WorkerOptions, registry: Registry) -> Result<()> {
|
||||
let metrics = Metrics::new(&options.worker_id, &options.worker_version)?;
|
||||
run_with_metrics(options, registry, metrics).await
|
||||
}
|
||||
|
||||
/// Runs with metrics a caller has already made, so it can serve them and add
|
||||
/// collectors of its own before the stream starts.
|
||||
pub async fn run_with_metrics(
|
||||
options: WorkerOptions,
|
||||
registry: Registry,
|
||||
metrics: Metrics,
|
||||
) -> Result<()> {
|
||||
if registry.is_empty() {
|
||||
return Err(anyhow!("no job handlers registered"));
|
||||
}
|
||||
@@ -36,20 +48,31 @@ pub async fn run(options: WorkerOptions, registry: Registry) -> Result<()> {
|
||||
));
|
||||
}
|
||||
let slots = Slots::new(&options);
|
||||
metrics.set_slots("detection", 0, slots.detection_total as i64);
|
||||
metrics.set_slots("execution", 0, slots.execution_total as i64);
|
||||
loop {
|
||||
match serve_once(&options, ®istry, &slots).await {
|
||||
Err(err) => warn!("worker stream ended: {err:#}"),
|
||||
match serve_once(&options, ®istry, &slots, &metrics).await {
|
||||
Err(err) => {
|
||||
metrics.stream_ended("failed");
|
||||
warn!("worker stream ended: {err:#}")
|
||||
}
|
||||
// Admin asked this worker to stop, so stop. Reconnecting here would
|
||||
// make shutdown impossible: the worker would log back in.
|
||||
Ok(Outcome::ShutdownRequested) => return Ok(()),
|
||||
Ok(Outcome::ShutdownRequested) => {
|
||||
metrics.stream_ended("shutdown");
|
||||
return Ok(());
|
||||
}
|
||||
// Admin closing a healthy stream is not an error, but reconnecting
|
||||
// in silence hides the reason - two workers sharing an id evict
|
||||
// each other and produce nothing but a login every few seconds.
|
||||
Ok(Outcome::StreamClosed) => warn!(
|
||||
"admin closed the stream; reconnecting in {:?}. If this repeats, check for \
|
||||
another worker using the id {}",
|
||||
options.reconnect_delay, options.worker_id
|
||||
),
|
||||
Ok(Outcome::StreamClosed) => {
|
||||
metrics.stream_ended("closed");
|
||||
warn!(
|
||||
"admin closed the stream; reconnecting in {:?}. If this repeats, check for \
|
||||
another worker using the id {}",
|
||||
options.reconnect_delay, options.worker_id
|
||||
)
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(options.reconnect_delay).await;
|
||||
}
|
||||
@@ -131,6 +154,7 @@ async fn serve_once(
|
||||
options: &WorkerOptions,
|
||||
registry: &Registry,
|
||||
slots: &Slots,
|
||||
metrics: &Metrics,
|
||||
) -> Result<Outcome> {
|
||||
// Operators give the admin's HTTP address; the gRPC port is derived, the
|
||||
// same way the Go worker does it.
|
||||
@@ -157,7 +181,12 @@ async fn serve_once(
|
||||
.await?
|
||||
.into_inner();
|
||||
|
||||
let heartbeat = spawn_heartbeat(sender.clone(), options.clone(), slots.clone());
|
||||
let heartbeat = spawn_heartbeat(
|
||||
sender.clone(),
|
||||
options.clone(),
|
||||
slots.clone(),
|
||||
metrics.clone(),
|
||||
);
|
||||
|
||||
while let Some(message) = inbound.message().await? {
|
||||
let request_id = message.request_id.clone();
|
||||
@@ -166,6 +195,7 @@ async fn serve_once(
|
||||
if !hello.accepted {
|
||||
return Err(anyhow!("admin rejected this worker: {}", hello.message));
|
||||
}
|
||||
metrics.stream_connected();
|
||||
info!(
|
||||
"connected to admin at {} ({})",
|
||||
options.admin_address, grpc_address
|
||||
@@ -194,15 +224,28 @@ async fn serve_once(
|
||||
spawn_preview(
|
||||
registry.clone(),
|
||||
sender.clone(),
|
||||
metrics.clone(),
|
||||
request_id.clone(),
|
||||
request,
|
||||
);
|
||||
}
|
||||
Some(AdminBody::RunDetectionRequest(request)) => {
|
||||
spawn_detection(registry.clone(), sender.clone(), slots.clone(), request);
|
||||
spawn_detection(
|
||||
registry.clone(),
|
||||
sender.clone(),
|
||||
slots.clone(),
|
||||
metrics.clone(),
|
||||
request,
|
||||
);
|
||||
}
|
||||
Some(AdminBody::ExecuteJobRequest(request)) => {
|
||||
spawn_execution(registry.clone(), sender.clone(), slots.clone(), request);
|
||||
spawn_execution(
|
||||
registry.clone(),
|
||||
sender.clone(),
|
||||
slots.clone(),
|
||||
metrics.clone(),
|
||||
request,
|
||||
);
|
||||
}
|
||||
Some(AdminBody::CancelRequest(request)) => {
|
||||
// Cancellation needs a per-request handle to be honoured; until
|
||||
@@ -230,6 +273,7 @@ async fn serve_once(
|
||||
fn spawn_preview(
|
||||
registry: Registry,
|
||||
sender: StreamSender,
|
||||
metrics: Metrics,
|
||||
request_id: String,
|
||||
request: RequestObjectPreview,
|
||||
) {
|
||||
@@ -263,6 +307,7 @@ fn spawn_preview(
|
||||
},
|
||||
},
|
||||
};
|
||||
metrics.preview_finished(if response.success { "ok" } else { "failed" });
|
||||
let _ = sender.send(WorkerBody::ObjectPreviewResponse(response));
|
||||
});
|
||||
}
|
||||
@@ -271,6 +316,7 @@ fn spawn_heartbeat(
|
||||
sender: StreamSender,
|
||||
options: WorkerOptions,
|
||||
slots: Slots,
|
||||
metrics: Metrics,
|
||||
) -> tokio::task::JoinHandle<()> {
|
||||
// The handle has to be the heartbeat's own, or aborting it aborts nothing
|
||||
// and every reconnect leaves another ticker running.
|
||||
@@ -278,6 +324,18 @@ fn spawn_heartbeat(
|
||||
let mut ticker = tokio::time::interval(options.heartbeat_interval);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
// The heartbeat already computes this for admin; publish the same
|
||||
// numbers so a scrape and the admin UI cannot disagree.
|
||||
metrics.set_slots(
|
||||
"detection",
|
||||
slots.detection_used() as i64,
|
||||
slots.detection_total as i64,
|
||||
);
|
||||
metrics.set_slots(
|
||||
"execution",
|
||||
slots.execution_used() as i64,
|
||||
slots.execution_total as i64,
|
||||
);
|
||||
let beat = WorkerHeartbeat {
|
||||
worker_id: options.worker_id.clone(),
|
||||
running_work: Vec::<RunningWork>::new(),
|
||||
@@ -299,6 +357,7 @@ fn spawn_detection(
|
||||
registry: Registry,
|
||||
sender: StreamSender,
|
||||
slots: Slots,
|
||||
metrics: Metrics,
|
||||
request: RunDetectionRequest,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
@@ -308,7 +367,10 @@ fn spawn_detection(
|
||||
// Held until the sweep finishes, so the worker keeps to the capacity it
|
||||
// advertised and the heartbeat reports the truth while it works.
|
||||
let _permit = slots.detection.acquire().await;
|
||||
if let Err(err) = handler.detect(&request, &sender).await {
|
||||
let metered = MeteredSender::new(&sender);
|
||||
let started = Instant::now();
|
||||
let outcome = handler.detect(&request, &metered).await;
|
||||
let result = if let Err(err) = &outcome {
|
||||
warn!("detection for {} failed: {err:#}", request.job_type);
|
||||
let _ = sender.send(WorkerBody::DetectionComplete(
|
||||
crate::pb::DetectionComplete {
|
||||
@@ -319,7 +381,18 @@ fn spawn_detection(
|
||||
total_proposals: 0,
|
||||
},
|
||||
));
|
||||
}
|
||||
"failed"
|
||||
} else if metered.reported_failure() {
|
||||
"failed"
|
||||
} else {
|
||||
"ok"
|
||||
};
|
||||
metrics.detection_finished(
|
||||
&request.job_type,
|
||||
result,
|
||||
started.elapsed().as_secs_f64(),
|
||||
metered.proposals(),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -327,6 +400,7 @@ fn spawn_execution(
|
||||
registry: Registry,
|
||||
sender: StreamSender,
|
||||
slots: Slots,
|
||||
metrics: Metrics,
|
||||
request: ExecuteJobRequest,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
@@ -344,17 +418,26 @@ fn spawn_execution(
|
||||
let Some(handler) = registry.get(&job_type) else {
|
||||
return;
|
||||
};
|
||||
if let Err(err) = handler.execute(&request, &sender).await {
|
||||
let metered = MeteredSender::new(&sender);
|
||||
let started = Instant::now();
|
||||
let outcome = handler.execute(&request, &metered).await;
|
||||
let result = if let Err(err) = &outcome {
|
||||
warn!("job {job_id} failed: {err:#}");
|
||||
let _ = sender.send(WorkerBody::JobCompleted(JobCompleted {
|
||||
request_id: request.request_id.clone(),
|
||||
job_id,
|
||||
job_type,
|
||||
job_type: job_type.clone(),
|
||||
success: false,
|
||||
error_message: format!("{err:#}"),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
"failed"
|
||||
} else if metered.reported_failure() {
|
||||
"failed"
|
||||
} else {
|
||||
"ok"
|
||||
};
|
||||
metrics.job_finished(&job_type, result, started.elapsed().as_secs_f64());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,16 @@ 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-lance-worker"
|
||||
name = "weed-worker"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
seaweed-worker-core = { path = "../core" }
|
||||
prometheus.workspace = true
|
||||
# Only the S3 backend: the other object stores lance enables by default are
|
||||
# build time this worker never spends.
|
||||
lance = { version = "10", default-features = false, features = ["aws"] }
|
||||
|
||||
@@ -32,6 +32,7 @@ const MAX_MIN_VERSIONS: i64 = 1000;
|
||||
pub struct CleanupVersionsHandler {
|
||||
namespace_url: String,
|
||||
fallback: dataset::FallbackOptions,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
|
||||
impl CleanupVersionsHandler {
|
||||
@@ -39,9 +40,15 @@ impl CleanupVersionsHandler {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metrics(mut self, metrics: Option<crate::metrics::LanceMetrics>) -> Self {
|
||||
self.metrics = metrics;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
self
|
||||
@@ -147,13 +154,22 @@ impl JobHandler for CleanupVersionsHandler {
|
||||
let table = match dataset::open(&client, &id, &self.fallback).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "open");
|
||||
}
|
||||
warn!("skipping {encoded}: {err:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_seen(JOB_TYPE);
|
||||
}
|
||||
let stats = match table.stats().await {
|
||||
Ok(stats) => stats,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "stats");
|
||||
}
|
||||
warn!("skipping {encoded}: reading its stats failed: {err:#}");
|
||||
continue;
|
||||
}
|
||||
@@ -281,6 +297,11 @@ impl JobHandler for CleanupVersionsHandler {
|
||||
.await
|
||||
.with_context(|| format!("clean up versions of {}", table.location))?;
|
||||
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.versions_removed.inc_by(stats.old_versions as u64);
|
||||
counters.bytes_reclaimed.inc_by(stats.bytes_removed as u64);
|
||||
}
|
||||
|
||||
let mut output: HashMap<String, ConfigValue> = HashMap::new();
|
||||
output.insert(
|
||||
"old_versions_removed".to_string(),
|
||||
|
||||
@@ -35,6 +35,7 @@ const MIN_FRAGMENTS_CEILING: i64 = 4096;
|
||||
pub struct CompactHandler {
|
||||
namespace_url: String,
|
||||
fallback: dataset::FallbackOptions,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
|
||||
impl CompactHandler {
|
||||
@@ -42,9 +43,15 @@ impl CompactHandler {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metrics(mut self, metrics: Option<crate::metrics::LanceMetrics>) -> Self {
|
||||
self.metrics = metrics;
|
||||
self
|
||||
}
|
||||
|
||||
/// Storage options to use where the namespace vends none.
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
@@ -143,6 +150,9 @@ impl JobHandler for CompactHandler {
|
||||
Err(err) => {
|
||||
// A table that cannot be opened is the next run's problem,
|
||||
// not a reason to abandon the whole sweep.
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "open");
|
||||
}
|
||||
warn!("skipping {encoded}: {err:#}");
|
||||
continue;
|
||||
}
|
||||
@@ -150,9 +160,15 @@ impl JobHandler for CompactHandler {
|
||||
// One unreadable table must not end the sweep: the tables already
|
||||
// read would lose their proposals, and admin would get no
|
||||
// completion for this request at all.
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_seen(JOB_TYPE);
|
||||
}
|
||||
let stats = match table.stats().await {
|
||||
Ok(stats) => stats,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "stats");
|
||||
}
|
||||
warn!("skipping {encoded}: reading its stats failed: {err:#}");
|
||||
continue;
|
||||
}
|
||||
@@ -264,6 +280,12 @@ impl JobHandler for CompactHandler {
|
||||
.await
|
||||
.with_context(|| format!("compact {}", table.location))?;
|
||||
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters
|
||||
.fragments_removed
|
||||
.inc_by(metrics.fragments_removed as u64);
|
||||
}
|
||||
|
||||
let after = table.stats().await?;
|
||||
let mut output: HashMap<String, ConfigValue> = HashMap::new();
|
||||
output.insert(
|
||||
|
||||
@@ -35,6 +35,7 @@ const MAX_UNINDEXED_CEILING: i64 = 100_000_000;
|
||||
pub struct OptimizeIndicesHandler {
|
||||
namespace_url: String,
|
||||
fallback: dataset::FallbackOptions,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
|
||||
impl OptimizeIndicesHandler {
|
||||
@@ -42,9 +43,15 @@ impl OptimizeIndicesHandler {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metrics(mut self, metrics: Option<crate::metrics::LanceMetrics>) -> Self {
|
||||
self.metrics = metrics;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
self
|
||||
@@ -149,14 +156,23 @@ impl JobHandler for OptimizeIndicesHandler {
|
||||
let table = match dataset::open(&client, &id, &self.fallback).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "open");
|
||||
}
|
||||
warn!("skipping {encoded}: {err:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_seen(JOB_TYPE);
|
||||
}
|
||||
let unindexed = match unindexed_rows(&table).await {
|
||||
Ok(Some(unindexed)) => unindexed,
|
||||
Ok(None) => continue,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "index_stats");
|
||||
}
|
||||
warn!("skipping {encoded}: reading its index stats failed: {err:#}");
|
||||
continue;
|
||||
}
|
||||
@@ -232,6 +248,9 @@ impl JobHandler for OptimizeIndicesHandler {
|
||||
.with_context(|| format!("optimize indices of {}", table.location))?;
|
||||
|
||||
let after = unindexed_rows(&table).await?.unwrap_or(0);
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.rows_indexed.inc_by(before.saturating_sub(after));
|
||||
}
|
||||
let mut output: HashMap<String, ConfigValue> = HashMap::new();
|
||||
output.insert(
|
||||
"unindexed_rows_before".to_string(),
|
||||
|
||||
@@ -41,16 +41,24 @@ pub(crate) fn table_id(parameters: &HashMap<String, ConfigValue>) -> Option<Vec<
|
||||
pub fn handlers(
|
||||
namespace_url: String,
|
||||
fallback: crate::dataset::FallbackOptions,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
) -> Vec<Arc<dyn JobHandler>> {
|
||||
vec![
|
||||
Arc::new(
|
||||
compact::CompactHandler::new(namespace_url.clone()).with_fallback(fallback.clone()),
|
||||
compact::CompactHandler::new(namespace_url.clone())
|
||||
.with_fallback(fallback.clone())
|
||||
.with_metrics(metrics.clone()),
|
||||
),
|
||||
Arc::new(
|
||||
indices::OptimizeIndicesHandler::new(namespace_url.clone())
|
||||
.with_fallback(fallback.clone()),
|
||||
.with_fallback(fallback.clone())
|
||||
.with_metrics(metrics.clone()),
|
||||
),
|
||||
Arc::new(
|
||||
cleanup::CleanupVersionsHandler::new(namespace_url)
|
||||
.with_fallback(fallback)
|
||||
.with_metrics(metrics),
|
||||
),
|
||||
Arc::new(cleanup::CleanupVersionsHandler::new(namespace_url).with_fallback(fallback)),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
pub mod catalog;
|
||||
pub mod dataset;
|
||||
pub mod jobs;
|
||||
pub mod metrics;
|
||||
pub mod preview;
|
||||
|
||||
pub use jobs::handlers;
|
||||
@@ -1,18 +1,20 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
|
||||
use seaweed_worker_core::{Registry, TlsOptions, WorkerOptions};
|
||||
use seaweed_worker_core::{Metrics, Registry, TlsOptions, WorkerOptions};
|
||||
use weed_lance_worker::handlers;
|
||||
use weed_lance_worker::metrics::LanceMetrics;
|
||||
|
||||
/// Mirrors `weed worker`'s flags, because this is the same contract from another
|
||||
/// language and an operator should not have to learn a second set of names.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "weed-lance-worker",
|
||||
about = "SeaweedFS maintenance worker for Lance tables"
|
||||
name = "weed-worker",
|
||||
about = "SeaweedFS maintenance worker"
|
||||
)]
|
||||
struct Args {
|
||||
/// Admin server gRPC address.
|
||||
@@ -61,6 +63,16 @@ struct Args {
|
||||
/// this worker dials.
|
||||
#[arg(long)]
|
||||
tls_server_name: Option<String>,
|
||||
|
||||
/// Serve /health, /ready and /metrics on this port, the way
|
||||
/// `weed worker -metricsPort` does. Zero, the default, serves nothing.
|
||||
#[arg(long, default_value = "0", env = "WEED_METRICS_PORT")]
|
||||
metrics_port: u16,
|
||||
|
||||
/// Address the metrics server binds. Loopback by default, since the
|
||||
/// endpoint is unauthenticated.
|
||||
#[arg(long, default_value = "127.0.0.1", env = "WEED_METRICS_IP")]
|
||||
metrics_ip: String,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
@@ -89,6 +101,19 @@ impl Args {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the metrics bind address. Parsing the host separately is what makes an
|
||||
/// IPv6 literal work: "::1" and 9327 joined with a colon is not an address, and
|
||||
/// formatting them that way turns `--metrics-ip ::1` into a startup failure.
|
||||
/// Brackets are accepted too, since that is how the same address is written in a
|
||||
/// URL and an operator will reasonably try it.
|
||||
fn metrics_address(ip: &str, port: u16) -> Result<SocketAddr> {
|
||||
let host = ip.trim().trim_start_matches('[').trim_end_matches(']');
|
||||
let parsed: IpAddr = host
|
||||
.parse()
|
||||
.with_context(|| format!("parse the metrics address {ip}"))?;
|
||||
Ok(SocketAddr::new(parsed, port))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
@@ -116,12 +141,54 @@ async fn main() -> Result<()> {
|
||||
fallback.insert("aws_secret_access_key".to_string(), secret);
|
||||
}
|
||||
|
||||
let metrics = Metrics::new(&options.worker_id, &options.worker_version)?;
|
||||
let lance_metrics = LanceMetrics::new(&metrics)?;
|
||||
if args.metrics_port > 0 {
|
||||
seaweed_worker_core::metrics::spawn(
|
||||
metrics.clone(),
|
||||
metrics_address(&args.metrics_ip, args.metrics_port)?,
|
||||
);
|
||||
}
|
||||
|
||||
let mut registry = Registry::new().with_preview(Arc::new(
|
||||
weed_lance_worker::preview::LancePreview::new(args.namespace.clone(), fallback.clone()),
|
||||
));
|
||||
for handler in handlers(args.namespace, fallback) {
|
||||
for handler in handlers(args.namespace, fallback, Some(lance_metrics)) {
|
||||
registry = registry.register(handler);
|
||||
}
|
||||
|
||||
seaweed_worker_core::run(options, registry).await
|
||||
seaweed_worker_core::stream::run_with_metrics(options, registry, metrics).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::metrics_address;
|
||||
|
||||
#[test]
|
||||
fn metrics_address_takes_ipv4_ipv6_and_brackets() {
|
||||
assert_eq!(
|
||||
metrics_address("127.0.0.1", 9327).unwrap().to_string(),
|
||||
"127.0.0.1:9327"
|
||||
);
|
||||
// Joining these with a colon gives "::1:9327", which is not an address.
|
||||
assert_eq!(
|
||||
metrics_address("::1", 9327).unwrap().to_string(),
|
||||
"[::1]:9327"
|
||||
);
|
||||
assert_eq!(
|
||||
metrics_address("[::1]", 9327).unwrap().to_string(),
|
||||
"[::1]:9327"
|
||||
);
|
||||
assert_eq!(
|
||||
metrics_address("0.0.0.0", 9327).unwrap().to_string(),
|
||||
"0.0.0.0:9327"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metrics_address_rejects_a_hostname() {
|
||||
// Binding takes an address, not a name; saying so beats a confusing
|
||||
// failure inside the server.
|
||||
assert!(metrics_address("localhost", 9327).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! What the Lance jobs reclaimed, in numbers a scrape can add up.
|
||||
//!
|
||||
//! The generic worker metrics say a job ran and how long it took. These say what
|
||||
//! it did: a compaction sweep that runs every minute and removes nothing is a
|
||||
//! different thing from one that never runs, and only these tell them apart.
|
||||
|
||||
use anyhow::Result;
|
||||
use prometheus::IntCounter;
|
||||
use seaweed_worker_core::Metrics;
|
||||
|
||||
/// Counters the Lance jobs raise, registered on the worker's own registry so
|
||||
/// they are served from the same endpoint.
|
||||
#[derive(Clone)]
|
||||
pub struct LanceMetrics {
|
||||
/// The worker's own metrics, so a job can also record what it read and what
|
||||
/// it had to skip - the pair that tells "nothing needed doing" apart from
|
||||
/// "nothing could be read".
|
||||
pub worker: Metrics,
|
||||
pub fragments_removed: IntCounter,
|
||||
pub rows_indexed: IntCounter,
|
||||
pub versions_removed: IntCounter,
|
||||
pub bytes_reclaimed: IntCounter,
|
||||
}
|
||||
|
||||
impl LanceMetrics {
|
||||
pub fn new(metrics: &Metrics) -> Result<Self> {
|
||||
Ok(Self {
|
||||
worker: metrics.clone(),
|
||||
fragments_removed: metrics.counter(
|
||||
"lance_fragments_removed_total",
|
||||
"Fragments merged away by compaction.",
|
||||
)?,
|
||||
rows_indexed: metrics.counter(
|
||||
"lance_rows_indexed_total",
|
||||
"Rows brought under an index that did not cover them.",
|
||||
)?,
|
||||
versions_removed: metrics.counter(
|
||||
"lance_versions_removed_total",
|
||||
"Dataset versions removed by cleanup.",
|
||||
)?,
|
||||
bytes_reclaimed: metrics
|
||||
.counter("lance_bytes_reclaimed_total", "Bytes freed by cleanup.")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! 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,82 +5,26 @@
|
||||
//! 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, ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest,
|
||||
JobCompleted, JobProgressUpdate, JobProposal, JobSpec, RunDetectionRequest,
|
||||
config_value::Kind, ExecuteJobRequest, JobSpec, RunDetectionRequest,
|
||||
};
|
||||
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler, PreviewProvider};
|
||||
use seaweed_worker_core::{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;
|
||||
|
||||
#[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(())
|
||||
}
|
||||
}
|
||||
mod common;
|
||||
use common::{fallback, int_config, namespace_url, Recorder};
|
||||
|
||||
/// 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.
|
||||
@@ -205,15 +149,12 @@ 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 {
|
||||
@@ -288,13 +229,6 @@ 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]
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! 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()
|
||||
);
|
||||
}
|
||||
@@ -109,6 +109,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -344,6 +345,62 @@ 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 {
|
||||
|
||||
@@ -190,7 +190,9 @@ 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))
|
||||
time.Sleep(3 * time.Second) // let the master see the heartbeat again
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
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())
|
||||
}
|
||||
@@ -33,6 +33,9 @@ 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.
|
||||
@@ -48,6 +51,9 @@ 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.
|
||||
@@ -61,6 +67,35 @@ 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)
|
||||
@@ -94,32 +129,14 @@ func StartMasterCluster(t testing.TB) *MasterCluster {
|
||||
}
|
||||
|
||||
mc := &MasterCluster{
|
||||
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: t,
|
||||
weedBinary: weedBinary,
|
||||
baseDir: baseDir,
|
||||
logsDir: logsDir,
|
||||
keepLogs: keepLogs,
|
||||
nodes: nodes,
|
||||
peersStr: strings.Join(peerParts, ","),
|
||||
raftHashicorp: raftHashicorp,
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
@@ -128,6 +145,14 @@ func StartMasterCluster(t testing.TB) *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()
|
||||
@@ -144,17 +169,24 @@ 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=" + mc.peersStr,
|
||||
"-peers=" + 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
|
||||
@@ -292,6 +324,24 @@ 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)
|
||||
@@ -305,18 +355,20 @@ 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.
|
||||
func (mc *MasterCluster) WaitForTopologyId(timeout time.Duration) error {
|
||||
// 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) {
|
||||
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 nil
|
||||
return id, 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.
|
||||
|
||||
@@ -9,7 +9,12 @@ import (
|
||||
|
||||
const (
|
||||
// Election timeout is 3s in our cluster config; allow generous margin.
|
||||
leaderElectionTimeout = 20 * time.Second
|
||||
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
|
||||
)
|
||||
|
||||
// TestLeaderDownAndRecoverQuickly verifies that when the leader is stopped and
|
||||
@@ -149,20 +154,11 @@ func TestTwoMastersDownAndRestart(t *testing.T) {
|
||||
mc.StopNode(down1)
|
||||
mc.StopNode(down2)
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
mc.DumpLogs()
|
||||
t.Fatalf("expected no leader with only 1 of 3 nodes, but node %d claims leadership", soloLeaderIdx)
|
||||
t.Fatalf("expected no leader with only 1 of 3 nodes: %v", err)
|
||||
}
|
||||
|
||||
// Restart both downed nodes.
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# 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"]
|
||||
@@ -0,0 +1,66 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,48 @@
|
||||
-- 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__';
|
||||
@@ -0,0 +1,390 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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"]
|
||||
@@ -0,0 +1,56 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,291 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,339 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# 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"]
|
||||
@@ -0,0 +1,10 @@
|
||||
# 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"]
|
||||
@@ -0,0 +1,77 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,277 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,389 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,130 @@
|
||||
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)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -902,3 +903,96 @@ 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")
|
||||
}
|
||||
@@ -20,8 +20,20 @@ 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
|
||||
@@ -395,7 +407,9 @@ func FindOrBuildWeedBinary() (string, error) {
|
||||
}
|
||||
binPath := filepath.Join(binDir, "weed")
|
||||
|
||||
cmd := exec.Command("go", "build", "-o", binPath, ".")
|
||||
args := append([]string{"build"}, goBuildTags()...)
|
||||
args = append(args, "-o", binPath, ".")
|
||||
cmd := exec.Command("go", args...)
|
||||
cmd.Dir = filepath.Join(repoRoot, "weed")
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
|
||||
@@ -14,6 +14,7 @@ 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.
|
||||
@@ -267,8 +268,15 @@ 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.
|
||||
cmd := exec.Command("cargo", "build", "--release")
|
||||
// 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...)
|
||||
cmd.Dir = rustCrateDir
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
|
||||
@@ -1001,6 +1001,133 @@ 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)
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -13,8 +14,15 @@ 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).
|
||||
@@ -102,6 +110,153 @@ 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
|
||||
|
||||
@@ -179,6 +179,8 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
|
||||
s3Api.Handle("/buckets/{bucket}", wrapWrite(h.adminServer.DeleteBucket)).Methods(http.MethodDelete)
|
||||
s3Api.HandleFunc("/buckets/{bucket}", h.adminServer.ShowBucketDetails).Methods(http.MethodGet)
|
||||
s3Api.HandleFunc("/buckets/{bucket}/lifecycle", h.adminServer.ShowBucketLifecycle).Methods(http.MethodGet)
|
||||
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.UpdateBucketLifecycle)).Methods(http.MethodPut)
|
||||
s3Api.Handle("/buckets/{bucket}/lifecycle", wrapWrite(h.adminServer.DeleteBucketLifecycle)).Methods(http.MethodDelete)
|
||||
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
|
||||
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
|
||||
|
||||
|
||||
@@ -42,6 +42,26 @@ func TestSetupRoutes_RegistersPluginSchedulerStatesAPI_WithAuth(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersBucketLifecycleAPI_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersPluginPages_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
|
||||
@@ -634,7 +634,7 @@ function formatDate(date) {
|
||||
function adminCopyToClipboard(text) {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
showAlert('Copied to clipboard!', 'success');
|
||||
showToast('Copied to clipboard!');
|
||||
}).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) {
|
||||
showAlert('Copied to clipboard!', 'success');
|
||||
showToast('Copied to clipboard!');
|
||||
} else {
|
||||
showAlert('Failed to copy to clipboard', 'danger');
|
||||
}
|
||||
@@ -2265,11 +2265,11 @@ function copyFromInput(inputId) {
|
||||
try {
|
||||
const successful = document.execCommand('copy');
|
||||
if (successful) {
|
||||
showAlert('Copied to clipboard!', 'success');
|
||||
showToast('Copied to clipboard!');
|
||||
} else {
|
||||
// Try modern clipboard API as fallback
|
||||
navigator.clipboard.writeText(input.value).then(() => {
|
||||
showAlert('Copied to clipboard!', 'success');
|
||||
showToast('Copied to clipboard!');
|
||||
}).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(() => {
|
||||
showAlert('Copied to clipboard!', 'success');
|
||||
showToast('Copied to clipboard!');
|
||||
}).catch(() => {
|
||||
showAlert('Failed to copy', 'danger');
|
||||
});
|
||||
|
||||
@@ -168,6 +168,36 @@
|
||||
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
|
||||
@@ -290,6 +320,40 @@
|
||||
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.
@@ -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-lg">
|
||||
<div class="modal-dialog modal-xl">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="bucketLifecycleModalLabel">
|
||||
@@ -649,7 +649,13 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
<div id="bucketLifecycleContent"></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-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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -712,6 +718,69 @@ 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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// 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 => {
|
||||
@@ -1074,6 +1143,10 @@ 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;
|
||||
|
||||
@@ -1090,14 +1163,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(response => response.json())
|
||||
.then(data => {
|
||||
.then(parseLifecycleResponse)
|
||||
.then(({ ok, data }) => {
|
||||
if (requestSeq !== lifecycleRequestSeq) return;
|
||||
if (data.error) {
|
||||
if (!ok || 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 +
|
||||
'Error loading lifecycle rules: ' + (data.error || 'unknown error') +
|
||||
'<\/div>';
|
||||
} else {
|
||||
displayBucketLifecycle(data);
|
||||
@@ -1114,6 +1187,67 @@ 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() {
|
||||
@@ -1145,23 +1279,6 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
function displayBucketDetails(data) {
|
||||
const bucket = data.bucket;
|
||||
|
||||
function escapeHtml(v) {
|
||||
return String(v ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -1232,112 +1349,518 @@ 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) {
|
||||
function escapeHtml(v) {
|
||||
return String(v ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
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 > ' + formatBytes(rule.size_greater_than));
|
||||
}
|
||||
if (rule.size_less_than) {
|
||||
parts.push('size < ' + 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 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];
|
||||
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 days(n) {
|
||||
return n + (n === 1 ? ' day' : ' days');
|
||||
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>';
|
||||
}
|
||||
|
||||
const rules = data.rules || [];
|
||||
if (rules.length === 0) {
|
||||
document.getElementById('bucketLifecycleContent').innerHTML =
|
||||
'<div class="text-center text-muted py-4">No lifecycle configuration<\/div>';
|
||||
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);
|
||||
return;
|
||||
}
|
||||
|
||||
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 > ' + formatBytes(rule.size_greater_than));
|
||||
}
|
||||
if (rule.size_less_than) {
|
||||
parts.push('size < ' + formatBytes(rule.size_less_than));
|
||||
}
|
||||
return parts.length ? parts.join(' ') : '<span class="text-muted">Whole bucket<\/span>';
|
||||
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 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>');
|
||||
const { rule, error } = readLifecycleRuleFromForm();
|
||||
if (error) {
|
||||
alert(error);
|
||||
return false;
|
||||
}
|
||||
|
||||
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>'
|
||||
);
|
||||
if (lifecycleEditor.editingIndex === 'new') {
|
||||
lifecycleEditor.rules.push(rule);
|
||||
} else {
|
||||
lifecycleEditor.rules[lifecycleEditor.editingIndex] = rule;
|
||||
}
|
||||
|
||||
document.getElementById('bucketLifecycleContent').innerHTML = rows.join('');
|
||||
lifecycleEditor.editingIndex = null;
|
||||
lifecycleEditor.editingRule = null;
|
||||
renderLifecycleEditor();
|
||||
return true;
|
||||
}
|
||||
|
||||
function goToPage(page) {
|
||||
@@ -1380,14 +1903,6 @@ function displayBucketLifecycle(data) {
|
||||
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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+34
-25
@@ -234,15 +234,17 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
if raftServer == nil {
|
||||
glog.Fatalf("please verify %s is writable, see https://github.com/seaweedfs/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
|
||||
}
|
||||
// For single-master mode with a fresh log, initialize cluster immediately.
|
||||
// When resuming with existing state, the server is already a member and
|
||||
// will self-elect via fastResume — sending another JoinCommand would block
|
||||
// because goraft's setCommitIndex returns early on JoinCommand entries,
|
||||
// preventing the new entry's event from being notified when old uncommitted
|
||||
// JoinCommands exist in the log.
|
||||
if isSingleMaster && !raftServer.HasExistingState() {
|
||||
glog.V(0).Infof("Single-master mode: initializing cluster immediately")
|
||||
raftServer.DoJoinCommand()
|
||||
}
|
||||
// For single-master mode with a fresh log, initialize cluster immediately.
|
||||
// When resuming with existing state, the server is already a member and
|
||||
// will self-elect via fastResume — sending another JoinCommand would block
|
||||
// because goraft's setCommitIndex returns early on JoinCommand entries,
|
||||
// preventing the new entry's event from being notified when old uncommitted
|
||||
// JoinCommands exist in the log.
|
||||
if isSingleMaster && !raftServer.HasExistingState() {
|
||||
glog.V(0).Infof("Single-master mode: initializing cluster immediately")
|
||||
if err := raftServer.Bootstrap(); err != nil {
|
||||
glog.Errorf("fail to bootstrap the cluster: %v", err)
|
||||
}
|
||||
}
|
||||
ms.SetRaftServer(raftServer)
|
||||
@@ -272,8 +274,13 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
go grpcS.Serve(grpcL)
|
||||
pb.ServeGrpcOnLocalSocket(grpcS, grpcPort)
|
||||
|
||||
// For multi-master mode with non-Hashicorp raft, wait and check if we should join
|
||||
if !*masterOption.raftHashicorp && !isSingleMaster {
|
||||
// A master that starts with no raft state cannot elect on its own — neither
|
||||
// raft implementation lets a server outside the configuration campaign — so
|
||||
// it has to be pulled in by a leader. Keep asking the peers who the leader is
|
||||
// until we are in: the leader admits us once our master client registers, and
|
||||
// only when nobody has one does the first peer mint a new cluster. Restarting
|
||||
// a master alone, or scaling the peer list up, both land here.
|
||||
if !isSingleMaster {
|
||||
go func() {
|
||||
// Stagger bootstrap by peer index so masters don't all check
|
||||
// simultaneously. Peer 0 waits ~1.5s, peer 1 ~3s, etc.
|
||||
@@ -282,22 +289,24 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
glog.V(0).Infof("bootstrap check in %v (peer index %d of %d)", delay, idx, len(peers))
|
||||
time.Sleep(delay)
|
||||
|
||||
ms.Topo.RaftServerAccessLock.RLock()
|
||||
isEmptyMaster := ms.Topo.RaftServer.Leader() == "" && ms.Topo.RaftServer.IsLogEmpty()
|
||||
isFirst := idx == 0
|
||||
if isEmptyMaster && isFirst {
|
||||
existingLeader := ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress)
|
||||
if existingLeader == "" {
|
||||
raftServer.DoJoinCommand()
|
||||
} else {
|
||||
glog.V(0).Infof("skip bootstrap: existing leader %s found from peers", existingLeader)
|
||||
for {
|
||||
if raftServer.HasExistingState() {
|
||||
return
|
||||
}
|
||||
} else if !isEmptyMaster {
|
||||
glog.V(0).Infof("skip bootstrap: leader=%q logEmpty=%v", ms.Topo.RaftServer.Leader(), ms.Topo.RaftServer.IsLogEmpty())
|
||||
} else {
|
||||
glog.V(0).Infof("skip bootstrap: %v is not the first master in peers (index %d)", myMasterAddress, idx)
|
||||
if leader, err := ms.Topo.MaybeLeader(); err == nil && leader != "" {
|
||||
return
|
||||
}
|
||||
if existingLeader := ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress); existingLeader != "" {
|
||||
glog.V(0).Infof("waiting to be admitted by existing leader %s", existingLeader)
|
||||
} else if idx == 0 {
|
||||
if err := raftServer.Bootstrap(); err != nil {
|
||||
glog.Errorf("fail to bootstrap the cluster: %v", err)
|
||||
}
|
||||
} else {
|
||||
glog.V(0).Infof("skip bootstrap: %v is not the first master in peers (index %d)", myMasterAddress, idx)
|
||||
}
|
||||
time.Sleep(raftJoinCheckDelay)
|
||||
}
|
||||
ms.Topo.RaftServerAccessLock.RUnlock()
|
||||
}()
|
||||
}
|
||||
|
||||
|
||||
+135
-39
@@ -394,7 +394,7 @@ var (
|
||||
miniS3AllowDeleteBucketNotEmpty = cmdMini.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
miniS3AutoCreateBucket = cmdMini.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
|
||||
miniBucket = cmdMini.Flag.String("bucket", "", "comma-separated S3 bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_BUCKET env var.")
|
||||
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
|
||||
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables buckets to create on startup if they do not already exist, each name[:FORMAT] with FORMAT one of ICEBERG (default) or LANCE, e.g. warehouse,vectors:LANCE; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
|
||||
)
|
||||
|
||||
// getBindIp determines the bind IP address based on miniIp and miniBindIp flags
|
||||
@@ -1367,14 +1367,20 @@ func runMini(cmd *Command, args []string) bool {
|
||||
tableBucketSpec := *miniTableBucket
|
||||
if tableBucketSpec == "" {
|
||||
tableBucketSpec = os.Getenv("S3_TABLE_BUCKET")
|
||||
} else if os.Getenv("S3_TABLE_BUCKET") == "" {
|
||||
// The catalog routes unprefixed requests to the first S3_TABLE_BUCKET
|
||||
// entry; let the -tableBucket flag mean the same thing.
|
||||
os.Setenv("S3_TABLE_BUCKET", tableBucketSpec)
|
||||
}
|
||||
if err := ensureMiniTableBuckets(tableBucketSpec); err != nil {
|
||||
ready, err := ensureMiniTableBuckets(parseTableBucketList(tableBucketSpec))
|
||||
if err != nil {
|
||||
glog.Warningf("failed to ensure table buckets %q: %v", tableBucketSpec, err)
|
||||
}
|
||||
// The Iceberg catalog routes unprefixed requests to the first
|
||||
// S3_TABLE_BUCKET entry and looks the name up as given, so rewrite the
|
||||
// variable whichever way the spec arrived: a Lance entry or a :FORMAT
|
||||
// suffix left in place names a bucket the catalog cannot find.
|
||||
if names := icebergRoutingNames(ready); len(names) > 0 {
|
||||
os.Setenv("S3_TABLE_BUCKET", strings.Join(names, ","))
|
||||
} else {
|
||||
os.Unsetenv("S3_TABLE_BUCKET")
|
||||
}
|
||||
|
||||
// Print welcome message after all services are running
|
||||
printWelcomeMessage()
|
||||
@@ -2012,67 +2018,157 @@ func ensureMiniBuckets(bucketSpec string) error {
|
||||
})
|
||||
}
|
||||
|
||||
// ensureMiniTableBuckets creates each named S3 Tables bucket on the embedded
|
||||
// filer if it does not already exist. bucketSpec is comma-separated; whitespace
|
||||
// is trimmed and duplicates are dropped. Per-bucket failures are logged so one
|
||||
// bad name does not block the rest. Buckets are owned by s3tables.DefaultAccountID
|
||||
// since mini does not yet model multi-account ownership.
|
||||
func ensureMiniTableBuckets(bucketSpec string) error {
|
||||
names := parseBucketList(bucketSpec)
|
||||
if len(names) == 0 {
|
||||
return nil
|
||||
}
|
||||
// tableBucketEntry is one -tableBucket entry: a bucket name and the table
|
||||
// format that bucket will hold.
|
||||
type tableBucketEntry struct {
|
||||
name string
|
||||
format string
|
||||
}
|
||||
|
||||
// A bucket holds one format, and the format decides which catalog serves it.
|
||||
// Creating one in a format this mini does not serve leaves a bucket no
|
||||
// client can reach, so take the format from the endpoint that is running.
|
||||
format := miniTableBucketFormat()
|
||||
if format == "" {
|
||||
glog.Warningf("not creating table buckets %q: neither the Iceberg nor the Lance endpoint is enabled, so nothing could reach them", bucketSpec)
|
||||
return nil
|
||||
// ensureMiniTableBuckets creates each named S3 Tables bucket on the embedded
|
||||
// filer if it does not already exist, and returns the ones that now hold the
|
||||
// format that was asked for. Per-bucket failures are logged so one bad name
|
||||
// does not block the rest. Buckets are owned by s3tables.DefaultAccountID
|
||||
// since mini does not yet model multi-account ownership.
|
||||
func ensureMiniTableBuckets(buckets []tableBucketEntry) ([]tableBucketEntry, error) {
|
||||
// A bucket holds one format, and the format decides which catalog serves
|
||||
// it, so one created in a format this mini does not serve is a bucket no
|
||||
// client can reach.
|
||||
var servable []tableBucketEntry
|
||||
for _, bucket := range buckets {
|
||||
if !miniServesTableFormat(bucket.format) {
|
||||
// An unsuffixed name means Iceberg, so on a Lance-only mini say how to ask.
|
||||
hint := ""
|
||||
if bucket.format == s3tables.FormatIceberg && miniServesTableFormat(s3tables.FormatLance) {
|
||||
hint = fmt.Sprintf("; name it %s:%s for the Lance namespace", bucket.name, s3tables.FormatLance)
|
||||
}
|
||||
glog.Warningf("not creating table bucket %s: no %s endpoint is enabled, so nothing could reach it%s", bucket.name, bucket.format, hint)
|
||||
continue
|
||||
}
|
||||
servable = append(servable, bucket)
|
||||
}
|
||||
if len(servable) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
filerAddress := pb.NewServerAddress(*miniIp, *miniFilerOptions.port, *miniFilerOptions.portGrpc)
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
|
||||
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var ready []tableBucketEntry
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
manager := s3tables.NewManager()
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
for _, name := range names {
|
||||
for _, bucket := range servable {
|
||||
ctx, cancel := context.WithTimeout(miniClientsCtx(), 5*time.Second)
|
||||
req := &s3tables.CreateTableBucketRequest{Name: name, Format: format}
|
||||
req := &s3tables.CreateTableBucketRequest{Name: bucket.name, Format: bucket.format}
|
||||
var resp s3tables.CreateTableBucketResponse
|
||||
err := manager.Execute(ctx, mgrClient, "CreateTableBucket", req, &resp, s3tables.DefaultAccountID)
|
||||
cancel()
|
||||
if err == nil {
|
||||
glog.V(0).Infof("created %s table bucket %s", format, name)
|
||||
glog.V(0).Infof("created %s table bucket %s", bucket.format, bucket.name)
|
||||
ready = append(ready, bucket)
|
||||
continue
|
||||
}
|
||||
var s3Err *s3tables.S3TablesError
|
||||
if errors.As(err, &s3Err) && s3Err.Type == s3tables.ErrCodeBucketAlreadyExists {
|
||||
glog.V(0).Infof("table bucket %s already exists", name)
|
||||
// The name being taken says nothing about what holds it: it
|
||||
// may be the other format, or an ordinary S3 bucket, which
|
||||
// answers the same conflict. Only reuse what reads back as
|
||||
// the format asked for, since the rest fails later at the
|
||||
// client instead of here.
|
||||
existing, readErr := existingTableBucketFormat(manager, mgrClient, bucket.name)
|
||||
switch {
|
||||
case readErr != nil:
|
||||
glog.Warningf("%s already exists but does not read back as a table bucket: %v; leaving it alone", bucket.name, readErr)
|
||||
case existing != "" && existing != bucket.format:
|
||||
glog.Warningf("table bucket %s already exists holding %s tables, not %s; leaving it alone", bucket.name, existing, bucket.format)
|
||||
default:
|
||||
glog.V(0).Infof("table bucket %s already exists", bucket.name)
|
||||
ready = append(ready, bucket)
|
||||
}
|
||||
continue
|
||||
}
|
||||
glog.Warningf("create table bucket %s: %v", name, err)
|
||||
glog.Warningf("create table bucket %s: %v", bucket.name, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return ready, err
|
||||
}
|
||||
|
||||
// miniTableBucketFormat is the format a pre-created table bucket should hold:
|
||||
// Iceberg when its catalog is running, else Lance, else none because neither
|
||||
// server is up.
|
||||
func miniTableBucketFormat() string {
|
||||
// icebergRoutingNames is the bare names of the buckets holding Iceberg tables,
|
||||
// which are the only ones the Iceberg catalog can take as its default warehouse.
|
||||
func icebergRoutingNames(buckets []tableBucketEntry) []string {
|
||||
var names []string
|
||||
for _, bucket := range buckets {
|
||||
if bucket.format == s3tables.FormatIceberg {
|
||||
names = append(names, bucket.name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// existingTableBucketFormat is the format the named table bucket holds. An empty
|
||||
// format with no error is a bucket predating declared formats, which accepts
|
||||
// either; an error means nothing was confirmed, an ordinary S3 bucket wearing
|
||||
// the name included.
|
||||
func existingTableBucketFormat(manager *s3tables.Manager, client *s3tables.ManagerClient, name string) (string, error) {
|
||||
arn, err := s3tables.BuildBucketARN(s3tables.DefaultRegion, s3tables.DefaultAccountID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(miniClientsCtx(), 5*time.Second)
|
||||
defer cancel()
|
||||
var resp s3tables.GetTableBucketResponse
|
||||
if err := manager.Execute(ctx, client, "GetTableBucket", &s3tables.GetTableBucketRequest{TableBucketARN: arn}, &resp, s3tables.DefaultAccountID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resp.Format, nil
|
||||
}
|
||||
|
||||
// miniServesTableFormat reports whether the endpoint that serves format is
|
||||
// running here: the Iceberg catalog for ICEBERG, the Lance namespace for LANCE.
|
||||
func miniServesTableFormat(format string) bool {
|
||||
if miniEnableS3 == nil || !*miniEnableS3 {
|
||||
return ""
|
||||
return false
|
||||
}
|
||||
if miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0 {
|
||||
return s3tables.FormatIceberg
|
||||
switch format {
|
||||
case s3tables.FormatIceberg:
|
||||
return miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0
|
||||
case s3tables.FormatLance:
|
||||
return miniS3Options.portLance != nil && *miniS3Options.portLance > 0
|
||||
}
|
||||
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
|
||||
return s3tables.FormatLance
|
||||
return false
|
||||
}
|
||||
|
||||
// parseTableBucketList splits a comma-separated table bucket spec into
|
||||
// deduplicated name[:FORMAT] entries, in the order given. The format is stated
|
||||
// rather than read off whichever catalog happens to be listening, so one spec
|
||||
// means one thing on every mini.
|
||||
func parseTableBucketList(spec string) []tableBucketEntry {
|
||||
if spec == "" {
|
||||
return nil
|
||||
}
|
||||
return ""
|
||||
seen := make(map[string]bool)
|
||||
var buckets []tableBucketEntry
|
||||
for _, raw := range strings.Split(spec, ",") {
|
||||
name, rawFormat, _ := strings.Cut(raw, ":")
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || seen[name] {
|
||||
continue
|
||||
}
|
||||
format := s3tables.FormatIceberg
|
||||
if rawFormat = strings.TrimSpace(rawFormat); rawFormat != "" {
|
||||
normalized, ok := s3tables.NormalizeFormat(rawFormat)
|
||||
if !ok {
|
||||
glog.Warningf("not creating table bucket %s: unsupported format %q", name, rawFormat)
|
||||
continue
|
||||
}
|
||||
format = normalized
|
||||
}
|
||||
seen[name] = true
|
||||
buckets = append(buckets, tableBucketEntry{name: name, format: format})
|
||||
}
|
||||
return buckets
|
||||
}
|
||||
|
||||
// parseBucketList splits a comma-separated bucket spec into a deduplicated list
|
||||
|
||||
@@ -3,6 +3,8 @@ package command
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
func TestParseBucketList(t *testing.T) {
|
||||
@@ -28,3 +30,94 @@ func TestParseBucketList(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTableBucketList(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want []tableBucketEntry
|
||||
}{
|
||||
{"empty", "", nil},
|
||||
{"defaults to iceberg", "warehouse", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
|
||||
{"explicit format", "vectors:LANCE", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
|
||||
{"format is case insensitive", "vectors:lance", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
|
||||
{"mixed formats", "warehouse,vectors:LANCE", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}}},
|
||||
{"trims whitespace", " warehouse , vectors : LANCE ", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}}},
|
||||
{"drops unsupported format", "warehouse,vectors:DELTA", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
|
||||
{"empty format is the default", "warehouse:", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}},
|
||||
{"dedupes by name", "vectors:LANCE,vectors:ICEBERG", []tableBucketEntry{{"vectors", s3tables.FormatLance}}},
|
||||
{"drops empty entries", "one,,two:LANCE,", []tableBucketEntry{{"one", s3tables.FormatIceberg}, {"two", s3tables.FormatLance}}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := parseTableBucketList(tt.in)
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("parseTableBucketList(%q) = %v, want %v", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A bucket's format decides which endpoint has to be up for it, so turning one
|
||||
// catalog off must not change what the other format means.
|
||||
func TestMiniServesTableFormat(t *testing.T) {
|
||||
icebergPort, lancePort := *miniS3Options.portIceberg, *miniS3Options.portLance
|
||||
t.Cleanup(func() {
|
||||
*miniS3Options.portIceberg, *miniS3Options.portLance = icebergPort, lancePort
|
||||
})
|
||||
|
||||
*miniS3Options.portIceberg, *miniS3Options.portLance = 8181, 9101
|
||||
if !miniServesTableFormat(s3tables.FormatIceberg) || !miniServesTableFormat(s3tables.FormatLance) {
|
||||
t.Errorf("both endpoints up: want both formats served")
|
||||
}
|
||||
|
||||
*miniS3Options.portIceberg = 0
|
||||
if miniServesTableFormat(s3tables.FormatIceberg) {
|
||||
t.Errorf("iceberg port 0: want ICEBERG unserved")
|
||||
}
|
||||
if !miniServesTableFormat(s3tables.FormatLance) {
|
||||
t.Errorf("iceberg port 0: want LANCE still served")
|
||||
}
|
||||
|
||||
*miniS3Options.portLance = 0
|
||||
if miniServesTableFormat(s3tables.FormatLance) {
|
||||
t.Errorf("lance port 0: want LANCE unserved")
|
||||
}
|
||||
|
||||
if miniServesTableFormat("DELTA") {
|
||||
t.Errorf("unknown format: want unserved")
|
||||
}
|
||||
}
|
||||
|
||||
// The Iceberg catalog looks its default warehouse up by name, so a Lance entry
|
||||
// or a leftover :FORMAT suffix in S3_TABLE_BUCKET names a bucket it cannot find.
|
||||
func TestIcebergRoutingNames(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in []tableBucketEntry
|
||||
want []string
|
||||
}{
|
||||
{"none", nil, nil},
|
||||
{"iceberg only", []tableBucketEntry{{"warehouse", s3tables.FormatIceberg}}, []string{"warehouse"}},
|
||||
{"lance is not routable", []tableBucketEntry{{"vectors", s3tables.FormatLance}}, nil},
|
||||
{"lance first", []tableBucketEntry{{"vectors", s3tables.FormatLance}, {"warehouse", s3tables.FormatIceberg}}, []string{"warehouse"}},
|
||||
{"order preserved", []tableBucketEntry{{"raw", s3tables.FormatIceberg}, {"vectors", s3tables.FormatLance}, {"curated", s3tables.FormatIceberg}}, []string{"raw", "curated"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := icebergRoutingNames(tt.in)
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("icebergRoutingNames(%v) = %v, want %v", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A spec arriving through S3_TABLE_BUCKET carries suffixes too, and the catalog
|
||||
// reads that same variable, so parsing and routing have to agree on the name.
|
||||
func TestIcebergRoutingNamesFromEnvSpec(t *testing.T) {
|
||||
got := icebergRoutingNames(parseTableBucketList("vectors:LANCE,warehouse"))
|
||||
if want := []string{"warehouse"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("routing names for env spec = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,12 @@ package filer
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
@@ -319,6 +323,173 @@ func ClearBucketReadOnly(ctx context.Context, client filer_pb.SeaweedFilerClient
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// filerConfSnapshot is a read of filer.conf plus enough of the entry (or its
|
||||
// absence) to make a follow-up write conditional via
|
||||
// saveFilerConfConditionally, instead of blindly overwriting whatever is
|
||||
// there by the time the write happens.
|
||||
type filerConfSnapshot struct {
|
||||
fc *FilerConf
|
||||
entry *filer_pb.Entry // nil if filer.conf did not exist at read time
|
||||
}
|
||||
|
||||
func readFilerConfSnapshot(ctx context.Context, client filer_pb.SeaweedFilerClient) (*filerConfSnapshot, error) {
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: DirectoryEtcSeaweedFS,
|
||||
Name: FilerConfName,
|
||||
})
|
||||
fc := NewFilerConf()
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return &filerConfSnapshot{fc: fc}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
|
||||
}
|
||||
if len(resp.Entry.Content) > 0 {
|
||||
if err := fc.LoadFromBytes(resp.Entry.Content); err != nil {
|
||||
return nil, fmt.Errorf("parse %s/%s: %v", DirectoryEtcSeaweedFS, FilerConfName, err)
|
||||
}
|
||||
}
|
||||
return &filerConfSnapshot{fc: fc, entry: resp.Entry}, nil
|
||||
}
|
||||
|
||||
// saveFilerConfConditionally writes snap.fc back to filer.conf, conditioned
|
||||
// on nothing having created or modified the file since snap was read. The
|
||||
// filer evaluates the condition under its per-path lock, so a racing writer
|
||||
// fails the precondition instead of silently losing its change.
|
||||
//
|
||||
// The condition is an exact content check (IF_ETAG_MATCH against the MD5
|
||||
// every writer stamps, see SaveInsideFiler), which mtime's one-second
|
||||
// resolution cannot match. A filer.conf written before that stamp existed
|
||||
// carries no hash, so that one write falls back to IF_UNMODIFIED_SINCE and
|
||||
// self-heals from the next write on.
|
||||
func saveFilerConfConditionally(ctx context.Context, client filer_pb.SeaweedFilerClient, snap *filerConfSnapshot) error {
|
||||
var buf bytes.Buffer
|
||||
if err := snap.fc.ToText(&buf); err != nil {
|
||||
return err
|
||||
}
|
||||
content := buf.Bytes()
|
||||
contentMd5 := md5.Sum(content)
|
||||
|
||||
if snap.entry == nil {
|
||||
err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
|
||||
Directory: DirectoryEtcSeaweedFS,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: FilerConfName,
|
||||
IsDirectory: false,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(),
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0644),
|
||||
FileSize: uint64(len(content)),
|
||||
Md5: contentMd5[:],
|
||||
},
|
||||
Content: content,
|
||||
},
|
||||
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
|
||||
{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create %s/%s: %w", DirectoryEtcSeaweedFS, FilerConfName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
entry := snap.entry
|
||||
var condition *filer_pb.WriteCondition
|
||||
if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
|
||||
condition = &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
|
||||
{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{fmt.Sprintf("%x", entry.Attributes.Md5)}},
|
||||
}}
|
||||
} else {
|
||||
var unmodifiedSince int64
|
||||
if entry.Attributes != nil {
|
||||
unmodifiedSince = entry.Attributes.Mtime
|
||||
} else {
|
||||
entry.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
condition = &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
|
||||
{Kind: filer_pb.WriteCondition_IF_UNMODIFIED_SINCE, UnixTime: unmodifiedSince},
|
||||
}}
|
||||
}
|
||||
|
||||
entry.Content = content
|
||||
entry.Attributes.Mtime = time.Now().Unix()
|
||||
entry.Attributes.FileSize = uint64(len(content))
|
||||
entry.Attributes.Md5 = contentMd5[:]
|
||||
err := filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
|
||||
Directory: DirectoryEtcSeaweedFS,
|
||||
Entry: entry,
|
||||
Condition: condition,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("update %s/%s: %w", DirectoryEtcSeaweedFS, FilerConfName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearBucketLifecycleDayTTLs removes any day-TTL filer.conf rules a legacy
|
||||
// PutBucketLifecycleConfiguration handler installed under the bucket's path.
|
||||
// Per-write TTL is now driven by the LifecycleTTLResolver built off the
|
||||
// stored lifecycle XML, so a lingering day-TTL rule would double-stamp
|
||||
// expiration (volume server expires under the old rule) or contradict a
|
||||
// newly saved XML. The write is conditioned on filer.conf being unchanged
|
||||
// since it was read here, so a concurrent writer fails this call rather than
|
||||
// silently losing one side's change.
|
||||
func ClearBucketLifecycleDayTTLs(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketsPath, bucketName, collection string) error {
|
||||
snap, err := readFilerConfSnapshot(ctx, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if snap.entry == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
changed := false
|
||||
bucketPrefix := fmt.Sprintf("%s/%s/", bucketsPath, bucketName)
|
||||
for prefix, ttl := range snap.fc.GetCollectionTtls(collection) {
|
||||
if !strings.HasPrefix(prefix, bucketPrefix) || !strings.HasSuffix(ttl, "d") {
|
||||
continue
|
||||
}
|
||||
locConf, found := snap.fc.GetLocationConf(prefix)
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
// Logged either way: this is a one-way migration, and the prefix and
|
||||
// TTL are all an operator needs to put a rule back by hand.
|
||||
if isLifecycleOwnedPathConf(locConf) {
|
||||
glog.V(0).Infof("lifecycle migration: dropping legacy day-TTL rule %s ttl=%s", prefix, ttl)
|
||||
snap.fc.DeleteLocationConf(prefix)
|
||||
} else {
|
||||
glog.V(0).Infof("lifecycle migration: clearing legacy day-TTL %s on operator rule %s", ttl, prefix)
|
||||
updated := ClonePathConf(locConf)
|
||||
updated.Ttl = ""
|
||||
if err := snap.fc.SetLocationConf(updated); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
|
||||
return saveFilerConfConditionally(ctx, client, snap)
|
||||
}
|
||||
|
||||
// isLifecycleOwnedPathConf reports whether a rule looks like one the removed
|
||||
// PutBucketLifecycleConfiguration add path created, which set only the
|
||||
// routing and TTL fields. That path merged onto whatever already sat at the
|
||||
// prefix, so anything else here - a disk type, WORM settings, a read-only
|
||||
// flag, a placement pin - is an operator's, and deleting the whole rule to
|
||||
// retire its TTL would take their configuration with it.
|
||||
func isLifecycleOwnedPathConf(c *filer_pb.FilerConf_PathConf) bool {
|
||||
return c.GetDiskType() == "" && !c.GetFsync() && !c.GetReadOnly() &&
|
||||
c.GetDataCenter() == "" && c.GetRack() == "" && c.GetDataNode() == "" &&
|
||||
c.GetMaxFileNameLength() == 0 && !c.GetDisableChunkDeletion() &&
|
||||
c.Worm == nil && c.GetWormGracePeriodSeconds() == 0 && c.GetWormRetentionTimeSeconds() == 0
|
||||
}
|
||||
|
||||
func (fc *FilerConf) GetCollectionTtls(collection string) (ttls map[string]string) {
|
||||
ttls = make(map[string]string)
|
||||
fc.rules.Walk(func(key []byte, value *filer_pb.FilerConf_PathConf) bool {
|
||||
|
||||
@@ -2,11 +2,17 @@ package filer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -248,3 +254,338 @@ func TestClearReadOnly(t *testing.T) {
|
||||
assert.False(t, rule.ReadOnly)
|
||||
assert.Equal(t, "7d", rule.Ttl)
|
||||
}
|
||||
|
||||
// fakeFilerConfClient is a minimal in-memory filer_pb.SeaweedFilerClient that
|
||||
// only supports the single-file round trip ReadInsideFiler/SaveInsideFiler
|
||||
// need: lookup, create-if-absent, update. Embedding the interface satisfies
|
||||
// the rest of it; calling any other method panics on the nil embedded value.
|
||||
type fakeFilerConfClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
|
||||
mu sync.Mutex
|
||||
entries map[string]*filer_pb.Entry // key: dir+"/"+name
|
||||
}
|
||||
|
||||
func newFakeFilerConfClient() *fakeFilerConfClient {
|
||||
return &fakeFilerConfClient{entries: make(map[string]*filer_pb.Entry)}
|
||||
}
|
||||
|
||||
func (c *fakeFilerConfClient) key(dir, name string) string { return dir + "/" + name }
|
||||
|
||||
func (c *fakeFilerConfClient) LookupDirectoryEntry(_ context.Context, in *filer_pb.LookupDirectoryEntryRequest, _ ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
e, ok := c.entries[c.key(in.Directory, in.Name)]
|
||||
if !ok {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
// A real gRPC round trip always hands back an independent copy (proto
|
||||
// marshal/unmarshal), so mutating what the caller gets back (as
|
||||
// saveFilerConfConditionally does before re-sending it) must not affect
|
||||
// what conditionHoldsLocked below compares against.
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: cloneFakeEntry(e)}, nil
|
||||
}
|
||||
|
||||
func cloneFakeEntry(e *filer_pb.Entry) *filer_pb.Entry {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
// proto.Clone rather than a struct copy: filer_pb.Entry embeds
|
||||
// protoimpl.MessageState (a sync.Mutex), which a plain `*e` copy would
|
||||
// duplicate by value — exactly what go vet's copylocks check flags.
|
||||
return proto.Clone(e).(*filer_pb.Entry)
|
||||
}
|
||||
|
||||
func (c *fakeFilerConfClient) CreateEntry(_ context.Context, in *filer_pb.CreateEntryRequest, _ ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
key := c.key(in.Directory, in.Entry.Name)
|
||||
if !conditionHoldsLocked(in.Condition, c.entries[key]) {
|
||||
return nil, errors.New("precondition failed")
|
||||
}
|
||||
c.entries[key] = in.Entry
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (c *fakeFilerConfClient) UpdateEntry(_ context.Context, in *filer_pb.UpdateEntryRequest, _ ...grpc.CallOption) (*filer_pb.UpdateEntryResponse, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
key := c.key(in.Directory, in.Entry.Name)
|
||||
if !conditionHoldsLocked(in.Condition, c.entries[key]) {
|
||||
return nil, errors.New("precondition failed")
|
||||
}
|
||||
c.entries[key] = in.Entry
|
||||
return &filer_pb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
// conditionHoldsLocked is a minimal stand-in for the filer server's
|
||||
// writeConditionSatisfied (weed/server/filer_grpc_server_condition.go),
|
||||
// covering just the clause kinds saveFilerConfConditionally uses, so tests
|
||||
// can exercise the CAS path without a real filer server.
|
||||
func conditionHoldsLocked(cond *filer_pb.WriteCondition, current *filer_pb.Entry) bool {
|
||||
if cond == nil {
|
||||
return true
|
||||
}
|
||||
for _, clause := range cond.Clauses {
|
||||
switch clause.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
if current != nil {
|
||||
return false
|
||||
}
|
||||
case filer_pb.WriteCondition_IF_UNMODIFIED_SINCE:
|
||||
if current != nil && current.Attributes != nil && current.Attributes.Mtime > clause.UnixTime {
|
||||
return false
|
||||
}
|
||||
case filer_pb.WriteCondition_IF_ETAG_MATCH:
|
||||
if current == nil {
|
||||
return false
|
||||
}
|
||||
stored := ""
|
||||
if current.Attributes != nil {
|
||||
stored = fmt.Sprintf("%x", current.Attributes.Md5)
|
||||
}
|
||||
matched := false
|
||||
for _, want := range clause.Etags {
|
||||
if want == stored {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// putFilerConf seeds the fake client's filer.conf with the given rules.
|
||||
func putFilerConf(t *testing.T, client *fakeFilerConfClient, rules ...*filer_pb.FilerConf_PathConf) {
|
||||
t.Helper()
|
||||
fc := NewFilerConf()
|
||||
for _, r := range rules {
|
||||
require.NoError(t, fc.SetLocationConf(r))
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, fc.ToText(&buf))
|
||||
client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)] = &filer_pb.Entry{
|
||||
Name: FilerConfName,
|
||||
Content: buf.Bytes(),
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
}
|
||||
|
||||
// readFilerConfText returns the current filer.conf content stored in the fake
|
||||
// client, or "" if none exists yet.
|
||||
func readFilerConfText(client *fakeFilerConfClient) string {
|
||||
e, ok := client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return string(e.Content)
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_NoFilerConf(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
assert.Empty(t, readFilerConfText(client))
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_NoMatchingRule(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/other/",
|
||||
Collection: "other",
|
||||
Ttl: "7d",
|
||||
})
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
assert.Contains(t, readFilerConfText(client), "other")
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_RemovesDayTTLUnderBucket(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/mybucket/",
|
||||
Collection: "mybucket",
|
||||
Ttl: "7d",
|
||||
})
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
|
||||
assert.False(t, found, "day-TTL rule should have been removed")
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_KeepsNonDayTTL(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/mybucket/",
|
||||
Collection: "mybucket",
|
||||
Ttl: "7m", // minutes, not days: not a legacy lifecycle TTL rule
|
||||
})
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
|
||||
assert.True(t, found, "non-day TTL rule should be left alone")
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_KeepsOperatorSettingsAndClearsOnlyTheTTL(t *testing.T) {
|
||||
// The removed add path merged its TTL onto whatever already sat at the
|
||||
// prefix, so a rule carrying operator settings must survive with only its
|
||||
// TTL retired - deleting it outright would drop the disk type and the
|
||||
// read-only flag with it.
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/mybucket/logs/",
|
||||
Collection: "mybucket",
|
||||
Ttl: "30d",
|
||||
DiskType: "hdd",
|
||||
ReadOnly: true,
|
||||
})
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
rule, found := reloaded.GetLocationConf("/buckets/mybucket/logs/")
|
||||
require.True(t, found, "a rule carrying operator settings must not be deleted")
|
||||
assert.Equal(t, "", rule.Ttl, "the legacy day TTL should be gone")
|
||||
assert.Equal(t, "hdd", rule.DiskType, "the operator's disk type must survive")
|
||||
assert.True(t, rule.ReadOnly, "the operator's read-only flag must survive")
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_KeepsWormSettings(t *testing.T) {
|
||||
worm := true
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/mybucket/locked/",
|
||||
Collection: "mybucket",
|
||||
Ttl: "7d",
|
||||
Worm: &worm,
|
||||
WormRetentionTimeSeconds: 3600,
|
||||
})
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
rule, found := reloaded.GetLocationConf("/buckets/mybucket/locked/")
|
||||
require.True(t, found, "a WORM rule must not be deleted to retire a TTL")
|
||||
assert.Equal(t, "", rule.Ttl)
|
||||
assert.True(t, rule.GetWorm())
|
||||
assert.Equal(t, uint64(3600), rule.WormRetentionTimeSeconds)
|
||||
}
|
||||
|
||||
func TestClearBucketLifecycleDayTTLs_KeepsOtherBucketsAndCollections(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client,
|
||||
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/mybucket/", Collection: "mybucket", Ttl: "7d"},
|
||||
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/other/", Collection: "other", Ttl: "7d"},
|
||||
// nested under the target bucket's path but tagged to a different
|
||||
// collection (e.g. a filer-group-prefixed name): must not be swept up
|
||||
// by this bucket's cleanup, since GetCollectionTtls filters by collection.
|
||||
&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/mybucket/nested/", Collection: "group_mybucket", Ttl: "7d"},
|
||||
)
|
||||
|
||||
require.NoError(t, ClearBucketLifecycleDayTTLs(context.Background(), client, "/buckets", "mybucket", "mybucket"))
|
||||
|
||||
reloaded := NewFilerConf()
|
||||
require.NoError(t, reloaded.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
_, found := reloaded.GetLocationConf("/buckets/mybucket/")
|
||||
assert.False(t, found, "the target bucket's day-TTL rule should be gone")
|
||||
|
||||
text := readFilerConfText(client)
|
||||
assert.Contains(t, text, "other")
|
||||
assert.Contains(t, text, "group_mybucket")
|
||||
}
|
||||
|
||||
// bumpMtime models a writer that landed after unmodifiedSince, so an
|
||||
// IF_UNMODIFIED_SINCE precondition built on that timestamp no longer holds.
|
||||
func bumpMtime(client *fakeFilerConfClient, unmodifiedSince int64) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
e := client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)]
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
if e.Attributes == nil {
|
||||
e.Attributes = &filer_pb.FuseAttributes{}
|
||||
}
|
||||
e.Attributes.Mtime = unmodifiedSince + 1
|
||||
}
|
||||
|
||||
func TestSaveFilerConfConditionally_RejectsUpdateModifiedConcurrently(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Collection: "a", Ttl: "7d"})
|
||||
|
||||
snap, err := readFilerConfSnapshot(context.Background(), client)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, snap.entry)
|
||||
require.Empty(t, snap.entry.Attributes.Md5, "test setup should model a pre-existing filer.conf with no stamped Md5")
|
||||
|
||||
// Someone else writes filer.conf after our read but before our write.
|
||||
bumpMtime(client, snap.entry.Attributes.Mtime)
|
||||
|
||||
err = saveFilerConfConditionally(context.Background(), client, snap)
|
||||
assert.Error(t, err, "expected a concurrent modification to fail the conditional write")
|
||||
}
|
||||
|
||||
// TestSaveFilerConfConditionally_ExactContentCheckRejectsConcurrentModification
|
||||
// exercises the primary path: once an entry has been written through this
|
||||
// function (so it carries a content Md5), a later write with a stale
|
||||
// snapshot is rejected by the exact IF_ETAG_MATCH check even when the
|
||||
// concurrent writer happened to leave mtime unchanged — something a
|
||||
// mtime-only precondition would have missed.
|
||||
func TestSaveFilerConfConditionally_ExactContentCheckRejectsConcurrentModification(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Collection: "a", Ttl: "7d"})
|
||||
|
||||
// First write through saveFilerConfConditionally stamps Md5, moving
|
||||
// subsequent reads onto the exact-content check.
|
||||
snap, err := readFilerConfSnapshot(context.Background(), client)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, saveFilerConfConditionally(context.Background(), client, snap))
|
||||
|
||||
snap2, err := readFilerConfSnapshot(context.Background(), client)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, snap2.entry.Attributes.Md5, "expected Md5 to have been stamped by the prior write")
|
||||
|
||||
// A concurrent writer goes through SaveInsideFiler, the path every
|
||||
// other filer.conf writer uses. It lands in the same wall-clock second,
|
||||
// so only the content hash can catch it.
|
||||
concurrentFc := NewFilerConf()
|
||||
require.NoError(t, concurrentFc.LoadFromBytes([]byte(readFilerConfText(client))))
|
||||
require.NoError(t, concurrentFc.SetLocationConf(&filer_pb.FilerConf_PathConf{
|
||||
LocationPrefix: "/buckets/other/", Collection: "other", Ttl: "3d",
|
||||
}))
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, concurrentFc.ToText(&buf))
|
||||
require.NoError(t, SaveInsideFiler(context.Background(), client, DirectoryEtcSeaweedFS, FilerConfName, buf.Bytes()))
|
||||
client.entries[client.key(DirectoryEtcSeaweedFS, FilerConfName)].Attributes.Mtime = snap2.entry.Attributes.Mtime
|
||||
|
||||
err = saveFilerConfConditionally(context.Background(), client, snap2)
|
||||
assert.Error(t, err, "expected the exact-content check to reject a write whose baseline content hash no longer matches")
|
||||
assert.Contains(t, readFilerConfText(client), "/buckets/other/", "the concurrent writer's content must survive")
|
||||
}
|
||||
|
||||
func TestSaveFilerConfConditionally_RejectsCreateWhenCreatedConcurrently(t *testing.T) {
|
||||
client := newFakeFilerConfClient()
|
||||
|
||||
snap, err := readFilerConfSnapshot(context.Background(), client)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, snap.entry, "filer.conf should not exist yet")
|
||||
|
||||
// Someone else creates filer.conf after our read but before our write.
|
||||
putFilerConf(t, client, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/", Collection: "b", Ttl: "3d"})
|
||||
|
||||
err = saveFilerConfConditionally(context.Background(), client, snap)
|
||||
assert.Error(t, err, "expected a concurrent create to fail the conditional write")
|
||||
assert.Contains(t, readFilerConfText(client), "/buckets/b/", "the concurrent writer's content must survive")
|
||||
}
|
||||
@@ -49,8 +49,19 @@ type MetaAggregator struct {
|
||||
// whose unflushed events still exist, and de-accounting it at once would
|
||||
// let subscribers advance past them. A re-add clears the mark; a peer
|
||||
// gone past the grace is dropped so it cannot pin the low-watermarks.
|
||||
peerRemovedAtNs map[pb.ServerAddress]int64
|
||||
peerWatermarksLock sync.Mutex
|
||||
peerRemovedAtNs map[pb.ServerAddress]int64
|
||||
// lowWatermarkTsNs and lowFlushWatermarkTsNs are the last minima signalled
|
||||
// on deliveryAdvanced and flushAdvanced, each closed and replaced when its
|
||||
// own minimum rises. Held readers park on the one that bounds them:
|
||||
// arriving data cannot release a watermark hold, only a peer reporting
|
||||
// the progress that hold waits on. The two are kept apart because a
|
||||
// delivery advance - one per event a peer streams - cannot release a read
|
||||
// held at the flush watermark, and waking it costs a whole pass.
|
||||
lowWatermarkTsNs int64
|
||||
lowFlushWatermarkTsNs int64
|
||||
deliveryAdvanced chan struct{}
|
||||
flushAdvanced chan struct{}
|
||||
peerWatermarksLock sync.Mutex
|
||||
}
|
||||
|
||||
// MetaAggregator only aggregates data "on the fly". The logs are not re-persisted to disk.
|
||||
@@ -116,6 +127,7 @@ func (ma *MetaAggregator) initPeerWatermark(peer pb.ServerAddress) {
|
||||
ma.peerFlushWatermarks[peer] = 0
|
||||
}
|
||||
delete(ma.peerRemovedAtNs, peer)
|
||||
ma.noteLowWatermarksLocked()
|
||||
}
|
||||
|
||||
func (ma *MetaAggregator) markPeerWatermarkRemoved(peer pb.ServerAddress) {
|
||||
@@ -144,6 +156,8 @@ func (ma *MetaAggregator) dropExpiredRemovedPeersLocked() {
|
||||
delete(ma.peerFlushWatermarks, peer)
|
||||
}
|
||||
}
|
||||
// Dropping the peer that pinned a minimum raises it, same as it reporting.
|
||||
ma.noteLowWatermarksLocked()
|
||||
}
|
||||
|
||||
// advancePeerWatermark records the peer as received-through tsNs. Monotonic,
|
||||
@@ -154,6 +168,7 @@ func (ma *MetaAggregator) advancePeerWatermark(peer pb.ServerAddress, tsNs int64
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
if cur, found := ma.peerWatermarks[peer]; found && tsNs > cur {
|
||||
ma.peerWatermarks[peer] = tsNs
|
||||
ma.noteLowWatermarksLocked()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +179,7 @@ func (ma *MetaAggregator) advancePeerFlushWatermark(peer pb.ServerAddress, tsNs
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
if cur, found := ma.peerFlushWatermarks[peer]; found && tsNs > cur {
|
||||
ma.peerFlushWatermarks[peer] = tsNs
|
||||
ma.noteLowWatermarksLocked()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,16 +190,7 @@ func (ma *MetaAggregator) PeerLowFlushWatermarkTsNs() int64 {
|
||||
ma.peerWatermarksLock.Lock()
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
ma.dropExpiredRemovedPeersLocked()
|
||||
if len(ma.peerFlushWatermarks) == 0 {
|
||||
return 0
|
||||
}
|
||||
var low int64 = math.MaxInt64
|
||||
for _, tsNs := range ma.peerFlushWatermarks {
|
||||
if tsNs < low {
|
||||
low = tsNs
|
||||
}
|
||||
}
|
||||
return low
|
||||
return lowWatermarkOf(ma.peerFlushWatermarks)
|
||||
}
|
||||
|
||||
// PeerLowWatermarkTsNs returns the minimum received-through timestamp across
|
||||
@@ -194,11 +201,67 @@ func (ma *MetaAggregator) PeerLowWatermarkTsNs() int64 {
|
||||
ma.peerWatermarksLock.Lock()
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
ma.dropExpiredRemovedPeersLocked()
|
||||
if len(ma.peerWatermarks) == 0 {
|
||||
return lowWatermarkOf(ma.peerWatermarks)
|
||||
}
|
||||
|
||||
// DeliveryWatermarkAdvancedChan returns a channel closed the next time the
|
||||
// delivery low-watermark rises, which is what releases an in-memory read held
|
||||
// at it. PeerLowFlushWatermarkTsNs has FlushWatermarkAdvancedChan. Callers
|
||||
// must take the channel before reading the watermark they hold at, so a rise
|
||||
// in between wakes them instead of being missed.
|
||||
func (ma *MetaAggregator) DeliveryWatermarkAdvancedChan() <-chan struct{} {
|
||||
ma.peerWatermarksLock.Lock()
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
if ma.deliveryAdvanced == nil {
|
||||
ma.deliveryAdvanced = make(chan struct{})
|
||||
}
|
||||
return ma.deliveryAdvanced
|
||||
}
|
||||
|
||||
// FlushWatermarkAdvancedChan returns a channel closed the next time the flush
|
||||
// low-watermark rises, which is what releases a persisted-log read held at it.
|
||||
func (ma *MetaAggregator) FlushWatermarkAdvancedChan() <-chan struct{} {
|
||||
ma.peerWatermarksLock.Lock()
|
||||
defer ma.peerWatermarksLock.Unlock()
|
||||
if ma.flushAdvanced == nil {
|
||||
ma.flushAdvanced = make(chan struct{})
|
||||
}
|
||||
return ma.flushAdvanced
|
||||
}
|
||||
|
||||
// noteLowWatermarksLocked recomputes both minima and wakes the readers parked
|
||||
// on each one that rose. Caller must hold peerWatermarksLock.
|
||||
func (ma *MetaAggregator) noteLowWatermarksLocked() {
|
||||
low, flushLow := lowWatermarkOf(ma.peerWatermarks), lowWatermarkOf(ma.peerFlushWatermarks)
|
||||
// Falls are recorded too (a joining peer sits at 0 until it signals), so
|
||||
// the climb back out of one is seen as a rise.
|
||||
if low > ma.lowWatermarkTsNs {
|
||||
ma.deliveryAdvanced = closeWatermarkChan(ma.deliveryAdvanced)
|
||||
}
|
||||
if flushLow > ma.lowFlushWatermarkTsNs {
|
||||
ma.flushAdvanced = closeWatermarkChan(ma.flushAdvanced)
|
||||
}
|
||||
ma.lowWatermarkTsNs, ma.lowFlushWatermarkTsNs = low, flushLow
|
||||
}
|
||||
|
||||
// closeWatermarkChan wakes everyone parked on ch and clears it, so the next
|
||||
// caller parks on a fresh one.
|
||||
func closeWatermarkChan(ch chan struct{}) chan struct{} {
|
||||
if ch != nil {
|
||||
close(ch)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lowWatermarkOf returns the minimum across the tracked peers, or 0 when none
|
||||
// are tracked: a peer that has not signalled sits at 0 and pins the minimum
|
||||
// there, which is what makes completeness unknown.
|
||||
func lowWatermarkOf(watermarks map[pb.ServerAddress]int64) int64 {
|
||||
if len(watermarks) == 0 {
|
||||
return 0
|
||||
}
|
||||
var low int64 = math.MaxInt64
|
||||
for _, tsNs := range ma.peerWatermarks {
|
||||
for _, tsNs := range watermarks {
|
||||
if tsNs < low {
|
||||
low = tsNs
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// TrackPeerForTesting registers a peer as if the master had announced it, but
|
||||
// without starting its subscription goroutine, so loop tests can drive the
|
||||
// low-watermarks by hand. Test support only.
|
||||
func (ma *MetaAggregator) TrackPeerForTesting(peer pb.ServerAddress) {
|
||||
ma.peerChansLock.Lock()
|
||||
ma.peerChans[peer] = make(chan struct{})
|
||||
ma.peerChansLock.Unlock()
|
||||
ma.initPeerWatermark(peer)
|
||||
}
|
||||
|
||||
// ReportPeerWatermarksForTesting stands in for what a peer's stream reports:
|
||||
// its delivery watermark (events and idle heartbeats) and its flush
|
||||
// watermark. Test support only.
|
||||
func (ma *MetaAggregator) ReportPeerWatermarksForTesting(peer pb.ServerAddress, deliveredTsNs, flushedTsNs int64) {
|
||||
ma.advancePeerWatermark(peer, deliveredTsNs)
|
||||
ma.advancePeerFlushWatermark(peer, flushedTsNs)
|
||||
}
|
||||
@@ -147,3 +147,67 @@ func TestPeerFlushWatermarkBookkeeping(t *testing.T) {
|
||||
}
|
||||
_ = a
|
||||
}
|
||||
|
||||
// closed reports whether ch has been signalled, without blocking.
|
||||
func closed(ch <-chan struct{}) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// TestWatermarkAdvancedChansAreScoped pins what each wake channel promises. A
|
||||
// held read re-runs a whole pass - a persisted-log listing in it - so waking
|
||||
// one whose bound did not move is pure waste, and peers advance their delivery
|
||||
// watermark on every event they stream.
|
||||
func TestWatermarkAdvancedChansAreScoped(t *testing.T) {
|
||||
ma := newTestAggregator()
|
||||
a, b := pb.ServerAddress("filer-a:8888"), pb.ServerAddress("filer-b:8888")
|
||||
ma.initPeerWatermark(a)
|
||||
ma.initPeerWatermark(b)
|
||||
|
||||
delivery, flush := ma.DeliveryWatermarkAdvancedChan(), ma.FlushWatermarkAdvancedChan()
|
||||
|
||||
// One peer alone does not move either minimum: the other still pins both.
|
||||
ma.advancePeerWatermark(a, 100)
|
||||
ma.advancePeerFlushWatermark(a, 100)
|
||||
if closed(delivery) || closed(flush) {
|
||||
t.Fatalf("a single peer moved a minimum: delivery=%v flush=%v", closed(delivery), closed(flush))
|
||||
}
|
||||
|
||||
// Delivery progress on every peer wakes the in-memory holds only.
|
||||
ma.advancePeerWatermark(b, 50)
|
||||
if !closed(delivery) {
|
||||
t.Fatal("delivery low-watermark rose without waking the in-memory holds")
|
||||
}
|
||||
if closed(flush) {
|
||||
t.Fatal("delivery progress woke the persisted-log holds, which it cannot release")
|
||||
}
|
||||
|
||||
// And flush progress the persisted-log holds only.
|
||||
delivery = ma.DeliveryWatermarkAdvancedChan()
|
||||
ma.advancePeerFlushWatermark(b, 50)
|
||||
if !closed(flush) {
|
||||
t.Fatal("flush low-watermark rose without waking the persisted-log holds")
|
||||
}
|
||||
if closed(delivery) {
|
||||
t.Fatal("flush progress woke the in-memory holds, which it cannot release")
|
||||
}
|
||||
|
||||
// A fresh channel is handed out after each signal, so the next park is on
|
||||
// the next rise rather than on one already consumed.
|
||||
flush = ma.FlushWatermarkAdvancedChan()
|
||||
if closed(flush) {
|
||||
t.Fatal("re-handed a signalled channel")
|
||||
}
|
||||
ma.advancePeerFlushWatermark(a, 200)
|
||||
if closed(flush) {
|
||||
t.Fatal("one peer above the minimum signalled a rise")
|
||||
}
|
||||
ma.advancePeerFlushWatermark(b, 200)
|
||||
if !closed(flush) {
|
||||
t.Fatal("the trailing peer catching up did not signal a rise")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package filer
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -41,6 +42,11 @@ func ReadInsideFiler(ctx context.Context, filerClient filer_pb.SeaweedFilerClien
|
||||
return
|
||||
}
|
||||
|
||||
// SaveInsideFiler writes content into the entry's inline Content. The content
|
||||
// MD5 is stamped on every write so the entry's ETag always describes what is
|
||||
// actually stored: conditional writers key IF_ETAG_MATCH off it, and a hash
|
||||
// left behind by an earlier write would make that condition pass against
|
||||
// content that has since changed.
|
||||
func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, name string, content []byte) error {
|
||||
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
@@ -48,6 +54,8 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
|
||||
Name: name,
|
||||
})
|
||||
|
||||
contentMd5 := md5.Sum(content)
|
||||
|
||||
if err == filer_pb.ErrNotFound {
|
||||
err = filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
@@ -59,6 +67,7 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
|
||||
Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0644),
|
||||
FileSize: uint64(len(content)),
|
||||
Md5: contentMd5[:],
|
||||
},
|
||||
Content: content,
|
||||
},
|
||||
@@ -69,6 +78,7 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di
|
||||
entry.Content = content
|
||||
entry.Attributes.Mtime = time.Now().Unix()
|
||||
entry.Attributes.FileSize = uint64(len(content))
|
||||
entry.Attributes.Md5 = contentMd5[:]
|
||||
err = filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: entry,
|
||||
|
||||
@@ -288,6 +288,15 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// a failed chunk leaves its window untouched while the tasks after it
|
||||
// may well have filled theirs, so only the prefix up to the hole is
|
||||
// data the caller may use
|
||||
for _, task := range tasks {
|
||||
if int64(task.bytesRead) != task.bufferEnd-task.bufferStart {
|
||||
n = int(task.bufferStart) + task.bytesRead
|
||||
break
|
||||
}
|
||||
}
|
||||
return n, ts, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ package filer
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type mockChunkCache struct {
|
||||
@@ -202,3 +206,54 @@ func TestReaderAtSparseFileDoesNotLeak(t *testing.T) {
|
||||
testReadAt(t, readerAt, 0, 3, 3, io.EOF, []byte{2, 2, 2}, []byte{0, 0, 0})
|
||||
testReadAt(t, readerAt, 1, 2, 2, io.EOF, []byte{2, 2}, []byte{0, 0})
|
||||
}
|
||||
|
||||
// holeChunkCache serves every chunk but one, so that chunk falls through to a
|
||||
// lookup that fails.
|
||||
type holeChunkCache struct {
|
||||
mockChunkCache
|
||||
missingFileId string
|
||||
}
|
||||
|
||||
func (c *holeChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (int, error) {
|
||||
if fileId == c.missingFileId {
|
||||
return 0, nil
|
||||
}
|
||||
return c.mockChunkCache.ReadChunkAt(data, fileId, offset)
|
||||
}
|
||||
|
||||
func (c *holeChunkCache) GetMaxFilePartSizeInCache() uint64 {
|
||||
return math.MaxUint64
|
||||
}
|
||||
|
||||
// The parallel reads place their bytes directly in the output buffer, so a
|
||||
// failing middle chunk leaves a hole with valid data after it. Reporting that
|
||||
// length would hand the caller bytes it never read.
|
||||
func TestReaderAtParallelFailureReturnsContiguousPrefix(t *testing.T) {
|
||||
visibles := NewIntervalList[*VisibleInterval]()
|
||||
for i, fileId := range []string{"1", "2", "3"} {
|
||||
addVisibleInterval(visibles, &VisibleInterval{
|
||||
start: int64(i) * 4,
|
||||
stop: int64(i)*4 + 4,
|
||||
fileId: fileId,
|
||||
chunkSize: 4,
|
||||
})
|
||||
}
|
||||
|
||||
readerAt := &ChunkReadAt{
|
||||
ctx: context.Background(),
|
||||
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
|
||||
fileSize: 12,
|
||||
readerCache: NewReaderCache(3, &holeChunkCache{missingFileId: "2"}, func(ctx context.Context, fileId string) ([]string, error) {
|
||||
return nil, errors.New("volume down")
|
||||
}, nil),
|
||||
readerPattern: NewReaderPattern(),
|
||||
prefetchCount: 3,
|
||||
}
|
||||
|
||||
buf := make([]byte, 12)
|
||||
n, err := readerAt.ReadAt(buf, 0)
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 4, n, "only the bytes before the failed chunk are readable")
|
||||
assert.Equal(t, []byte{1, 1, 1, 1}, buf[:n])
|
||||
}
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user