mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1ffea7522 | ||
|
|
389b99f8e8 | ||
|
|
654502ce8f | ||
|
|
1b5e98143e | ||
|
|
d86c692a39 | ||
|
|
e0f07c762a | ||
|
|
2d5ffecc1f | ||
|
|
004fc32503 | ||
|
|
641fc8b031 | ||
|
|
228500fe37 | ||
|
|
7ebf2ebac3 | ||
|
|
cc8364a03e | ||
|
|
c3f4d799b5 | ||
|
|
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,26 @@ 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
|
||||
# The version from the lock, not whatever else a restored cache holds.
|
||||
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
|
||||
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
|
||||
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build normal variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -67,11 +84,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 +109,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 +123,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,26 @@ 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
|
||||
# The version from the lock, not whatever else a restored cache holds.
|
||||
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
|
||||
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
|
||||
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build large-disk variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -120,13 +136,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 +197,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 +211,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 +318,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 +336,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,26 @@ 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
|
||||
# The version from the lock, not whatever else a restored cache holds.
|
||||
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
|
||||
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
|
||||
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build large-disk variant
|
||||
env:
|
||||
SEAWEEDFS_COMMIT: ${{ github.sha }}
|
||||
@@ -103,13 +120,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 +179,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 +194,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
|
||||
|
||||
@@ -3,10 +3,10 @@ name: "helm: lint and test charts"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths: ['k8s/**']
|
||||
paths: ['k8s/**', '.github/workflows/helm_ci.yml']
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths: ['k8s/**']
|
||||
paths: ['k8s/**', '.github/workflows/helm_ci.yml']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -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
|
||||
@@ -1472,11 +1549,37 @@ jobs:
|
||||
|
||||
echo "All template rendering tests passed!"
|
||||
|
||||
- name: Resolve an image tag that is published
|
||||
run: |
|
||||
set -e
|
||||
# A release bumps appVersion on master ~40 minutes before the container
|
||||
# build publishes that tag, and this workflow runs on the bump commit.
|
||||
# Install the last released image for the length of that window instead
|
||||
# of failing on ImagePullBackOff.
|
||||
IMAGE=$(helm template test k8s/charts/seaweedfs \
|
||||
-s templates/master/master-statefulset.yaml | awk '$1 == "image:" {print $2; exit}')
|
||||
REPO=${IMAGE%:*}
|
||||
TAG=${IMAGE##*:}
|
||||
# Anything but a published tag installs latest, which between releases
|
||||
# is the same digest as the chart's own appVersion, so a registry blip
|
||||
# costs nothing while failing the job on one would cost a red build.
|
||||
STATUS=$(curl -sSL --connect-timeout 5 --max-time 15 -o /dev/null \
|
||||
-w '%{http_code}' "https://hub.docker.com/v2/repositories/$REPO/tags/$TAG" || true)
|
||||
if [ "$STATUS" = 200 ]; then
|
||||
echo "installing $IMAGE"
|
||||
else
|
||||
echo "$IMAGE is unavailable (HTTP ${STATUS:-none}), installing $REPO:latest"
|
||||
TAG=latest
|
||||
fi
|
||||
echo "IMAGE_TAG=$TAG" >> $GITHUB_ENV
|
||||
|
||||
- name: Create kind cluster
|
||||
uses: helm/kind-action@v1.14.0
|
||||
|
||||
- name: Run chart-testing (install)
|
||||
run: ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts
|
||||
run: |
|
||||
ct install --target-branch ${{ github.event.repository.default_branch }} --all --chart-dirs k8s/charts \
|
||||
--helm-extra-set-args "--set=image.tag=$IMAGE_TAG"
|
||||
|
||||
- name: Verify SFTP host key secret lifecycle
|
||||
run: |
|
||||
@@ -1484,7 +1587,7 @@ jobs:
|
||||
CHART_DIR="k8s/charts/seaweedfs"
|
||||
NS="sftp-hostkey"
|
||||
SECRET="hk-seaweedfs-sftp-ssh-secret"
|
||||
SFTP_ARGS="--set sftp.enabled=true --set master.enabled=false --set volume.enabled=false --set filer.enabled=false"
|
||||
SFTP_ARGS="--set image.tag=$IMAGE_TAG --set sftp.enabled=true --set master.enabled=false --set volume.enabled=false --set filer.enabled=false"
|
||||
kubectl create namespace "$NS"
|
||||
|
||||
echo "=== install generates a host key, upgrade keeps it ==="
|
||||
@@ -1561,6 +1664,7 @@ jobs:
|
||||
# release if the hook Job does not finish, so a clean install is the
|
||||
# assertion.
|
||||
helm install np $CHART_DIR -n "$NS" --wait --timeout 8m \
|
||||
--set image.tag=$IMAGE_TAG \
|
||||
--set s3.enabled=true \
|
||||
--set s3.createBuckets[0].name=testbucket \
|
||||
--set networkPolicy.enabled=true \
|
||||
|
||||
@@ -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,82 @@
|
||||
name: "Rust Plugin Worker Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'seaweed-worker/**'
|
||||
- 'weed/pb/plugin.proto'
|
||||
- '.github/workflows/rust-worker-tests.yml'
|
||||
push:
|
||||
branches: [ master, main ]
|
||||
paths:
|
||||
- 'seaweed-worker/**'
|
||||
- 'weed/pb/plugin.proto'
|
||||
- '.github/workflows/rust-worker-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
rust-worker-build:
|
||||
name: Rust Plugin Worker Build and Unit Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
# cargo tracks its own inputs but not the runner's C toolchain, so a cached
|
||||
# target/ can carry C objects built against a different glibc than we link against.
|
||||
- name: Fingerprint build toolchain
|
||||
id: toolchain
|
||||
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
seaweed-worker/target/release
|
||||
key: rust-worker-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-worker/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
rust-worker-${{ steps.toolchain.outputs.fingerprint }}-
|
||||
|
||||
# lance's build scripts compile their own protos and look for a protoc.
|
||||
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
|
||||
# own build already uses, so no job depends on a system package and every
|
||||
# build sees the same version.
|
||||
- name: Use the vendored protoc
|
||||
run: |
|
||||
cd seaweed-worker
|
||||
cargo fetch
|
||||
# The version from the lock, not whatever else a restored cache holds.
|
||||
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
|
||||
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
|
||||
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
# The release profile is what ships, and it is where the release and the
|
||||
# container builds would otherwise discover a break for the first time.
|
||||
- name: Build the plugin workers
|
||||
run: cd seaweed-worker && cargo build --release
|
||||
|
||||
# The tests that need a live gateway skip themselves without one, the way
|
||||
# the Go integration tests skip without Docker; the lifecycle suite in
|
||||
# test/s3tables/lifecycle is what runs them against a real cluster.
|
||||
# Release, so this reuses the build above rather than compiling lance,
|
||||
# arrow and datafusion a second time in another profile.
|
||||
- name: Run unit tests
|
||||
run: cd seaweed-worker && cargo test --release --workspace
|
||||
@@ -1,4 +1,4 @@
|
||||
name: "rust: build versioned volume server binaries"
|
||||
name: "rust: build versioned binaries"
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -113,6 +113,102 @@ jobs:
|
||||
weed-volume_${{ matrix.asset_suffix }}.tar.gz
|
||||
weed-volume_${{ matrix.asset_suffix }}.tar.gz.md5
|
||||
|
||||
# The Rust maintenance worker: Linux only, because it runs beside the cluster
|
||||
# it maintains rather than on a laptop, and its dependency tree (lance, arrow,
|
||||
# datafusion) makes every extra target an expensive build.
|
||||
build-rust-worker-linux:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- target: x86_64-unknown-linux-gnu
|
||||
asset_suffix: linux_amd64
|
||||
- target: aarch64-unknown-linux-gnu
|
||||
asset_suffix: linux_arm64
|
||||
cross: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# The upload step is handed a token explicitly; a cargo build script
|
||||
# should not find another one sitting in the checkout's git config.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Install cross-compilation tools
|
||||
if: matrix.cross
|
||||
run: |
|
||||
sudo dpkg --add-architecture arm64
|
||||
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
|
||||
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gcc-aarch64-linux-gnu
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
seaweed-worker/target/${{ matrix.target }}/release
|
||||
key: rust-worker-release-${{ matrix.target }}-${{ hashFiles('seaweed-worker/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
rust-worker-release-${{ matrix.target }}-
|
||||
|
||||
# lance's build scripts compile their own protos and look for a protoc.
|
||||
# Point them at the one protoc-bin-vendored ships, which seaweed-worker's
|
||||
# own build already uses, so no job depends on a system package and every
|
||||
# build sees the same version.
|
||||
- name: Use the vendored protoc
|
||||
run: |
|
||||
cd seaweed-worker
|
||||
cargo fetch
|
||||
# The version from the lock, not whatever else a restored cache holds.
|
||||
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
|
||||
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
|
||||
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
|
||||
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
|
||||
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build the Rust maintenance worker
|
||||
run: |
|
||||
cd seaweed-worker
|
||||
cargo build --release -p weed-lance-worker --target ${{ matrix.target }}
|
||||
|
||||
- name: Package binary
|
||||
run: |
|
||||
cp seaweed-worker/target/${{ matrix.target }}/release/weed-worker weed-worker
|
||||
tar czf weed-worker_${{ matrix.asset_suffix }}.tar.gz weed-worker
|
||||
rm weed-worker
|
||||
md5sum weed-worker_${{ matrix.asset_suffix }}.tar.gz > weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
|
||||
|
||||
- name: Upload release assets
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
files: |
|
||||
weed-worker_${{ matrix.asset_suffix }}.tar.gz
|
||||
weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload artifacts
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: rust-worker-${{ matrix.asset_suffix }}
|
||||
path: |
|
||||
weed-worker_${{ matrix.asset_suffix }}.tar.gz
|
||||
weed-worker_${{ matrix.asset_suffix }}.tar.gz.md5
|
||||
|
||||
build-rust-volume-darwin:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -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
|
||||
@@ -238,12 +238,12 @@ require (
|
||||
github.com/lpar/calendar v0.2.0 // indirect
|
||||
github.com/magiconair/properties v1.8.10 // indirect
|
||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||
github.com/moby/go-archive v0.2.0 // indirect
|
||||
github.com/moby/go-archive v0.3.0 // indirect
|
||||
github.com/moby/moby/api v1.54.2 // indirect
|
||||
github.com/moby/moby/client v0.4.0 // indirect
|
||||
github.com/moby/patternmatcher v0.6.1 // indirect
|
||||
github.com/moby/sys/sequential v0.6.0 // indirect
|
||||
github.com/moby/sys/user v0.4.0 // indirect
|
||||
github.com/moby/sys/sequential v0.7.0 // indirect
|
||||
github.com/moby/sys/user v0.4.1 // indirect
|
||||
github.com/moby/sys/userns v0.1.0 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/oklog/ulid/v2 v2.1.1 // indirect
|
||||
|
||||
@@ -1543,8 +1543,8 @@ github.com/moby/buildkit v0.29.0 h1:wxLEFbCOJntEDjSNNN2YWd8zxltZxT5muDQ0LzpbtpU=
|
||||
github.com/moby/buildkit v0.29.0/go.mod h1:Dmv2FeDe34t75QuzeU87rBoZpAAkcpT5zeu4hXzmASc=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
|
||||
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
|
||||
github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c=
|
||||
github.com/moby/go-archive v0.3.0/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
|
||||
github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg=
|
||||
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
|
||||
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||
@@ -1559,14 +1559,14 @@ github.com/moby/sys/capability v0.4.0 h1:4D4mI6KlNtWMCM1Z/K0i7RV1FkX+DBDHKVJpCnd
|
||||
github.com/moby/sys/capability v0.4.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I=
|
||||
github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg=
|
||||
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
|
||||
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
|
||||
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
|
||||
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
|
||||
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
|
||||
github.com/moby/sys/signal v0.7.1 h1:PrQxdvxcGijdo6UXXo/lU/TvHUWyPhj7UOpSo8tuvk0=
|
||||
github.com/moby/sys/signal v0.7.1/go.mod h1:Se1VGehYokAkrSQwL4tDzHvETwUZlnY7S5XtQ50mQp8=
|
||||
github.com/moby/sys/symlink v0.3.0 h1:GZX89mEZ9u53f97npBy4Rc3vJKj7JBDj/PN2I22GrNU=
|
||||
github.com/moby/sys/symlink v0.3.0/go.mod h1:3eNdhduHmYPcgsJtZXW1W4XUJdZGBIkttZ8xKqPUJq0=
|
||||
github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs=
|
||||
github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
|
||||
github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0=
|
||||
github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y=
|
||||
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
|
||||
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
@@ -1636,8 +1636,8 @@ github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxP
|
||||
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
|
||||
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
|
||||
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
|
||||
github.com/parquet-go/parquet-go v0.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=
|
||||
|
||||
+84
-2
@@ -9,7 +9,7 @@
|
||||
# curl -fsSL ... | bash -s -- --version 4.34 --dir /usr/local/bin
|
||||
#
|
||||
# Options:
|
||||
# --component COMP Which binary to install: weed, volume-rust, all (default: weed)
|
||||
# --component COMP Which binary to install: weed, volume-rust, worker-rust, all (default: weed)
|
||||
# --version VER Release version tag (default: latest)
|
||||
# --large-disk Use large disk variant (5-byte offset, 8TB max volume)
|
||||
# --dir DIR Installation directory (default: /usr/local/bin)
|
||||
@@ -22,6 +22,7 @@ COMPONENT="weed"
|
||||
VERSION=""
|
||||
LARGE_DISK=false
|
||||
INSTALL_DIR="/usr/local/bin"
|
||||
WORKER_INSTALLED=false
|
||||
|
||||
# Colors (if terminal supports them)
|
||||
if [ -t 1 ]; then
|
||||
@@ -128,6 +129,33 @@ rust_asset_name() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Does a release carry this asset? Answers 0 for yes and 1 for a 404, and stops
|
||||
# the installer on anything else: a rate limit or a network blip must not read
|
||||
# as "this release predates the binary" and quietly skip it.
|
||||
asset_exists() {
|
||||
local url="$1" code=""
|
||||
if command -v curl &>/dev/null; then
|
||||
code="$(curl -sL -o /dev/null -I -w '%{http_code}' "$url" || true)"
|
||||
elif command -v wget &>/dev/null; then
|
||||
# --spider's exit status folds 404 in with every other server error, so
|
||||
# read the status line itself; -S prints one per redirect hop.
|
||||
code="$(wget -S --spider -q -O /dev/null "$url" 2>&1 | awk '/^ *HTTP\// {c=$2} END {print c}')"
|
||||
fi
|
||||
|
||||
case "$code" in
|
||||
200) return 0 ;;
|
||||
404) return 1 ;;
|
||||
*) error "Could not check ${url} (HTTP ${code:-none}). Retry, or install components one at a time." ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Build Rust maintenance worker asset name. No large-disk variant: the worker
|
||||
# maintains tables through the namespace and never opens a volume file.
|
||||
worker_asset_name() {
|
||||
local os="$1" arch="$2"
|
||||
echo "weed-worker_${os}_${arch}.tar.gz"
|
||||
}
|
||||
|
||||
# Install a single component
|
||||
install_component() {
|
||||
local component="$1" os="$2" arch="$3"
|
||||
@@ -204,10 +232,48 @@ install_component() {
|
||||
ok "Installed weed-volume to ${INSTALL_DIR}/${dest_name}"
|
||||
;;
|
||||
|
||||
worker-rust)
|
||||
# Published for linux only: the worker runs beside the cluster it
|
||||
# maintains, and its dependency tree makes every extra target an
|
||||
# expensive build.
|
||||
case "$os" in
|
||||
linux) ;;
|
||||
*) error "Rust maintenance worker is not available for ${os}. Supported: linux" ;;
|
||||
esac
|
||||
case "$arch" in
|
||||
amd64|arm64) ;;
|
||||
*) error "Rust maintenance worker is not available for ${arch}. Supported: amd64, arm64" ;;
|
||||
esac
|
||||
|
||||
asset_name="$(worker_asset_name "$os" "$arch")"
|
||||
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
|
||||
download "$download_url" "${tmpdir}/${asset_name}"
|
||||
|
||||
info "Extracting ${asset_name}..."
|
||||
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
|
||||
|
||||
local worker_bin
|
||||
worker_bin="$(find "$tmpdir" -name 'weed-worker' -type f | head -1)"
|
||||
if [ -z "$worker_bin" ]; then
|
||||
error "Could not find weed-worker binary in archive"
|
||||
fi
|
||||
|
||||
chmod +x "$worker_bin"
|
||||
install_binary "$worker_bin" "weed-worker"
|
||||
WORKER_INSTALLED=true
|
||||
ok "Installed weed-worker to ${INSTALL_DIR}/weed-worker"
|
||||
;;
|
||||
|
||||
*)
|
||||
error "Unknown component: ${component}. Use: weed, volume-rust, all"
|
||||
error "Unknown component: ${component}. Use: weed, volume-rust, worker-rust, all"
|
||||
;;
|
||||
esac
|
||||
|
||||
# The trap is per-process, so a later component's would replace this one and
|
||||
# leave the earlier extraction behind. Clean up here and hand the trap back;
|
||||
# the error paths above exit, which still fires it.
|
||||
rm -rf "$tmpdir"
|
||||
trap - EXIT
|
||||
}
|
||||
|
||||
# Copy binary to install dir, using sudo if needed
|
||||
@@ -251,6 +317,16 @@ main() {
|
||||
all)
|
||||
install_component "weed" "$os" "$arch"
|
||||
install_component "volume-rust" "$os" "$arch"
|
||||
# The worker is published for linux amd64/arm64 only, and only by
|
||||
# releases new enough to carry it; skip either case rather than fail
|
||||
# an install that has already put two binaries in place.
|
||||
if [ "$os" != "linux" ] || { [ "$arch" != "amd64" ] && [ "$arch" != "arm64" ]; }; then
|
||||
warn "Skipping the Rust maintenance worker: no build for ${os}/${arch}"
|
||||
elif ! asset_exists "https://github.com/${REPO}/releases/download/${VERSION}/$(worker_asset_name "$os" "$arch")"; then
|
||||
warn "Skipping the Rust maintenance worker: ${VERSION} does not carry one"
|
||||
else
|
||||
install_component "worker-rust" "$os" "$arch"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
install_component "$COMPONENT" "$os" "$arch"
|
||||
@@ -265,11 +341,17 @@ main() {
|
||||
if [ "$COMPONENT" = "volume-rust" ] || [ "$COMPONENT" = "all" ]; then
|
||||
info " weed-volume: ${INSTALL_DIR}/weed-volume"
|
||||
fi
|
||||
if [ "$WORKER_INSTALLED" = true ]; then
|
||||
info " weed-worker: ${INSTALL_DIR}/weed-worker"
|
||||
fi
|
||||
echo ""
|
||||
info "Quick start:"
|
||||
info " weed master # Start master server"
|
||||
info " weed volume -mserver=localhost:9333 # Start Go volume server"
|
||||
info " weed-volume -mserver localhost:9333 # Start Rust volume server"
|
||||
if [ "$WORKER_INSTALLED" = true ]; then
|
||||
info " weed-worker --admin localhost:23646 # Start the Rust maintenance worker"
|
||||
fi
|
||||
}
|
||||
|
||||
main
|
||||
@@ -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,17 @@ one.
|
||||
`core` knows nothing about any job. A second worker is a new crate beside
|
||||
`lance` that depends on it, not a fork of the protocol.
|
||||
|
||||
## Building
|
||||
|
||||
`core` compiles `plugin.proto` with the protoc that protoc-bin-vendored ships,
|
||||
the way seaweed-volume does, so it needs no system install.
|
||||
|
||||
The lance crates compile protos of their own, in their own build-script
|
||||
processes, which nothing our build script sets can reach. They need a protoc of
|
||||
their own: either one on PATH — `brew install protobuf`, `apt install
|
||||
protobuf-compiler` — or `PROTOC` naming one. CI points it at the vendored
|
||||
binary for the runner's platform, resolved from the version in `Cargo.lock`.
|
||||
|
||||
## Running
|
||||
|
||||
cargo run -p weed-lance-worker -- --admin 127.0.0.1:23646
|
||||
@@ -20,6 +31,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
|
||||
|
||||
@@ -278,12 +278,17 @@ func NewAdminServer(masters string, filerGroup string, templateFS http.FileSyste
|
||||
glog.V(1).Infof("No data directory configured, maintenance system will run in memory-only mode (enabled: %v)", maintenanceConfig.Enabled)
|
||||
}
|
||||
|
||||
// Load saved task configurations from persistence. This has to run before the maintenance
|
||||
// manager is created: creating it applies the maintenance policy to the registered
|
||||
// detectors and schedulers, while this call replaces each task's whole config object, so
|
||||
// running it afterwards would discard what the policy just applied. Both read the same
|
||||
// persisted task config files, so the policy ends up as the last writer and stays
|
||||
// authoritative for the task types it covers.
|
||||
server.loadTaskConfigurationsFromPersistence()
|
||||
|
||||
// Always initialize maintenance manager
|
||||
server.InitMaintenanceManager(maintenanceConfig)
|
||||
|
||||
// Load saved task configurations from persistence
|
||||
server.loadTaskConfigurationsFromPersistence()
|
||||
|
||||
// Start maintenance manager if enabled
|
||||
if maintenanceConfig.Enabled {
|
||||
go func() {
|
||||
@@ -1001,6 +1006,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)
|
||||
@@ -1652,7 +1784,16 @@ func (s *AdminServer) ListPluginSchedulerStates() ([]adminplugin.SchedulerJobTyp
|
||||
|
||||
// InitMaintenanceManager initializes the maintenance manager
|
||||
func (s *AdminServer) InitMaintenanceManager(config *maintenance.MaintenanceConfig) {
|
||||
s.maintenanceManager = maintenance.NewMaintenanceManager(s, config)
|
||||
// Hand the real config store to the manager so that, if it has to build the maintenance policy
|
||||
// itself, it reads the persisted task configs instead of compiled-in defaults. Only pass it when
|
||||
// a data directory is actually configured: an unconfigured store has nothing to read, and a typed
|
||||
// nil pointer would satisfy the loaders' type assertion and then panic on use.
|
||||
var configPersistence interface{}
|
||||
if s.configPersistence != nil && s.configPersistence.IsConfigured() {
|
||||
configPersistence = s.configPersistence
|
||||
}
|
||||
|
||||
s.maintenanceManager = maintenance.NewMaintenanceManager(s, config, configPersistence)
|
||||
|
||||
// Set up task persistence if config persistence is available
|
||||
if s.configPersistence != nil {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
@@ -29,6 +30,7 @@ const (
|
||||
VacuumTaskConfigFile = "task_vacuum.pb"
|
||||
ECTaskConfigFile = "task_erasure_coding.pb"
|
||||
BalanceTaskConfigFile = "task_balance.pb"
|
||||
EcBalanceTaskConfigFile = "task_ec_balance.pb"
|
||||
ReplicationTaskConfigFile = "task_replication.pb"
|
||||
|
||||
// JSON reference files
|
||||
@@ -36,6 +38,7 @@ const (
|
||||
VacuumTaskConfigJSONFile = "task_vacuum.json"
|
||||
ECTaskConfigJSONFile = "task_erasure_coding.json"
|
||||
BalanceTaskConfigJSONFile = "task_balance.json"
|
||||
EcBalanceTaskConfigJSONFile = "task_ec_balance.json"
|
||||
ReplicationTaskConfigJSONFile = "task_replication.json"
|
||||
|
||||
// Task persistence subdirectories and settings
|
||||
@@ -53,6 +56,7 @@ type (
|
||||
VacuumTaskConfig = worker_pb.VacuumTaskConfig
|
||||
ErasureCodingTaskConfig = worker_pb.ErasureCodingTaskConfig
|
||||
BalanceTaskConfig = worker_pb.BalanceTaskConfig
|
||||
EcBalanceTaskConfig = worker_pb.EcBalanceTaskConfig
|
||||
ReplicationTaskConfig = worker_pb.ReplicationTaskConfig
|
||||
)
|
||||
|
||||
@@ -156,7 +160,7 @@ func (cp *ConfigPersistence) LoadMaintenanceConfig() (*MaintenanceConfig, error)
|
||||
var config MaintenanceConfig
|
||||
if err := proto.Unmarshal(configData, &config); err == nil {
|
||||
// Always populate policy from separate task configuration files
|
||||
config.Policy = buildPolicyFromTaskConfigs()
|
||||
config.Policy = cp.buildPolicyFromTaskConfigs()
|
||||
return &config, nil
|
||||
}
|
||||
}
|
||||
@@ -268,6 +272,28 @@ func (cp *ConfigPersistence) RestoreConfig(filename, backupName string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Default task policies. These derive from each task's own NewDefaultConfig() so that a
|
||||
// task type has exactly one definition of its defaults. They used to be hand-written copies
|
||||
// here, and had drifted from the values the tasks themselves and the admin UI schema use:
|
||||
// vacuum scanned every 24h instead of 2h, balance every 6h instead of 30m with a 0.1 instead
|
||||
// of 0.2 imbalance threshold, and erasure coding every 168h instead of 1h with a 0.90 instead
|
||||
// of 0.95 fullness ratio and a 1024MB instead of 30MB minimum volume size.
|
||||
func defaultVacuumTaskPolicy() *worker_pb.TaskPolicy {
|
||||
return vacuum.NewDefaultConfig().ToTaskPolicy()
|
||||
}
|
||||
|
||||
func defaultErasureCodingTaskPolicy() *worker_pb.TaskPolicy {
|
||||
return erasure_coding.NewDefaultConfig().ToTaskPolicy()
|
||||
}
|
||||
|
||||
func defaultBalanceTaskPolicy() *worker_pb.TaskPolicy {
|
||||
return balance.NewDefaultConfig().ToTaskPolicy()
|
||||
}
|
||||
|
||||
func defaultEcBalanceTaskPolicy() *worker_pb.TaskPolicy {
|
||||
return ec_balance.NewDefaultConfig().ToTaskPolicy()
|
||||
}
|
||||
|
||||
// SaveVacuumTaskConfig saves vacuum task configuration to protobuf file
|
||||
func (cp *ConfigPersistence) SaveVacuumTaskConfig(config *VacuumTaskConfig) error {
|
||||
return cp.saveTaskConfig(VacuumTaskConfigFile, config)
|
||||
@@ -288,28 +314,14 @@ func (cp *ConfigPersistence) LoadVacuumTaskConfig() (*VacuumTaskConfig, error) {
|
||||
}
|
||||
|
||||
// Return default config if no valid config found
|
||||
return &VacuumTaskConfig{
|
||||
GarbageThreshold: 0.3,
|
||||
MinVolumeAgeHours: 24,
|
||||
}, nil
|
||||
return defaultVacuumTaskPolicy().GetVacuumConfig(), nil
|
||||
}
|
||||
|
||||
// LoadVacuumTaskPolicy loads complete vacuum task policy from protobuf file
|
||||
func (cp *ConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
if cp.dataDir == "" {
|
||||
// Return default policy if no data directory
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 2,
|
||||
RepeatIntervalSeconds: 24 * 3600, // 24 hours in seconds
|
||||
CheckIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: 0.3,
|
||||
MinVolumeAgeHours: 24,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultVacuumTaskPolicy(), nil
|
||||
}
|
||||
|
||||
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
|
||||
@@ -318,18 +330,7 @@ func (cp *ConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, erro
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
// Return default policy if file doesn't exist
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 2,
|
||||
RepeatIntervalSeconds: 24 * 3600, // 24 hours in seconds
|
||||
CheckIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: 0.3,
|
||||
MinVolumeAgeHours: 24,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultVacuumTaskPolicy(), nil
|
||||
}
|
||||
|
||||
// Read file
|
||||
@@ -371,32 +372,14 @@ func (cp *ConfigPersistence) LoadErasureCodingTaskConfig() (*ErasureCodingTaskCo
|
||||
}
|
||||
|
||||
// Return default config if no valid config found
|
||||
return &ErasureCodingTaskConfig{
|
||||
FullnessRatio: 0.9,
|
||||
QuietForSeconds: 3600,
|
||||
MinVolumeSizeMb: 1024,
|
||||
CollectionFilter: "",
|
||||
}, nil
|
||||
return defaultErasureCodingTaskPolicy().GetErasureCodingConfig(), nil
|
||||
}
|
||||
|
||||
// LoadErasureCodingTaskPolicy loads complete EC task policy from protobuf file
|
||||
func (cp *ConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
if cp.dataDir == "" {
|
||||
// Return default policy if no data directory
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 168 * 3600, // 1 week in seconds
|
||||
CheckIntervalSeconds: 24 * 3600, // 24 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
|
||||
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
|
||||
FullnessRatio: 0.9,
|
||||
QuietForSeconds: 3600,
|
||||
MinVolumeSizeMb: 1024,
|
||||
CollectionFilter: "",
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultErasureCodingTaskPolicy(), nil
|
||||
}
|
||||
|
||||
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
|
||||
@@ -405,20 +388,7 @@ func (cp *ConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolic
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
// Return default policy if file doesn't exist
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 168 * 3600, // 1 week in seconds
|
||||
CheckIntervalSeconds: 24 * 3600, // 24 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
|
||||
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
|
||||
FullnessRatio: 0.9,
|
||||
QuietForSeconds: 3600,
|
||||
MinVolumeSizeMb: 1024,
|
||||
CollectionFilter: "",
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultErasureCodingTaskPolicy(), nil
|
||||
}
|
||||
|
||||
// Read file
|
||||
@@ -460,28 +430,14 @@ func (cp *ConfigPersistence) LoadBalanceTaskConfig() (*BalanceTaskConfig, error)
|
||||
}
|
||||
|
||||
// Return default config if no valid config found
|
||||
return &BalanceTaskConfig{
|
||||
ImbalanceThreshold: 0.1,
|
||||
MinServerCount: 2,
|
||||
}, nil
|
||||
return defaultBalanceTaskPolicy().GetBalanceConfig(), nil
|
||||
}
|
||||
|
||||
// LoadBalanceTaskPolicy loads complete balance task policy from protobuf file
|
||||
func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
if cp.dataDir == "" {
|
||||
// Return default policy if no data directory
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
CheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
|
||||
BalanceConfig: &worker_pb.BalanceTaskConfig{
|
||||
ImbalanceThreshold: 0.1,
|
||||
MinServerCount: 2,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultBalanceTaskPolicy(), nil
|
||||
}
|
||||
|
||||
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
|
||||
@@ -490,18 +446,7 @@ func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, err
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
// Return default policy if file doesn't exist
|
||||
return &worker_pb.TaskPolicy{
|
||||
Enabled: true,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
CheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
|
||||
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
|
||||
BalanceConfig: &worker_pb.BalanceTaskConfig{
|
||||
ImbalanceThreshold: 0.1,
|
||||
MinServerCount: 2,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
return defaultBalanceTaskPolicy(), nil
|
||||
}
|
||||
|
||||
// Read file
|
||||
@@ -523,6 +468,60 @@ func (cp *ConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, err
|
||||
return nil, fmt.Errorf("failed to unmarshal balance task configuration")
|
||||
}
|
||||
|
||||
// SaveEcBalanceTaskPolicy saves complete EC balance task policy to protobuf file
|
||||
func (cp *ConfigPersistence) SaveEcBalanceTaskPolicy(policy *worker_pb.TaskPolicy) error {
|
||||
return cp.saveTaskConfig(EcBalanceTaskConfigFile, policy)
|
||||
}
|
||||
|
||||
// LoadEcBalanceTaskConfig loads EC balance task configuration from protobuf file
|
||||
func (cp *ConfigPersistence) LoadEcBalanceTaskConfig() (*EcBalanceTaskConfig, error) {
|
||||
if taskPolicy, err := cp.LoadEcBalanceTaskPolicy(); err == nil && taskPolicy != nil {
|
||||
if ecBalanceConfig := taskPolicy.GetEcBalanceConfig(); ecBalanceConfig != nil {
|
||||
return ecBalanceConfig, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Return default config if no valid config found
|
||||
return defaultEcBalanceTaskPolicy().GetEcBalanceConfig(), nil
|
||||
}
|
||||
|
||||
// LoadEcBalanceTaskPolicy loads complete EC balance task policy from protobuf file.
|
||||
// ec_balance is registered like the other maintenance tasks and ec_balance.LoadConfigFromPersistence
|
||||
// asserts on this accessor, so without it the task could never be configured at all.
|
||||
func (cp *ConfigPersistence) LoadEcBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
if cp.dataDir == "" {
|
||||
// Return default policy if no data directory
|
||||
return defaultEcBalanceTaskPolicy(), nil
|
||||
}
|
||||
|
||||
confDir := filepath.Join(cp.dataDir, ConfigSubdir)
|
||||
configPath := filepath.Join(confDir, EcBalanceTaskConfigFile)
|
||||
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
// Return default policy if file doesn't exist
|
||||
return defaultEcBalanceTaskPolicy(), nil
|
||||
}
|
||||
|
||||
// Read file
|
||||
configData, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read EC balance task config file: %w", err)
|
||||
}
|
||||
|
||||
// Try to unmarshal as TaskPolicy
|
||||
var policy worker_pb.TaskPolicy
|
||||
if err := proto.Unmarshal(configData, &policy); err == nil {
|
||||
// Validate that it's actually a TaskPolicy with EC balance config
|
||||
if policy.GetEcBalanceConfig() != nil {
|
||||
glog.V(1).Infof("Loaded EC balance task policy from %s", configPath)
|
||||
return &policy, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to unmarshal EC balance task configuration")
|
||||
}
|
||||
|
||||
// SaveReplicationTaskConfig saves replication task configuration to protobuf file
|
||||
func (cp *ConfigPersistence) SaveReplicationTaskConfig(config *ReplicationTaskConfig) error {
|
||||
return cp.saveTaskConfig(ReplicationTaskConfigFile, config)
|
||||
@@ -632,6 +631,8 @@ func (cp *ConfigPersistence) SaveTaskPolicy(taskType string, policy *worker_pb.T
|
||||
return cp.SaveErasureCodingTaskPolicy(policy)
|
||||
case "balance":
|
||||
return cp.SaveBalanceTaskPolicy(policy)
|
||||
case "ec_balance":
|
||||
return cp.SaveEcBalanceTaskPolicy(policy)
|
||||
case "replication":
|
||||
return cp.SaveReplicationTaskPolicy(policy)
|
||||
}
|
||||
@@ -687,67 +688,13 @@ func (cp *ConfigPersistence) GetConfigInfo() map[string]interface{} {
|
||||
return info
|
||||
}
|
||||
|
||||
// buildPolicyFromTaskConfigs loads task configurations from separate files and builds a MaintenancePolicy
|
||||
func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
policy := &worker_pb.MaintenancePolicy{
|
||||
GlobalMaxConcurrent: 4,
|
||||
DefaultRepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
DefaultCheckIntervalSeconds: 12 * 3600, // 12 hours in seconds
|
||||
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
|
||||
}
|
||||
|
||||
// Load vacuum task configuration
|
||||
if vacuumConfig := vacuum.LoadConfigFromPersistence(nil); vacuumConfig != nil {
|
||||
policy.TaskPolicies["vacuum"] = &worker_pb.TaskPolicy{
|
||||
Enabled: vacuumConfig.Enabled,
|
||||
MaxConcurrent: int32(vacuumConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
|
||||
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Load erasure coding task configuration
|
||||
if ecConfig := erasure_coding.LoadConfigFromPersistence(nil); ecConfig != nil {
|
||||
policy.TaskPolicies["erasure_coding"] = &worker_pb.TaskPolicy{
|
||||
Enabled: ecConfig.Enabled,
|
||||
MaxConcurrent: int32(ecConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
|
||||
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
|
||||
FullnessRatio: float64(ecConfig.FullnessRatio),
|
||||
QuietForSeconds: int32(ecConfig.QuietForSeconds),
|
||||
MinVolumeSizeMb: int32(ecConfig.MinSizeMB),
|
||||
CollectionFilter: ecConfig.CollectionFilter,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Load balance task configuration
|
||||
if balanceConfig := balance.LoadConfigFromPersistence(nil); balanceConfig != nil {
|
||||
policy.TaskPolicies["balance"] = &worker_pb.TaskPolicy{
|
||||
Enabled: balanceConfig.Enabled,
|
||||
MaxConcurrent: int32(balanceConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
|
||||
BalanceConfig: &worker_pb.BalanceTaskConfig{
|
||||
ImbalanceThreshold: float64(balanceConfig.ImbalanceThreshold),
|
||||
MinServerCount: int32(balanceConfig.MinServerCount),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Built maintenance policy from separate task configs - %d task policies loaded", len(policy.TaskPolicies))
|
||||
return policy
|
||||
// buildPolicyFromTaskConfigs builds the maintenance policy from the persisted task configs.
|
||||
//
|
||||
// The body lives in weed/admin/maintenance because the maintenance manager needs the same
|
||||
// policy when it has to build one itself, and this package already imports that one. Keeping
|
||||
// a second copy here is what let the two drift apart in the first place.
|
||||
func (cp *ConfigPersistence) buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
return maintenance.BuildPolicyFromTaskConfigs(cp)
|
||||
}
|
||||
|
||||
// SaveTaskDetail saves detailed task information to disk
|
||||
|
||||
@@ -53,8 +53,11 @@ type FileBrowserData struct {
|
||||
CurrentLastFileName string `json:"current_last_file_name"` // Cursor from current request (for page size changes)
|
||||
}
|
||||
|
||||
// GetFileBrowser retrieves file browser data for a given path with cursor-based pagination
|
||||
func (s *AdminServer) GetFileBrowser(dir string, lastFileName string, pageSize int) (*FileBrowserData, error) {
|
||||
// GetFileBrowser retrieves file browser data for a given path with cursor-based
|
||||
// pagination. A non-empty prefix limits the listing to entries whose name starts
|
||||
// with it, so callers that only want part of a large directory don't have to page
|
||||
// through all of it.
|
||||
func (s *AdminServer) GetFileBrowser(dir string, prefix string, lastFileName string, pageSize int) (*FileBrowserData, error) {
|
||||
if dir == "" {
|
||||
dir = "/"
|
||||
}
|
||||
@@ -76,7 +79,7 @@ func (s *AdminServer) GetFileBrowser(dir string, lastFileName string, pageSize i
|
||||
// Fetch entries starting from the cursor (lastFileName)
|
||||
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
|
||||
Directory: dir,
|
||||
Prefix: "",
|
||||
Prefix: prefix,
|
||||
Limit: uint32(fetchLimit),
|
||||
StartFromFileName: lastFileName,
|
||||
InclusiveStartFrom: false, // Don't include the cursor file itself
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
)
|
||||
|
||||
// TestLoadMaintenanceConfigHonoursPersistedTaskConfigs guards against a regression: buildPolicyFromTaskConfigs used to call
|
||||
// LoadConfigFromPersistence(nil), which can never satisfy the loaders' type assertion, so every
|
||||
// task silently fell back to its compiled-in defaults (Enabled: true) and a task disabled in the
|
||||
// admin UI kept being scheduled.
|
||||
func TestLoadMaintenanceConfigHonoursPersistedTaskConfigs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
// A maintenance.pb must exist, otherwise LoadMaintenanceConfig returns early with defaults.
|
||||
if err := cp.SaveMaintenanceConfig(DefaultMaintenanceConfig()); err != nil {
|
||||
t.Fatalf("save maintenance config: %v", err)
|
||||
}
|
||||
|
||||
// Disable balance and vacuum the way the admin UI does, and change a value that is not a bool
|
||||
// so a fallback to defaults cannot pass by coincidence.
|
||||
disabledBalance := balance.NewDefaultConfig()
|
||||
disabledBalance.Enabled = false
|
||||
disabledBalance.MinServerCount = 7
|
||||
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save balance policy: %v", err)
|
||||
}
|
||||
|
||||
disabledVacuum := vacuum.NewDefaultConfig()
|
||||
disabledVacuum.Enabled = false
|
||||
if err := cp.SaveVacuumTaskPolicy(disabledVacuum.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save vacuum policy: %v", err)
|
||||
}
|
||||
|
||||
config, err := cp.LoadMaintenanceConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("load maintenance config: %v", err)
|
||||
}
|
||||
if config.Policy == nil {
|
||||
t.Fatal("policy is nil, want it populated from the persisted task configs")
|
||||
}
|
||||
|
||||
balancePolicy := config.Policy.TaskPolicies["balance"]
|
||||
if balancePolicy == nil {
|
||||
t.Fatal("no balance task policy in the built maintenance policy")
|
||||
}
|
||||
if balancePolicy.Enabled {
|
||||
t.Error("balance enabled = true, want false from the persisted config")
|
||||
}
|
||||
if got := balancePolicy.GetBalanceConfig().GetMinServerCount(); got != 7 {
|
||||
t.Errorf("balance min server count = %d, want persisted 7", got)
|
||||
}
|
||||
|
||||
vacuumPolicy := config.Policy.TaskPolicies["vacuum"]
|
||||
if vacuumPolicy == nil {
|
||||
t.Fatal("no vacuum task policy in the built maintenance policy")
|
||||
}
|
||||
if vacuumPolicy.Enabled {
|
||||
t.Error("vacuum enabled = true, want false from the persisted config")
|
||||
}
|
||||
|
||||
// erasure_coding was never saved, so it keeps the loader's default of enabled.
|
||||
ecPolicy := config.Policy.TaskPolicies["erasure_coding"]
|
||||
if ecPolicy == nil {
|
||||
t.Fatal("no erasure_coding task policy in the built maintenance policy")
|
||||
}
|
||||
if !ecPolicy.Enabled {
|
||||
t.Error("erasure_coding enabled = false, want the default true for a config never saved")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/maintenance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/types"
|
||||
)
|
||||
|
||||
// The task definitions these tests configure are process-global, so put them back the way a
|
||||
// fresh process would have them. Passing no config store makes every task fall back to its
|
||||
// own NewDefaultConfig, which is exactly the state package init left them in.
|
||||
func restoreGlobalTaskState(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
t.Cleanup(func() {
|
||||
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(nil)
|
||||
})
|
||||
}
|
||||
|
||||
// TestDisabledTaskIsNotScannedAfterStartup walks the admin server's startup sequence over a
|
||||
// data directory that has a disabled balance task saved in it, and checks the end state that
|
||||
// actually matters: the balance detector reports disabled, so ScanWithTaskDetectors skips it.
|
||||
//
|
||||
// This is the whole reported bug in one test. The reporter disabled balance, and the
|
||||
// scanner kept detecting balance tasks, cancelling them and re-detecting them. Two separate
|
||||
// defects had to line up for the disabled flag to survive to here: the policy had to be built
|
||||
// from the persisted configs rather than from a nil store, and the policy had to reach
|
||||
// detector.IsEnabled() rather than dying in a failed type assertion.
|
||||
func TestDisabledTaskIsNotScannedAfterStartup(t *testing.T) {
|
||||
restoreGlobalTaskState(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
// What the admin writes when a user turns balance off, and leaves vacuum on.
|
||||
disabledBalance := balance.NewDefaultConfig()
|
||||
disabledBalance.Enabled = false
|
||||
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save balance policy: %v", err)
|
||||
}
|
||||
|
||||
enabledVacuum := vacuum.NewDefaultConfig()
|
||||
enabledVacuum.Enabled = true
|
||||
if err := cp.SaveVacuumTaskPolicy(enabledVacuum.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save vacuum policy: %v", err)
|
||||
}
|
||||
|
||||
// The admin server's startup sequence, in order:
|
||||
// loadTaskConfigurationsFromPersistence, then InitMaintenanceManager.
|
||||
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(cp)
|
||||
|
||||
maintenanceConfig, err := cp.LoadMaintenanceConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("load maintenance config: %v", err)
|
||||
}
|
||||
manager := maintenance.NewMaintenanceManager(nil, maintenanceConfig, cp)
|
||||
if manager == nil {
|
||||
t.Fatal("NewMaintenanceManager returned nil")
|
||||
}
|
||||
|
||||
registry := tasks.GetGlobalTypesRegistry()
|
||||
|
||||
balanceDetector := registry.GetDetector(types.TaskTypeBalance)
|
||||
if balanceDetector == nil {
|
||||
t.Fatal("no balance detector registered")
|
||||
}
|
||||
if balanceDetector.IsEnabled() {
|
||||
t.Error("balance detector reports enabled after startup over a data directory where " +
|
||||
"balance is saved as disabled; the scanner will keep detecting and cancelling balance tasks")
|
||||
}
|
||||
|
||||
vacuumDetector := registry.GetDetector(types.TaskTypeVacuum)
|
||||
if vacuumDetector == nil {
|
||||
t.Fatal("no vacuum detector registered")
|
||||
}
|
||||
if !vacuumDetector.IsEnabled() {
|
||||
t.Error("vacuum detector reports disabled although vacuum is saved as enabled; " +
|
||||
"the fix must not switch off tasks the user left on")
|
||||
}
|
||||
|
||||
// Tasks the user never touched keep their compiled-in default of enabled rather than
|
||||
// being switched off by a policy entry built from a config that was never saved.
|
||||
for _, taskType := range []types.TaskType{types.TaskTypeErasureCoding, types.TaskTypeECBalance} {
|
||||
detector := registry.GetDetector(taskType)
|
||||
if detector == nil {
|
||||
t.Fatalf("no %s detector registered", taskType)
|
||||
}
|
||||
if !detector.IsEnabled() {
|
||||
t.Errorf("%s detector reports disabled although its config was never saved", taskType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPolicyMirrorsWhatTheDetectorsReport checks that the maintenance policy the queue and
|
||||
// the scanner run on agrees with the detectors. A disagreement means one of the two paths
|
||||
// into the task configs has gone stale again.
|
||||
func TestPolicyMirrorsWhatTheDetectorsReport(t *testing.T) {
|
||||
restoreGlobalTaskState(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
|
||||
disabledBalance := balance.NewDefaultConfig()
|
||||
disabledBalance.Enabled = false
|
||||
if err := cp.SaveBalanceTaskPolicy(disabledBalance.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save balance policy: %v", err)
|
||||
}
|
||||
|
||||
tasks.GetGlobalConfigUpdateRegistry().UpdateAllConfigs(cp)
|
||||
policy := cp.buildPolicyFromTaskConfigs()
|
||||
|
||||
for taskType, detector := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
|
||||
policyEnabled := maintenance.IsTaskEnabled(policy, maintenance.MaintenanceTaskType(taskType))
|
||||
if policyEnabled != detector.IsEnabled() {
|
||||
t.Errorf("%s: policy says enabled=%v but the detector says enabled=%v",
|
||||
taskType, policyEnabled, detector.IsEnabled())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
weediam "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// principalRoleArn builds the ARN SeaweedFS assigns a role by default (when
|
||||
// its RoleDefinition.RoleArn isn't explicitly set) - see
|
||||
// weed/iam/integration/iam_manager.go's CreateRole. ListRoles only returns
|
||||
// role names, so this reconstructs the well-known default rather than
|
||||
// fetching every role's stored definition just to populate a suggestion list.
|
||||
func principalRoleArn(roleName string) string {
|
||||
return "arn:aws:iam::role/" + roleName
|
||||
}
|
||||
|
||||
// GetPrincipalSuggestions returns candidate ARNs for the policy editor's
|
||||
// Principal/NotPrincipal autocomplete: one per S3 user, plus one per IAM
|
||||
// role. Service accounts are deliberately not listed separately - a service
|
||||
// account is just an additional credential for its parent user, so its ARN
|
||||
// is identical to the one already suggested for that user.
|
||||
//
|
||||
// Role listing is best-effort: if the filer or role store is unavailable,
|
||||
// the error is logged and suggestions fall back to users only, since an
|
||||
// incomplete autocomplete list is far less disruptive than blocking policy
|
||||
// editing over a suggestions-only feature.
|
||||
func (s *AdminServer) GetPrincipalSuggestions(ctx context.Context) ([]string, error) {
|
||||
var suggestions []string
|
||||
|
||||
users, err := s.GetObjectStoreUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, u := range users {
|
||||
suggestions = append(suggestions, weediam.UserArn(u.Username))
|
||||
}
|
||||
|
||||
roleStore, err := integration.NewFilerRoleStore(nil, func() string { return s.GetFilerAddress() })
|
||||
if err != nil {
|
||||
glog.Warningf("GetPrincipalSuggestions: failed to create role store: %v", err)
|
||||
return suggestions, nil
|
||||
}
|
||||
roleNames, err := roleStore.ListRoles(ctx, s.GetFilerAddress())
|
||||
if err != nil {
|
||||
glog.Warningf("GetPrincipalSuggestions: failed to list roles: %v", err)
|
||||
return suggestions, nil
|
||||
}
|
||||
for _, roleName := range roleNames {
|
||||
suggestions = append(suggestions, principalRoleArn(roleName))
|
||||
}
|
||||
|
||||
return suggestions, nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dash
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPrincipalRoleArn(t *testing.T) {
|
||||
got := principalRoleArn("S3ReadOnlyRole")
|
||||
want := "arn:aws:iam::role/S3ReadOnlyRole"
|
||||
if got != want {
|
||||
t.Fatalf("principalRoleArn() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// TestLoadTaskPolicyDefaultsMatchTaskDefaults pins the persistence layer's "nothing saved
|
||||
// yet" defaults to each task's own NewDefaultConfig(). They used to be a second, hand-written
|
||||
// copy and had drifted: with a data directory but no config file on disk, vacuum ran on a 24h
|
||||
// scan interval instead of 2h, balance on 6h with a 0.1 imbalance threshold instead of 30m
|
||||
// with 0.2, and erasure coding on 168h with a 0.90 fullness ratio and a 1024MB minimum volume
|
||||
// size instead of 1h with 0.95 and 30MB - none of which is what the admin UI shows as the
|
||||
// default for those fields.
|
||||
func TestLoadTaskPolicyDefaultsMatchTaskDefaults(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
want *worker_pb.TaskPolicy
|
||||
load func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error)
|
||||
}{
|
||||
{
|
||||
name: "vacuum",
|
||||
want: vacuum.NewDefaultConfig().ToTaskPolicy(),
|
||||
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadVacuumTaskPolicy() },
|
||||
},
|
||||
{
|
||||
name: "erasure_coding",
|
||||
want: erasure_coding.NewDefaultConfig().ToTaskPolicy(),
|
||||
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) {
|
||||
return cp.LoadErasureCodingTaskPolicy()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "balance",
|
||||
want: balance.NewDefaultConfig().ToTaskPolicy(),
|
||||
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadBalanceTaskPolicy() },
|
||||
},
|
||||
{
|
||||
name: "ec_balance",
|
||||
want: ec_balance.NewDefaultConfig().ToTaskPolicy(),
|
||||
load: func(cp *ConfigPersistence) (*worker_pb.TaskPolicy, error) { return cp.LoadEcBalanceTaskPolicy() },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Both no-file branches have to agree with the task's own defaults: no data
|
||||
// directory at all, and a data directory that has never been written to.
|
||||
for _, cp := range []*ConfigPersistence{NewConfigPersistence(""), NewConfigPersistence(t.TempDir())} {
|
||||
got, err := tc.load(cp)
|
||||
if err != nil {
|
||||
t.Fatalf("load %s policy: %v", tc.name, err)
|
||||
}
|
||||
if !proto.Equal(got, tc.want) {
|
||||
t.Errorf("%s default policy (dataDir=%q) =\n %v\nwant NewDefaultConfig().ToTaskPolicy() =\n %v",
|
||||
tc.name, cp.GetDataDir(), got, tc.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadTaskConfigDefaultsMatchTaskDefaults covers the narrower Load*TaskConfig accessors,
|
||||
// which carried a third copy of the same defaults.
|
||||
func TestLoadTaskConfigDefaultsMatchTaskDefaults(t *testing.T) {
|
||||
cp := NewConfigPersistence(t.TempDir())
|
||||
|
||||
vacuumConfig, err := cp.LoadVacuumTaskConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("load vacuum config: %v", err)
|
||||
}
|
||||
if want := vacuum.NewDefaultConfig().ToTaskPolicy().GetVacuumConfig(); !proto.Equal(vacuumConfig, want) {
|
||||
t.Errorf("vacuum default config = %v, want %v", vacuumConfig, want)
|
||||
}
|
||||
|
||||
ecConfig, err := cp.LoadErasureCodingTaskConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("load erasure coding config: %v", err)
|
||||
}
|
||||
if want := erasure_coding.NewDefaultConfig().ToTaskPolicy().GetErasureCodingConfig(); !proto.Equal(ecConfig, want) {
|
||||
t.Errorf("erasure coding default config = %v, want %v", ecConfig, want)
|
||||
}
|
||||
|
||||
balanceConfig, err := cp.LoadBalanceTaskConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("load balance config: %v", err)
|
||||
}
|
||||
if want := balance.NewDefaultConfig().ToTaskPolicy().GetBalanceConfig(); !proto.Equal(balanceConfig, want) {
|
||||
t.Errorf("balance default config = %v, want %v", balanceConfig, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEcBalanceTaskPolicyRoundTrip checks the accessor ec_balance.LoadConfigFromPersistence
|
||||
// asserts on. Before it existed, ec_balance was the one registered maintenance task whose
|
||||
// configuration could not be persisted at all.
|
||||
func TestEcBalanceTaskPolicyRoundTrip(t *testing.T) {
|
||||
cp := NewConfigPersistence(t.TempDir())
|
||||
|
||||
saved := ec_balance.NewDefaultConfig()
|
||||
saved.Enabled = false
|
||||
saved.MinServerCount = 9
|
||||
saved.ImbalanceThreshold = 0.42
|
||||
saved.CollectionFilter = "pictures"
|
||||
|
||||
if err := cp.SaveEcBalanceTaskPolicy(saved.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save ec_balance policy: %v", err)
|
||||
}
|
||||
|
||||
loaded := ec_balance.LoadConfigFromPersistence(cp)
|
||||
if loaded == nil {
|
||||
t.Fatal("ec_balance.LoadConfigFromPersistence returned nil")
|
||||
}
|
||||
if loaded.Enabled {
|
||||
t.Error("ec_balance enabled = true, want the persisted false")
|
||||
}
|
||||
if loaded.MinServerCount != 9 {
|
||||
t.Errorf("ec_balance min server count = %d, want the persisted 9", loaded.MinServerCount)
|
||||
}
|
||||
if loaded.ImbalanceThreshold != 0.42 {
|
||||
t.Errorf("ec_balance imbalance threshold = %v, want the persisted 0.42", loaded.ImbalanceThreshold)
|
||||
}
|
||||
if loaded.CollectionFilter != "pictures" {
|
||||
t.Errorf("ec_balance collection filter = %q, want the persisted %q", loaded.CollectionFilter, "pictures")
|
||||
}
|
||||
|
||||
// The generic dispatcher the maintenance manager uses has to know the type too, and
|
||||
// has to write the same file the dedicated loader reads.
|
||||
dispatched := NewConfigPersistence(t.TempDir())
|
||||
if err := dispatched.SaveTaskPolicy("ec_balance", saved.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("SaveTaskPolicy(ec_balance): %v", err)
|
||||
}
|
||||
roundTripped := ec_balance.LoadConfigFromPersistence(dispatched)
|
||||
if roundTripped == nil || roundTripped.MinServerCount != 9 {
|
||||
t.Errorf("SaveTaskPolicy(ec_balance) did not round-trip through the ec_balance store: %+v", roundTripped)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildPolicyKeepsTaskSpecificFields guards the fields the hand-written policy builder
|
||||
// used to drop on the floor: the erasure coding preferred tags and replica placement, and
|
||||
// the balance IO rate limit. Building each entry from the task's own ToTaskPolicy() keeps
|
||||
// them, so a value set in admin.toml survives into the maintenance policy.
|
||||
func TestBuildPolicyKeepsTaskSpecificFields(t *testing.T) {
|
||||
cp := NewConfigPersistence(t.TempDir())
|
||||
|
||||
ecConfig := erasure_coding.NewDefaultConfig()
|
||||
ecConfig.PreferredTags = []string{"ssd", "archive"}
|
||||
ecConfig.ReplicaPlacement = "020"
|
||||
if err := cp.SaveErasureCodingTaskPolicy(ecConfig.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save erasure coding policy: %v", err)
|
||||
}
|
||||
|
||||
balanceConfig := balance.NewDefaultConfig()
|
||||
balanceConfig.IoBytePerSecond = 5 << 20
|
||||
if err := cp.SaveBalanceTaskPolicy(balanceConfig.ToTaskPolicy()); err != nil {
|
||||
t.Fatalf("save balance policy: %v", err)
|
||||
}
|
||||
|
||||
policy := cp.buildPolicyFromTaskConfigs()
|
||||
|
||||
ecPolicy := policy.TaskPolicies["erasure_coding"].GetErasureCodingConfig()
|
||||
if ecPolicy == nil {
|
||||
t.Fatal("no erasure coding config in the built policy")
|
||||
}
|
||||
if got := ecPolicy.GetReplicaPlacement(); got != "020" {
|
||||
t.Errorf("erasure coding replica placement = %q, want the persisted %q", got, "020")
|
||||
}
|
||||
if got := ecPolicy.GetPreferredTags(); len(got) != 2 || got[0] != "ssd" || got[1] != "archive" {
|
||||
t.Errorf("erasure coding preferred tags = %v, want the persisted [ssd archive]", got)
|
||||
}
|
||||
|
||||
balancePolicy := policy.TaskPolicies["balance"].GetBalanceConfig()
|
||||
if balancePolicy == nil {
|
||||
t.Fatal("no balance config in the built policy")
|
||||
}
|
||||
if got := balancePolicy.GetIoBytePerSecond(); got != 5<<20 {
|
||||
t.Errorf("balance IO limit = %d, want the persisted %d", got, 5<<20)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -222,6 +224,10 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
|
||||
policyApi.Handle("/{name}", wrapWrite(h.policyHandlers.DeletePolicy)).Methods(http.MethodDelete)
|
||||
policyApi.HandleFunc("/validate", h.policyHandlers.ValidatePolicy).Methods(http.MethodPost)
|
||||
|
||||
// Registered at the API root, not under policyApi: policyApi's "/{name}"
|
||||
// GET route would shadow any single-segment GET route registered after it.
|
||||
api.HandleFunc("/principals", h.policyHandlers.GetPrincipalSuggestions).Methods(http.MethodGet)
|
||||
|
||||
s3TablesApi := api.PathPrefix("/s3tables").Subrouter()
|
||||
s3TablesApi.HandleFunc("/buckets", h.adminServer.ListS3TablesBucketsAPI).Methods(http.MethodGet)
|
||||
s3TablesApi.Handle("/buckets", wrapWrite(h.adminServer.CreateS3TablesBucket)).Methods(http.MethodPost)
|
||||
@@ -251,6 +257,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
|
||||
filesApi.HandleFunc("/view", h.fileBrowserHandlers.ViewFile).Methods(http.MethodGet)
|
||||
filesApi.HandleFunc("/properties", h.fileBrowserHandlers.GetFileProperties).Methods(http.MethodGet)
|
||||
filesApi.HandleFunc("/metadata", h.fileBrowserHandlers.ExportMetadata).Methods(http.MethodGet)
|
||||
filesApi.HandleFunc("/list-folders", h.fileBrowserHandlers.ListFolders).Methods(http.MethodGet)
|
||||
|
||||
volumeApi := api.PathPrefix("/volumes").Subrouter()
|
||||
volumeApi.HandleFunc("/export", h.clusterHandlers.ExportClusterVolumes).Methods(http.MethodGet)
|
||||
|
||||
@@ -42,6 +42,68 @@ func TestSetupRoutes_RegistersPluginSchedulerStatesAPI_WithAuth(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersBucketLifecycleAPI_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/s3/buckets/example/lifecycle")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersPolicyAPI_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")
|
||||
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersPolicyAPI_WithAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, true, "admin", "password", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies")
|
||||
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies")
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodPut, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodDelete, "/api/object-store/policies/example")
|
||||
assertHasRoute(t, router, http.MethodPost, "/api/object-store/policies/validate")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersPrincipalsAPI_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/principals")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersFilesListFoldersAPI_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
newRouteTestAdminHandlers().SetupRoutes(router, false, "", "", "", "", true)
|
||||
|
||||
assertHasRoute(t, router, http.MethodGet, "/api/files/list-folders")
|
||||
}
|
||||
|
||||
func TestSetupRoutes_RegistersPluginPages_NoAuth(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
// Get file browser data with cursor-based pagination
|
||||
browserData, err := h.adminServer.GetFileBrowser(path, lastFileName, pageSize)
|
||||
browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())
|
||||
return
|
||||
@@ -778,3 +778,63 @@ func min(a, b int64) int64 {
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// maxListFoldersEntries caps how many subfolder names ListFolders will
|
||||
// collect for a single request, so a directory with an unusually large
|
||||
// number of children can't turn one autocomplete keystroke into an
|
||||
// unbounded, slow full-directory walk.
|
||||
const maxListFoldersEntries = 2000
|
||||
|
||||
// maxListFoldersScanned caps how many entries ListFolders will page through
|
||||
// looking for those subfolders. The folder cap alone doesn't bound the work:
|
||||
// a bucket holding nothing but flat object keys has no subfolders to count,
|
||||
// so the walk runs to the end of the directory - a million keys is a million
|
||||
// entries read, 200 per round trip, behind a single keystroke.
|
||||
const maxListFoldersScanned = 10000
|
||||
|
||||
// ListFolders returns, as JSON, the names of the subdirectories directly
|
||||
// under the given path. It exists to back progressive autocomplete (e.g. the
|
||||
// policy editor's Resource ARN field building up "bucket/folder/subfolder"
|
||||
// one path segment at a time) rather than to be a general directory listing
|
||||
// API, so it's restricted to paths under /buckets. The optional prefix is the
|
||||
// segment the caller is still typing, and narrows the listing to it.
|
||||
func (h *FileBrowserHandlers) ListFolders(w http.ResponseWriter, r *http.Request) {
|
||||
dirPath := defaultQuery(r.URL.Query().Get("path"), "/buckets")
|
||||
// Clean before the scope check: CleanWindowsPath only rewrites backslashes,
|
||||
// so "/buckets/../etc" would otherwise satisfy the prefix test below.
|
||||
dirPath = path.Clean(util.CleanWindowsPath(dirPath))
|
||||
|
||||
if dirPath != "/buckets" && !strings.HasPrefix(dirPath, "/buckets/") {
|
||||
writeJSONError(w, http.StatusBadRequest, "path must be under /buckets")
|
||||
return
|
||||
}
|
||||
|
||||
prefix := r.URL.Query().Get("prefix")
|
||||
|
||||
folders := []string{}
|
||||
lastFileName := ""
|
||||
scanned := 0
|
||||
for {
|
||||
browserData, err := h.adminServer.GetFileBrowser(dirPath, prefix, lastFileName, 200)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to list directory: "+err.Error())
|
||||
return
|
||||
}
|
||||
scanned += len(browserData.Entries)
|
||||
for _, entry := range browserData.Entries {
|
||||
if entry.IsDirectory {
|
||||
folders = append(folders, entry.Name)
|
||||
if len(folders) >= maxListFoldersEntries {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(browserData.Entries) == 0 || !browserData.HasNextPage ||
|
||||
len(folders) >= maxListFoldersEntries || scanned >= maxListFoldersScanned {
|
||||
break
|
||||
}
|
||||
lastFileName = browserData.Entries[len(browserData.Entries)-1].Name
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{"folders": folders})
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
)
|
||||
|
||||
func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
|
||||
@@ -42,3 +46,20 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
|
||||
h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}
|
||||
|
||||
cases := []string{"/etc/seaweedfs", "/", "/notbuckets/foo", "/buckets-not-really/foo",
|
||||
"/buckets/../etc", "/buckets/..", "/buckets/foo/../../etc", `/buckets\..\etc`}
|
||||
for _, path := range cases {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/list-folders?path="+path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ListFolders(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("path %q: expected 400, got %d (body: %s)", path, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,17 @@ func (h *PolicyHandlers) GetPolicies(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{"policies": policies})
|
||||
}
|
||||
|
||||
// GetPrincipalSuggestions returns candidate ARNs (existing users and IAM
|
||||
// roles) for the policy editor's Principal/NotPrincipal autocomplete.
|
||||
func (h *PolicyHandlers) GetPrincipalSuggestions(w http.ResponseWriter, r *http.Request) {
|
||||
suggestions, err := h.adminServer.GetPrincipalSuggestions(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get principal suggestions: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{"principals": suggestions})
|
||||
}
|
||||
|
||||
// CreatePolicy handles policy creation
|
||||
func (h *PolicyHandlers) CreatePolicy(w http.ResponseWriter, r *http.Request) {
|
||||
var req dash.CreatePolicyRequest
|
||||
@@ -221,8 +232,18 @@ func (h *PolicyHandlers) ValidatePolicy(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
if len(statement.Resource.Strings()) == 0 {
|
||||
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource is required", i+1))
|
||||
if len(statement.Resource.Strings()) == 0 && len(statement.NotResource.Strings()) == 0 {
|
||||
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: Resource or NotResource is required", i+1))
|
||||
return
|
||||
}
|
||||
|
||||
if statement.Resource != nil && statement.NotResource != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Resource and NotResource", i+1))
|
||||
return
|
||||
}
|
||||
|
||||
if statement.Principal != nil && statement.NotPrincipal != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("Statement %d: cannot specify both Principal and NotPrincipal", i+1))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
)
|
||||
|
||||
func newValidatePolicyRequest(t *testing.T, document map[string]interface{}) *http.Request {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]interface{}{"document": document})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal request body: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/object-store/policies/validate", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return req
|
||||
}
|
||||
|
||||
func TestValidatePolicy(t *testing.T) {
|
||||
handlers := &PolicyHandlers{adminServer: &dash.AdminServer{}}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
document map[string]interface{}
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "valid document with Resource",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "valid document with NotResource only",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "NotResource": "arn:aws:s3:::secret-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "missing version",
|
||||
document: map[string]interface{}{
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "no statements",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "invalid effect",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Maybe", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "missing action",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Resource": "arn:aws:s3:::my-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "neither Resource nor NotResource",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "both Resource and NotResource",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "NotResource": "arn:aws:s3:::secret-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "empty Resource alongside non-empty NotResource is still a conflict",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": []string{}, "NotResource": "arn:aws:s3:::secret-bucket/*"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "both Principal and NotPrincipal",
|
||||
document: map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Principal": "*", "NotPrincipal": "arn:aws:iam::123456789012:user/bob"},
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := newValidatePolicyRequest(t, tt.document)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handlers.ValidatePolicy(w, req)
|
||||
|
||||
if w.Code != tt.wantStatus {
|
||||
t.Fatalf("expected status %d, got %d (body: %s)", tt.wantStatus, w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity check that policy_engine.PolicyStatement (the type ValidatePolicy
|
||||
// actually decodes into) round-trips NotResource-only statements the way the
|
||||
// test above assumes.
|
||||
func TestValidatePolicy_NotResourceOnlyDecodes(t *testing.T) {
|
||||
raw := []byte(`{"Effect":"Allow","Action":"s3:GetObject","NotResource":"arn:aws:s3:::secret/*"}`)
|
||||
var stmt policy_engine.PolicyStatement
|
||||
if err := json.Unmarshal(raw, &stmt); err != nil {
|
||||
t.Fatalf("failed to unmarshal statement: %v", err)
|
||||
}
|
||||
if len(stmt.Resource.Strings()) != 0 {
|
||||
t.Fatalf("expected no Resource, got %v", stmt.Resource.Strings())
|
||||
}
|
||||
if len(stmt.NotResource.Strings()) != 1 {
|
||||
t.Fatalf("expected exactly one NotResource entry, got %v", stmt.NotResource.Strings())
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,22 @@ func (s *MaintenanceIntegration) registerAllTasks() {
|
||||
glog.V(1).Infof("Registered tasks: %v", registeredTaskTypes)
|
||||
}
|
||||
|
||||
// SetPolicy replaces the maintenance policy the integration configures tasks from and
|
||||
// applies it immediately. Without this the integration kept the policy it was built with,
|
||||
// so a policy updated at runtime reached the queue but never the detectors that decide
|
||||
// which task types are scanned for.
|
||||
//
|
||||
// Not safe to call concurrently with a running scan. ConfigureTasksFromPolicy writes
|
||||
// TaskDefinition.Config and TaskDefinition.MaxConcurrent, which ScanWithTaskDetectors reads
|
||||
// through detector.IsEnabled(); nothing synchronises the two. Today every caller runs during
|
||||
// admin server startup, before the scan loop exists. Anything that wires this to an HTTP
|
||||
// handler has to add that synchronisation first - the same applies to
|
||||
// tasks.ConfigUpdateRegistry.UpdateAllConfigs, which replaces TaskDefinition.Config outright.
|
||||
func (s *MaintenanceIntegration) SetPolicy(policy *MaintenancePolicy) {
|
||||
s.maintenancePolicy = policy
|
||||
s.ConfigureTasksFromPolicy()
|
||||
}
|
||||
|
||||
// ConfigureTasksFromPolicy dynamically configures all registered tasks based on the maintenance policy
|
||||
func (s *MaintenanceIntegration) ConfigureTasksFromPolicy() {
|
||||
if s.maintenancePolicy == nil {
|
||||
@@ -155,20 +171,32 @@ func (s *MaintenanceIntegration) configureDetectorFromPolicy(taskType types.Task
|
||||
return
|
||||
}
|
||||
|
||||
// Apply basic configuration that all detectors should support
|
||||
if basicDetector, ok := detector.(interface{ SetEnabled(bool) }); ok {
|
||||
// Convert task system type to maintenance task type for policy lookup
|
||||
maintenanceTaskType, exists := s.taskTypeMap[taskType]
|
||||
if exists {
|
||||
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
|
||||
basicDetector.SetEnabled(enabled)
|
||||
glog.V(3).Infof("Set enabled=%v for detector %s", enabled, taskType)
|
||||
}
|
||||
// Convert task system type to maintenance task type for policy lookup
|
||||
maintenanceTaskType, exists := s.taskTypeMap[taskType]
|
||||
if !exists {
|
||||
glog.V(3).Infof("No maintenance task type mapping for %s, skipping configuration", taskType)
|
||||
return
|
||||
}
|
||||
|
||||
// For detectors that don't implement PolicyConfigurableDetector interface,
|
||||
// they should be updated to implement it for full policy-based configuration
|
||||
glog.V(2).Infof("Detector %s should implement PolicyConfigurableDetector interface for full policy support", taskType)
|
||||
// A task type the policy says nothing about is left alone. IsTaskEnabled reports
|
||||
// false for a missing entry, so applying it unconditionally would silently disable
|
||||
// every task the policy does not list - which is how ec_balance would have been
|
||||
// switched off the moment SetEnabled started working.
|
||||
if GetTaskPolicy(s.maintenancePolicy, maintenanceTaskType) == nil {
|
||||
glog.V(2).Infof("Maintenance policy has no entry for %s, leaving its detector configuration untouched", taskType)
|
||||
return
|
||||
}
|
||||
|
||||
// Apply basic configuration that all detectors should support
|
||||
if basicDetector, ok := detector.(interface{ SetEnabled(bool) }); ok {
|
||||
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
|
||||
basicDetector.SetEnabled(enabled)
|
||||
glog.V(3).Infof("Set enabled=%v for detector %s", enabled, taskType)
|
||||
} else {
|
||||
// For detectors that don't implement PolicyConfigurableDetector interface,
|
||||
// they should be updated to implement it for full policy-based configuration
|
||||
glog.V(2).Infof("Detector %s supports neither PolicyConfigurableDetector nor SetEnabled, its policy is ignored", taskType)
|
||||
}
|
||||
}
|
||||
|
||||
// configureSchedulerFromPolicy configures a scheduler using policy-based configuration
|
||||
@@ -187,11 +215,21 @@ func (s *MaintenanceIntegration) configureSchedulerFromPolicy(taskType types.Tas
|
||||
return
|
||||
}
|
||||
|
||||
// Same guard as on the detector side: no policy entry means no opinion, not disabled.
|
||||
if GetTaskPolicy(s.maintenancePolicy, maintenanceTaskType) == nil {
|
||||
glog.V(2).Infof("Maintenance policy has no entry for %s, leaving its scheduler configuration untouched", taskType)
|
||||
return
|
||||
}
|
||||
|
||||
// Set enabled status if scheduler supports it
|
||||
if enableableScheduler, ok := scheduler.(interface{ SetEnabled(bool) }); ok {
|
||||
enabled := IsTaskEnabled(s.maintenancePolicy, maintenanceTaskType)
|
||||
enableableScheduler.SetEnabled(enabled)
|
||||
glog.V(3).Infof("Set enabled=%v for scheduler %s", enabled, taskType)
|
||||
} else {
|
||||
// For schedulers that don't implement PolicyConfigurableScheduler interface,
|
||||
// they should be updated to implement it for full policy-based configuration
|
||||
glog.V(2).Infof("Scheduler %s supports neither PolicyConfigurableScheduler nor SetEnabled, its policy is ignored", taskType)
|
||||
}
|
||||
|
||||
// Set max concurrent if scheduler supports it
|
||||
@@ -202,10 +240,6 @@ func (s *MaintenanceIntegration) configureSchedulerFromPolicy(taskType types.Tas
|
||||
glog.V(3).Infof("Set max concurrent=%d for scheduler %s", maxConcurrent, taskType)
|
||||
}
|
||||
}
|
||||
|
||||
// For schedulers that don't implement PolicyConfigurableScheduler interface,
|
||||
// they should be updated to implement it for full policy-based configuration
|
||||
glog.V(2).Infof("Scheduler %s should implement PolicyConfigurableScheduler interface for full policy support", taskType)
|
||||
}
|
||||
|
||||
// ScanWithTaskDetectors performs a scan using the task system
|
||||
|
||||
@@ -10,12 +10,29 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/types"
|
||||
)
|
||||
|
||||
// buildPolicyFromTaskConfigs loads task configurations from separate files and builds a MaintenancePolicy
|
||||
func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
// BuildPolicyFromTaskConfigs loads each registered task's configuration and builds the
|
||||
// MaintenancePolicy the maintenance system runs on.
|
||||
//
|
||||
// Every entry is produced by the task's own ToTaskPolicy(), so a policy entry always carries
|
||||
// exactly what that task's config holds. Hand-copying the fields here instead made this a
|
||||
// second, silently diverging definition of every task's policy: it dropped the erasure
|
||||
// coding preferred tags and replica placement and the balance IO rate limit outright.
|
||||
//
|
||||
// Every task registered through base.RegisterTask needs an entry, because a task type the
|
||||
// policy does not list has no enabled flag and no concurrency limit of its own -
|
||||
// IsTaskEnabled reports false for a missing entry.
|
||||
//
|
||||
// configPersistence is duck-typed as interface{} because weed/admin/dash already imports this
|
||||
// package, so importing *dash.ConfigPersistence back here would create an import cycle. It must be
|
||||
// a value implementing the LoadXTaskPolicy() accessors the task loaders assert on; passing nil (or
|
||||
// anything else) makes every task fall back to its compiled-in defaults.
|
||||
func BuildPolicyFromTaskConfigs(configPersistence interface{}) *worker_pb.MaintenancePolicy {
|
||||
policy := &worker_pb.MaintenancePolicy{
|
||||
GlobalMaxConcurrent: 4,
|
||||
DefaultRepeatIntervalSeconds: 6 * 3600, // 6 hours in seconds
|
||||
@@ -23,54 +40,20 @@ func buildPolicyFromTaskConfigs() *worker_pb.MaintenancePolicy {
|
||||
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
|
||||
}
|
||||
|
||||
// Load vacuum task configuration
|
||||
if vacuumConfig := vacuum.LoadConfigFromPersistence(nil); vacuumConfig != nil {
|
||||
policy.TaskPolicies["vacuum"] = &worker_pb.TaskPolicy{
|
||||
Enabled: vacuumConfig.Enabled,
|
||||
MaxConcurrent: int32(vacuumConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(vacuumConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{
|
||||
GarbageThreshold: float64(vacuumConfig.GarbageThreshold),
|
||||
MinVolumeAgeHours: int32((vacuumConfig.MinVolumeAgeSeconds + 3599) / 3600), // round up so sub-hour values don't become 0
|
||||
},
|
||||
},
|
||||
}
|
||||
if vacuumConfig := vacuum.LoadConfigFromPersistence(configPersistence); vacuumConfig != nil {
|
||||
policy.TaskPolicies[string(types.TaskTypeVacuum)] = vacuumConfig.ToTaskPolicy()
|
||||
}
|
||||
|
||||
// Load erasure coding task configuration
|
||||
if ecConfig := erasure_coding.LoadConfigFromPersistence(nil); ecConfig != nil {
|
||||
policy.TaskPolicies["erasure_coding"] = &worker_pb.TaskPolicy{
|
||||
Enabled: ecConfig.Enabled,
|
||||
MaxConcurrent: int32(ecConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(ecConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
|
||||
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{
|
||||
FullnessRatio: float64(ecConfig.FullnessRatio),
|
||||
QuietForSeconds: int32(ecConfig.QuietForSeconds),
|
||||
MinVolumeSizeMb: int32(ecConfig.MinSizeMB),
|
||||
CollectionFilter: ecConfig.CollectionFilter,
|
||||
},
|
||||
},
|
||||
}
|
||||
if ecConfig := erasure_coding.LoadConfigFromPersistence(configPersistence); ecConfig != nil {
|
||||
policy.TaskPolicies[string(types.TaskTypeErasureCoding)] = ecConfig.ToTaskPolicy()
|
||||
}
|
||||
|
||||
// Load balance task configuration
|
||||
if balanceConfig := balance.LoadConfigFromPersistence(nil); balanceConfig != nil {
|
||||
policy.TaskPolicies["balance"] = &worker_pb.TaskPolicy{
|
||||
Enabled: balanceConfig.Enabled,
|
||||
MaxConcurrent: int32(balanceConfig.MaxConcurrent),
|
||||
RepeatIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
|
||||
CheckIntervalSeconds: int32(balanceConfig.ScanIntervalSeconds),
|
||||
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
|
||||
BalanceConfig: &worker_pb.BalanceTaskConfig{
|
||||
ImbalanceThreshold: float64(balanceConfig.ImbalanceThreshold),
|
||||
MinServerCount: int32(balanceConfig.MinServerCount),
|
||||
},
|
||||
},
|
||||
}
|
||||
if balanceConfig := balance.LoadConfigFromPersistence(configPersistence); balanceConfig != nil {
|
||||
policy.TaskPolicies[string(types.TaskTypeBalance)] = balanceConfig.ToTaskPolicy()
|
||||
}
|
||||
|
||||
if ecBalanceConfig := ec_balance.LoadConfigFromPersistence(configPersistence); ecBalanceConfig != nil {
|
||||
policy.TaskPolicies[string(types.TaskTypeECBalance)] = ecBalanceConfig.ToTaskPolicy()
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Built maintenance policy from separate task configs - %d task policies loaded", len(policy.TaskPolicies))
|
||||
@@ -94,8 +77,12 @@ type MaintenanceManager struct {
|
||||
scanInProgress bool
|
||||
}
|
||||
|
||||
// NewMaintenanceManager creates a new maintenance manager
|
||||
func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig) *MaintenanceManager {
|
||||
// NewMaintenanceManager creates a new maintenance manager.
|
||||
//
|
||||
// configPersistence is the config store to read persisted task configs from when the policy has to
|
||||
// be built here. See BuildPolicyFromTaskConfigs for why it is duck-typed; pass nil when no config
|
||||
// store is available.
|
||||
func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig, configPersistence interface{}) *MaintenanceManager {
|
||||
if config == nil {
|
||||
config = DefaultMaintenanceConfig()
|
||||
}
|
||||
@@ -104,7 +91,7 @@ func NewMaintenanceManager(adminClient AdminClient, config *MaintenanceConfig) *
|
||||
policy := config.Policy
|
||||
if policy == nil {
|
||||
// Fallback: build policy from separate task configuration files if not already populated
|
||||
policy = buildPolicyFromTaskConfigs()
|
||||
policy = BuildPolicyFromTaskConfigs(configPersistence)
|
||||
}
|
||||
|
||||
queue := NewMaintenanceQueue(policy)
|
||||
@@ -132,7 +119,9 @@ func (mm *MaintenanceManager) Start() error {
|
||||
return fmt.Errorf("invalid maintenance configuration: %w", err)
|
||||
}
|
||||
|
||||
mm.mutex.Lock()
|
||||
mm.running = true
|
||||
mm.mutex.Unlock()
|
||||
|
||||
// Start background processes
|
||||
go mm.scanLoop()
|
||||
@@ -178,30 +167,53 @@ func (mm *MaintenanceManager) validateConfig() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsRunning returns whether the maintenance manager is currently running
|
||||
// IsRunning returns whether the maintenance manager is currently running.
|
||||
// running is guarded by mm.mutex because the background loops read it on every
|
||||
// iteration while Start and Stop are called from the admin server's goroutines.
|
||||
func (mm *MaintenanceManager) IsRunning() bool {
|
||||
mm.mutex.RLock()
|
||||
defer mm.mutex.RUnlock()
|
||||
return mm.running
|
||||
}
|
||||
|
||||
// Stop terminates the maintenance manager
|
||||
// Stop terminates the maintenance manager. It is a no-op when the manager is not
|
||||
// running, so a second call cannot close the already closed stop channel.
|
||||
func (mm *MaintenanceManager) Stop() {
|
||||
mm.mutex.Lock()
|
||||
if !mm.running {
|
||||
mm.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
mm.running = false
|
||||
close(mm.stopChan)
|
||||
mm.mutex.Unlock()
|
||||
|
||||
glog.Infof("Maintenance manager stopped")
|
||||
}
|
||||
|
||||
// scanLoop periodically scans for maintenance tasks with adaptive timing
|
||||
func (mm *MaintenanceManager) scanLoop() {
|
||||
scanInterval := time.Duration(mm.config.ScanIntervalSeconds) * time.Second
|
||||
ticker := time.NewTicker(scanInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for mm.running {
|
||||
// activeInterval is the interval the ticker is actually running at right now. It has
|
||||
// to be tracked separately from the configured scanInterval, because the error backoff
|
||||
// replaces the ticker with a much shorter one. Comparing the target against the
|
||||
// configured interval instead never restores the normal cadence: once the errors stop,
|
||||
// getScanInterval returns scanInterval again, the comparison comes out false, and the
|
||||
// ticker is left at the backoff delay. A single transient scan failure therefore pinned
|
||||
// the scanner to one scan per second forever.
|
||||
activeInterval := scanInterval
|
||||
ticker := time.NewTicker(activeInterval)
|
||||
// Wrapped in a closure so the replacement ticker is stopped, not the one that happened
|
||||
// to be current when the defer was registered.
|
||||
defer func() { ticker.Stop() }()
|
||||
|
||||
for mm.IsRunning() {
|
||||
select {
|
||||
case <-mm.stopChan:
|
||||
return
|
||||
case <-ticker.C:
|
||||
glog.V(1).Infof("Performing maintenance scan every %v", scanInterval)
|
||||
glog.V(1).Infof("Performing maintenance scan every %v", activeInterval)
|
||||
|
||||
// Use the same synchronization as TriggerScan to prevent concurrent scans
|
||||
if err := mm.triggerScanInternal(false); err != nil {
|
||||
@@ -211,10 +223,13 @@ func (mm *MaintenanceManager) scanLoop() {
|
||||
// Adjust ticker interval based on error state (read error state safely)
|
||||
currentInterval := mm.getScanInterval(scanInterval)
|
||||
|
||||
// Reset ticker with new interval if needed
|
||||
if currentInterval != scanInterval {
|
||||
// Reset ticker whenever the target differs from what the ticker is running at,
|
||||
// which covers both entering the backoff and returning to the normal cadence.
|
||||
if currentInterval != activeInterval {
|
||||
ticker.Stop()
|
||||
ticker = time.NewTicker(currentInterval)
|
||||
glog.V(1).Infof("Maintenance scan cadence changed from %v to %v", activeInterval, currentInterval)
|
||||
activeInterval = currentInterval
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,7 +261,7 @@ func (mm *MaintenanceManager) cleanupLoop() {
|
||||
ticker := time.NewTicker(cleanupInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for mm.running {
|
||||
for mm.IsRunning() {
|
||||
select {
|
||||
case <-mm.stopChan:
|
||||
return
|
||||
@@ -263,7 +278,7 @@ func (mm *MaintenanceManager) topologyStatusLoop() {
|
||||
ticker := time.NewTicker(statusInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for mm.running {
|
||||
for mm.IsRunning() {
|
||||
select {
|
||||
case <-mm.stopChan:
|
||||
return
|
||||
@@ -532,12 +547,15 @@ func (mm *MaintenanceManager) TriggerScan() error {
|
||||
|
||||
// triggerScanInternal handles both manual and automatic scan triggers
|
||||
func (mm *MaintenanceManager) triggerScanInternal(isManual bool) error {
|
||||
// running and scanInProgress are checked under one lock so a Stop that lands
|
||||
// between the two checks cannot leave a scan running after shutdown.
|
||||
mm.mutex.Lock()
|
||||
if !mm.running {
|
||||
mm.mutex.Unlock()
|
||||
return fmt.Errorf("maintenance manager is not running")
|
||||
}
|
||||
|
||||
// Prevent multiple concurrent scans
|
||||
mm.mutex.Lock()
|
||||
if mm.scanInProgress {
|
||||
mm.mutex.Unlock()
|
||||
if isManual {
|
||||
@@ -569,6 +587,14 @@ func (mm *MaintenanceManager) UpdateConfig(config *MaintenanceConfig) error {
|
||||
mm.saveTaskConfigsFromPolicy(config.Policy)
|
||||
}
|
||||
|
||||
// The integration holds its own reference to the policy and is what pushes the
|
||||
// enabled flag and the concurrency limit into the registered detectors and
|
||||
// schedulers. Without this the queue and the scanner saw the new policy while the
|
||||
// detectors kept scanning under the old one until the next restart.
|
||||
if mm.scanner != nil && mm.scanner.integration != nil {
|
||||
mm.scanner.integration.SetPolicy(config.Policy)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Maintenance configuration updated")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ func TestMaintenanceManager_ErrorHandling(t *testing.T) {
|
||||
config := DefaultMaintenanceConfig()
|
||||
config.ScanIntervalSeconds = 1 // Short interval for testing (1 second)
|
||||
|
||||
manager := NewMaintenanceManager(nil, config)
|
||||
manager := NewMaintenanceManager(nil, config, nil)
|
||||
|
||||
// Test initial state
|
||||
if manager.errorCount != 0 {
|
||||
@@ -96,7 +96,7 @@ func TestIsConnectionError(t *testing.T) {
|
||||
|
||||
func TestMaintenanceManager_GetErrorState(t *testing.T) {
|
||||
config := DefaultMaintenanceConfig()
|
||||
manager := NewMaintenanceManager(nil, config)
|
||||
manager := NewMaintenanceManager(nil, config, nil)
|
||||
|
||||
// Test initial state
|
||||
errorCount, lastError, backoffDelay := manager.GetErrorState()
|
||||
@@ -118,7 +118,7 @@ func TestMaintenanceManager_GetErrorState(t *testing.T) {
|
||||
|
||||
func TestMaintenanceManager_LogThrottling(t *testing.T) {
|
||||
config := DefaultMaintenanceConfig()
|
||||
manager := NewMaintenanceManager(nil, config)
|
||||
manager := NewMaintenanceManager(nil, config, nil)
|
||||
|
||||
// This is a basic test to ensure the error handling doesn't panic
|
||||
// In practice, you'd want to capture log output to verify throttling
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package maintenance
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
)
|
||||
|
||||
// stubConfigPersistence implements the LoadXTaskPolicy accessors that the task config loaders
|
||||
// type-assert on. The real implementation is *dash.ConfigPersistence, which this package cannot
|
||||
// import: weed/admin/dash already imports weed/admin/maintenance, so the dependency only runs one
|
||||
// way and the persistence argument has to stay duck-typed.
|
||||
type stubConfigPersistence struct {
|
||||
vacuum *worker_pb.TaskPolicy
|
||||
ec *worker_pb.TaskPolicy
|
||||
balance *worker_pb.TaskPolicy
|
||||
ecBalance *worker_pb.TaskPolicy
|
||||
}
|
||||
|
||||
func (s *stubConfigPersistence) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
return s.vacuum, nil
|
||||
}
|
||||
|
||||
func (s *stubConfigPersistence) LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
return s.ec, nil
|
||||
}
|
||||
|
||||
func (s *stubConfigPersistence) LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
return s.balance, nil
|
||||
}
|
||||
|
||||
func (s *stubConfigPersistence) LoadEcBalanceTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
return s.ecBalance, nil
|
||||
}
|
||||
|
||||
func disabledStub() *stubConfigPersistence {
|
||||
return &stubConfigPersistence{
|
||||
vacuum: &worker_pb.TaskPolicy{
|
||||
Enabled: false,
|
||||
MaxConcurrent: 2,
|
||||
RepeatIntervalSeconds: 2 * 3600,
|
||||
TaskConfig: &worker_pb.TaskPolicy_VacuumConfig{
|
||||
VacuumConfig: &worker_pb.VacuumTaskConfig{GarbageThreshold: 0.3, MinVolumeAgeHours: 24},
|
||||
},
|
||||
},
|
||||
ec: &worker_pb.TaskPolicy{
|
||||
Enabled: false,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 3600,
|
||||
TaskConfig: &worker_pb.TaskPolicy_ErasureCodingConfig{
|
||||
ErasureCodingConfig: &worker_pb.ErasureCodingTaskConfig{FullnessRatio: 0.95, QuietForSeconds: 3600, MinVolumeSizeMb: 30},
|
||||
},
|
||||
},
|
||||
balance: &worker_pb.TaskPolicy{
|
||||
Enabled: false,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 30 * 60,
|
||||
TaskConfig: &worker_pb.TaskPolicy_BalanceConfig{
|
||||
BalanceConfig: &worker_pb.BalanceTaskConfig{ImbalanceThreshold: 0.2, MinServerCount: 7},
|
||||
},
|
||||
},
|
||||
ecBalance: &worker_pb.TaskPolicy{
|
||||
Enabled: false,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 60 * 60,
|
||||
TaskConfig: &worker_pb.TaskPolicy_EcBalanceConfig{
|
||||
EcBalanceConfig: &worker_pb.EcBalanceTaskConfig{ImbalanceThreshold: 0.2, MinServerCount: 5},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildPolicyFromTaskConfigsUsesPersistence covers a reported bug: the persistence argument used to be a
|
||||
// literal nil, which no type assertion can satisfy, so a task disabled on disk came back enabled.
|
||||
func TestBuildPolicyFromTaskConfigsUsesPersistence(t *testing.T) {
|
||||
policy := BuildPolicyFromTaskConfigs(disabledStub())
|
||||
|
||||
for _, taskType := range []string{"vacuum", "erasure_coding", "balance", "ec_balance"} {
|
||||
taskPolicy := policy.TaskPolicies[taskType]
|
||||
if taskPolicy == nil {
|
||||
t.Fatalf("no %s task policy built", taskType)
|
||||
}
|
||||
if taskPolicy.Enabled {
|
||||
t.Errorf("%s enabled = true, want false from the persisted config", taskType)
|
||||
}
|
||||
}
|
||||
|
||||
if got := policy.TaskPolicies["balance"].GetBalanceConfig().GetMinServerCount(); got != 7 {
|
||||
t.Errorf("balance min server count = %d, want persisted 7", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildPolicyFromTaskConfigsWithoutPersistence keeps the documented fallback: with no config
|
||||
// store there is nothing to read, so the compiled-in defaults apply.
|
||||
func TestBuildPolicyFromTaskConfigsWithoutPersistence(t *testing.T) {
|
||||
policy := BuildPolicyFromTaskConfigs(nil)
|
||||
|
||||
for _, taskType := range []string{"vacuum", "erasure_coding", "balance", "ec_balance"} {
|
||||
taskPolicy := policy.TaskPolicies[taskType]
|
||||
if taskPolicy == nil {
|
||||
t.Fatalf("no %s task policy built", taskType)
|
||||
}
|
||||
if !taskPolicy.Enabled {
|
||||
t.Errorf("%s enabled = false, want the compiled-in default true", taskType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewMaintenanceManagerUsesPersistenceForPolicyFallback covers the path the admin server takes
|
||||
// when no maintenance.pb has been written yet: the config carries no policy, so the manager builds
|
||||
// one itself and must read the persisted task configs to do it.
|
||||
func TestNewMaintenanceManagerUsesPersistenceForPolicyFallback(t *testing.T) {
|
||||
config := DefaultMaintenanceConfig()
|
||||
if config.Policy != nil {
|
||||
t.Fatal("default config unexpectedly carries a policy, test no longer covers the fallback")
|
||||
}
|
||||
|
||||
manager := NewMaintenanceManager(nil, config, disabledStub())
|
||||
|
||||
policy := manager.queue.policy
|
||||
if policy == nil {
|
||||
t.Fatal("queue policy is nil")
|
||||
}
|
||||
if IsTaskEnabled(policy, MaintenanceTaskType("balance")) {
|
||||
t.Error("balance enabled = true, want false from the persisted config")
|
||||
}
|
||||
if IsTaskEnabled(policy, MaintenanceTaskType("vacuum")) {
|
||||
t.Error("vacuum enabled = true, want false from the persisted config")
|
||||
}
|
||||
if manager.scanner.policy != policy {
|
||||
t.Error("scanner and queue disagree on the policy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package maintenance
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/types"
|
||||
)
|
||||
|
||||
// The detectors and schedulers live in a process-global registry, so these tests restore
|
||||
// whatever they change. Otherwise a test that disables a task leaks that state into every
|
||||
// later test in the package.
|
||||
func snapshotDetectorState(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
registry := tasks.GetGlobalTypesRegistry()
|
||||
enabled := make(map[types.TaskType]bool)
|
||||
maxConcurrent := make(map[types.TaskType]int)
|
||||
for taskType, detector := range registry.GetAllDetectors() {
|
||||
enabled[taskType] = detector.IsEnabled()
|
||||
}
|
||||
for taskType, scheduler := range registry.GetAllSchedulers() {
|
||||
maxConcurrent[taskType] = scheduler.GetMaxConcurrent()
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
for taskType, detector := range registry.GetAllDetectors() {
|
||||
if setter, ok := detector.(interface{ SetEnabled(bool) }); ok {
|
||||
setter.SetEnabled(enabled[taskType])
|
||||
}
|
||||
}
|
||||
for taskType, scheduler := range registry.GetAllSchedulers() {
|
||||
if setter, ok := scheduler.(interface{ SetMaxConcurrent(int) }); ok {
|
||||
setter.SetMaxConcurrent(maxConcurrent[taskType])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestPolicyReachesRegisteredDetectors is the regression test for the half of the scan-flood bug
|
||||
// that a corrected policy alone did not fix: MaintenanceIntegration pushes the policy into
|
||||
// detectors and schedulers through interface{ SetEnabled(bool) } and
|
||||
// interface{ SetMaxConcurrent(int) } type assertions, but every task is backed by
|
||||
// base.GenericDetector/base.GenericScheduler, which implemented neither. The assertions
|
||||
// failed silently for every task on every startup, so the policy never reached
|
||||
// detector.IsEnabled() - which is what ScanWithTaskDetectors gates scanning on.
|
||||
func TestPolicyReachesRegisteredDetectors(t *testing.T) {
|
||||
snapshotDetectorState(t)
|
||||
|
||||
registry := tasks.GetGlobalTypesRegistry()
|
||||
if len(registry.GetAllDetectors()) == 0 {
|
||||
t.Fatal("no detectors registered, the test cannot prove anything")
|
||||
}
|
||||
|
||||
// Enable everything first so the disabling below cannot pass by accident.
|
||||
policy := policyWithAllTasks(t, true)
|
||||
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
|
||||
|
||||
for taskType, detector := range registry.GetAllDetectors() {
|
||||
if !detector.IsEnabled() {
|
||||
t.Fatalf("detector %s is disabled after an all-enabled policy was applied", taskType)
|
||||
}
|
||||
}
|
||||
|
||||
// Now disable everything through the policy and check it lands on the detectors.
|
||||
policy = policyWithAllTasks(t, false)
|
||||
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
|
||||
|
||||
for taskType, detector := range registry.GetAllDetectors() {
|
||||
if detector.IsEnabled() {
|
||||
t.Errorf("detector %s still reports enabled after the policy disabled it; "+
|
||||
"the policy is not reaching the flag ScanWithTaskDetectors gates on", taskType)
|
||||
}
|
||||
}
|
||||
for taskType, scheduler := range registry.GetAllSchedulers() {
|
||||
if scheduler.IsEnabled() {
|
||||
t.Errorf("scheduler %s still reports enabled after the policy disabled it", taskType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPolicyMaxConcurrentReachesSchedulers covers the SetMaxConcurrent half of the same
|
||||
// wiring. GetMaxConcurrent is what MaintenanceQueue.getMaxConcurrentForTaskType asks before
|
||||
// starting another task of a type.
|
||||
func TestPolicyMaxConcurrentReachesSchedulers(t *testing.T) {
|
||||
snapshotDetectorState(t)
|
||||
|
||||
const wantMaxConcurrent = 7
|
||||
|
||||
policy := policyWithAllTasks(t, true)
|
||||
for _, taskPolicy := range policy.TaskPolicies {
|
||||
taskPolicy.MaxConcurrent = wantMaxConcurrent
|
||||
}
|
||||
NewMaintenanceIntegration(NewMaintenanceQueue(policy), policy)
|
||||
|
||||
registry := tasks.GetGlobalTypesRegistry()
|
||||
for taskType, scheduler := range registry.GetAllSchedulers() {
|
||||
if _, covered := policy.TaskPolicies[string(taskType)]; !covered {
|
||||
continue
|
||||
}
|
||||
if got := scheduler.GetMaxConcurrent(); got != wantMaxConcurrent {
|
||||
t.Errorf("scheduler %s max concurrent = %d, want %d from the policy", taskType, got, wantMaxConcurrent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPolicyWithoutEntryLeavesTaskAlone guards the direction that would have been a silent
|
||||
// outage: IsTaskEnabled reports false for a task type the policy does not list, so applying
|
||||
// it unconditionally would disable every task the policy has no entry for.
|
||||
func TestPolicyWithoutEntryLeavesTaskAlone(t *testing.T) {
|
||||
snapshotDetectorState(t)
|
||||
|
||||
registry := tasks.GetGlobalTypesRegistry()
|
||||
|
||||
// Start from a policy that enables everything.
|
||||
enabling := policyWithAllTasks(t, true)
|
||||
NewMaintenanceIntegration(NewMaintenanceQueue(enabling), enabling)
|
||||
|
||||
// An empty policy has an entry for nothing at all.
|
||||
empty := &MaintenancePolicy{TaskPolicies: make(map[string]*worker_pb.TaskPolicy)}
|
||||
NewMaintenanceIntegration(NewMaintenanceQueue(empty), empty)
|
||||
|
||||
for taskType, detector := range registry.GetAllDetectors() {
|
||||
if !detector.IsEnabled() {
|
||||
t.Errorf("detector %s was disabled by a policy that has no entry for it; "+
|
||||
"a missing entry means no opinion, not disabled", taskType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildPolicyCoversEveryRegisteredTask keeps BuildPolicyFromTaskConfigs and the task
|
||||
// registry in step. A registered task with no policy entry has no enabled flag and no
|
||||
// concurrency limit of its own, which is the state ec_balance was in.
|
||||
func TestBuildPolicyCoversEveryRegisteredTask(t *testing.T) {
|
||||
policy := BuildPolicyFromTaskConfigs(nil)
|
||||
|
||||
for taskType := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
|
||||
if _, ok := policy.TaskPolicies[string(taskType)]; !ok {
|
||||
t.Errorf("task %s is registered as a detector but BuildPolicyFromTaskConfigs "+
|
||||
"builds no policy entry for it, so IsTaskEnabled reports false for it", taskType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildPolicyIncludesEcBalance pins the specific gap above.
|
||||
func TestBuildPolicyIncludesEcBalance(t *testing.T) {
|
||||
policy := BuildPolicyFromTaskConfigs(nil)
|
||||
|
||||
ecBalance := policy.TaskPolicies[string(types.TaskTypeECBalance)]
|
||||
if ecBalance == nil {
|
||||
t.Fatal("no ec_balance entry in the built maintenance policy")
|
||||
}
|
||||
if !IsTaskEnabled(policy, MaintenanceTaskType(types.TaskTypeECBalance)) {
|
||||
t.Error("ec_balance reports disabled with no persisted config, want the compiled-in default of enabled")
|
||||
}
|
||||
if ecBalance.GetEcBalanceConfig() == nil {
|
||||
t.Error("ec_balance policy entry carries no EcBalanceConfig")
|
||||
}
|
||||
}
|
||||
|
||||
// policyWithAllTasks builds a policy that has an entry for every registered task type,
|
||||
// all sharing the same enabled flag.
|
||||
func policyWithAllTasks(t *testing.T, enabled bool) *MaintenancePolicy {
|
||||
t.Helper()
|
||||
|
||||
policy := &MaintenancePolicy{
|
||||
GlobalMaxConcurrent: 4,
|
||||
TaskPolicies: make(map[string]*worker_pb.TaskPolicy),
|
||||
}
|
||||
for taskType := range tasks.GetGlobalTypesRegistry().GetAllDetectors() {
|
||||
policy.TaskPolicies[string(taskType)] = &worker_pb.TaskPolicy{
|
||||
Enabled: enabled,
|
||||
MaxConcurrent: 1,
|
||||
RepeatIntervalSeconds: 3600,
|
||||
}
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
// TestPolicyHelpersTolerateNilPolicy pins the nil handling in the exported policy helpers.
|
||||
// MaintenanceConfig.Policy is nil until something builds one, and UpdateConfig accepts a
|
||||
// config that has none, so these are reachable with a nil policy - GetTaskPolicy used to
|
||||
// dereference it and take the admin process down.
|
||||
func TestPolicyHelpersTolerateNilPolicy(t *testing.T) {
|
||||
const taskType = MaintenanceTaskType("balance")
|
||||
|
||||
if got := GetTaskPolicy(nil, taskType); got != nil {
|
||||
t.Errorf("GetTaskPolicy(nil) = %v, want nil", got)
|
||||
}
|
||||
if IsTaskEnabled(nil, taskType) {
|
||||
t.Error("IsTaskEnabled(nil) = true, want false")
|
||||
}
|
||||
if got := GetMaxConcurrent(nil, taskType); got != 1 {
|
||||
t.Errorf("GetMaxConcurrent(nil) = %d, want the safe default 1", got)
|
||||
}
|
||||
if got := GetRepeatInterval(nil, taskType); got != 0 {
|
||||
t.Errorf("GetRepeatInterval(nil) = %d, want 0 so callers fall back to their own default", got)
|
||||
}
|
||||
|
||||
// A policy that exists but lists nothing must behave the same way.
|
||||
empty := &MaintenancePolicy{}
|
||||
if got := GetTaskPolicy(empty, taskType); got != nil {
|
||||
t.Errorf("GetTaskPolicy(empty) = %v, want nil", got)
|
||||
}
|
||||
if IsTaskEnabled(empty, taskType) {
|
||||
t.Error("IsTaskEnabled(empty) = true, want false")
|
||||
}
|
||||
}
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user