mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-02 17:17:07 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1ffea7522 | ||
|
|
389b99f8e8 | ||
|
|
654502ce8f | ||
|
|
1b5e98143e | ||
|
|
d86c692a39 | ||
|
|
e0f07c762a | ||
|
|
2d5ffecc1f | ||
|
|
004fc32503 | ||
|
|
641fc8b031 | ||
|
|
228500fe37 | ||
|
|
7ebf2ebac3 | ||
|
|
cc8364a03e | ||
|
|
c3f4d799b5 |
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
|
||||
@@ -1549,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: |
|
||||
@@ -1561,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 ==="
|
||||
@@ -1638,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 \
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Whitespace-only changes.
@@ -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=
|
||||
|
||||
+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
|
||||
Generated
+65
@@ -4666,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"
|
||||
@@ -5379,6 +5443,7 @@ dependencies = [
|
||||
"prometheus",
|
||||
"prost 0.13.5",
|
||||
"prost-types 0.13.5",
|
||||
"protoc-bin-vendored",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
|
||||
@@ -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,22 @@ 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
|
||||
|
||||
@@ -21,3 +21,7 @@ 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()
|
||||
|
||||
@@ -7,8 +7,11 @@ 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]
|
||||
|
||||
@@ -13,8 +13,8 @@ use weed_lance_worker::metrics::LanceMetrics;
|
||||
/// language and an operator should not have to learn a second set of names.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "weed-lance-worker",
|
||||
about = "SeaweedFS maintenance worker for Lance tables"
|
||||
name = "weed-worker",
|
||||
about = "SeaweedFS maintenance worker"
|
||||
)]
|
||||
struct Args {
|
||||
/// Admin server gRPC address.
|
||||
|
||||
@@ -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() {
|
||||
@@ -1779,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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -224,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)
|
||||
@@ -253,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)
|
||||
|
||||
@@ -62,6 +62,48 @@ func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -618,7 +618,7 @@ func TestMaintenanceQueue_StaleWorkerCapacityRelease(t *testing.T) {
|
||||
func TestMaintenanceManager_CancelTaskCapacityRelease(t *testing.T) {
|
||||
// Setup Manager
|
||||
config := DefaultMaintenanceConfig()
|
||||
mm := NewMaintenanceManager(nil, config)
|
||||
mm := NewMaintenanceManager(nil, config, nil)
|
||||
integration := mm.scanner.integration
|
||||
mq := mm.queue
|
||||
at := integration.GetActiveTopology()
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package maintenance
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// scanCadenceClient is a minimal AdminClient whose first call blocks until the test
|
||||
// releases it. Blocking the first scan is what makes the cadence test deterministic:
|
||||
// the scan loop evaluates the error state right after triggering a scan, and that scan
|
||||
// runs in its own goroutine, so without the block the loop could observe the error
|
||||
// counter either before or after the scan finished.
|
||||
type scanCadenceClient struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (c *scanCadenceClient) WithMasterClient(fn func(client master_pb.SeaweedClient) error) error {
|
||||
c.mu.Lock()
|
||||
c.calls++
|
||||
first := c.calls == 1
|
||||
c.mu.Unlock()
|
||||
|
||||
if first {
|
||||
<-c.release
|
||||
}
|
||||
|
||||
// Returning nil without invoking fn yields an empty, successful scan.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *scanCadenceClient) callCount() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.calls
|
||||
}
|
||||
|
||||
// TestScanLoopRestoresIntervalAfterBackoff is the regression test for the scan flood. The loop shortens its ticker to the
|
||||
// error backoff delay after a failed scan. It used to compare the target interval against
|
||||
// the *configured* scan interval rather than against the interval the ticker was actually
|
||||
// running at, so once the errors stopped the comparison came out false and the ticker was
|
||||
// never restored: one transient failure pinned the scanner to one scan per second for as
|
||||
// long as the process lived.
|
||||
//
|
||||
// The test seeds the error state, lets the loop drop into the 1s backoff, then lets a scan
|
||||
// succeed and asserts the loop goes back to the configured 3s cadence instead of keeping
|
||||
// the 1s one.
|
||||
func TestScanLoopRestoresIntervalAfterBackoff(t *testing.T) {
|
||||
const baseInterval = 3 * time.Second
|
||||
|
||||
client := &scanCadenceClient{release: make(chan struct{})}
|
||||
|
||||
config := DefaultMaintenanceConfig()
|
||||
config.ScanIntervalSeconds = int32(baseInterval / time.Second)
|
||||
manager := NewMaintenanceManager(client, config, nil)
|
||||
|
||||
// Seed a failed scan so the very first cadence decision drops to the backoff delay.
|
||||
// backoffDelay is what getScanInterval returns while errorCount > 0.
|
||||
manager.mutex.Lock()
|
||||
manager.errorCount = 1
|
||||
manager.backoffDelay = time.Second
|
||||
manager.running = true
|
||||
manager.mutex.Unlock()
|
||||
|
||||
go manager.scanLoop()
|
||||
defer manager.Stop()
|
||||
|
||||
// First tick at ~3s: the scan blocks in the client, so the loop still sees errorCount == 1
|
||||
// and switches the ticker to the 1s backoff.
|
||||
deadline := time.Now().Add(baseInterval + 2*time.Second)
|
||||
for client.callCount() == 0 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("scan loop never triggered its first scan")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Let the blocked scan complete successfully, which clears the error state.
|
||||
close(client.release)
|
||||
|
||||
// Wait for the error state to clear so the next cadence decision is unambiguous.
|
||||
deadline = time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
errorCount, _, _ := manager.GetErrorState()
|
||||
if errorCount == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("error tracking never reset, errorCount=%d", errorCount)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
// The ticker is at 1s now. Wait for the next tick, where the loop must notice the
|
||||
// recovery and restore the 3s cadence.
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
before := client.callCount()
|
||||
|
||||
// Observe a window that a 1s cadence would fill with scans and a 3s cadence would not.
|
||||
const window = 5 * time.Second
|
||||
time.Sleep(window)
|
||||
callsInWindow := client.callCount() - before
|
||||
|
||||
// One scan makes two master-client calls. 3s cadence: at most 2 scans (4 calls) in 5s,
|
||||
// even if a stall shifts the window. 1s cadence: about 5 scans (10 calls).
|
||||
if callsInWindow > 4 {
|
||||
t.Errorf("scan loop made %d master-client calls in %v after recovering from a failed scan; "+
|
||||
"the ticker was left at the %v backoff instead of returning to the configured %v",
|
||||
callsInWindow, window, time.Second, baseInterval)
|
||||
}
|
||||
if callsInWindow == 0 {
|
||||
t.Errorf("scan loop ran no scans in %v, expected the %v cadence to fire at least once", window, baseInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanLoopEntersBackoffOnError checks the other half of the cadence logic: a failing
|
||||
// scan still has to shorten the ticker, so the fix above did not simply pin the loop to
|
||||
// the configured interval.
|
||||
func TestScanLoopEntersBackoffOnError(t *testing.T) {
|
||||
config := DefaultMaintenanceConfig()
|
||||
config.ScanIntervalSeconds = 600
|
||||
manager := NewMaintenanceManager(nil, config, nil)
|
||||
|
||||
baseInterval := time.Duration(config.ScanIntervalSeconds) * time.Second
|
||||
|
||||
if got := manager.getScanInterval(baseInterval); got != baseInterval {
|
||||
t.Errorf("healthy scan interval = %v, want the configured %v", got, baseInterval)
|
||||
}
|
||||
|
||||
manager.mutex.Lock()
|
||||
manager.errorCount = 1
|
||||
manager.backoffDelay = time.Second
|
||||
manager.mutex.Unlock()
|
||||
|
||||
if got := manager.getScanInterval(baseInterval); got != time.Second {
|
||||
t.Errorf("scan interval while failing = %v, want the %v backoff", got, time.Second)
|
||||
}
|
||||
|
||||
manager.mutex.Lock()
|
||||
manager.resetErrorTracking()
|
||||
manager.mutex.Unlock()
|
||||
|
||||
if got := manager.getScanInterval(baseInterval); got != baseInterval {
|
||||
t.Errorf("scan interval after recovery = %v, want the configured %v", got, baseInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopIsIdempotent guards the stop channel against a double close, which used to panic
|
||||
// when StopMaintenanceManager ran twice (for example on a shutdown path that also runs on
|
||||
// a signal handler).
|
||||
func TestStopIsIdempotent(t *testing.T) {
|
||||
manager := NewMaintenanceManager(nil, DefaultMaintenanceConfig(), nil)
|
||||
|
||||
manager.mutex.Lock()
|
||||
manager.running = true
|
||||
manager.mutex.Unlock()
|
||||
|
||||
manager.Stop()
|
||||
manager.Stop()
|
||||
|
||||
if manager.IsRunning() {
|
||||
t.Error("manager still reports running after Stop")
|
||||
}
|
||||
}
|
||||
@@ -144,9 +144,14 @@ func DefaultMaintenanceConfig() *MaintenanceConfig {
|
||||
|
||||
// Policy helper functions (since we can't add methods to type aliases)
|
||||
|
||||
// GetTaskPolicy returns the policy for a specific task type
|
||||
// GetTaskPolicy returns the policy for a specific task type, or nil when the maintenance
|
||||
// policy has no entry for it.
|
||||
//
|
||||
// A nil maintenance policy is a legitimate state, not a programming error:
|
||||
// MaintenanceConfig.Policy is unset until something builds one, and UpdateConfig accepts a
|
||||
// config that carries none. Dereferencing it here panicked the whole admin process.
|
||||
func GetTaskPolicy(mp *MaintenancePolicy, taskType MaintenanceTaskType) *TaskPolicy {
|
||||
if mp.TaskPolicies == nil {
|
||||
if mp == nil || mp.TaskPolicies == nil {
|
||||
return nil
|
||||
}
|
||||
return mp.TaskPolicies[string(taskType)]
|
||||
@@ -174,6 +179,9 @@ func GetMaxConcurrent(mp *MaintenancePolicy, taskType MaintenanceTaskType) int {
|
||||
func GetRepeatInterval(mp *MaintenancePolicy, taskType MaintenanceTaskType) int {
|
||||
policy := GetTaskPolicy(mp, taskType)
|
||||
if policy == nil {
|
||||
if mp == nil {
|
||||
return 0
|
||||
}
|
||||
return int(mp.DefaultRepeatIntervalSeconds)
|
||||
}
|
||||
return int(policy.RepeatIntervalSeconds)
|
||||
|
||||
+1018
-188
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1001
|
||||
// templ: version: v0.3.1020
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -148,11 +148,11 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -161,11 +161,11 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -174,11 +174,11 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.ResolveAttributeValue(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -193,7 +193,30 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><style>\n /* Groups a statement's Sid/Effect and its Action/Resource/Principal\n sections in the structured policy editor. Plain <fieldset>/<legend>\n render fine natively, but Bootstrap's form reset stretches <legend> to\n the fieldset's full width (float: left; width: 100%), which loses the\n usual \"notch in the border\" look and makes the label bar as wide as\n the card. Undo just that here so the legend hugs its content instead.\n */\n .policy-stmt-fieldset {\n border: 1px solid var(--bs-border-color, #dee2e6);\n border-radius: 0.375rem;\n padding: 0 0.75rem 0.75rem;\n margin: 0.75rem 0 0;\n }\n .policy-stmt-legend {\n float: none;\n width: auto;\n max-width: 100%;\n padding: 0 0.5rem;\n margin: 0 0 0.25rem;\n font-size: 0.8125rem;\n font-weight: 600;\n color: var(--bs-secondary-color, #6c757d);\n }\n </style><!-- Datalist of suggested action names, shared by the create/edit editors --><datalist id=\"policyActionSuggestions\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, action := range PolicyActionSuggestions {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "<option value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.ResolveAttributeValue(action)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 204, Col: 33}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\"></option>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</datalist><!-- Populated dynamically as the user types in a Resource field: bucket\n names first, then subfolders one path segment at a time. See\n updatePolicyResourceSuggestions() below. --><datalist id=\"policyResourceSuggestions\"></datalist><!-- Populated dynamically as the user types/focuses a Principal field:\n existing users and IAM roles, fetched once from /api/principals. See\n updatePolicyPrincipalSuggestions() below. --><datalist id=\"policyPrincipalSuggestions\"></datalist><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><ul class=\"nav nav-tabs\" role=\"tablist\"><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link active\" id=\"createPolicyEditorTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyEditorTab\">Editor</button></li><li class=\"nav-item\" role=\"presentation\"><button class=\"nav-link\" id=\"createPolicyJsonTabBtn\" type=\"button\" data-bs-toggle=\"tab\" data-bs-target=\"#createPolicyJsonTab\">JSON</button></li></ul><div class=\"tab-content border border-top-0 rounded-bottom p-3 mb-3\"><div class=\"tab-pane fade show active\" id=\"createPolicyEditorTab\"><div id=\"createPolicyEditorBody\"></div><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"createPolicyAddStatementBtn\"><i class=\"fas fa-plus me-1\"></i>Add statement</button></div><div class=\"tab-pane fade\" id=\"createPolicyJsonTab\"><textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div></div><div class=\"mb-3 d-flex justify-content-between\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy('create')\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument('create')\"><i class=\"fas fa-check me-1\"></i>Validate</button></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><ul class=\"nav nav-tabs\" role=\Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package app
|
||||
|
||||
import "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
|
||||
// PolicyActionSuggestions feeds the <datalist> used by the structured policy
|
||||
// editor's Action inputs. This is an input-assistance aid, NOT a validation
|
||||
// list: the editor accepts any action string typed by hand, since IAM policy
|
||||
// actions are not restricted to this set (custom/future actions, wildcards
|
||||
// like "s3:Get*", etc.).
|
||||
var PolicyActionSuggestions = buildPolicyActionSuggestions()
|
||||
|
||||
func buildPolicyActionSuggestions() []string {
|
||||
return []string{
|
||||
// s3: actions, sourced from the constants used elsewhere for policy
|
||||
// evaluation (weed/s3api/s3_constants/s3_action_strings.go) so the
|
||||
// suggestion list can't drift from the strings the engine actually
|
||||
// understands.
|
||||
s3_constants.S3_ACTION_ALL,
|
||||
s3_constants.S3_ACTION_GET_OBJECT,
|
||||
s3_constants.S3_ACTION_PUT_OBJECT,
|
||||
s3_constants.S3_ACTION_DELETE_OBJECT,
|
||||
s3_constants.S3_ACTION_DELETE_OBJECT_VERSION,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_VERSION,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_ACL,
|
||||
s3_constants.S3_ACTION_PUT_OBJECT_ACL,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_TAGGING,
|
||||
s3_constants.S3_ACTION_PUT_OBJECT_TAGGING,
|
||||
s3_constants.S3_ACTION_DELETE_OBJECT_TAGGING,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_RETENTION,
|
||||
s3_constants.S3_ACTION_PUT_OBJECT_RETENTION,
|
||||
s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
|
||||
s3_constants.S3_ACTION_CREATE_MULTIPART,
|
||||
s3_constants.S3_ACTION_UPLOAD_PART,
|
||||
s3_constants.S3_ACTION_COMPLETE_MULTIPART,
|
||||
s3_constants.S3_ACTION_ABORT_MULTIPART,
|
||||
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
|
||||
s3_constants.S3_ACTION_LIST_PARTS,
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
|
||||
s3_constants.S3_ACTION_CREATE_BUCKET,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET,
|
||||
s3_constants.S3_ACTION_LIST_BUCKET,
|
||||
s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_ACL,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_ACL,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_POLICY,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_POLICY,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET_POLICY,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_TAGGING,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_TAGGING,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET_TAGGING,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_CORS,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_CORS,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET_CORS,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_LIFECYCLE,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_LIFECYCLE,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_VERSIONING,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_VERSIONING,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_LOCATION,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_NOTIFICATION,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_NOTIFICATION,
|
||||
s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK,
|
||||
s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK,
|
||||
|
||||
// s3tables: actions, sourced from weed/s3api/s3_constants so this list
|
||||
// can't drift from the strings the s3tables engine actually understands.
|
||||
s3_constants.S3TABLES_ACTION_ALL,
|
||||
s3_constants.S3TABLES_ACTION_CREATE_TABLE_BUCKET,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET,
|
||||
s3_constants.S3TABLES_ACTION_LIST_TABLE_BUCKETS,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET,
|
||||
s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_TABLE_BUCKET_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_CREATE_NAMESPACE,
|
||||
s3_constants.S3TABLES_ACTION_GET_NAMESPACE,
|
||||
s3_constants.S3TABLES_ACTION_UPDATE_NAMESPACE,
|
||||
s3_constants.S3TABLES_ACTION_LIST_NAMESPACES,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_NAMESPACE,
|
||||
s3_constants.S3TABLES_ACTION_CREATE_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_REGISTER_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_LIST_TABLES,
|
||||
s3_constants.S3TABLES_ACTION_UPDATE_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_RENAME_TABLE,
|
||||
s3_constants.S3TABLES_ACTION_CREATE_VIEW,
|
||||
s3_constants.S3TABLES_ACTION_GET_VIEW,
|
||||
s3_constants.S3TABLES_ACTION_LIST_VIEWS,
|
||||
s3_constants.S3TABLES_ACTION_UPDATE_VIEW,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_VIEW,
|
||||
s3_constants.S3TABLES_ACTION_RENAME_VIEW,
|
||||
s3_constants.S3TABLES_ACTION_PUT_TABLE_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_DELETE_TABLE_POLICY,
|
||||
s3_constants.S3TABLES_ACTION_PUT_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_BUCKET_MAINTENANCE_CONFIGURATION,
|
||||
s3_constants.S3TABLES_ACTION_PUT_TABLE_MAINTENANCE_CONFIGURATION,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_CONFIGURATION,
|
||||
s3_constants.S3TABLES_ACTION_GET_TABLE_MAINTENANCE_JOB_STATUS,
|
||||
s3_constants.S3TABLES_ACTION_TAG_RESOURCE,
|
||||
s3_constants.S3TABLES_ACTION_LIST_TAGS_FOR_RESOURCE,
|
||||
s3_constants.S3TABLES_ACTION_UNTAG_RESOURCE,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPolicyActionSuggestions_NotEmpty(t *testing.T) {
|
||||
if len(PolicyActionSuggestions) == 0 {
|
||||
t.Fatal("expected at least one suggestion")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyActionSuggestions_NoDuplicates(t *testing.T) {
|
||||
seen := make(map[string]bool, len(PolicyActionSuggestions))
|
||||
for _, action := range PolicyActionSuggestions {
|
||||
if seen[action] {
|
||||
t.Errorf("duplicate action suggestion: %q", action)
|
||||
}
|
||||
seen[action] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyActionSuggestions_AllPrefixed(t *testing.T) {
|
||||
for _, action := range PolicyActionSuggestions {
|
||||
if !strings.HasPrefix(action, "s3:") && !strings.HasPrefix(action, "s3tables:") {
|
||||
t.Errorf("action suggestion %q is not prefixed with a known service", action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyActionSuggestions_NoEmptyStrings(t *testing.T) {
|
||||
for i, action := range PolicyActionSuggestions {
|
||||
if strings.TrimSpace(action) == "" {
|
||||
t.Errorf("suggestion at index %d is empty", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,3 +84,64 @@ const (
|
||||
// Wildcard for all S3 actions
|
||||
S3_ACTION_ALL = "s3:*"
|
||||
)
|
||||
|
||||
// S3 Tables action strings for policy evaluation.
|
||||
// Source of truth for the operation names: the dispatch switch in
|
||||
// weed/s3api/s3tables/handler.go. Keep this list in sync with that switch
|
||||
// when operations are added, renamed, or removed.
|
||||
const (
|
||||
// Table bucket operations
|
||||
S3TABLES_ACTION_CREATE_TABLE_BUCKET = "s3tables:CreateTableBucket"
|
||||
S3TABLES_ACTION_GET_TABLE_BUCKET = "s3tables:GetTableBucket"
|
||||
S3TABLES_ACTION_LIST_TABLE_BUCKETS = "s3tables:ListTableBuckets"
|
||||
S3TABLES_ACTION_DELETE_TABLE_BUCKET = "s3tables:DeleteTableBucket"
|
||||
|
||||
// Table bucket policy operations
|
||||
S3TABLES_ACTION_PUT_TABLE_BUCKET_POLICY = "s3tables:PutTableBucketPolicy"
|
||||
S3TABLES_ACTION_GET_TABLE_BUCKET_POLICY = "s3tables:GetTableBucketPolicy"
|
||||
S3TABLES_ACTION_DELETE_TABLE_BUCKET_POLICY = "s3tables:DeleteTableBucketPolicy"
|
||||
|
||||
// Namespace operations
|
||||
S3TABLES_ACTION_CREATE_NAMESPACE = "s3tables:CreateNamespace"
|
||||
S3TABLES_ACTION_GET_NAMESPACE = "s3tables:GetNamespace"
|
||||
S3TABLES_ACTION_UPDATE_NAMESPACE = "s3tables:UpdateNamespace"
|
||||
S3TABLES_ACTION_LIST_NAMESPACES = "s3tables:ListNamespaces"
|
||||
S3TABLES_ACTION_DELETE_NAMESPACE = "s3tables:DeleteNamespace"
|
||||
|
||||
// Table operations
|
||||
S3TABLES_ACTION_CREATE_TABLE = "s3tables:CreateTable"
|
||||
S3TABLES_ACTION_REGISTER_TABLE = "s3tables:RegisterTable"
|
||||
S3TABLES_ACTION_GET_TABLE = "s3tables:GetTable"
|
||||
S3TABLES_ACTION_LIST_TABLES = "s3tables:ListTables"
|
||||
S3TABLES_ACTION_UPDATE_TABLE = "s3tables:UpdateTable"
|
||||
S3TABLES_ACTION_DELETE_TABLE = "s3tables:DeleteTable"
|
||||
S3TABLES_ACTION_RENAME_TABLE = "s3tables:RenameTable"
|
||||
|
||||
// View operations
|
||||
S3TABLES_ACTION_CREATE_VIEW = "s3tables:CreateView"
|
||||
S3TABLES_ACTION_GET_VIEW = "s3tables:GetView"
|
||||
S3TABLES_ACTION_LIST_VIEWS = "s3tables:ListViews"
|
||||
S3TABLES_ACTION_UPDATE_VIEW = "s3tables:UpdateView"
|
||||
S3TABLES_ACTION_DELETE_VIEW = "s3tables:DeleteView"
|
||||
S3TABLES_ACTION_RENAME_VIEW = "s3tables:RenameView"
|
||||
|
||||
// Table policy operations
|
||||
S3TABLES_ACTION_PUT_TABLE_POLICY = "s3tables:PutTablePolicy"
|
||||
S3TABLES_ACTION_GET_TABLE_POLICY = "s3tables:GetTablePolicy"
|
||||
S3TABLES_ACTION_DELETE_TABLE_POLICY = "s3tables:DeleteTablePolicy"
|
||||
|
||||
// Maintenance configuration operations
|
||||
S3TABLES_ACTION_PUT_TABLE_BUCKET_MAINTENANCE_CONFIGURATION = "s3tables:PutTableBucketMaintenanceConfiguration"
|
||||
S3TABLES_ACTION_GET_TABLE_BUCKET_MAINTENANCE_CONFIGURATION = "s3tables:GetTableBucketMaintenanceConfiguration"
|
||||
S3TABLES_ACTION_PUT_TABLE_MAINTENANCE_CONFIGURATION = "s3tables:PutTableMaintenanceConfiguration"
|
||||
S3TABLES_ACTION_GET_TABLE_MAINTENANCE_CONFIGURATION = "s3tables:GetTableMaintenanceConfiguration"
|
||||
S3TABLES_ACTION_GET_TABLE_MAINTENANCE_JOB_STATUS = "s3tables:GetTableMaintenanceJobStatus"
|
||||
|
||||
// Tagging operations
|
||||
S3TABLES_ACTION_TAG_RESOURCE = "s3tables:TagResource"
|
||||
S3TABLES_ACTION_LIST_TAGS_FOR_RESOURCE = "s3tables:ListTagsForResource"
|
||||
S3TABLES_ACTION_UNTAG_RESOURCE = "s3tables:UntagResource"
|
||||
|
||||
// Wildcard for all S3 Tables actions
|
||||
S3TABLES_ACTION_ALL = "s3tables:*"
|
||||
)
|
||||
@@ -178,12 +178,25 @@ func LoadConfigFromPersistence(configPersistence interface{}) *Config {
|
||||
if persistence, ok := configPersistence.(interface {
|
||||
LoadBalanceTaskPolicy() (*worker_pb.TaskPolicy, error)
|
||||
}); ok {
|
||||
if policy, err := persistence.LoadBalanceTaskPolicy(); err == nil && policy != nil {
|
||||
if err := config.FromTaskPolicy(policy); err == nil {
|
||||
policy, err := persistence.LoadBalanceTaskPolicy()
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("Could not read the persisted balance configuration, falling back to defaults: %v", err)
|
||||
case policy == nil:
|
||||
glog.V(1).Infof("No balance configuration persisted yet, using defaults")
|
||||
default:
|
||||
if err := config.FromTaskPolicy(policy); err != nil {
|
||||
glog.Warningf("Could not apply the persisted balance configuration, falling back to defaults: %v", err)
|
||||
} else {
|
||||
glog.V(1).Infof("Loaded balance configuration from persistence")
|
||||
return config
|
||||
}
|
||||
}
|
||||
} else if configPersistence != nil {
|
||||
// A store was handed in but does not expose the accessor, so the persisted
|
||||
// settings are silently ignored - always a wiring bug, never a normal state.
|
||||
glog.Warningf("%T cannot provide the persisted balance configuration: it has no LoadBalanceTaskPolicy() method, "+
|
||||
"so the compiled-in defaults are used and any saved balance settings are ignored", configPersistence)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Using default balance configuration")
|
||||
|
||||
@@ -42,6 +42,18 @@ func (d *GenericDetector) IsEnabled() bool {
|
||||
return d.taskDef.Config.IsEnabled()
|
||||
}
|
||||
|
||||
// SetEnabled turns detection for this task type on or off.
|
||||
//
|
||||
// The admin maintenance policy is applied to detectors through an
|
||||
// interface{ SetEnabled(bool) } type assertion (see
|
||||
// MaintenanceIntegration.configureDetectorFromPolicy). Every registered task is
|
||||
// backed by this generic detector, so without this method that assertion failed
|
||||
// for every task and the policy never reached the flag that
|
||||
// ScanWithTaskDetectors actually gates on.
|
||||
func (d *GenericDetector) SetEnabled(enabled bool) {
|
||||
d.taskDef.Config.SetEnabled(enabled)
|
||||
}
|
||||
|
||||
// GenericScheduler implements TaskScheduler using function-based logic
|
||||
type GenericScheduler struct {
|
||||
taskDef *TaskDefinition
|
||||
@@ -127,3 +139,22 @@ func (s *GenericScheduler) GetDefaultRepeatInterval() time.Duration {
|
||||
func (s *GenericScheduler) IsEnabled() bool {
|
||||
return s.taskDef.Config.IsEnabled()
|
||||
}
|
||||
|
||||
// SetEnabled turns scheduling for this task type on or off. Detector and scheduler
|
||||
// share one TaskDefinition, so this is the same flag GenericDetector.SetEnabled sets;
|
||||
// both setters exist because the maintenance integration configures the two
|
||||
// independently. See GenericDetector.SetEnabled.
|
||||
func (s *GenericScheduler) SetEnabled(enabled bool) {
|
||||
s.taskDef.Config.SetEnabled(enabled)
|
||||
}
|
||||
|
||||
// SetMaxConcurrent applies the policy's concurrency limit for this task type. It is
|
||||
// the value GetMaxConcurrent returns, which the maintenance queue uses to decide
|
||||
// whether another task of this type may start. Non-positive limits are ignored
|
||||
// rather than turning into the implicit default of 1.
|
||||
func (s *GenericScheduler) SetMaxConcurrent(maxConcurrent int) {
|
||||
if maxConcurrent <= 0 {
|
||||
return
|
||||
}
|
||||
s.taskDef.MaxConcurrent = maxConcurrent
|
||||
}
|
||||
@@ -241,12 +241,25 @@ func LoadConfigFromPersistence(configPersistence interface{}) *Config {
|
||||
if persistence, ok := configPersistence.(interface {
|
||||
LoadEcBalanceTaskPolicy() (*worker_pb.TaskPolicy, error)
|
||||
}); ok {
|
||||
if policy, err := persistence.LoadEcBalanceTaskPolicy(); err == nil && policy != nil {
|
||||
if err := cfg.FromTaskPolicy(policy); err == nil {
|
||||
policy, err := persistence.LoadEcBalanceTaskPolicy()
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("Could not read the persisted EC balance configuration, falling back to defaults: %v", err)
|
||||
case policy == nil:
|
||||
glog.V(1).Infof("No EC balance configuration persisted yet, using defaults")
|
||||
default:
|
||||
if err := cfg.FromTaskPolicy(policy); err != nil {
|
||||
glog.Warningf("Could not apply the persisted EC balance configuration, falling back to defaults: %v", err)
|
||||
} else {
|
||||
glog.V(1).Infof("Loaded EC balance configuration from persistence")
|
||||
return cfg
|
||||
}
|
||||
}
|
||||
} else if configPersistence != nil {
|
||||
// A store was handed in but does not expose the accessor, so the persisted
|
||||
// settings are silently ignored - always a wiring bug, never a normal state.
|
||||
glog.Warningf("%T cannot provide the persisted EC balance configuration: it has no LoadEcBalanceTaskPolicy() method, "+
|
||||
"so the compiled-in defaults are used and any saved EC balance settings are ignored", configPersistence)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Using default EC balance configuration")
|
||||
|
||||
@@ -229,12 +229,25 @@ func LoadConfigFromPersistence(configPersistence interface{}) *Config {
|
||||
if persistence, ok := configPersistence.(interface {
|
||||
LoadErasureCodingTaskPolicy() (*worker_pb.TaskPolicy, error)
|
||||
}); ok {
|
||||
if policy, err := persistence.LoadErasureCodingTaskPolicy(); err == nil && policy != nil {
|
||||
if err := config.FromTaskPolicy(policy); err == nil {
|
||||
policy, err := persistence.LoadErasureCodingTaskPolicy()
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("Could not read the persisted erasure coding configuration, falling back to defaults: %v", err)
|
||||
case policy == nil:
|
||||
glog.V(1).Infof("No erasure coding configuration persisted yet, using defaults")
|
||||
default:
|
||||
if err := config.FromTaskPolicy(policy); err != nil {
|
||||
glog.Warningf("Could not apply the persisted erasure coding configuration, falling back to defaults: %v", err)
|
||||
} else {
|
||||
glog.V(1).Infof("Loaded erasure coding configuration from persistence")
|
||||
return config
|
||||
}
|
||||
}
|
||||
} else if configPersistence != nil {
|
||||
// A store was handed in but does not expose the accessor, so the persisted
|
||||
// settings are silently ignored - always a wiring bug, never a normal state.
|
||||
glog.Warningf("%T cannot provide the persisted erasure coding configuration: it has no LoadErasureCodingTaskPolicy() method, "+
|
||||
"so the compiled-in defaults are used and any saved erasure coding settings are ignored", configPersistence)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Using default erasure coding configuration")
|
||||
|
||||
@@ -73,12 +73,25 @@ func LoadConfigFromPersistence(configPersistence interface{}) *Config {
|
||||
if persistence, ok := configPersistence.(interface {
|
||||
LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error)
|
||||
}); ok {
|
||||
if policy, err := persistence.LoadVacuumTaskPolicy(); err == nil && policy != nil {
|
||||
if err := config.FromTaskPolicy(policy); err == nil {
|
||||
policy, err := persistence.LoadVacuumTaskPolicy()
|
||||
switch {
|
||||
case err != nil:
|
||||
glog.Warningf("Could not read the persisted vacuum configuration, falling back to defaults: %v", err)
|
||||
case policy == nil:
|
||||
glog.V(1).Infof("No vacuum configuration persisted yet, using defaults")
|
||||
default:
|
||||
if err := config.FromTaskPolicy(policy); err != nil {
|
||||
glog.Warningf("Could not apply the persisted vacuum configuration, falling back to defaults: %v", err)
|
||||
} else {
|
||||
glog.V(1).Infof("Loaded vacuum configuration from persistence")
|
||||
return config
|
||||
}
|
||||
}
|
||||
} else if configPersistence != nil {
|
||||
// A store was handed in but does not expose the accessor, so the persisted
|
||||
// settings are silently ignored - always a wiring bug, never a normal state.
|
||||
glog.Warningf("%T cannot provide the persisted vacuum configuration: it has no LoadVacuumTaskPolicy() method, "+
|
||||
"so the compiled-in defaults are used and any saved vacuum settings are ignored", configPersistence)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Using default vacuum configuration")
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package vacuum
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
)
|
||||
|
||||
type stubVacuumStore struct {
|
||||
policy *worker_pb.TaskPolicy
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *stubVacuumStore) LoadVacuumTaskPolicy() (*worker_pb.TaskPolicy, error) {
|
||||
return s.policy, s.err
|
||||
}
|
||||
|
||||
// wrongShapedStore is what the maintenance manager used to be handed: a non-nil value that
|
||||
// does not satisfy the accessor the loader asserts on. It has to keep falling back to the
|
||||
// defaults, but no longer silently: a fallback the operator cannot see reads as a disabled task
|
||||
// that keeps running.
|
||||
type wrongShapedStore struct{}
|
||||
|
||||
func (wrongShapedStore) SomethingElse() {}
|
||||
|
||||
func TestLoadConfigFromPersistenceUsesPersistedPolicy(t *testing.T) {
|
||||
persisted := NewDefaultConfig()
|
||||
persisted.Enabled = false
|
||||
persisted.GarbageThreshold = 0.75
|
||||
persisted.MaxConcurrent = 5
|
||||
|
||||
loaded := LoadConfigFromPersistence(&stubVacuumStore{policy: persisted.ToTaskPolicy()})
|
||||
if loaded == nil {
|
||||
t.Fatal("LoadConfigFromPersistence returned nil")
|
||||
}
|
||||
if loaded.Enabled {
|
||||
t.Error("enabled = true, want the persisted false")
|
||||
}
|
||||
if loaded.GarbageThreshold != 0.75 {
|
||||
t.Errorf("garbage threshold = %v, want the persisted 0.75", loaded.GarbageThreshold)
|
||||
}
|
||||
if loaded.MaxConcurrent != 5 {
|
||||
t.Errorf("max concurrent = %d, want the persisted 5", loaded.MaxConcurrent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigFromPersistenceFallsBackToDefaults(t *testing.T) {
|
||||
defaults := NewDefaultConfig()
|
||||
|
||||
cases := map[string]interface{}{
|
||||
"no store configured": nil,
|
||||
"store without the value": &stubVacuumStore{},
|
||||
"store that errors": &stubVacuumStore{err: errors.New("disk on fire")},
|
||||
"store of the wrong type": wrongShapedStore{},
|
||||
}
|
||||
|
||||
for name, store := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
loaded := LoadConfigFromPersistence(store)
|
||||
if loaded == nil {
|
||||
t.Fatal("LoadConfigFromPersistence returned nil")
|
||||
}
|
||||
if !loaded.Enabled {
|
||||
t.Error("enabled = false, want the compiled-in default true")
|
||||
}
|
||||
if loaded.GarbageThreshold != defaults.GarbageThreshold {
|
||||
t.Errorf("garbage threshold = %v, want the default %v", loaded.GarbageThreshold, defaults.GarbageThreshold)
|
||||
}
|
||||
if loaded.ScanIntervalSeconds != defaults.ScanIntervalSeconds {
|
||||
t.Errorf("scan interval = %d, want the default %d", loaded.ScanIntervalSeconds, defaults.ScanIntervalSeconds)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user