mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 13:47:10 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
875cd1f67e | ||
|
|
eb6d8ebd5f | ||
|
|
07c9e0db85 | ||
|
|
d8196428e7 | ||
|
|
efdfeaba44 | ||
|
|
02df1cf428 | ||
|
|
fba01ae2dd | ||
|
|
564803becd | ||
|
|
6f14be1138 | ||
|
|
1f8d0a9ccf | ||
|
|
267f595660 | ||
|
|
1fda7aa7f1 | ||
|
|
8a71327324 | ||
|
|
8bff3b3213 | ||
|
|
ae46e79e98 | ||
|
|
7bfc44432d | ||
|
|
5553e7b876 | ||
|
|
25ab4c3cac | ||
|
|
c015cc3939 | ||
|
|
0ad83d5061 | ||
|
|
8f29d0a91e | ||
|
|
68e6fc5f7c | ||
|
|
f3e4a73696 | ||
|
|
311bc3a6df | ||
|
|
10cdaf3818 | ||
|
|
cd7c8ae784 | ||
|
|
a7073a9778 | ||
|
|
0dc504733e | ||
|
|
9964d5b82a | ||
|
|
7b2bee9890 | ||
|
|
bd9b5c25ff | ||
|
|
19dc085e33 | ||
|
|
013281b498 | ||
|
|
fa549e9c83 | ||
|
|
c1a1e3c1e3 | ||
|
|
40ee4a08c5 | ||
|
|
29981f8d24 | ||
|
|
e7be6bb2f8 | ||
|
|
c006dc563e | ||
|
|
ce82e3a057 | ||
|
|
298ab35fd7 | ||
|
|
5c511c4894 | ||
|
|
76ec1d8f0f | ||
|
|
ac524e140a | ||
|
|
c17aebeecf | ||
|
|
db42bb4975 | ||
|
|
9a7cfaf371 | ||
|
|
6fd82b7e6f | ||
|
|
3a0021e144 | ||
|
|
6f816c955d | ||
|
|
e6b2849381 | ||
|
|
95023af489 | ||
|
|
fd5a6ff427 | ||
|
|
399f8033f8 | ||
|
|
02b5b66a3f | ||
|
|
78e428758b | ||
|
|
a9cfbd8d3a | ||
|
|
11fd20e2b0 | ||
|
|
b43089f721 | ||
|
|
cfb46ee19f | ||
|
|
65f2f1488a | ||
|
|
63db56ff7d | ||
|
|
e873e671b6 | ||
|
|
24fb7e47f3 | ||
|
|
0ae1fdcad2 | ||
|
|
a16194f5b4 | ||
|
|
c000addfc9 | ||
|
|
6413b774df | ||
|
|
274a41fd26 | ||
|
|
218f23fdf0 | ||
|
|
1262147d9f | ||
|
|
56fec510e4 | ||
|
|
94078b6e3f | ||
|
|
cc9549def8 | ||
|
|
60d9c7ef4c | ||
|
|
254c2a1024 | ||
|
|
2d2fdeac3d | ||
|
|
bcc528a517 | ||
|
|
d35c4b3d2d | ||
|
|
f58721b22f | ||
|
|
4f1f0dcb17 | ||
|
|
73165203fc | ||
|
|
e521a2a7b9 | ||
|
|
e5215f0785 | ||
|
|
9d55a8bf8a | ||
|
|
d774f4abe2 | ||
|
|
46b0fea62f | ||
|
|
9c11efce6b | ||
|
|
ed1fbeac19 | ||
|
|
6e477ae00f | ||
|
|
e98cbfc8f1 | ||
|
|
65dff4a492 | ||
|
|
eefe634962 | ||
|
|
39ff5ae767 | ||
|
|
873705baf9 | ||
|
|
c332323b01 | ||
|
|
e64d01825f | ||
|
|
843210790e | ||
|
|
d0e47cf4da | ||
|
|
a6effe3cfb | ||
|
|
60e7b30009 | ||
|
|
292c7493fa | ||
|
|
1d8a6e832c | ||
|
|
2480c2521a | ||
|
|
2c980fb468 | ||
|
|
98e49d2d42 | ||
|
|
17af32f3ff | ||
|
|
c4f0b12a9a | ||
|
|
3089480c30 | ||
|
|
39961ce5d7 | ||
|
|
267ff3b187 | ||
|
|
0e97794f1a | ||
|
|
6206f60032 | ||
|
|
c5240944e4 | ||
|
|
2540141ee7 | ||
|
|
77694d3a93 | ||
|
|
9b1ff91949 | ||
|
|
b0d1786c28 | ||
|
|
01406e661a | ||
|
|
292abfae33 | ||
|
|
0ead130bfc | ||
|
|
c46526822b | ||
|
|
cc4043c9d2 | ||
|
|
ece4f42ecd | ||
|
|
155140bed8 | ||
|
|
cf64cafc3b | ||
|
|
f6032cf23d | ||
|
|
746ed82662 | ||
|
|
9d75048594 | ||
|
|
ebeab4b6ec | ||
|
|
e6441d84e0 | ||
|
|
05b4b5bf56 | ||
|
|
b872d5e683 | ||
|
|
430d4b5394 | ||
|
|
36e51e5542 | ||
|
|
bdcc3154ed | ||
|
|
ce3ba31bcd | ||
|
|
b4a99b996d | ||
|
|
9550b830d0 | ||
|
|
d02ee6d5df | ||
|
|
bea1357d38 | ||
|
|
77bf2a3ab0 | ||
|
|
41d6c821ba | ||
|
|
a9c0ed91b5 | ||
|
|
a653a7f72a | ||
|
|
424cd164e9 | ||
|
|
803c5a8dca | ||
|
|
8f2a2abae4 | ||
|
|
a85318111c | ||
|
|
bb5e6e40df | ||
|
|
d18b85ef61 | ||
|
|
53087cb237 | ||
|
|
cac83bb4a8 | ||
|
|
acbb6f7550 | ||
|
|
c9f2ef9ef7 | ||
|
|
473f7b2367 | ||
|
|
dccc015a1f | ||
|
|
1df7a0e653 | ||
|
|
72009c607b | ||
|
|
0e293c9b0a | ||
|
|
270ac332ff | ||
|
|
96f93d8e3b | ||
|
|
9752286fd4 | ||
|
|
b55a608ae0 | ||
|
|
cb95b45282 | ||
|
|
2acae706d2 | ||
|
|
6de556a9e3 | ||
|
|
9bc8260532 | ||
|
|
990b168766 | ||
|
|
e2c649d56f | ||
|
|
1e42dd77ca |
No files matched your search
@@ -5,6 +5,7 @@ on:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/**'
|
||||
- 'seaweed-volume/**'
|
||||
- 'docker/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
@@ -51,7 +52,7 @@ jobs:
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -117,7 +118,7 @@ jobs:
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4.1.0
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
|
||||
- name: Create BuildKit config
|
||||
run: |
|
||||
@@ -134,14 +135,14 @@ jobs:
|
||||
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
|
||||
@@ -126,14 +126,14 @@ jobs:
|
||||
echo "seaweedfs_ref=$seaweed" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4.1.0
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
- name: Set up QEMU
|
||||
if: matrix.platform != 'amd64'
|
||||
uses: docker/setup-qemu-action@v4.1.0
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
- name: Create BuildKit config
|
||||
run: |
|
||||
cat > /tmp/buildkitd.toml <<EOF
|
||||
@@ -221,13 +221,13 @@ jobs:
|
||||
buildkitd-config: /tmp/buildkitd.toml
|
||||
- name: Login to Docker Hub
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Login to GHCR
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
@@ -275,7 +275,7 @@ jobs:
|
||||
fi
|
||||
- name: Login to GHCR
|
||||
if: needs.setup.outputs.publish == 'true'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
@@ -430,12 +430,12 @@ jobs:
|
||||
ghcr.io/chrislusf/seaweedfs
|
||||
tags: type=raw,value=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }},suffix=${{ steps.config.outputs.tag_suffix }}
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
|
||||
@@ -43,14 +43,14 @@ jobs:
|
||||
org.opencontainers.image.vendor=Chris Lu
|
||||
-
|
||||
name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4.1.0
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
-
|
||||
name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
-
|
||||
name: Login to Docker Hub
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -201,7 +201,7 @@ jobs:
|
||||
|
||||
- name: Set up QEMU
|
||||
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && matrix.qemu
|
||||
uses: docker/setup-qemu-action@v4.1.0
|
||||
uses: docker/setup-qemu-action@v4.2.0
|
||||
|
||||
- name: Create BuildKit config
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
@@ -219,7 +219,7 @@ jobs:
|
||||
|
||||
- name: Login to GHCR
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
@@ -293,7 +293,7 @@ jobs:
|
||||
|
||||
- name: Login to GHCR
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
@@ -310,7 +310,7 @@ jobs:
|
||||
|
||||
- name: Login to Docker Hub
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
@@ -374,7 +374,7 @@ jobs:
|
||||
variant: large_disk
|
||||
steps:
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
@@ -423,13 +423,13 @@ jobs:
|
||||
latest_tag: latest_large_disk
|
||||
steps:
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4.2.0
|
||||
uses: docker/login-action@v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ secrets.GHCR_USERNAME }}
|
||||
|
||||
@@ -82,13 +82,13 @@ jobs:
|
||||
echo "seaweedfs_ref=$seaweed" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v1
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v1
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v1
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
@@ -52,7 +52,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-e2e-${{ github.sha }}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
name: "release: java clients"
|
||||
|
||||
# Publishes the SeaweedFS Java clients (seaweedfs-client and
|
||||
# seaweedfs-hadoop3-client) to Maven Central via the Sonatype Central Portal.
|
||||
#
|
||||
# Required repository secrets:
|
||||
# MAVEN_CENTRAL_USERNAME - Central Portal user token username (central.sonatype.com -> Account -> Generate User Token)
|
||||
# MAVEN_CENTRAL_PASSWORD - Central Portal user token password
|
||||
# MAVEN_GPG_PRIVATE_KEY - ASCII-armored signing key:
|
||||
# gpg --homedir <keyring> --armor --export-secret-keys <KEYID> > key.asc
|
||||
# MAVEN_GPG_PASSPHRASE - passphrase for that key
|
||||
#
|
||||
# A plain run publishes to Central. Check dry_run to exercise secrets, GPG
|
||||
# signing, and the build without committing or publishing.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version to publish, e.g. 4.39. Leave blank to use the current SeaweedFS version."
|
||||
type: string
|
||||
required: false
|
||||
dry_run:
|
||||
description: "Build and GPG-sign only; skip the version commit and the Central upload"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: java-release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
# Java 17 needs these opens for the Maven publishing plugins' reflective access.
|
||||
MAVEN_OPTS: >-
|
||||
--add-opens=java.base/java.util=ALL-UNNAMED
|
||||
--add-opens=java.base/java.lang.reflect=ALL-UNNAMED
|
||||
--add-opens=java.base/java.text=ALL-UNNAMED
|
||||
--add-opens=java.desktop/java.awt.font=ALL-UNNAMED
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish to Maven Central
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# Full history so the version-bump commit can rebase onto a moved master.
|
||||
fetch-depth: 0
|
||||
|
||||
# An explicit input wins; otherwise fall back to the current SeaweedFS
|
||||
# version (MAJOR.MINOR) from constants.go, matching its %d.%02d formatting.
|
||||
- name: Resolve version
|
||||
id: resolve
|
||||
env:
|
||||
INPUT_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="$INPUT_VERSION"
|
||||
if [ -z "$VERSION" ]; then
|
||||
CONST=weed/util/version/constants.go
|
||||
MAJOR=$(grep -oP 'MAJOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
|
||||
MINOR=$(grep -oP 'MINOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
|
||||
VERSION=$(printf '%d.%02d' "$MAJOR" "$MINOR")
|
||||
echo "No version given; using current SeaweedFS version ${VERSION}."
|
||||
fi
|
||||
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::version must be MAJOR.MINOR, e.g. 4.39 (got '$VERSION')"
|
||||
exit 1
|
||||
fi
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: 'maven'
|
||||
server-id: central
|
||||
server-username: MAVEN_CENTRAL_USERNAME
|
||||
server-password: MAVEN_CENTRAL_PASSWORD
|
||||
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
|
||||
gpg-passphrase: MAVEN_GPG_PASSPHRASE
|
||||
|
||||
# client carries the version literally; hdfs3 derives its own version and
|
||||
# its seaweedfs-client dependency from the seaweedfs.client.version property.
|
||||
- name: Set versions in poms
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
V=org.codehaus.mojo:versions-maven-plugin:2.16.2
|
||||
mvn -B -ntp -f other/java/client/pom.xml "${V}:set" \
|
||||
-DnewVersion="$VERSION" -DgenerateBackupPoms=false
|
||||
mvn -B -ntp -f other/java/hdfs3/pom.xml "${V}:set-property" \
|
||||
-Dproperty=seaweedfs.client.version -DnewVersion="$VERSION" -DgenerateBackupPoms=false
|
||||
|
||||
- name: Commit version bump
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if git diff --quiet; then
|
||||
echo "Poms already at ${VERSION}; nothing to commit."
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add other/java/client/pom.xml other/java/hdfs3/pom.xml
|
||||
git commit -m "java ${VERSION}"
|
||||
# Rebase and retry so a concurrent push to master doesn't lose the bump.
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if git push origin HEAD:master; then
|
||||
exit 0
|
||||
fi
|
||||
echo "push rejected (attempt ${attempt}); rebasing onto latest master"
|
||||
git pull --rebase origin master
|
||||
done
|
||||
echo "::error::could not push version bump after retries"
|
||||
exit 1
|
||||
|
||||
# Tests are skipped here: the integration tests need a live filer, and the
|
||||
# offline unit tests already run on every push in java_unit_tests.yml.
|
||||
# dry_run stops at `install` (build + GPG sign, no upload). A real run deploys.
|
||||
# client goes first either way so its install populates the local repo for hdfs3.
|
||||
- name: Publish seaweedfs-client
|
||||
working-directory: other/java/client
|
||||
env:
|
||||
MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
|
||||
MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
|
||||
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[ "$DRY_RUN" = "true" ] && GOAL="clean install" || GOAL="clean deploy"
|
||||
mvn -B -ntp $GOAL -DskipTests
|
||||
|
||||
- name: Publish seaweedfs-hadoop3-client
|
||||
working-directory: other/java/hdfs3
|
||||
env:
|
||||
MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
|
||||
MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
|
||||
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[ "$DRY_RUN" = "true" ] && GOAL="clean install" || GOAL="clean deploy"
|
||||
mvn -B -ntp $GOAL -DskipTests
|
||||
|
||||
# Bump every version the wiki quotes for the Java clients. Runs only after
|
||||
# a successful real publish. Uses GITHUB_TOKEN; set a WIKI_TOKEN secret if
|
||||
# the token can't push to the wiki.
|
||||
- name: Update wiki client versions
|
||||
if: ${{ !inputs.dry_run }}
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
WIKI_TOKEN: ${{ secrets.WIKI_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TOKEN="${WIKI_TOKEN:-$GH_TOKEN}"
|
||||
git clone -q "https://x-access-token:${TOKEN}@github.com/${{ github.repository }}.wiki.git" wiki
|
||||
cd wiki
|
||||
for f in $(grep -rlE "seaweedfs-(client|hadoop3-client)" --include="*.md" .); do
|
||||
NEWV="$VERSION" perl -0777 -i -pe '
|
||||
my $v = $ENV{NEWV};
|
||||
s{(<artifactId>seaweedfs-(?:client|hadoop3-client)</artifactId>\s*<version>)[0-9]+\.[0-9]+(</version>)}{$1$v$2}g;
|
||||
s{(seaweedfs-(?:client|hadoop3-client):)[0-9]+\.[0-9]+}{$1$v}g;
|
||||
s{(seaweedfs-(?:client|hadoop3-client)-)[0-9]+\.[0-9]+(\.jar)}{$1$v$2}g;
|
||||
s{(seaweedfs-(?:client|hadoop3-client)/)[0-9]+\.[0-9]+(/)}{$1$v$2}g;
|
||||
' "$f"
|
||||
done
|
||||
if git diff --quiet; then
|
||||
echo "Wiki already references ${VERSION}."
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -am "java clients ${VERSION}"
|
||||
git push
|
||||
@@ -0,0 +1,79 @@
|
||||
name: "Master Cold Start Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/server/master_*.go'
|
||||
- 'weed/topology/**'
|
||||
- 'weed/operation/**'
|
||||
- 'test/master_cold_start/**'
|
||||
- 'test/testutil/**'
|
||||
- '.github/workflows/master-cold-start-tests.yml'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths:
|
||||
- 'weed/server/master_*.go'
|
||||
- 'weed/topology/**'
|
||||
- 'weed/operation/**'
|
||||
- 'test/master_cold_start/**'
|
||||
- 'test/testutil/**'
|
||||
- '.github/workflows/master-cold-start-tests.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.head_ref || github.ref }}/master-cold-start-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
master-cold-start-tests:
|
||||
name: Master Cold Start Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
|
||||
- name: Build weed binary
|
||||
run: |
|
||||
cd weed && go install -buildvcs=false
|
||||
|
||||
- name: Run master cold start tests
|
||||
# test/master_cold_start boots a fresh master plus empty volume
|
||||
# servers and requires the very first assign (HTTP and gRPC, no
|
||||
# client retries) to complete a write: the assign that triggers
|
||||
# volume growth must wait for it instead of failing with
|
||||
# "volume growth in progress".
|
||||
run: |
|
||||
export WEED_BINARY=$(go env GOPATH)/bin/weed
|
||||
go test -v -timeout=8m ./test/master_cold_start/...
|
||||
|
||||
- name: Collect server logs on failure
|
||||
if: failure()
|
||||
run: |
|
||||
# test/master_cold_start/cluster.go keeps failing-test dirs created
|
||||
# via os.MkdirTemp("", "seaweedfs_master_cold_start_it_") with each
|
||||
# process log under <baseDir>/logs/.
|
||||
mkdir -p /tmp/master-cold-start-logs
|
||||
find /tmp -maxdepth 1 -type d -name "seaweedfs_master_cold_start_it_*" 2>/dev/null | while read dir; do
|
||||
echo "Found test directory: $dir"
|
||||
cp -r "$dir" /tmp/master-cold-start-logs/ 2>/dev/null || true
|
||||
done
|
||||
find /tmp/master-cold-start-logs -type f -name "*.log" -print -exec tail -n 100 {} \; 2>/dev/null || echo "No logs found"
|
||||
|
||||
- name: Archive logs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: master-cold-start-test-logs
|
||||
path: /tmp/master-cold-start-logs/
|
||||
retention-days: 7
|
||||
@@ -185,7 +185,7 @@ jobs:
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
if: matrix.impl == 'rust'
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -341,7 +341,7 @@ jobs:
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
if: matrix.impl == 'rust'
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-postgres-${{ github.sha }}
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -119,7 +119,7 @@ jobs:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
echo "OPENSSL_LIB_DIR=/usr/lib/aarch64-linux-gnu" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -140,7 +140,7 @@ jobs:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -218,7 +218,7 @@ jobs:
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
|
||||
@@ -588,7 +588,7 @@ jobs:
|
||||
|
||||
- name: Restore python:3 image cache
|
||||
id: python-image
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: /tmp/python3-image.tar
|
||||
key: python3-image-${{ steps.week.outputs.week }}
|
||||
|
||||
@@ -150,7 +150,7 @@ jobs:
|
||||
- name: Cache Apache Spark
|
||||
if: false && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
id: cache-spark
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: spark-3.5.0-bin-hadoop3
|
||||
key: spark-3.5.0-hadoop3
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/seaweedfs/seaweedfs
|
||||
|
||||
go 1.25.5
|
||||
go 1.25.8
|
||||
|
||||
require (
|
||||
cloud.google.com/go v0.123.0 // indirect
|
||||
@@ -25,7 +25,7 @@ require (
|
||||
github.com/facebookgo/stats v0.0.0-20151006221625-1b76add642e4
|
||||
github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-redsync/redsync/v4 v4.16.0
|
||||
github.com/go-redsync/redsync/v4 v4.17.0
|
||||
github.com/go-sql-driver/mysql v1.10.0
|
||||
github.com/go-zookeeper/zk v1.0.4 // indirect
|
||||
github.com/golang/protobuf v1.5.4
|
||||
@@ -38,7 +38,7 @@ require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
@@ -50,7 +50,7 @@ require (
|
||||
github.com/kurin/blazer v0.5.3
|
||||
github.com/linxGnu/grocksdb v1.10.8
|
||||
github.com/mailru/easyjson v0.9.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
@@ -89,18 +89,18 @@ require (
|
||||
go.mongodb.org/mongo-driver v1.17.9
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
gocloud.dev v0.46.0
|
||||
gocloud.dev/pubsub/natspubsub v0.45.0
|
||||
gocloud.dev/pubsub/natspubsub v0.46.0
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.46.0
|
||||
golang.org/x/crypto v0.52.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/net v0.55.0
|
||||
golang.org/x/image v0.43.0
|
||||
golang.org/x/net v0.56.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.45.0
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/tools v0.45.0 // indirect
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.278.0
|
||||
google.golang.org/api v0.287.0
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
google.golang.org/grpc v1.81.1
|
||||
google.golang.org/protobuf v1.36.11
|
||||
@@ -123,16 +123,17 @@ require (
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
|
||||
github.com/arangodb/go-driver v1.6.9
|
||||
github.com/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.1
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.28
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
|
||||
github.com/cognusion/imaging v1.0.3
|
||||
github.com/cognusion/imaging v1.0.4
|
||||
github.com/fluent/fluent-logger-golang v1.10.1
|
||||
github.com/getsentry/sentry-go v0.44.1
|
||||
github.com/go-ldap/ldap/v3 v3.4.13
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7
|
||||
github.com/hashicorp/raft v1.7.3
|
||||
github.com/hashicorp/raft-boltdb/v2 v2.3.1
|
||||
github.com/hashicorp/vault/api v1.23.0
|
||||
@@ -145,19 +146,19 @@ require (
|
||||
github.com/rabbitmq/amqp091-go v1.11.0
|
||||
github.com/rclone/rclone v1.74.3
|
||||
github.com/rdleal/intervalst v1.5.0
|
||||
github.com/redis/go-redis/v9 v9.20.0
|
||||
github.com/schollz/progressbar/v3 v3.19.0
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
github.com/schollz/progressbar/v3 v3.19.1
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.3
|
||||
github.com/shirou/gopsutil/v4 v4.26.5
|
||||
github.com/tarantool/go-tarantool/v2 v2.4.2
|
||||
github.com/testcontainers/testcontainers-go v0.43.0
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.12
|
||||
go.uber.org/atomic v1.11.0
|
||||
golang.org/x/sync v0.21.0
|
||||
golang.org/x/sync v0.22.0
|
||||
golang.org/x/tools/godoc v0.1.0-deprecated
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0
|
||||
)
|
||||
@@ -180,7 +181,7 @@ require (
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
|
||||
github.com/apache/arrow-go/v18 v18.6.0 // indirect
|
||||
github.com/apache/thrift v0.23.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/bazelbuild/rules_go v0.46.0 // indirect
|
||||
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
|
||||
@@ -219,7 +220,6 @@ require (
|
||||
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
|
||||
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260331173834-036f908d0160 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
@@ -280,7 +280,7 @@ require (
|
||||
go.uber.org/mock v0.5.2 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/mod v0.36.0 // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
gonum.org/v1/gonum v0.17.0 // indirect
|
||||
)
|
||||
|
||||
@@ -292,10 +292,10 @@ require (
|
||||
cloud.google.com/go/iam v1.7.0 // indirect
|
||||
cloud.google.com/go/monitoring v1.24.3 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect
|
||||
@@ -319,21 +319,21 @@ require (
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3
|
||||
github.com/aws/smithy-go v1.27.2
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0
|
||||
github.com/aws/smithy-go v1.27.3
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/bradenaw/juniper v0.15.3 // indirect
|
||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||
@@ -381,7 +381,7 @@ require (
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
|
||||
github.com/google/s2a-go v0.1.9 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.17 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
@@ -420,8 +420,8 @@ require (
|
||||
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/nats-io/nats.go v1.48.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nats.go v1.49.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.15 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/ncw/swift/v2 v2.0.5 // indirect
|
||||
@@ -442,7 +442,7 @@ require (
|
||||
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/xattr v0.4.12 // indirect
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
|
||||
github.com/relvacode/iso8601 v1.7.0 // indirect
|
||||
@@ -492,10 +492,10 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.43.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
golang.org/x/term v0.43.0
|
||||
golang.org/x/term v0.45.0
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/validator.v2 v2.0.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
@@ -513,10 +513,12 @@ require (
|
||||
|
||||
// replace github.com/seaweedfs/raft => /Users/chrislu/go/src/github.com/seaweedfs/raft
|
||||
|
||||
// apache/thrift v0.23.0 uses math.MaxUint32 as an untyped int constant in
|
||||
// lib/go/thrift/framed_transport.go, which overflows int on 32-bit GOARCHes
|
||||
// (e.g. openbsd/arm, linux/arm). Pin to v0.22.0 until upstream fixes it.
|
||||
replace github.com/apache/thrift => github.com/apache/thrift v0.22.0
|
||||
// apache/thrift v0.23.0 fixes CVE-2026-41602 but compares int against the
|
||||
// untyped math.MaxUint32 in lib/go/thrift/framed_transport.go, which overflows
|
||||
// int on 32-bit GOARCHes (e.g. openbsd/arm, linux/arm) and fails to compile.
|
||||
// Upstream fixed the range check post-release; pin to that commit until the
|
||||
// next tagged release carries both the CVE fix and the 32-bit fix.
|
||||
replace github.com/apache/thrift => github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58
|
||||
|
||||
// tyler-smith/go-bip39 was deleted from GitHub, so `go mod download` fails for
|
||||
// anyone resolving it directly (GOPROXY=direct). It only reaches us transitively
|
||||
|
||||
@@ -553,12 +553,12 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
|
||||
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1 h1:jHb/wfvRikGdxMXYV3QG/SzUOPYN9KEUUuC0Yd0/vC0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.1/go.mod h1:pzBXCYn05zvYIrwLgtK8Ap8QcjRg+0i76tMQdWN6wOk=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0 h1:m/sWOGCREuSBqg2htVQTBY8nOZpyajYztF0vUvSZTuM=
|
||||
@@ -567,8 +567,8 @@ github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 h1:FbH3BbSb4bvGlu
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1/go.mod h1:9V2j0jn9jDEkCkv8w/bKTNppX/d0FVA1ud77xCIP4KA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0 h1:BM85pSYlVYQHdq00nxyPoOkyLF5NArJG3bOsrmbwr4k=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.7.0/go.mod h1:QYjP2cB7ZYtS/8jAbE0VSBZde/tjExqGjp+8JY6/+ts=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0 h1:irsmOWwkp0KCTTNS5e2hdFeIvSQClQo2No3IaNmL3Vw=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0/go.mod h1:GWcBkQj3MqN7ozHKLaCCAuNLiXoIGv2RtanfAwSjY/Y=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4 h1:tZh20RjgfMxKBxJiIS75iTVAKIUxrST5X2dVHMTptL4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.4/go.mod h1:vGYAk36rhMVCfTP7v+RVruCR0zmPe6S+36KRpDCLySw=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
@@ -683,8 +683,8 @@ github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUS
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op h1:Ucf+QxEKMbPogRO5guBNe5cgd9uZgfoJLOYs8WWhtjM=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0mDD1gk7o9BhI16b9p5yYAXRlidpqJE=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
|
||||
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
|
||||
github.com/apache/arrow-go/v18 v18.6.0 h1:GX/Jyd3R7mCLiECAwY9FWbbaYblie2WXBSz4Sw8fNpM=
|
||||
@@ -694,8 +694,8 @@ github.com/apache/cassandra-gocql-driver/v2 v2.1.2 h1:lu/p0Db2av18enHJvWJQoChLss
|
||||
github.com/apache/cassandra-gocql-driver/v2 v2.1.2/go.mod h1:QH/asJjB3mHvY6Dot6ZKMMpTcOrWJ8i9GhsvG1g0PK4=
|
||||
github.com/apache/iceberg-go v0.6.0 h1:tOVhC5BhBOEgPTowo5AVrPnAgsDo00qEbUPprFcLd4s=
|
||||
github.com/apache/iceberg-go v0.6.0/go.mod h1:kESfDlyaW/6hK0WW6TzA4EWps+0NMhhrDYE4qajVjlo=
|
||||
github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=
|
||||
github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=
|
||||
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58 h1:rDLE+tSW60VzRD7v5I+DU22Mjhmm+mfLc5Xl5dHkx6w=
|
||||
github.com/apache/thrift v0.23.1-0.20260429145742-d2acd3c49e58/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3 h1:WZaTKNHCfcw7fWSR6/RKnCldVzvYZC+Y20Su4lffEIg=
|
||||
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU=
|
||||
@@ -709,50 +709,50 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
|
||||
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0 h1:XvXMJTkFQtpBKIWZnmr9ZEOc2InWM2yldjXEJ/bymhA=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.0/go.mod h1:27+ACypSLljLAEKsCYOmrjKh83vuTRkuAe9Uv/3A4bg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.1 h1:9eOTgu1z/dVtYpNZ3/8/XbbaX0x/BqE3HUzAzs6K0ek=
|
||||
github.com/aws/aws-sdk-go-v2 v1.42.1/go.mod h1:5pKeft2eJj+gElQ38Jqg4ibCqh+/AK33/0X3hip7IjM=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25 h1:ACCejvStYoilgwrfegSt5ZntCbPrk52qfwyNcnl3omM=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.25/go.mod h1:LJyU8sDRbXUxFn8xMJIGP+v9QYYwveNLI8a/giAOiAs=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24 h1:2hQqYCV9yqyePQ9o6dCrZc/zO8U3TwPr9mIKlZnPu/I=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.24/go.mod h1:IDwpACtwqHLISdzfwUUNq4P9DsB/h5BLg4FwJPNfqFY=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29 h1:r6qZHbT+wxgWO/e9vYNUEtg7lv5+UN3pRqKhLXvnArg=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.29/go.mod h1:QRnaRcTVGKPGRy8w78HMQtKUGRYcnMZAANATkeVA6Mo=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.28 h1:zTXJSsNcoO91/mTXsZoYf0AK8dvNPiA58/VtyGXR+wM=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.28/go.mod h1:Kd9E0JzDBW/q1xbsHFrev/GnbAf5J0Ng8xoyc7HZ91Q=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 h1:/hi1JADLEW9YYryEz1w4GQu0EtP23pP553Cf9KgsDV4=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30/go.mod h1:/3AOgy4K17Dm4ucMZVC/MJkzy5kmfKUcINRHZyo0koQ=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 h1:uMC4oL6G3MNhodo358QEqSDjrgvzV3TUQ58nyQSGq2E=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13/go.mod h1:Cer86AE2686DvVUe57LPve3jUBmbujuaonSX8pNzGgw=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29 h1:f3vKqSo13fhTYb+JEcXwXefZQE26I1FB5eTSniU67ko=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.29/go.mod h1:MzoLFUArKGpGD+ukmPiTPG1X5x4o6M2kq4v2dr1FiEc=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29 h1:RdwIf/CuUsvJX3RgJagbOyotl/cxoLY4xviKuE7p2GY=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.29/go.mod h1:71wt8W2EgswdZy9Mf9KNnzxZ3TiZlv4caKghPktDOkA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30 h1:VTGy885W5DKBxWRUJbym9hytNaYzsyaPkCHGRRMAOhU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.30/go.mod h1:AS0HycUvJRFvTt613AYDOgO2jzw+00cVSMny8XB3yMY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12 h1:ZD2+BSw9vFsNlKYIasSNt3uDbjqqXIBcM13UJv/Lx2k=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.12/go.mod h1:Ms4zlcVBbXbiP7EVLhl+lgjvA/a7YphqQ3Ih3174EmI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 h1:xM/Is9cKMHa8Jj8zkvWhvrFkZsXJV9E+BB4g0HW0duQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30/go.mod h1:WueJeNDZvK1fMYEWJIkcivBfEzUkTpBhzlrUKKY8EuA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 h1:jn46zC9LdsVR/ZpMIJqMqb8hHv31BlLx3ulVqNspUOk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30/go.mod h1:1hTMsAgbdS/AtUi4bw8+gUuh1pceo+eXRLfpSuSQj3M=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 h1:3GUprIsfmGcC5SACIyB0e7E0BM1O1b3Erl5CePYIAeQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31/go.mod h1:7PuV1yl5e2xnUbm+RqvVg5i2iBM8EyijZNoI9wsOoOc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 h1:mbRIur/BiHK6SKPjoBIXSE/hJ6g6JGRLuxQy1jGjlN4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13/go.mod h1:ITg9em2KbJx1s0y4aqRX5OYWG6HBZ5TVR//OdpEZ2CQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29 h1:DRebniUGZ2MqiiIVmQJ04vIXr918hubdHMnarSLEWyU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.29/go.mod h1:LfRkPCD8YHDM2E5eTkos2UpwYeZnBcVarTa8L59bJHA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 h1:/Z5jmNrKsSD7EmDjzAPsm/3L9IuOkzaynklJZ1qX7S4=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30/go.mod h1:lEzEZnOosE7zi8Z6royW1cFJTD9fpab4Ul1SBrllewk=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0 h1:3nXpRcFwRCW8n7HgO2QGy0Dc20eQNfBuUemGQhpF8m8=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.2.0/go.mod h1:LxYujSTLPRlp2vTtcUO/+1ilrew8ytt6SvQyOgejzFQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 h1:sLzmJGCMv+C8KqiJgEqDLB6vxaJGmobRh4rr//ZpA3w=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.4.0/go.mod h1:mxC0nT/C8wMMS97DemZPzvUZxvIt+2Iq+eS3JdFZGgg=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14 h1:p8WdWDh5AwSZdp19Haa3XMyPCICi9Z375a/Nu3IIEZY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.39.14/go.mod h1:NKVY7DER6VXHkt2I/ycmHakALNboi3Rqwt4eEf/1Cnk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24 h1:JP2wjWGmUp8lTCZb13Dv0Eciyc1jbO8pd0HZVMHFlrc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.24/go.mod h1:Ql9ziDutk8ERAN9HMaYANCW3lop451ppebkxEJMLCTM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3 h1:ey1XLTYXb9PcLt4535632o5kCGXNXEhNb620Dqwuylo=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.31.3/go.mod h1:Lk7PlmoTYryQmyBG0EXqj5BcUbj3whXdU2s3yGI3EAc=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6 h1:yLr03zQE/5Eu5l3QU0Si+xMbLMbSDF2YXsigqXngs6g=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.6/go.mod h1:Q5N6icH+KJZDLh+ESNwzdv6cZ6vLFF/egy3IOxWhmz4=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3 h1:VrIhKRCSK1umelSgB9RghvA9RTUYeQffyAS5ApXehNI=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.43.3/go.mod h1:r8wkDOuLaaMFqFiYAb8dGY2A3gJCOujMc6CFOVC4Zhc=
|
||||
github.com/aws/smithy-go v1.27.2 h1:y9NPmSE6am6LjEFPfqHqG/jJk7AauQvhCJONKh7kpzk=
|
||||
github.com/aws/smithy-go v1.27.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 h1:qjMmry/cBDee1E/2gyvel0uRYCi3mwRZ2hf6N+GAodo=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.32.0/go.mod h1:u8af9Nqkmqnr96f7v9nHqzZT9XBwbXEkTiqT4ROuJSE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 h1:fpOlDPI55HdszaxapEGk6HsGosOUaM2YPWJpjMgp8UI=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0/go.mod h1:DMPWJBjYs6+3+f/qhBFEFPPlQ6NlhWjai3dJNvipJ84=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0 h1:bLZ0PolJ8J+HkJHztcXORUpHXBye2U8298lCEMi6ZCU=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.44.0/go.mod h1:9gdl4RrflIdpDb2TlXshWgR1F9TeCkvqDx77Vpr4Z/Q=
|
||||
github.com/aws/smithy-go v1.27.3 h1:F3Zb497UhhskkfpJmfkXswyo+t0sh9OTBnIHjogWbVY=
|
||||
github.com/aws/smithy-go v1.27.3/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
|
||||
@@ -860,8 +860,8 @@ github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwP
|
||||
github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
|
||||
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2 h1:8Vfw2iNEpYIV6aLtMwT5UOGuPmp9MKlEKWKFTuB+MPU=
|
||||
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2/go.mod h1:P9WiZOdQ1R/ZZDL0WzF5wlyRvrjtfhNOwMZymFpBwjE=
|
||||
github.com/cognusion/imaging v1.0.3 h1:nHyIeEVDV8JkBbuhgx8iSBW72W8rHbDEyruA0Jh7Lnk=
|
||||
github.com/cognusion/imaging v1.0.3/go.mod h1:38tFLFhGK81ORThZG8dVXPtp1uhd+3xM1WXuMn+unOA=
|
||||
github.com/cognusion/imaging v1.0.4 h1:hrmWVa4S9fiLJJFKEHYYRNBUnHEKZD8/oxnC77xTUa0=
|
||||
github.com/cognusion/imaging v1.0.4/go.mod h1:X1mPSSZpMyiva54chCO/1NROp+b6xG4uMcud8VLii+U=
|
||||
github.com/colinmarc/hdfs/v2 v2.4.0 h1:v6R8oBx/Wu9fHpdPoJJjpGSUxo8NhHIwrwsfhFvU9W0=
|
||||
github.com/colinmarc/hdfs/v2 v2.4.0/go.mod h1:0NAO+/3knbMx6+5pCv+Hcbaz4xn/Zzbn9+WIib2rKVI=
|
||||
github.com/compose-spec/compose-go/v2 v2.10.2 h1:USa1NUbDcl/cjb8T9iwnuFsnO79H+2ho2L5SjFKz3uI=
|
||||
@@ -1102,8 +1102,8 @@ github.com/go-redis/redis/v7 v7.4.1 h1:PASvf36gyUpr2zdOUS/9Zqc80GbM+9BDyiJSJDDOr
|
||||
github.com/go-redis/redis/v7 v7.4.1/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/go-redsync/redsync/v4 v4.16.0 h1:bNcOzeHH9d3s6pghU9NJFMPrQa41f5Nx3L4YKr3BdEU=
|
||||
github.com/go-redsync/redsync/v4 v4.16.0/go.mod h1:V4gagqgyASWBZuwx4xGzu72aZNb/6Mo05byUa3mVmKQ=
|
||||
github.com/go-redsync/redsync/v4 v4.17.0 h1:FFJ+uxZs44y4Sq10//IFKic9T94AYl+u3Sog98AHzBo=
|
||||
github.com/go-redsync/redsync/v4 v4.17.0/go.mod h1:CKVA6qwT07S/916i+Yd9h1/8YFQhCCpPYTQhvvYytJo=
|
||||
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
|
||||
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
|
||||
@@ -1260,8 +1260,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.1.0/go.mod h1:17drOmN3MwGY
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.2.1/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.15 h1:xolVQTEXusUcAA5UgtyRLjelpFFHWlPQ4XfWGc7MBas=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.15/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.17 h1:73NfMHdiqo9JFU9+7a5ExpVa10/R29pXfZIaW559nrg=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.17/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k=
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0=
|
||||
@@ -1379,8 +1379,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
||||
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
|
||||
@@ -1516,8 +1516,8 @@ github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stg
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.22 h1:76lXsPn6FyHtTY+jt2fTTvsMUCZq1k0qwRsAMuxzKAk=
|
||||
@@ -1591,14 +1591,14 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/nats-io/jwt/v2 v2.8.0 h1:K7uzyz50+yGZDO5o772eRE7atlcSEENpL7P+b74JV1g=
|
||||
github.com/nats-io/jwt/v2 v2.8.0/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
|
||||
github.com/nats-io/nats-server/v2 v2.11.12 h1:jGDXTkcjqQ5fCRstwIxvv1K0RHfftFUoSCT/iIZcqOc=
|
||||
github.com/nats-io/nats-server/v2 v2.11.12/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=
|
||||
github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
|
||||
github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
|
||||
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
|
||||
github.com/nats-io/nats-server/v2 v2.11.15 h1:StSf9TINInaZtr4oww2+kXmfwa9SkN//g/LwS19/UJ0=
|
||||
github.com/nats-io/nats-server/v2 v2.11.15/go.mod h1:zwhv8Y0PE3KHyKgznJc/9Xoai638SaJd83zzJ5GJn74=
|
||||
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
|
||||
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
|
||||
github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
|
||||
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
@@ -1763,12 +1763,12 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
github.com/rdleal/intervalst v1.5.0/go.mod h1:xO89Z6BC+LQDH+IPQQw/OESt5UADgFD41tYMUINGpxQ=
|
||||
github.com/redis/go-redis/v9 v9.20.0 h1:WnQYxLkgO2xiXTCJY0ldIiI8dNqCDlQAG+AtaH7a2a0=
|
||||
github.com/redis/go-redis/v9 v9.20.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/redis/rueidis v1.0.71 h1:pODtnAR5GAB7j4ekhldZ29HKOxe4Hph0GTDGk1ayEQY=
|
||||
github.com/redis/rueidis v1.0.71/go.mod h1:lfdcZzJ1oKGKL37vh9fO3ymwt+0TdjkkUCJxbgpmcgQ=
|
||||
github.com/redis/rueidis/rueidiscompat v1.0.71 h1:wNZ//kEjMZgBM0KCk7ncOX8KmAgROU2kDdDNpwheG4w=
|
||||
github.com/redis/rueidis/rueidiscompat v1.0.71/go.mod h1:esmCLJvaRzZoKlgB82G1bY7Iky5TnO9Rz+NlhbEccFI=
|
||||
github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
|
||||
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/redis/rueidis v1.0.76 h1:RdDWuvlYBSp+bTrBvaXqJnNEL3VVzsnjo+0psPFgLc4=
|
||||
github.com/redis/rueidis v1.0.76/go.mod h1:UsfHPSbomB6QAVMk4iiFkzRy0nh9o7scDGa+SitvBY4=
|
||||
github.com/redis/rueidis/rueidiscompat v1.0.76 h1:7LikbiqCQqCsZXeZ+akgZMnjIV/J0VHih9PIX4gGZC4=
|
||||
github.com/redis/rueidis/rueidiscompat v1.0.76/go.mod h1:UatQQLVj4QMIsZtpvRWY28qm6r2d72idhcS+C/RM+Zg=
|
||||
github.com/rekby/fixenv v0.3.2/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c=
|
||||
github.com/rekby/fixenv v0.6.1 h1:jUFiSPpajT4WY2cYuc++7Y1zWrnCxnovGCIX72PZniM=
|
||||
github.com/rekby/fixenv v0.6.1/go.mod h1:/b5LRc06BYJtslRtHKxsPWFT/ySpHV+rWvzTg+XWk4c=
|
||||
@@ -1804,8 +1804,8 @@ github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 h1:PKK9DyHxif4LZo+uQSgXNqs0jj5+x
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0=
|
||||
github.com/sasha-s/go-deadlock v0.3.1/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM=
|
||||
github.com/schollz/progressbar/v3 v3.19.0 h1:Ea18xuIRQXLAUidVDox3AbwfUhD0/1IvohyTutOIFoc=
|
||||
github.com/schollz/progressbar/v3 v3.19.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
|
||||
github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vPZYa2EdrU=
|
||||
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.3 h1:rJufGrHImTx7yoGUmetUi+To4LrmTQJROJnBHWt92ic=
|
||||
@@ -2028,12 +2028,12 @@ github.com/ydb-platform/ydb-go-genproto v0.0.0-20221215182650-986f9d10542f/go.mo
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20230528143953-42c825ace222/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260428144813-1c07baab7f7b h1:xeiobG1riqe6dTMZuTcOvwOY0BbFidSk3gRLyVeLfJA=
|
||||
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260428144813-1c07baab7f7b/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1 h1:XaRxeVrOyl3y6v9CiYMWaFdZ6zevvYe+TRxOR8ifa2s=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2 h1:e2nGQPGC5OEPBWlMnLPFpdgyqNA8iTOPiZShCrv6944=
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.44.0/go.mod h1:oSLwnuilwIpaF5bJJMAofnGgzPJusoI3zWMNb8I+GnM=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.47.3/go.mod h1:bWnOIcUHd7+Sl7DN+yhyY1H/I61z53GczvwJgXMgvj0=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0 h1:VLrLlCEk21r9PgiH5Hkm0/ACad9gEDMjFUxVWY8wWOw=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.141.0/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0 h1:kCrI6EtKLeuFCNJzDeweUZf+wKB3ms4TJL3aWnkTV0c=
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.143.0/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.1 h1:qw3Fa+T81+Kpu5Io2vYHJOwcrYrVjgJlT6t/0dOXJrA=
|
||||
github.com/ydb-platform/ydb-go-yc v0.12.1/go.mod h1:t/ZA4ECdgPWjAb4jyDe8AzQZB5dhpGbi3iCahFaNwBY=
|
||||
github.com/ydb-platform/ydb-go-yc-metadata v0.6.1 h1:9E5q8Nsy2RiJMZDNVy0A3KUrIMBPakJ2VgloeWbcI84=
|
||||
@@ -2152,8 +2152,8 @@ go.yaml.in/yaml/v4 v4.0.0-rc.4 h1:UP4+v6fFrBIb1l934bDl//mmnoIZEDK0idg1+AIvX5U=
|
||||
go.yaml.in/yaml/v4 v4.0.0-rc.4/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
|
||||
gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
|
||||
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
|
||||
gocloud.dev/pubsub/natspubsub v0.45.0 h1:kfCupVejeynIQcS1GaIvkY3Nj/acLlM5yPWyxZN8wJ8=
|
||||
gocloud.dev/pubsub/natspubsub v0.45.0/go.mod h1:WU5SMDWuF7CCr2U8UpbrEONYYFOmvigCAvTpOOpUvYE=
|
||||
gocloud.dev/pubsub/natspubsub v0.46.0 h1:cTmJnWOmhb3dYRzX7PvNkq2m5mQdBLFFxZbl/21pfjk=
|
||||
gocloud.dev/pubsub/natspubsub v0.46.0/go.mod h1:hbEEsNt6mGQoonGQi39VOjHfx2f13DOmWouh4hGsfrU=
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.46.0 h1:uWJ8z/F8xYxoTlBafTweoKvX2V85cwtN+/+nyRRtjZ0=
|
||||
gocloud.dev/pubsub/rabbitpubsub v0.46.0/go.mod h1:Ef5XHxv17zV9B3U9xoYAqJ8Rutslxt5Emb5e1cScuXc=
|
||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||
@@ -2179,8 +2179,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
@@ -2211,8 +2211,8 @@ golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeap
|
||||
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
|
||||
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
@@ -2246,8 +2246,8 @@ golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
|
||||
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@@ -2315,8 +2315,8 @@ golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -2368,8 +2368,8 @@ golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -2474,8 +2474,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
@@ -2492,8 +2492,8 @@ golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -2514,8 +2514,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -2593,8 +2593,8 @@ golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/tools/godoc v0.1.0-deprecated h1:o+aZ1BOj6Hsx/GBdJO/s815sqftjSnrZZwyYTHODvtk=
|
||||
golang.org/x/tools/godoc v0.1.0-deprecated/go.mod h1:qM63CriJ961IHWmnWa9CjZnBndniPt4a3CK0PVB9bIg=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -2672,8 +2672,8 @@ google.golang.org/api v0.106.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/
|
||||
google.golang.org/api v0.107.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY=
|
||||
google.golang.org/api v0.108.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY=
|
||||
google.golang.org/api v0.110.0/go.mod h1:7FC4Vvx1Mooxh8C5HWjzZHcavuS2f6pmJpZx60ca7iI=
|
||||
google.golang.org/api v0.278.0 h1:W7jiRvRi53VYFfZ/HoZjQBtJk7gOFbHD8ot1RzVZU6E=
|
||||
google.golang.org/api v0.278.0/go.mod h1:B9TqLBwJqVjp1mtt7WeoQwWRwvu/400y5lETOql+giQ=
|
||||
google.golang.org/api v0.287.0 h1:CQDMqUiqZZ0U/Yge3zyjAhNQ0OSYEH0PaA7l4xtEen4=
|
||||
google.golang.org/api v0.287.0/go.mod h1:pPW85yt3Iuc3unkpaMhFtMmOqnTdCwCqEOaUlnuxRlQ=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
@@ -2811,8 +2811,8 @@ google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgn
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 h1:tEkOQcXgF6dH1G+MVKZrfpYvozGrzb91k6ha7jireSM=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d h1:mpAgMyM9vQHxycBlDq50y1VHpfSfVwzXvrQKtYbXuUY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.37"
|
||||
appVersion: "4.40"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.37.0
|
||||
version: 4.40.0
|
||||
@@ -29,6 +29,11 @@ spec:
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.certificates.ipAddresses }}
|
||||
ipAddresses:
|
||||
{{- range .Values.certificates.ipAddresses }}
|
||||
|
||||
@@ -23,6 +23,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -28,6 +28,11 @@ spec:
|
||||
- '*.{{ .Release.Namespace }}'
|
||||
- '*.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ .Release.Namespace }}.svc'
|
||||
|
||||
@@ -29,6 +29,11 @@ spec:
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-worker.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
{{- if .Values.certificates.dnsNames }}
|
||||
{{- range .Values.certificates.dnsNames }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.certificates.ipAddresses }}
|
||||
ipAddresses:
|
||||
{{- range .Values.certificates.ipAddresses }}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
{{- /* Traefik IngressRouteTCP for the filer gRPC port. Rendered instead of the
|
||||
standard Ingress when the gRPC ingress className starts with "traefik",
|
||||
since a Kubernetes Ingress can't do raw TCP/gRPC passthrough.
|
||||
|
||||
global.seaweedfs.enableSecurity controls the mode:
|
||||
false: plain TCP, Traefik forwards h2c to the pod. A non-TLS TCP
|
||||
router can only match HostSNI(`*`) (SNI needs TLS).
|
||||
true: TLS passthrough, matched by SNI so it can route on the host. */}}
|
||||
|
||||
{{- $filerEnabled := or .Values.filer.enabled .Values.allInOne.enabled }}
|
||||
{{- $isTraefik := hasPrefix "traefik" (default "" .Values.filer.ingresses.grpc.className) }}
|
||||
{{- $securityEnabled := .Values.global.seaweedfs.enableSecurity }}
|
||||
|
||||
{{- if and $filerEnabled .Values.filer.ingresses.grpc.enabled $isTraefik }}
|
||||
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRouteTCP
|
||||
metadata:
|
||||
name: {{ include "seaweedfs.fullname" . }}-filer-grpc
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/component: filer
|
||||
spec:
|
||||
{{- if $securityEnabled }}
|
||||
tls:
|
||||
passthrough: true
|
||||
{{- end }}
|
||||
entryPoints:
|
||||
{{- with .Values.filer.ingresses.grpc.entryPoint }}
|
||||
- {{ . | quote }}
|
||||
{{- else }}
|
||||
- filer-grpc
|
||||
{{- end }}
|
||||
routes:
|
||||
{{- if $securityEnabled }}
|
||||
- match: HostSNI(`{{ .Values.filer.ingresses.grpc.host }}`)
|
||||
{{- else }}
|
||||
- match: HostSNI(`*`)
|
||||
{{- end }}
|
||||
services:
|
||||
- name: {{ $serviceName }}
|
||||
port: {{ .Values.filer.grpcPort }}
|
||||
{{- end }}
|
||||
@@ -1,6 +1,8 @@
|
||||
{{- /* Filer ingress works for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
|
||||
{{- /* Filer ingresses work for both normal mode (filer.enabled) and all-in-one mode (allInOne.enabled) */}}
|
||||
{{- $filerEnabled := or .Values.filer.enabled .Values.allInOne.enabled }}
|
||||
{{- if and $filerEnabled .Values.filer.ingress.enabled }}
|
||||
|
||||
{{- /* HTTP Ingress */}}
|
||||
{{- if and $filerEnabled .Values.filer.ingresses.http.enabled }}
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
@@ -12,10 +14,13 @@ apiVersion: extensions/v1beta1
|
||||
{{- end }}
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-http
|
||||
namespace: {{ .Release.Namespace }}
|
||||
{{- with .Values.filer.ingress.annotations }}
|
||||
annotations:
|
||||
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.http.className }}
|
||||
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.http.className }}
|
||||
{{- end }}
|
||||
{{- with .Values.filer.ingresses.http.annotations }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
labels:
|
||||
@@ -25,14 +30,21 @@ metadata:
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/component: filer
|
||||
spec:
|
||||
ingressClassName: {{ .Values.filer.ingress.className | quote }}
|
||||
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.http.className }}
|
||||
ingressClassName: {{ .Values.filer.ingresses.http.className | quote }}
|
||||
{{- end }}
|
||||
tls:
|
||||
{{ .Values.filer.ingress.tls | default list | toYaml | nindent 6}}
|
||||
{{ .Values.filer.ingresses.http.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
- http:
|
||||
- {{- if .Values.filer.ingresses.http.host }}
|
||||
host: {{ .Values.filer.ingresses.http.host | quote }}
|
||||
{{- end }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ .Values.filer.ingress.path | quote }}
|
||||
pathType: {{ .Values.filer.ingress.pathType | quote }}
|
||||
- path: {{ .Values.filer.ingresses.http.path | quote }}
|
||||
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
pathType: {{ .Values.filer.ingresses.http.pathType | quote }}
|
||||
{{- end }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
@@ -43,7 +55,62 @@ spec:
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ .Values.filer.port }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.ingress.host }}
|
||||
host: {{ .Values.filer.ingress.host }}
|
||||
{{- end }}
|
||||
|
||||
---
|
||||
|
||||
{{- /* gRPC Ingress (standard Kubernetes Ingress, NOT for Traefik) */}}
|
||||
{{- if and $filerEnabled .Values.filer.ingresses.grpc.enabled (not (hasPrefix "traefik" (default "" .Values.filer.ingresses.grpc.className))) }}
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "filer")) .Values.allInOne.enabled }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1beta1
|
||||
{{- else }}
|
||||
apiVersion: extensions/v1beta1
|
||||
{{- end }}
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: ingress-{{ include "seaweedfs.fullname" . }}-filer-grpc
|
||||
namespace: {{ .Release.Namespace }}
|
||||
annotations:
|
||||
{{- if and (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) .Values.filer.ingresses.grpc.className }}
|
||||
kubernetes.io/ingress.class: {{ .Values.filer.ingresses.grpc.className }}
|
||||
{{- end }}
|
||||
{{- with .Values.filer.ingresses.grpc.annotations }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/component: filer
|
||||
spec:
|
||||
{{- if and (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) .Values.filer.ingresses.grpc.className }}
|
||||
ingressClassName: {{ .Values.filer.ingresses.grpc.className | quote }}
|
||||
{{- end }}
|
||||
tls:
|
||||
{{ .Values.filer.ingresses.grpc.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
- {{- if .Values.filer.ingresses.grpc.host }}
|
||||
host: {{ .Values.filer.ingresses.grpc.host | quote }}
|
||||
{{- end }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ .Values.filer.ingresses.grpc.path | quote }}
|
||||
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
pathType: {{ .Values.filer.ingresses.grpc.pathType | quote }}
|
||||
{{- end }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
name: {{ $serviceName }}
|
||||
port:
|
||||
number: {{ .Values.filer.grpcPort }}
|
||||
{{- else }}
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ .Values.filer.grpcPort }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -2,8 +2,6 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
annotations:
|
||||
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
|
||||
name: {{ include "seaweedfs.componentName" (list . "filer") }}
|
||||
namespace: {{ .Release.Namespace }}
|
||||
labels:
|
||||
@@ -12,8 +10,9 @@ metadata:
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/component: filer
|
||||
{{- if .Values.filer.annotations }}
|
||||
annotations:
|
||||
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
|
||||
{{- if .Values.filer.annotations }}
|
||||
{{- toYaml .Values.filer.annotations | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
|
||||
@@ -824,30 +824,50 @@ filer:
|
||||
# allowPrivilegeEscalation: false
|
||||
containerSecurityContext: {}
|
||||
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/sw-filer/?(.*)"
|
||||
pathType: ImplementationSpecific
|
||||
annotations: {}
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
|
||||
# nginx.ingress.kubernetes.io/auth-type: "basic"
|
||||
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
|
||||
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
|
||||
# nginx.ingress.kubernetes.io/service-upstream: "true"
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /$1
|
||||
# nginx.ingress.kubernetes.io/use-regex: "true"
|
||||
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
|
||||
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/configuration-snippet: |
|
||||
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
|
||||
# sub_filter '="/' '="./'; #make absolute paths to relative
|
||||
# sub_filter '=/' '=./';
|
||||
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
|
||||
# sub_filter_once off;
|
||||
ingresses:
|
||||
http:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/sw-filer/?(.*)"
|
||||
pathType: ImplementationSpecific
|
||||
annotations: {}
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: GRPC
|
||||
# nginx.ingress.kubernetes.io/auth-type: "basic"
|
||||
# nginx.ingress.kubernetes.io/auth-secret: "default/ingress-basic-auth-secret"
|
||||
# nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - SW-Filer'
|
||||
# nginx.ingress.kubernetes.io/service-upstream: "true"
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /$1
|
||||
# nginx.ingress.kubernetes.io/use-regex: "true"
|
||||
# nginx.ingress.kubernetes.io/enable-rewrite-log: "true"
|
||||
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
|
||||
# nginx.ingress.kubernetes.io/configuration-snippet: |
|
||||
# sub_filter '<head>' '<head> <base href="/sw-filer/">'; #add base url
|
||||
# sub_filter '="/' '="./'; #make absolute paths to relative
|
||||
# sub_filter '=/' '=./';
|
||||
# sub_filter '/seaweedfsstatic' './seaweedfsstatic';
|
||||
# sub_filter_once off;
|
||||
tls: []
|
||||
grpc:
|
||||
enabled: false
|
||||
className: ""
|
||||
host: "seaweedfs.cluster.local"
|
||||
# gRPC methods are called at /<package>.<Service>/<Method>, so route the
|
||||
# whole host, not the HTTP UI's regex path.
|
||||
path: "/"
|
||||
pathType: Prefix
|
||||
annotations:
|
||||
# Ingress terminates TLS and re-originates gRPC (HTTP/2) to the filer.
|
||||
nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
|
||||
# For end-to-end mTLS (the filer's own TLS reaches the client, not
|
||||
# terminated at the edge), drop backend-protocol above and use TLS
|
||||
# passthrough instead:
|
||||
# nginx.ingress.kubernetes.io/ssl-passthrough: "true"
|
||||
# Passthrough routes by SNI (set `host` above), ignores `path`, and
|
||||
# requires ingress-nginx to run with --enable-ssl-passthrough.
|
||||
tls: []
|
||||
|
||||
# extraEnvVars is a list of extra environment variables to set with the stateful set.
|
||||
extraEnvironmentVars:
|
||||
@@ -1745,6 +1765,7 @@ cosi:
|
||||
|
||||
certificates:
|
||||
commonName: "SeaweedFS CA"
|
||||
dnsNames: []
|
||||
ipAddresses: []
|
||||
keyAlgorithm: RSA
|
||||
keySize: 2048
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
<groupId>com.seaweedfs</groupId>
|
||||
<artifactId>seaweedfs-client</artifactId>
|
||||
<version>4.00</version>
|
||||
<version>4.38</version>
|
||||
|
||||
<name>SeaweedFS Java Client</name>
|
||||
<description>A java client for SeaweedFS.</description>
|
||||
@@ -133,7 +133,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-gpg-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>sign-artifacts</id>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import io.grpc.CallOptions;
|
||||
import io.grpc.Channel;
|
||||
import io.grpc.ClientCall;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.ForwardingClientCall;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
|
||||
// Adds an HTTP Basic Auth "Authorization" header to every gRPC call so the filer can be
|
||||
// reached through an Nginx reverse proxy with auth_basic enabled.
|
||||
public class BasicAuthInterceptor implements ClientInterceptor {
|
||||
|
||||
private static final Metadata.Key<String> AUTHORIZATION_KEY =
|
||||
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
|
||||
|
||||
private final String headerValue;
|
||||
|
||||
public BasicAuthInterceptor(String headerValue) {
|
||||
this.headerValue = headerValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
|
||||
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
|
||||
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
|
||||
@Override
|
||||
public void start(Listener<RespT> responseListener, Metadata headers) {
|
||||
headers.put(AUTHORIZATION_KEY, headerValue);
|
||||
super.start(responseListener, headers);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class FilerGrpcClient {
|
||||
@@ -37,6 +38,8 @@ public class FilerGrpcClient {
|
||||
public final Map<String, FilerProto.Locations> vidLocations = new HashMap<>();
|
||||
protected int randomClientId;
|
||||
|
||||
private static final AtomicBoolean plaintextBasicAuthWarned = new AtomicBoolean(false);
|
||||
|
||||
// Connection pool to handle concurrent requests
|
||||
private static final int CHANNEL_POOL_SIZE = 4;
|
||||
private final List<ManagedChannel> channelPool;
|
||||
@@ -99,6 +102,14 @@ public class FilerGrpcClient {
|
||||
builder.overrideAuthority(cn);
|
||||
}
|
||||
}
|
||||
|
||||
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
if (basicAuthHeader != null) {
|
||||
if (sslContext == null && plaintextBasicAuthWarned.compareAndSet(false, true)) {
|
||||
logger.warn("Basic Auth is enabled on a plaintext gRPC channel; credentials are sent in cleartext. Use TLS to the proxy.");
|
||||
}
|
||||
builder.intercept(new BasicAuthInterceptor(basicAuthHeader));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,12 @@ import org.slf4j.LoggerFactory;
|
||||
import javax.net.ssl.*;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Base64;
|
||||
|
||||
public abstract class FilerSecurityContext extends SslContext {
|
||||
//extends Netty SslContext to access its protected static utility methods in
|
||||
@@ -36,6 +38,11 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
private static String httpClientCertChainFilePath;
|
||||
private static String httpClientPrivateKeyFilePath;
|
||||
|
||||
// Optional HTTP Basic Auth for reaching SeaweedFS through an Nginx reverse proxy
|
||||
// that has auth_basic enabled. Applied to both the filer gRPC channel and the
|
||||
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
|
||||
private static volatile String basicAuthHeaderValue;
|
||||
|
||||
|
||||
static {
|
||||
String securityFileName = "security.toml";
|
||||
@@ -55,6 +62,9 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
Toml toml = new Toml().read(securityFile);
|
||||
logger.debug("reading ssl setup from {}", securityFile);
|
||||
|
||||
basicAuthHeaderValue = computeBasicAuthHeaderValue(
|
||||
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
|
||||
|
||||
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
|
||||
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
|
||||
grpcClientCertChainFilePath = toml.getString("grpc.client.cert");
|
||||
@@ -120,6 +130,30 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
return httpSslContext;
|
||||
}
|
||||
|
||||
// Configure HTTP Basic Auth programmatically instead of via security.toml. Must be
|
||||
// called before constructing a FilerClient so the credentials reach the gRPC channel.
|
||||
public static void setBasicAuth(String username, String password) {
|
||||
basicAuthHeaderValue = computeBasicAuthHeaderValue(username, password);
|
||||
}
|
||||
|
||||
public static boolean isBasicAuthEnabled() {
|
||||
return basicAuthHeaderValue != null;
|
||||
}
|
||||
|
||||
// Returns the "Basic <base64(user:password)>" Authorization header value, or null
|
||||
// when no Basic Auth credentials are configured.
|
||||
public static String getBasicAuthHeaderValue() {
|
||||
return basicAuthHeaderValue;
|
||||
}
|
||||
|
||||
private static String computeBasicAuthHeaderValue(String username, String password) {
|
||||
if (Strings.isNullOrEmpty(username)) {
|
||||
return null;
|
||||
}
|
||||
String credentials = username + ":" + (password == null ? "" : password);
|
||||
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static SslContext buildGrpcSslContext() throws SSLException {
|
||||
SslContextBuilder builder = GrpcSslContexts.forClient();
|
||||
if (grpcTrustCertCollectionFilePath != null) {
|
||||
|
||||
@@ -111,10 +111,18 @@ public class SeaweedRead {
|
||||
}
|
||||
|
||||
int len = (int) chunkView.size - (int) (startOffset - chunkView.logicOffset);
|
||||
int srcOffset = (int) (startOffset - chunkView.logicOffset + chunkView.offset);
|
||||
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} chunkView[{};{}) startOffset:{}",
|
||||
chunkView.fileId, chunkData.length, chunkView.offset, chunkView.logicOffset,
|
||||
chunkView.logicOffset + chunkView.size, startOffset);
|
||||
buf.put(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), len);
|
||||
// The fetched chunk can be shorter than the view claims when a read briefly
|
||||
// returns an empty body (seen right after an append). Fail clearly instead of
|
||||
// letting ByteBuffer.put throw an opaque IndexOutOfBoundsException.
|
||||
if (srcOffset < 0 || len < 0 || srcOffset > chunkData.length - len) {
|
||||
throw new IOException("chunk " + chunkView.fileId + " returned " + chunkData.length
|
||||
+ " bytes, need [" + srcOffset + "," + ((long) srcOffset + len) + ")");
|
||||
}
|
||||
buf.put(chunkData, srcOffset, len);
|
||||
|
||||
return len;
|
||||
}
|
||||
@@ -128,7 +136,15 @@ public class SeaweedRead {
|
||||
for (FilerProto.Location location : locations.getLocationsList()) {
|
||||
String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl());
|
||||
try {
|
||||
data = doFetchOneFullChunkData(chunkView, url);
|
||||
byte[] fetched = doFetchOneFullChunkData(chunkView, url);
|
||||
// An empty (or null) body for a chunk we are reading from is never
|
||||
// valid; treat it as a transient failure so the retry loop tries
|
||||
// another location and backs off, rather than caching an empty chunk.
|
||||
if (fetched == null || fetched.length == 0) {
|
||||
lastException = new IOException("empty or null response for chunk " + chunkView.fileId + " from " + url);
|
||||
continue;
|
||||
}
|
||||
data = fetched;
|
||||
lastException = null;
|
||||
break;
|
||||
} catch (IOException ioe) {
|
||||
@@ -161,6 +177,11 @@ public class SeaweedRead {
|
||||
|
||||
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
|
||||
|
||||
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
if (basicAuthHeader != null) {
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
|
||||
}
|
||||
|
||||
byte[] data = null;
|
||||
|
||||
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
|
||||
|
||||
@@ -179,7 +179,14 @@ public class SeaweedWrite {
|
||||
|
||||
HttpPost post = new HttpPost(targetUrl);
|
||||
if (auth != null && auth.length() != 0) {
|
||||
// Volume JWT and Basic Auth both use the Authorization header; the JWT wins
|
||||
// when present. Front the volume with a JWT-free path to use Basic Auth here.
|
||||
post.addHeader("Authorization", "BEARER " + auth);
|
||||
} else {
|
||||
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
if (basicAuthHeader != null) {
|
||||
post.addHeader("Authorization", basicAuthHeader);
|
||||
}
|
||||
}
|
||||
post.addHeader("Content-MD5", Base64.getEncoder().encodeToString(md.digest()));
|
||||
|
||||
|
||||
@@ -143,6 +143,9 @@ message RemoteEntry {
|
||||
string remote_e_tag = 3;
|
||||
int64 remote_mtime = 4;
|
||||
int64 remote_size = 5;
|
||||
// unset when the remote listing does not report encodings (S3);
|
||||
// empty when the remote object authoritatively has none
|
||||
optional string remote_content_encoding = 6;
|
||||
}
|
||||
message Entry {
|
||||
string name = 1;
|
||||
@@ -325,6 +328,7 @@ message ObjectMutation {
|
||||
bool set_content = 10; // PATCH_EXTENDED: replace Entry.content with content
|
||||
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
|
||||
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
|
||||
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
|
||||
}
|
||||
|
||||
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
|
||||
@@ -527,6 +531,7 @@ message AssignVolumeResponse {
|
||||
string replication = 7;
|
||||
string error = 8;
|
||||
Location location = 9;
|
||||
repeated Location replicas = 10;
|
||||
}
|
||||
|
||||
message LookupVolumeRequest {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import io.grpc.CallOptions;
|
||||
import io.grpc.Channel;
|
||||
import io.grpc.ClientCall;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.MethodDescriptor;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BasicAuthTest {
|
||||
|
||||
@After
|
||||
public void clearCredentials() {
|
||||
FilerSecurityContext.setBasicAuth(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noCredentialsMeansNoHeader() {
|
||||
FilerSecurityContext.setBasicAuth(null, null);
|
||||
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
|
||||
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
|
||||
|
||||
FilerSecurityContext.setBasicAuth("", "ignored");
|
||||
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
|
||||
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodesUserAndPassword() {
|
||||
FilerSecurityContext.setBasicAuth("alice", "s3cret");
|
||||
String expected = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(expected, FilerSecurityContext.getBasicAuthHeaderValue());
|
||||
assertTrue(FilerSecurityContext.isBasicAuthEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void interceptorAddsAuthorizationHeader() {
|
||||
String headerValue = "Basic dGVzdDp0ZXN0";
|
||||
final Metadata[] captured = new Metadata[1];
|
||||
|
||||
Channel channel = new Channel() {
|
||||
@Override
|
||||
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
|
||||
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
|
||||
return new ClientCall<ReqT, RespT>() {
|
||||
@Override
|
||||
public void start(Listener<RespT> responseListener, Metadata headers) {
|
||||
captured[0] = headers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void request(int numMessages) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(String message, Throwable cause) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void halfClose() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(ReqT message) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String authority() {
|
||||
return "test";
|
||||
}
|
||||
};
|
||||
|
||||
BasicAuthInterceptor interceptor = new BasicAuthInterceptor(headerValue);
|
||||
ClientCall<Object, Object> call =
|
||||
interceptor.interceptCall(null, CallOptions.DEFAULT, channel);
|
||||
call.start(null, new Metadata());
|
||||
|
||||
Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
|
||||
assertNotNull(captured[0]);
|
||||
assertEquals(headerValue, captured[0].get(key));
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,38 @@ import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class SeaweedReadTest {
|
||||
|
||||
// A chunk fetch that briefly returns an empty body (observed right after an
|
||||
// append) must not overrun the buffer with an opaque IndexOutOfBoundsException.
|
||||
@Test
|
||||
public void testReadChunkShorterThanViewFailsCleanly() throws IOException {
|
||||
String fileId = "7,readchunkshort01";
|
||||
SeaweedRead.volumeIdCache.setLocations("7",
|
||||
FilerProto.Locations.newBuilder()
|
||||
.addLocations(FilerProto.Location.newBuilder().setUrl("localhost:0").build())
|
||||
.build());
|
||||
// seed the chunk cache with an empty body so the fetch is skipped
|
||||
SeaweedRead.chunkCache.setChunk(fileId, new byte[0]);
|
||||
|
||||
List<SeaweedRead.VisibleInterval> visibles = new ArrayList<>();
|
||||
visibles.add(new SeaweedRead.VisibleInterval(0, 175, fileId, 1L, 0, true, null, false));
|
||||
|
||||
ByteBuffer buf = ByteBuffer.allocate(175);
|
||||
try {
|
||||
SeaweedRead.read(null, visibles, 0, buf, 175);
|
||||
Assert.fail("expected IOException for a chunk shorter than its view");
|
||||
} catch (IOException e) {
|
||||
Assert.assertTrue(e.getMessage(), e.getMessage().contains(fileId));
|
||||
Assert.assertTrue(e.getMessage(), e.getMessage().contains("[0,175)"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonOverlappingVisibleIntervals() throws IOException {
|
||||
List<FilerProto.FileChunk> chunks = new ArrayList<>();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<properties>
|
||||
<seaweedfs.client.version>4.00</seaweedfs.client.version>
|
||||
<seaweedfs.client.version>4.38</seaweedfs.client.version>
|
||||
<hadoop.version>3.4.0</hadoop.version>
|
||||
</properties>
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-gpg-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<version>3.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>sign-artifacts</id>
|
||||
|
||||
@@ -3,6 +3,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tonic_build::configure()
|
||||
.build_server(true)
|
||||
.build_client(true)
|
||||
// filer.proto uses proto3 optional; older protoc (e.g. 3.12 from ubuntu-22.04 apt)
|
||||
// rejects it without this flag, and newer protoc still accepts the flag
|
||||
.protoc_arg("--experimental_allow_proto3_optional")
|
||||
.file_descriptor_set_path(out_dir.join("seaweed_descriptor.bin"))
|
||||
.compile_protos(
|
||||
&[
|
||||
|
||||
@@ -45,6 +45,8 @@ service Seaweed {
|
||||
}
|
||||
rpc ReleaseAdminToken (ReleaseAdminTokenRequest) returns (ReleaseAdminTokenResponse) {
|
||||
}
|
||||
rpc GetAdminLockStatus (GetAdminLockStatusRequest) returns (GetAdminLockStatusResponse) {
|
||||
}
|
||||
rpc Ping (PingRequest) returns (PingResponse) {
|
||||
}
|
||||
rpc RaftListClusterServers (RaftListClusterServersRequest) returns (RaftListClusterServersResponse) {
|
||||
@@ -64,6 +66,9 @@ service Seaweed {
|
||||
message DiskTag {
|
||||
uint32 disk_id = 1;
|
||||
repeated string tags = 2;
|
||||
// Physical disk descriptor, reported for every location including empty ones.
|
||||
string type = 3;
|
||||
int64 max_volume_count = 4;
|
||||
}
|
||||
|
||||
message Heartbeat {
|
||||
@@ -96,6 +101,10 @@ message Heartbeat {
|
||||
volume_server_pb.VolumeServerState state = 23;
|
||||
|
||||
repeated DiskTag disk_tags = 24;
|
||||
|
||||
// physical disk capacity per disk type, in bytes, from the underlying filesystem
|
||||
map<string, uint64> disk_total_bytes = 25;
|
||||
map<string, uint64> disk_free_bytes = 26;
|
||||
}
|
||||
|
||||
message HeartbeatResponse {
|
||||
@@ -206,6 +215,17 @@ message ClusterNodeUpdate {
|
||||
message KeepConnectedResponse {
|
||||
VolumeLocation volume_location = 1;
|
||||
ClusterNodeUpdate cluster_node_update = 2;
|
||||
LockRingUpdate lock_ring_update = 3;
|
||||
}
|
||||
|
||||
// LockRingUpdate is sent by the master to all filers when the lock ring
|
||||
// membership changes. The master batches rapid changes (e.g., node drop + join)
|
||||
// and sends the complete member list atomically, avoiding intermediate ring
|
||||
// states that would cause unnecessary lock churn.
|
||||
message LockRingUpdate {
|
||||
string filer_group = 1;
|
||||
repeated string servers = 2;
|
||||
int64 version = 3;
|
||||
}
|
||||
|
||||
message LookupVolumeRequest {
|
||||
@@ -308,8 +328,18 @@ message DiskInfo {
|
||||
repeated VolumeInformationMessage volume_infos = 6;
|
||||
repeated VolumeEcShardInformationMessage ec_shard_infos = 7;
|
||||
int64 remote_volume_count = 8;
|
||||
// On a per-physical-disk DiskInfo (from SplitByPhysicalDisk) this is the disk's
|
||||
// identity; on the type-keyed aggregate it is only a representative fallback
|
||||
// (the first volume's disk id).
|
||||
uint32 disk_id = 9;
|
||||
repeated string tags = 10;
|
||||
// Max volume count for every physical disk of this type, keyed by disk id,
|
||||
// including disks with no volumes or EC shards; recovers empty disks that
|
||||
// carry no per-volume/per-shard records.
|
||||
map<uint32, int64> max_volume_count_by_disk = 11;
|
||||
// physical disk capacity in bytes, from the underlying filesystem (0 if unknown)
|
||||
uint64 disk_total_bytes = 12;
|
||||
uint64 disk_free_bytes = 13;
|
||||
}
|
||||
message DataNodeInfo {
|
||||
string id = 1;
|
||||
@@ -360,11 +390,13 @@ message VacuumVolumeResponse {
|
||||
}
|
||||
|
||||
message DisableVacuumRequest {
|
||||
bool by_plugin = 1;
|
||||
}
|
||||
message DisableVacuumResponse {
|
||||
}
|
||||
|
||||
message EnableVacuumRequest {
|
||||
bool by_plugin = 1;
|
||||
}
|
||||
message EnableVacuumResponse {
|
||||
}
|
||||
@@ -434,6 +466,15 @@ message ReleaseAdminTokenRequest {
|
||||
message ReleaseAdminTokenResponse {
|
||||
}
|
||||
|
||||
message GetAdminLockStatusRequest {
|
||||
string lock_name = 1;
|
||||
}
|
||||
message GetAdminLockStatusResponse {
|
||||
bool is_locked = 1;
|
||||
string client_name = 2;
|
||||
string message = 3;
|
||||
}
|
||||
|
||||
message PingRequest {
|
||||
string target = 1; // default to ping itself
|
||||
string target_type = 2;
|
||||
|
||||
@@ -442,6 +442,7 @@ message VolumeEcShardsCopyRequest {
|
||||
bool copy_ecj_file = 6;
|
||||
bool copy_vif_file = 7;
|
||||
uint32 disk_id = 8; // Target disk ID for storing EC shards
|
||||
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
|
||||
}
|
||||
message VolumeEcShardsCopyResponse {
|
||||
}
|
||||
@@ -587,6 +588,29 @@ message EcShardConfig {
|
||||
uint32 parity_shards = 2; // Number of parity shards (e.g., 4)
|
||||
int64 encode_ts_ns = 3; // encode time (unix nanos); a read served from a shard of a different encode run is rejected
|
||||
}
|
||||
// EcBitrotProtection is the entire content of a bitrot checksum sidecar
|
||||
// (<base>.ecsum for the legacy generation, <base>.ecsum.v<N> for vacuum
|
||||
// generation N): per-shard, per-block CRC32C so a CHECKSUM scrub can detect
|
||||
// silent bit rot in any shard (including parity) without decoding. Field
|
||||
// numbers and types match weed/pb/volume_server.proto byte-for-byte so the
|
||||
// serialized sidecar payload is wire-identical across the Go and Rust binaries.
|
||||
message EcBitrotProtection {
|
||||
ChecksumAlgorithm algorithm = 1; // CRC32C (Castagnoli)
|
||||
uint32 block_size = 2; // bytes per checksum block; default 16777216 (16 MiB), a power-of-two multiple of 1 MiB
|
||||
uint32 generation = 3; // EC vacuum generation these checksums describe (0 = legacy/fresh); must match the sidecar filename version
|
||||
EcShardConfig ec_shard_config = 4; // data/parity shard counts at encode time
|
||||
repeated EcShardChecksums shards = 5; // one entry per shard id in the active layout
|
||||
bytes encode_uuid = 6; // random per-encode identity, for stale-sidecar detection across in-place re-encodes
|
||||
}
|
||||
message EcShardChecksums {
|
||||
uint32 shard_id = 1; // 0..MaxShardCount-1 (custom EC ratios go up to 32)
|
||||
int64 covered_size = 2; // shard byte length these checksums cover (must equal the on-disk shard length)
|
||||
bytes block_crc32c = 3; // packed little-endian uint32[] = ceil(covered_size/block_size) entries
|
||||
}
|
||||
enum ChecksumAlgorithm {
|
||||
CHECKSUM_NONE = 0;
|
||||
CHECKSUM_CRC32C = 1;
|
||||
}
|
||||
message OldVersionVolumeInfo {
|
||||
repeated RemoteFile files = 1;
|
||||
uint32 version = 2;
|
||||
@@ -664,6 +688,7 @@ enum VolumeScrubMode {
|
||||
INDEX = 1;
|
||||
FULL = 2;
|
||||
LOCAL = 3;
|
||||
CHECKSUM = 4; // EC only: verify each local shard's raw bytes against the bitrot checksum sidecar
|
||||
}
|
||||
|
||||
message ScrubVolumeRequest {
|
||||
@@ -683,6 +708,7 @@ message ScrubEcVolumeRequest {
|
||||
VolumeScrubMode mode = 1;
|
||||
// optional list of volume IDs to scrub. if empty, all EC volumes for the server are scrubbed.
|
||||
repeated uint32 volume_ids = 2;
|
||||
bool force_deleted_needles_check = 3; // FULL mode only; may report false positives when EC indexes disagree
|
||||
}
|
||||
message ScrubEcVolumeResponse {
|
||||
uint64 total_volumes = 1;
|
||||
|
||||
@@ -7,7 +7,7 @@ use seaweed_volume::metrics;
|
||||
use seaweed_volume::pb::volume_server_pb::volume_server_server::VolumeServerServer;
|
||||
use seaweed_volume::security::tls::{
|
||||
build_rustls_server_config, build_rustls_server_config_with_grpc_client_auth,
|
||||
GrpcClientAuthPolicy, TlsPolicy,
|
||||
install_default_crypto_provider, GrpcClientAuthPolicy, TlsPolicy,
|
||||
};
|
||||
use seaweed_volume::security::{Guard, SigningKey};
|
||||
#[cfg(unix)]
|
||||
@@ -39,6 +39,8 @@ const GRPC_MAX_HEADER_LIST_SIZE: u32 = 8 * 1024 * 1024;
|
||||
const GRPC_MAX_CONCURRENT_STREAMS: u32 = 1000;
|
||||
|
||||
fn main() {
|
||||
install_default_crypto_provider();
|
||||
|
||||
// Initialize tracing
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
|
||||
@@ -118,6 +118,13 @@ impl ClientCertVerifier for CommonNameVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
// aws-lc-rs and ring both get linked transitively, so rustls can't auto-select
|
||||
// a provider and tonic's client TLS panics on first use. Pin the default to
|
||||
// aws-lc-rs, matching the server config. Idempotent.
|
||||
pub fn install_default_crypto_provider() {
|
||||
let _ = aws_lc_rs::default_provider().install_default();
|
||||
}
|
||||
|
||||
pub fn build_rustls_server_config(
|
||||
cert_path: &str,
|
||||
key_path: &str,
|
||||
|
||||
@@ -164,6 +164,21 @@ mod tests {
|
||||
use crate::config::{NeedleMapKind, ReadMode, VolumeServerConfig};
|
||||
use crate::security::tls::TlsPolicy;
|
||||
|
||||
const TEST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBPDCB76ADAgECAhRuRPQgeAu43BT/M7EfAWSdapVdYDAFBgMrZXAwFDESMBAG\nA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNTE2MTUyOVoXDTM2MDcwMjE2MTUyOVow\nFDESMBAGA1UEAwwJbG9jYWxob3N0MCowBQYDK2VwAyEAr/3bNIFI+8V32oCiY6y+\nXRFmZpdNQ2g//VtRkT+nQg+jUzBRMB0GA1UdDgQWBBTsy9tLf1zPiXCQfgci6zNi\ndEzRSjAfBgNVHSMEGDAWgBTsy9tLf1zPiXCQfgci6zNidEzRSjAPBgNVHRMBAf8E\nBTADAQH/MAUGAytlcANBAIvsdw0IbvOBBkb9cd7BfMJfIP9pQQrAL03pCRWJFnFh\nSysaLVgFXI4T078IiaM874oO+iB+5vNbWEpc7CkGow4=\n-----END CERTIFICATE-----\n";
|
||||
const TEST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHbyn71Kk+Y7KT3sBctit7uZpErpoH6qDbFj6P8qGaZH\n-----END PRIVATE KEY-----\n";
|
||||
|
||||
#[test]
|
||||
fn test_build_grpc_endpoint_with_tls_resolves_crypto_provider() {
|
||||
crate::security::tls::install_default_crypto_provider();
|
||||
let tls = super::OutgoingGrpcTlsConfig {
|
||||
cert_pem: TEST_CERT_PEM.to_string(),
|
||||
key_pem: TEST_KEY_PEM.to_string(),
|
||||
ca_pem: TEST_CERT_PEM.to_string(),
|
||||
};
|
||||
let endpoint = build_grpc_endpoint("127.0.0.1:19333", Some(&tls)).unwrap();
|
||||
assert_eq!(endpoint.uri().scheme_str(), Some("https"));
|
||||
}
|
||||
|
||||
fn sample_config() -> VolumeServerConfig {
|
||||
VolumeServerConfig {
|
||||
port: 8080,
|
||||
|
||||
@@ -37,6 +37,7 @@ fn scrub_mode_label(mode: i32) -> &'static str {
|
||||
1 => "INDEX",
|
||||
2 => "FULL",
|
||||
3 => "LOCAL",
|
||||
4 => "CHECKSUM",
|
||||
_ => "UNKNOWN",
|
||||
}
|
||||
}
|
||||
@@ -379,7 +380,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
size: 0,
|
||||
version: 0,
|
||||
});
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1233,12 +1234,24 @@ impl VolumeServer for VolumeGrpcService {
|
||||
DiskType::from_string(&vol_info.disk_type)
|
||||
};
|
||||
|
||||
let has_remote_dat = vol_info
|
||||
.volume_info
|
||||
.as_ref()
|
||||
.map(|vi| !vi.files.is_empty())
|
||||
.unwrap_or(false);
|
||||
// a remote-backed volume only lands its .idx/.vif locally; the .dat stays in the tier
|
||||
let needed_space = if has_remote_dat {
|
||||
vol_info.idx_file_size
|
||||
} else {
|
||||
vol_info.dat_file_size
|
||||
};
|
||||
|
||||
// Find a free disk location using Go's Store.FindFreeLocation semantics.
|
||||
let (data_base, idx_base, selected_disk_type) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let Some(loc_idx) = store.find_free_location_predicate(|loc| {
|
||||
loc.disk_type == requested_disk_type
|
||||
&& loc.available_space.load(Ordering::Relaxed) > vol_info.dat_file_size
|
||||
&& loc.available_space.load(Ordering::Relaxed) > needed_space
|
||||
}) else {
|
||||
return Err(Status::internal(format!(
|
||||
"no space left {}",
|
||||
@@ -1265,12 +1278,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
Status::internal(format!("write .note for volume {}: {}", vid, e))
|
||||
})?;
|
||||
|
||||
let has_remote_dat = vol_info
|
||||
.volume_info
|
||||
.as_ref()
|
||||
.map(|vi| !vi.files.is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
let (tx, rx) =
|
||||
tokio::sync::mpsc::channel::<Result<volume_server_pb::VolumeCopyResponse, Status>>(16);
|
||||
let state = self.state.clone();
|
||||
@@ -1515,9 +1522,16 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.find_volume(vid)
|
||||
.ok_or_else(|| Status::not_found(format!("not found volume id {}", vid)))?;
|
||||
|
||||
// Check compaction revision
|
||||
// Check compaction revision. Compare against the volume's live
|
||||
// super_block.compaction_revision (matching Go's v.CompactionRevision,
|
||||
// which is the embedded SuperBlock field). last_compact_revision() is
|
||||
// a separate bookkeeping value recorded just before a compaction starts
|
||||
// (for makeup-diff catch-up) and is intentionally left behind the live
|
||||
// revision afterward — it is not interchangeable with the live value and
|
||||
// must not be used here, or this check spuriously fails on every volume
|
||||
// that has ever been compacted even once.
|
||||
if req.compaction_revision != u32::MAX
|
||||
&& v.last_compact_revision() != req.compaction_revision as u16
|
||||
&& u32::from(v.super_block.compaction_revision) != req.compaction_revision
|
||||
{
|
||||
return Err(Status::failed_precondition(format!(
|
||||
"volume {} is compacted",
|
||||
@@ -2464,7 +2478,10 @@ impl VolumeServer for VolumeGrpcService {
|
||||
));
|
||||
}
|
||||
|
||||
// Rebuild missing shards, searching all locations for input shards
|
||||
// Rebuild missing shards, searching all locations for input shards.
|
||||
// Pass other_dirs so shards on sibling disks are found even when the
|
||||
// primary rebuild dir doesn't hold them.
|
||||
let other_dir_refs: Vec<&str> = other_dirs.iter().map(|s| s.as_str()).collect();
|
||||
crate::storage::erasure_coding::ec_encoder::rebuild_ec_files(
|
||||
&rebuild_dir,
|
||||
collection,
|
||||
@@ -2472,6 +2489,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&missing,
|
||||
data_shards as usize,
|
||||
parity_shards as usize,
|
||||
&other_dir_refs,
|
||||
)
|
||||
.map_err(|e| Status::internal(format!("RebuildEcFiles: {}", e)))?;
|
||||
|
||||
@@ -2485,11 +2503,23 @@ impl VolumeServer for VolumeGrpcService {
|
||||
rebuild_idx_dir
|
||||
};
|
||||
|
||||
// .ecx may live in a different directory than the data shards (split
|
||||
// data/idx layout). Ensure rebuild_dir is searchable for data shards
|
||||
// even when it isn't the chosen .ecx rebuild directory and isn't
|
||||
// already covered by other_dir_refs.
|
||||
let mut ecx_dir_refs: Vec<&str> =
|
||||
Vec::with_capacity(other_dir_refs.len() + usize::from(ecx_rebuild_dir != rebuild_dir));
|
||||
if ecx_rebuild_dir != rebuild_dir {
|
||||
ecx_dir_refs.push(rebuild_dir.as_str());
|
||||
}
|
||||
ecx_dir_refs.extend(other_dir_refs.iter().copied());
|
||||
|
||||
crate::storage::erasure_coding::ec_encoder::rebuild_ecx_file(
|
||||
&ecx_rebuild_dir,
|
||||
collection,
|
||||
vid,
|
||||
data_shards as usize,
|
||||
&ecx_dir_refs,
|
||||
)
|
||||
.map_err(|e| Status::internal(format!("RebuildEcxFile: {}", e)))?;
|
||||
|
||||
@@ -2611,17 +2641,10 @@ impl VolumeServer for VolumeGrpcService {
|
||||
crate::storage::volume::volume_file_name(&dest_dir, &req.collection, vid);
|
||||
format!("{}{}", base, ext)
|
||||
};
|
||||
let mut file = std::fs::File::create(&file_path)
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
let file = tokio::fs::File::create(&file_path)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv {}: {}", ext, e)))?
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&chunk.file_content)
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
}
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
drain_copy_stream_to_file(&mut stream, file, &file_path, &ext).await?;
|
||||
}
|
||||
|
||||
// Copy .ecx file if requested
|
||||
@@ -2651,17 +2674,10 @@ impl VolumeServer for VolumeGrpcService {
|
||||
crate::storage::volume::volume_file_name(&dest_idx_dir, &req.collection, vid);
|
||||
format!("{}.ecx", base)
|
||||
};
|
||||
let mut file = std::fs::File::create(&file_path)
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
let file = tokio::fs::File::create(&file_path)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv .ecx: {}", e)))?
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&chunk.file_content)
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
}
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
drain_copy_stream_to_file(&mut stream, file, &file_path, ".ecx").await?;
|
||||
}
|
||||
|
||||
// Copy .ecj file if requested
|
||||
@@ -2692,20 +2708,13 @@ impl VolumeServer for VolumeGrpcService {
|
||||
crate::storage::volume::volume_file_name(&dest_idx_dir, &req.collection, vid);
|
||||
format!("{}.ecj", base)
|
||||
};
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
let file = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&file_path)
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv .ecj: {}", e)))?
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&chunk.file_content)
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
}
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
drain_copy_stream_to_file(&mut stream, file, &file_path, ".ecj").await?;
|
||||
}
|
||||
|
||||
// Copy .vif file if requested
|
||||
@@ -2736,16 +2745,53 @@ impl VolumeServer for VolumeGrpcService {
|
||||
crate::storage::volume::volume_file_name(&dest_dir, &req.collection, vid);
|
||||
format!("{}.vif", base)
|
||||
};
|
||||
let mut file = std::fs::File::create(&file_path)
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
let file = tokio::fs::File::create(&file_path)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv .vif: {}", e)))?
|
||||
{
|
||||
use std::io::Write;
|
||||
file.write_all(&chunk.file_content)
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
drain_copy_stream_to_file(&mut stream, file, &file_path, ".vif").await?;
|
||||
}
|
||||
|
||||
// Copy the generation-0 bitrot checksum sidecar (.ecsum) when requested, so
|
||||
// protection travels with the shards. Tolerant of a missing source (no-op):
|
||||
// this non-2PC path has no Prepare backstop, and an unprotected source
|
||||
// simply leaves the copy unprotected.
|
||||
if req.copy_ecsum_file {
|
||||
let copy_req = volume_server_pb::CopyFileRequest {
|
||||
volume_id: req.volume_id,
|
||||
collection: req.collection.clone(),
|
||||
is_ec_volume: true,
|
||||
ext: ".ecsum".to_string(),
|
||||
compaction_revision: u32::MAX,
|
||||
stop_offset: i64::MAX as u64,
|
||||
ignore_source_file_not_found: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut stream = client
|
||||
.copy_file(copy_req)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::internal(format!(
|
||||
"VolumeEcShardsCopy volume {} copy .ecsum: {}",
|
||||
vid, e
|
||||
))
|
||||
})?
|
||||
.into_inner();
|
||||
|
||||
let file_path = {
|
||||
let base =
|
||||
crate::storage::volume::volume_file_name(&dest_dir, &req.collection, vid);
|
||||
format!("{}.ecsum", base)
|
||||
};
|
||||
let file = tokio::fs::File::create(&file_path)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("create {}: {}", file_path, e)))?;
|
||||
let written =
|
||||
drain_copy_stream_to_file(&mut stream, file, &file_path, ".ecsum").await?;
|
||||
// A missing source yields an empty stream; drop the 0-byte file so mount
|
||||
// sees no sidecar (protection Off) rather than a truncated/invalid one.
|
||||
// (drain_copy_stream_to_file has already closed the file on return.)
|
||||
if written == 0 {
|
||||
let _ = tokio::fs::remove_file(&file_path).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3826,7 +3872,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.ok_or_else(|| Status::not_found(format!("volume id {} not found", vid.0)))?;
|
||||
total_volumes += 1;
|
||||
|
||||
// INDEX mode (1) calls scrub_index; LOCAL (2) and FULL (3) call scrub
|
||||
// INDEX mode (1) calls scrub_index; FULL (2) and LOCAL (3) call scrub
|
||||
let scrub_result = if mode == 1 {
|
||||
v.scrub_index()
|
||||
} else {
|
||||
@@ -3895,7 +3941,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Validate mode
|
||||
let mode = req.mode;
|
||||
match mode {
|
||||
1 | 2 | 3 => {} // INDEX=1, FULL=2, LOCAL=3
|
||||
1 | 2 | 3 | 4 => {} // INDEX=1, FULL=2, LOCAL=3, CHECKSUM=4
|
||||
_ => {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"unsupported EC volume scrub mode {}",
|
||||
@@ -3904,15 +3950,19 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
|
||||
let store = self.state.store.read().unwrap();
|
||||
let vids: Vec<VolumeId> = if req.volume_ids.is_empty() {
|
||||
store
|
||||
.locations
|
||||
.iter()
|
||||
.flat_map(|loc| loc.ec_volumes().map(|(vid, _)| *vid))
|
||||
.collect()
|
||||
} else {
|
||||
req.volume_ids.iter().map(|&id| VolumeId(id)).collect()
|
||||
// Collect the volume ids under a brief lock, then release it: FULL (mode 2)
|
||||
// reads remote shards and must not hold the !Send store guard across .await.
|
||||
let vids: Vec<VolumeId> = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
if req.volume_ids.is_empty() {
|
||||
store
|
||||
.locations
|
||||
.iter()
|
||||
.flat_map(|loc| loc.ec_volumes().map(|(vid, _)| *vid))
|
||||
.collect()
|
||||
} else {
|
||||
req.volume_ids.iter().map(|&id| VolumeId(id)).collect()
|
||||
}
|
||||
};
|
||||
|
||||
let mut total_volumes: u64 = 0;
|
||||
@@ -3921,17 +3971,17 @@ impl VolumeServer for VolumeGrpcService {
|
||||
let mut broken_shard_infos: Vec<volume_server_pb::EcShardInfo> = Vec::new();
|
||||
let mut details: Vec<String> = Vec::new();
|
||||
|
||||
for vid in &vids {
|
||||
let ecv = store
|
||||
.find_ec_volume(*vid)
|
||||
.ok_or_else(|| Status::not_found(format!("EC volume id {} not found", vid.0)))?;
|
||||
let collection = ecv.collection.clone();
|
||||
|
||||
for vid in vids {
|
||||
match mode {
|
||||
1 => {
|
||||
// INDEX mode: check ecx index integrity only, no shard verification
|
||||
// Matches Go's v.ScrubIndex() → idx.CheckIndexFile()
|
||||
let (count, errs) = ecv.scrub_index();
|
||||
// INDEX mode: check ecx index integrity only, no shard verification.
|
||||
let (count, errs) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
ecv.scrub_index()
|
||||
};
|
||||
total_volumes += 1;
|
||||
total_files += count;
|
||||
if !errs.is_empty() {
|
||||
@@ -3941,59 +3991,130 @@ impl VolumeServer for VolumeGrpcService {
|
||||
}
|
||||
}
|
||||
}
|
||||
2 | 3 => {
|
||||
// LOCAL (2) / FULL (3): verify EC shard data
|
||||
let files = ecv.walk_ecx_stats().map(|(f, _, _)| f).unwrap_or(0);
|
||||
|
||||
// After cross-disk reconciliation, an EcVolume can
|
||||
// legitimately have ecv.dir != ecv.dir_idx (shards
|
||||
// on one disk, .ecx / .ecj / .vif on a sibling).
|
||||
// Use the EcVolume's own dirs rather than collapsing
|
||||
// both args to find_ec_dir's single answer, otherwise
|
||||
// read_ec_shard_config falls back to the wrong .vif
|
||||
// location for split-disk volumes (#9252).
|
||||
let dir = ecv.dir.clone();
|
||||
let idx_dir = ecv.dir_idx.clone();
|
||||
if dir.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
2 => {
|
||||
// FULL: Go-parity per-needle local+remote walk, PLUS a TEMPORARY
|
||||
// local Reed-Solomon parity check. The needle walk only reads
|
||||
// DATA-shard intervals of LIVE needles, so on its own it can't
|
||||
// catch silent bitrot in a PARITY shard or an unwalked cold
|
||||
// region. Go closes that gap with a separate CHECKSUM mode over
|
||||
// .ecsum, which Rust does not have yet; running both here is a
|
||||
// deliberate divergence from Go FULL to preserve coverage. Drop
|
||||
// verify_ec_shards from this arm once mode 4 (CHECKSUM) lands.
|
||||
//
|
||||
// The RS recompute needs every shard co-located, so only run it
|
||||
// when this node holds all data+parity shards (single-node EC);
|
||||
// on a distributed layout it would report every non-local shard
|
||||
// as missing. Snapshot under a brief lock; release before await.
|
||||
let (dir, collection, data_shards, parity_shards, all_local) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
let total = (ecv.data_shards + ecv.parity_shards) as usize;
|
||||
let local = ecv.shards.iter().filter(|s| s.is_some()).count();
|
||||
(
|
||||
ecv.dir.clone(),
|
||||
ecv.collection.clone(),
|
||||
ecv.data_shards as usize,
|
||||
ecv.parity_shards as usize,
|
||||
local == total,
|
||||
)
|
||||
};
|
||||
total_volumes += 1;
|
||||
total_files += files;
|
||||
let (data_shards, parity_shards) =
|
||||
crate::storage::erasure_coding::ec_volume::read_ec_shard_config(
|
||||
&dir,
|
||||
&idx_dir,
|
||||
&collection,
|
||||
*vid,
|
||||
);
|
||||
|
||||
match crate::storage::erasure_coding::ec_encoder::verify_ec_shards(
|
||||
&dir,
|
||||
&collection,
|
||||
*vid,
|
||||
data_shards as usize,
|
||||
parity_shards as usize,
|
||||
) {
|
||||
Ok((broken, msgs)) => {
|
||||
if !broken.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
for b in broken {
|
||||
broken_shard_infos.push(volume_server_pb::EcShardInfo {
|
||||
volume_id: vid.0,
|
||||
collection: collection.clone(),
|
||||
shard_id: b,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
for msg in msgs {
|
||||
details.push(format!("ecvol {}: {}", vid.0, msg));
|
||||
// (1) Per-needle local+remote walk (Go ScrubEcVolume parity).
|
||||
let (files, mut shard_infos, mut errs) =
|
||||
crate::server::store_ec::scrub_ec_volume_distributed(&self.state, vid, false)
|
||||
.await;
|
||||
total_files += files as u64; // count comes from the needle walk only
|
||||
|
||||
// (2) Local parity check, gated on all-shards-local. Blocking RS
|
||||
// verify -> spawn_blocking; inputs are owned, no lock held.
|
||||
if all_local && !dir.is_empty() {
|
||||
let collection_pc = collection.clone();
|
||||
let (parity_broken, parity_details) = tokio::task::spawn_blocking(move || {
|
||||
crate::storage::erasure_coding::ec_encoder::verify_ec_shards(
|
||||
&dir,
|
||||
&collection_pc,
|
||||
vid,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("verify_ec_shards join: {}", e)))?
|
||||
.unwrap_or_else(|e| (Vec::new(), vec![format!("verify_ec_shards: {}", e)]));
|
||||
|
||||
let mut seen: std::collections::HashSet<u32> =
|
||||
shard_infos.iter().map(|s| s.shard_id).collect();
|
||||
for sid in parity_broken {
|
||||
if seen.insert(sid) {
|
||||
shard_infos.push(volume_server_pb::EcShardInfo {
|
||||
shard_id: sid,
|
||||
collection: collection.clone(),
|
||||
volume_id: vid.0,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
broken_volume_ids.push(vid.0);
|
||||
details.push(format!("ecvol {}: scrub error: {}", vid.0, e));
|
||||
shard_infos.sort_by_key(|s| s.shard_id);
|
||||
errs.extend(parity_details);
|
||||
}
|
||||
|
||||
if !errs.is_empty() || !shard_infos.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
broken_shard_infos.extend(shard_infos);
|
||||
for msg in errs {
|
||||
details.push(format!("ecvol {}: {}", vid.0, msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
3 => {
|
||||
// LOCAL: verify each needle against the locally-held shards.
|
||||
let (files, shard_infos, errs) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
ecv.scrub_local()
|
||||
};
|
||||
total_volumes += 1;
|
||||
total_files += files;
|
||||
if !errs.is_empty() || !shard_infos.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
broken_shard_infos.extend(shard_infos);
|
||||
for msg in errs {
|
||||
details.push(format!("ecvol {}: {}", vid.0, msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
// CHECKSUM: verify each local shard's raw bytes against the
|
||||
// bitrot checksum sidecar, exercising cold parity shards.
|
||||
// Read-only. Mirrors Go's v.ChecksumScrub().
|
||||
let (blocks_scanned, broken, errs, collection) = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
|
||||
Status::not_found(format!("EC volume id {} not found", vid.0))
|
||||
})?;
|
||||
let collection = ecv.collection.clone();
|
||||
let (blocks, broken, errs) = ecv.checksum_scrub();
|
||||
(blocks, broken, errs, collection)
|
||||
};
|
||||
total_volumes += 1;
|
||||
total_files += blocks_scanned;
|
||||
if !errs.is_empty() || !broken.is_empty() {
|
||||
broken_volume_ids.push(vid.0);
|
||||
for b in broken {
|
||||
broken_shard_infos.push(volume_server_pb::EcShardInfo {
|
||||
volume_id: vid.0,
|
||||
collection: collection.clone(),
|
||||
shard_id: b,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
for msg in errs {
|
||||
details.push(format!("ecvol {}: {}", vid.0, msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4423,6 +4544,55 @@ fn set_file_mtime(path: &str, modified_ts_ns: i64) -> std::io::Result<()> {
|
||||
file.set_times(ft)
|
||||
}
|
||||
|
||||
/// Drain a CopyFile stream into `file`, returning the number of bytes written.
|
||||
///
|
||||
/// Uses async, buffered I/O (`tokio::fs` + `BufWriter`) so the receive-and-write
|
||||
/// loop never blocks a Tokio worker thread on disk I/O — a synchronous
|
||||
/// `std::fs::File::write_all` per chunk would stall the runtime for the duration
|
||||
/// of each write (noticeable for a large `.ecx`/`.dat` on a slow or busy disk).
|
||||
///
|
||||
/// On any recv/write/flush error the partially written destination is removed
|
||||
/// (matching `receive_file` and the Go volume server), so a failed copy never
|
||||
/// leaves a truncated shard or checksum file behind for a later reader to trip on.
|
||||
async fn drain_copy_stream_to_file(
|
||||
stream: &mut tonic::Streaming<volume_server_pb::CopyFileResponse>,
|
||||
file: tokio::fs::File,
|
||||
file_path: &str,
|
||||
what: &str,
|
||||
) -> Result<u64, Status> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let mut writer = tokio::io::BufWriter::new(file);
|
||||
let write_all = async {
|
||||
let mut written: u64 = 0;
|
||||
while let Some(chunk) = stream
|
||||
.message()
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("recv {}: {}", what, e)))?
|
||||
{
|
||||
writer
|
||||
.write_all(&chunk.file_content)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("write {}: {}", file_path, e)))?;
|
||||
written += chunk.file_content.len() as u64;
|
||||
}
|
||||
writer
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("flush {}: {}", file_path, e)))?;
|
||||
Ok::<u64, Status>(written)
|
||||
};
|
||||
match write_all.await {
|
||||
Ok(written) => Ok(written),
|
||||
Err(e) => {
|
||||
// Close the handle, then drop the truncated file so it isn't mistaken
|
||||
// for a complete shard/sidecar. Best-effort: the original error wins.
|
||||
drop(writer);
|
||||
let _ = tokio::fs::remove_file(file_path).await;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a file from a remote volume server via CopyFile streaming RPC.
|
||||
/// Returns the modified_ts_ns received from the source.
|
||||
async fn copy_file_from_source<T>(
|
||||
@@ -5514,6 +5684,105 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for comparing the wrong compaction-revision field.
|
||||
// last_compact_revision() is bookkeeping recorded just before a compaction
|
||||
// starts (for makeup-diff catch-up) and is intentionally left behind
|
||||
// super_block.compaction_revision once the compaction commits. copy_file's
|
||||
// precondition check must compare against the live super_block value
|
||||
// (matching Go's v.CompactionRevision), not the stale bookkeeping one, or
|
||||
// it fails "volume N is compacted" on every volume that has ever been
|
||||
// compacted even once.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_copy_file_accepts_live_revision_after_compaction() {
|
||||
let (service, _tmp) = make_local_service_with_volume("", None);
|
||||
|
||||
// Drive a real compaction to completion so the two revision fields
|
||||
// actually diverge the way they do in production, rather than poking
|
||||
// the struct fields directly.
|
||||
let (revision_before, revision_after, last_compact_revision_after) = {
|
||||
let mut store = service.state.store.write().unwrap();
|
||||
let (_, v) = store.find_volume_mut(VolumeId(1)).unwrap();
|
||||
let before = v.super_block.compaction_revision;
|
||||
|
||||
v.compact_by_index(0, 0, |_| true).unwrap();
|
||||
v.commit_compact().unwrap();
|
||||
|
||||
(before, v.super_block.compaction_revision, v.last_compact_revision())
|
||||
};
|
||||
|
||||
assert_eq!(revision_before, 0, "fresh volume starts at revision 0");
|
||||
assert_eq!(
|
||||
revision_after, 1,
|
||||
"live super_block.compaction_revision must advance after commit_compact"
|
||||
);
|
||||
assert_eq!(
|
||||
last_compact_revision_after, 0,
|
||||
"last_compact_revision() is recorded pre-compaction and must stay \
|
||||
behind the live revision — this divergence is exactly what made \
|
||||
the old check fail permanently"
|
||||
);
|
||||
|
||||
// The live revision (1) must be accepted: this is what
|
||||
// read_volume_file_status would report to a caller right now.
|
||||
let response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: revision_after as u32,
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
assert!(
|
||||
response.is_ok(),
|
||||
"copy_file must accept the live compaction_revision, got: {:?}",
|
||||
response.err()
|
||||
);
|
||||
|
||||
// A genuinely stale/wrong revision must still be rejected — the fix
|
||||
// corrects which field is compared, it does not disable the check.
|
||||
let stale_response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: 99,
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
let err = match stale_response {
|
||||
Ok(_) => panic!("a genuinely stale revision must be rejected"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
|
||||
assert!(err.message().contains("is compacted"));
|
||||
|
||||
// A request revision that only collides after truncating to u16 must be
|
||||
// rejected: 65537 as u16 == 1 == the live revision, but as u32 they differ.
|
||||
// Compare in u32 space (matching Go) so this cannot spuriously pass.
|
||||
let truncating_response = service
|
||||
.copy_file(Request::new(volume_server_pb::CopyFileRequest {
|
||||
volume_id: 1,
|
||||
ext: ".dat".to_string(),
|
||||
compaction_revision: u32::from(revision_after) + (1 << 16),
|
||||
stop_offset: u64::MAX,
|
||||
collection: String::new(),
|
||||
is_ec_volume: false,
|
||||
ignore_source_file_not_found: false,
|
||||
}))
|
||||
.await;
|
||||
let err = match truncating_response {
|
||||
Ok(_) => panic!("a revision that only matches after u16 truncation must be rejected"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
|
||||
assert!(err.message().contains("is compacted"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_volume_ec_shards_generate_persists_expire_at_sec() {
|
||||
let ttl = crate::storage::needle::ttl::TTL::read("3m").unwrap();
|
||||
|
||||
@@ -356,12 +356,23 @@ fn parse_url_path(path: &str) -> Option<(VolumeId, NeedleId, Cookie)> {
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
struct VolumeLocation {
|
||||
url: String,
|
||||
#[serde(rename = "publicUrl")]
|
||||
// Master often omits publicUrl when it matches url (Go json omitempty).
|
||||
#[serde(rename = "publicUrl", default)]
|
||||
public_url: String,
|
||||
#[serde(rename = "grpcPort", default)]
|
||||
grpc_port: u32,
|
||||
}
|
||||
|
||||
impl VolumeLocation {
|
||||
fn public_or_url(&self) -> &str {
|
||||
if self.public_url.is_empty() {
|
||||
&self.url
|
||||
} else {
|
||||
&self.public_url
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Master /dir/lookup response.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct LookupResult {
|
||||
@@ -535,9 +546,30 @@ async fn do_replicated_request(
|
||||
.await
|
||||
.map_err(|e| format!("lookup volume failed: {}", e))?;
|
||||
|
||||
// Mirror Go's GetWritableRemoteReplications: reject when the master reports fewer replicas than
|
||||
// the copy count. lookup_volume is uncached, so recovery is immediate once the replica re-registers.
|
||||
let copy_count = {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
|
||||
v.super_block.replica_placement.get_copy_count()
|
||||
})
|
||||
};
|
||||
if locations.len() < copy_count as usize {
|
||||
return Err(format!(
|
||||
"replicating operations [{}] is less than volume {} replication copy count [{}]",
|
||||
locations.len(),
|
||||
vid,
|
||||
copy_count
|
||||
));
|
||||
}
|
||||
|
||||
let self_http = to_http_address(&state.self_url);
|
||||
let remote_locations: Vec<_> = locations
|
||||
.into_iter()
|
||||
.filter(|loc| loc.url != state.self_url && loc.public_url != state.self_url)
|
||||
.filter(|loc| {
|
||||
to_http_address(&loc.url) != self_http
|
||||
&& to_http_address(loc.public_or_url()) != self_http
|
||||
})
|
||||
.collect();
|
||||
|
||||
if remote_locations.is_empty() {
|
||||
@@ -1247,7 +1279,9 @@ async fn get_or_head_handler_inner(
|
||||
&query,
|
||||
&etag,
|
||||
&last_modified_str,
|
||||
) {
|
||||
)
|
||||
.await
|
||||
{
|
||||
return resp;
|
||||
}
|
||||
// If manifest expansion fails (invalid JSON etc.), fall through to raw data
|
||||
@@ -3164,12 +3198,11 @@ struct ChunkManifest {
|
||||
struct ChunkInfo {
|
||||
fid: String,
|
||||
offset: i64,
|
||||
#[allow(dead_code)]
|
||||
size: i64,
|
||||
}
|
||||
|
||||
/// Try to expand a chunk manifest needle. Returns None if manifest can't be parsed.
|
||||
fn try_expand_chunk_manifest(
|
||||
async fn try_expand_chunk_manifest(
|
||||
state: &Arc<VolumeServerState>,
|
||||
n: &Needle,
|
||||
_headers: &HeaderMap,
|
||||
@@ -3209,29 +3242,26 @@ fn try_expand_chunk_manifest(
|
||||
return None;
|
||||
}
|
||||
|
||||
// Read and concatenate all chunks
|
||||
// Read and concatenate all chunks. Each chunk is resolved to wherever it
|
||||
// lives — a local regular volume, a local EC volume (reconstruct-on-read),
|
||||
// or a peer via master lookup — mirroring Go's ChunkedFileReader, which
|
||||
// never assumes chunks are local regular needles.
|
||||
let mut result = vec![0u8; manifest.size as usize];
|
||||
let store = state.store.read().unwrap();
|
||||
for chunk in &manifest.chunks {
|
||||
let (chunk_vid, chunk_nid, chunk_cookie) = match parse_url_path(&chunk.fid) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid chunk fid: {}", chunk.fid),
|
||||
)
|
||||
.into_response(),
|
||||
// Validate the attacker-controlled chunk offset before indexing: a
|
||||
// negative value would wrap to a huge usize, and an out-of-range one has
|
||||
// nowhere to land.
|
||||
if chunk.offset < 0 || chunk.size < 0 {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid negative chunk offset/size in {}", chunk.fid),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut chunk_needle = Needle {
|
||||
id: chunk_nid,
|
||||
cookie: chunk_cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
match store.read_volume_needle(chunk_vid, &mut chunk_needle) {
|
||||
Ok(_) => {}
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
let data = match read_chunk_needle(state, &chunk.fid).await {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
return Some(
|
||||
(
|
||||
@@ -3241,56 +3271,16 @@ fn try_expand_chunk_manifest(
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
}
|
||||
// Validate the attacker-controlled chunk offset before indexing: a
|
||||
// negative value would wrap to a huge usize, and an out-of-range one has
|
||||
// nowhere to land.
|
||||
if chunk.offset < 0 {
|
||||
return Some(
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("invalid negative chunk offset in {}", chunk.fid),
|
||||
)
|
||||
.into_response(),
|
||||
);
|
||||
}
|
||||
};
|
||||
let offset = chunk.offset as usize;
|
||||
if offset >= result.len() {
|
||||
continue;
|
||||
}
|
||||
// Write the chunk into its window in `result`. Compressed chunks inflate
|
||||
// directly into the destination slice (bounded by the remaining window),
|
||||
// so a chunk never allocates a second large buffer — peak memory stays at
|
||||
// ~manifest.size instead of doubling. Bytes past the window are dropped,
|
||||
// matching the prior truncation behavior.
|
||||
if chunk_needle.is_compressed() {
|
||||
use flate2::read::GzDecoder;
|
||||
use std::io::Read as _;
|
||||
let mut decoder = GzDecoder::new(&chunk_needle.data[..]);
|
||||
let window = &mut result[offset..];
|
||||
let mut written = 0usize;
|
||||
let mut decode_failed = false;
|
||||
while written < window.len() {
|
||||
match decoder.read(&mut window[written..]) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => written += n,
|
||||
Err(_) => {
|
||||
decode_failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// On any decode failure, drop the partial output and fall back to the
|
||||
// chunk's raw bytes (truncated to the window), preserving prior behavior.
|
||||
if decode_failed {
|
||||
window[..written].fill(0);
|
||||
let copy_len = chunk_needle.data.len().min(window.len());
|
||||
window[..copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
|
||||
}
|
||||
} else {
|
||||
let copy_len = chunk_needle.data.len().min(result.len() - offset);
|
||||
result[offset..offset + copy_len].copy_from_slice(&chunk_needle.data[..copy_len]);
|
||||
}
|
||||
// Clamp to the chunk's declared size so an over-long chunk can't bleed
|
||||
// into the next chunk's window; also drop bytes past the buffer end.
|
||||
let bound = (chunk.size as usize).min(result.len() - offset);
|
||||
let copy_len = data.len().min(bound);
|
||||
result[offset..offset + copy_len].copy_from_slice(&data[..copy_len]);
|
||||
}
|
||||
|
||||
// Determine filename: URL path filename, then manifest name
|
||||
@@ -3436,6 +3426,136 @@ fn try_expand_chunk_manifest(
|
||||
Some((StatusCode::OK, response_headers, result).into_response())
|
||||
}
|
||||
|
||||
/// Read one chunk-manifest chunk's final (decompressed) content bytes from
|
||||
/// wherever it lives: a local regular volume, a local EC volume
|
||||
/// (reconstruct-on-read from surviving shards), or a peer resolved via the
|
||||
/// master. Mirrors Go's ChunkedFileReader, which looks every chunk up through
|
||||
/// the master instead of assuming a local regular needle.
|
||||
async fn read_chunk_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
fid: &str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let (vid, nid, cookie) =
|
||||
parse_url_path(fid).ok_or_else(|| format!("invalid chunk fid: {}", fid))?;
|
||||
|
||||
// Decide where the chunk lives under one store read lock; drop it before any
|
||||
// await (the EC and remote paths are async).
|
||||
enum Placement {
|
||||
Ec,
|
||||
Remote,
|
||||
}
|
||||
let placement = {
|
||||
let store = state.store.read().unwrap();
|
||||
if store.find_volume(vid).is_some() {
|
||||
let mut n = Needle {
|
||||
id: nid,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
return store
|
||||
.read_volume_needle(vid, &mut n)
|
||||
.map_err(|e| format!("{}", e))
|
||||
.and_then(|_| cookie_checked_chunk(n, cookie));
|
||||
} else if store.find_ec_volume(vid).is_some() {
|
||||
Placement::Ec
|
||||
} else {
|
||||
Placement::Remote
|
||||
}
|
||||
};
|
||||
|
||||
match placement {
|
||||
Placement::Ec => {
|
||||
match crate::server::store_ec::read_ec_shard_needle_distributed(state, vid, nid).await {
|
||||
Ok(Some(n)) => cookie_checked_chunk(n, cookie),
|
||||
Ok(None) => Err("not found".to_string()),
|
||||
Err(e) => Err(format!("{}", e)),
|
||||
}
|
||||
}
|
||||
// The peer serves through its own GET handler, which validates the cookie.
|
||||
Placement::Remote => read_remote_chunk_needle(state, vid, fid).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a locally-read chunk's cookie against the one in its fid, then return
|
||||
/// its content bytes. The main GET paths check the cookie after a read; a chunk
|
||||
/// read must do the same so a stale/guessed id can't serve another needle's data.
|
||||
fn cookie_checked_chunk(n: Needle, cookie: Cookie) -> Result<Vec<u8>, String> {
|
||||
if n.cookie != cookie {
|
||||
return Err("not found".to_string());
|
||||
}
|
||||
decompress_chunk(n)
|
||||
}
|
||||
|
||||
/// Return a needle's content bytes, decompressing gzip payloads the way the read
|
||||
/// handler does for a client that did not ask for gzip.
|
||||
fn decompress_chunk(n: Needle) -> Result<Vec<u8>, String> {
|
||||
if n.is_compressed() {
|
||||
match maybe_decompress_gzip(&n.data) {
|
||||
Ok(d) => Ok(d),
|
||||
Err(GunzipError::TooLarge) => {
|
||||
Err("compressed chunk exceeds decompression limit".to_string())
|
||||
}
|
||||
// Not valid gzip; keep the raw bytes, matching the prior fallback.
|
||||
Err(GunzipError::Decode) => Ok(n.data),
|
||||
}
|
||||
} else {
|
||||
Ok(n.data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch a chunk that is not hosted locally from a peer volume server. The peer
|
||||
/// serves the final (decompressed) bytes whether the chunk is on a regular or EC
|
||||
/// volume, so a chunk whose EC shards live elsewhere is still reconstructed on
|
||||
/// the holder's side. Mirrors Go's ChunkedFileReader.readChunkNeedle.
|
||||
async fn read_remote_chunk_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
fid: &str,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let locations = lookup_volume(
|
||||
&state.http_client,
|
||||
&state.outgoing_http_scheme,
|
||||
&state.master_url,
|
||||
vid.0,
|
||||
)
|
||||
.await?;
|
||||
if locations.is_empty() {
|
||||
return Err("not found".to_string());
|
||||
}
|
||||
|
||||
let mut last_err = String::new();
|
||||
for loc in &locations {
|
||||
// Skip self: the local paths already ruled this server out.
|
||||
if loc.url.contains(&state.self_url) {
|
||||
continue;
|
||||
}
|
||||
let target_http = to_http_address(&loc.url);
|
||||
let url = match normalize_outgoing_http_url(
|
||||
&state.outgoing_http_scheme,
|
||||
&format!("{}/{}?proxied=true", target_http, fid),
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
last_err = e;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match state.http_client.get(&url).send().await {
|
||||
Ok(resp) if resp.status().is_success() => match resp.bytes().await {
|
||||
Ok(b) => return Ok(b.to_vec()),
|
||||
Err(e) => last_err = format!("read body from {}: {}", url, e),
|
||||
},
|
||||
Ok(resp) => last_err = format!("{} returned {}", url, resp.status()),
|
||||
Err(e) => last_err = format!("request to {} failed: {}", url, e),
|
||||
}
|
||||
}
|
||||
Err(if last_err.is_empty() {
|
||||
"not found".to_string()
|
||||
} else {
|
||||
last_err
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
@@ -4022,6 +4142,26 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Master /dir/lookup often omits publicUrl when empty (Go `json:"publicUrl,omitempty"`).
|
||||
/// Replication must still parse locations or every cross-DC write fails.
|
||||
#[test]
|
||||
fn test_lookup_result_deserializes_without_public_url() {
|
||||
let body = r#"{
|
||||
"volumeOrFileId": "9",
|
||||
"locations": [
|
||||
{"url": "volume-a.example:8080", "dataCenter": "dc-a", "grpcPort": 18080},
|
||||
{"url": "volume-b.example:8080", "dataCenter": "dc-b", "grpcPort": 18080}
|
||||
]
|
||||
}"#;
|
||||
let result: LookupResult = serde_json::from_str(body).expect("parse lookup JSON");
|
||||
let locations = result.locations.expect("locations");
|
||||
assert_eq!(locations.len(), 2);
|
||||
assert_eq!(locations[0].url, "volume-a.example:8080");
|
||||
assert!(locations[0].public_url.is_empty());
|
||||
assert_eq!(locations[0].public_or_url(), "volume-a.example:8080");
|
||||
assert_eq!(locations[0].grpc_port, 18080);
|
||||
}
|
||||
|
||||
/// Regression test for issue #9274.
|
||||
///
|
||||
/// SeaweedFS encodes a server's gRPC port by appending `.grpcPort` to
|
||||
|
||||
@@ -625,7 +625,8 @@ async fn send_deregister_heartbeat(
|
||||
) {
|
||||
let empty = {
|
||||
let store = state.store.read().unwrap();
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store);
|
||||
// Deregister: no effective max computed, fall back to configured max.
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(&store, &[]);
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
ip: config.ip.clone(),
|
||||
@@ -747,7 +748,10 @@ fn collect_heartbeat(
|
||||
)
|
||||
}
|
||||
|
||||
fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::DiskTag>) {
|
||||
fn collect_location_metadata(
|
||||
store: &Store,
|
||||
disk_max_by_id: &[i32],
|
||||
) -> (Vec<String>, Vec<master_pb::DiskTag>) {
|
||||
let location_uuids = store
|
||||
.locations
|
||||
.iter()
|
||||
@@ -757,9 +761,17 @@ fn collect_location_metadata(store: &Store) -> (Vec<String>, Vec<master_pb::Disk
|
||||
.locations
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(disk_id, loc)| master_pb::DiskTag {
|
||||
disk_id: disk_id as u32,
|
||||
tags: loc.tags.clone(),
|
||||
.map(|(disk_id, loc)| {
|
||||
let max_volume_count = disk_max_by_id
|
||||
.get(disk_id)
|
||||
.copied()
|
||||
.unwrap_or_else(|| loc.max_volume_count.load(Ordering::Relaxed));
|
||||
master_pb::DiskTag {
|
||||
disk_id: disk_id as u32,
|
||||
tags: loc.tags.clone(),
|
||||
r#type: loc.disk_type.to_string(),
|
||||
max_volume_count: max_volume_count as i64,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(location_uuids, disk_tags)
|
||||
@@ -790,6 +802,8 @@ fn build_heartbeat_with_ec_status(
|
||||
let mut volumes = Vec::new();
|
||||
let mut max_file_key = NeedleId(0);
|
||||
let mut max_volume_counts: HashMap<String, u32> = HashMap::new();
|
||||
let mut disk_total_bytes: HashMap<String, u64> = HashMap::new();
|
||||
let mut disk_free_bytes: HashMap<String, u64> = HashMap::new();
|
||||
|
||||
// Collect per-collection disk size and read-only counts for metrics
|
||||
let mut disk_sizes: HashMap<String, (u64, u64)> = HashMap::new(); // (normal, deleted)
|
||||
@@ -797,6 +811,9 @@ fn build_heartbeat_with_ec_status(
|
||||
|
||||
let volume_size_limit = store.volume_size_limit.load(Ordering::Relaxed);
|
||||
|
||||
// Per-disk effective max for DiskTag, captured alongside the per-type sum.
|
||||
let mut disk_max_by_id = vec![0i32; store.locations.len()];
|
||||
|
||||
for (disk_id, loc) in store.locations.iter_mut().enumerate() {
|
||||
let disk_type_str = loc.disk_type.to_string();
|
||||
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
|
||||
@@ -812,7 +829,15 @@ fn build_heartbeat_with_ec_status(
|
||||
if effective_max_count < 0 {
|
||||
effective_max_count = 0;
|
||||
}
|
||||
*max_volume_counts.entry(disk_type_str).or_insert(0) += effective_max_count as u32;
|
||||
*max_volume_counts.entry(disk_type_str.clone()).or_insert(0) += effective_max_count as u32;
|
||||
disk_max_by_id[disk_id] = effective_max_count;
|
||||
// Sum capacity per disk type; assumes one location per filesystem. Locations
|
||||
// sharing a mount over-report absolute bytes but not the used ratio the gate
|
||||
// uses. Mirrors weed/storage/store.go.
|
||||
*disk_total_bytes.entry(disk_type_str.clone()).or_insert(0) +=
|
||||
loc.disk_total_bytes.load(Ordering::Relaxed);
|
||||
*disk_free_bytes.entry(disk_type_str).or_insert(0) +=
|
||||
loc.disk_free_bytes.load(Ordering::Relaxed);
|
||||
|
||||
let mut delete_vids = Vec::new();
|
||||
for (_, vol) in loc.iter_volumes() {
|
||||
@@ -861,7 +886,7 @@ fn build_heartbeat_with_ec_status(
|
||||
replica_placement: vol.super_block.replica_placement.to_byte() as u32,
|
||||
version: vol.super_block.version.0 as u32,
|
||||
ttl: vol.super_block.ttl.to_u32(),
|
||||
compact_revision: vol.last_compact_revision() as u32,
|
||||
compact_revision: vol.super_block.compaction_revision as u32,
|
||||
modified_at_second: vol.last_modified_ts() as i64,
|
||||
disk_type: loc.disk_type.to_string(),
|
||||
disk_id: disk_id as u32,
|
||||
@@ -930,7 +955,7 @@ fn build_heartbeat_with_ec_status(
|
||||
crate::metrics::MAX_VOLUMES.set(total_max);
|
||||
|
||||
let has_no_volumes = volumes.is_empty();
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(store);
|
||||
let (location_uuids, disk_tags) = collect_location_metadata(store, &disk_max_by_id);
|
||||
|
||||
master_pb::Heartbeat {
|
||||
id: store.id.clone(),
|
||||
@@ -946,6 +971,8 @@ fn build_heartbeat_with_ec_status(
|
||||
has_no_volumes,
|
||||
has_no_ec_shards,
|
||||
max_volume_counts,
|
||||
disk_total_bytes,
|
||||
disk_free_bytes,
|
||||
grpc_port: config.grpc_port as u32,
|
||||
location_uuids,
|
||||
disk_tags,
|
||||
@@ -1153,6 +1180,46 @@ mod tests {
|
||||
heartbeat.disk_tags[0].tags,
|
||||
vec!["fast".to_string(), "ssd".to_string()]
|
||||
);
|
||||
assert_eq!(heartbeat.disk_tags[0].r#type, DiskType::HardDrive.to_string());
|
||||
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_disk_tag_reflects_disk_space_low_override() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
3,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(7),
|
||||
"pics",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Low disk space caps the per-disk max at used slots (1 volume, 0 EC).
|
||||
store.locations[0]
|
||||
.is_disk_space_low
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
assert_eq!(heartbeat.disk_tags[0].max_volume_count, 1);
|
||||
assert_eq!(heartbeat.max_volume_counts[&DiskType::HardDrive.to_string()], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1262,6 +1329,43 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_heartbeat_reports_disk_bytes() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let dir = temp_dir.path().to_str().unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
8,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
// Populate the cached physical-capacity fields from a real statvfs probe.
|
||||
store.locations[0].check_disk_space();
|
||||
|
||||
let heartbeat = build_heartbeat(&test_config(), &mut store);
|
||||
let disk_type = store.locations[0].disk_type.to_string();
|
||||
|
||||
assert!(
|
||||
heartbeat
|
||||
.disk_total_bytes
|
||||
.get(&disk_type)
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
> 0,
|
||||
"expected nonzero disk_total_bytes for the temp filesystem"
|
||||
);
|
||||
assert!(
|
||||
heartbeat.disk_free_bytes.contains_key(&disk_type),
|
||||
"expected a disk_free_bytes entry for the disk type"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collect_ec_heartbeat_sets_go_metadata_and_ec_metrics() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -44,7 +44,7 @@ use crate::server::grpc_client::{build_grpc_endpoint, parse_grpc_address, GRPC_M
|
||||
use crate::server::request_id::outgoing_request_id_interceptor;
|
||||
use crate::server::volume_server::{to_http_address, VolumeServerState};
|
||||
use crate::storage::erasure_coding::ec_shard::ShardId;
|
||||
use crate::storage::needle::needle::{get_actual_size, Needle};
|
||||
use crate::storage::needle::needle::{get_actual_size, Needle, NeedleError};
|
||||
use crate::storage::store_ec_reconcile::EcVolumeMissingIndex;
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::volume_file_name;
|
||||
@@ -115,8 +115,13 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
{
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => {
|
||||
shard_locations = fresh.clone();
|
||||
write_back_shard_locations(state, vid, fresh);
|
||||
// A complete reply merges into the cache; an incomplete one
|
||||
// (< data_shards) is left unwritten — keep the prior cache.
|
||||
if let Some(merged) =
|
||||
write_back_shard_locations(state, vid, fresh, snapshot.data_shards as usize)
|
||||
{
|
||||
shard_locations = merged;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Lookup failed — proceed with cached values. If cache
|
||||
@@ -144,7 +149,7 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
shard_offset,
|
||||
size,
|
||||
} => {
|
||||
let buf = fetch_one_interval(
|
||||
let (buf, is_deleted) = fetch_one_interval(
|
||||
state,
|
||||
vid,
|
||||
needle_id,
|
||||
@@ -157,6 +162,12 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
snapshot.encode_ts_ns,
|
||||
)
|
||||
.await?;
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): treat as not-found rather than
|
||||
// serving zeros, mirroring Go's ErrorDeleted.
|
||||
if is_deleted {
|
||||
return Ok(None);
|
||||
}
|
||||
assembled.push(buf);
|
||||
}
|
||||
}
|
||||
@@ -193,6 +204,229 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
Ok(Some(n))
|
||||
}
|
||||
|
||||
/// FULL EC scrub: verify every needle's bytes across local AND remote shards,
|
||||
/// without decoding (so genuine shard faults are reported rather than healed).
|
||||
/// Mirrors Go's `Store.ScrubEcVolume`. Returns (rows walked, broken shards,
|
||||
/// errors). `force_deleted_needles_check` disables the benign delete-state
|
||||
/// size-mismatch suppression.
|
||||
///
|
||||
/// Shard locations are refreshed once up front. Each needle is then processed via
|
||||
/// `scrub_snapshot_under_lock` + lock-drop + no-reconstruct `read_remote_ec_shard_interval`,
|
||||
/// so no `!Send` store guard is held across an `.await`.
|
||||
pub async fn scrub_ec_volume_distributed(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
force_deleted_needles_check: bool,
|
||||
) -> (i64, Vec<crate::pb::volume_server_pb::EcShardInfo>, Vec<String>) {
|
||||
// Phase A — under the Store read lock, run the index scrub and grab the
|
||||
// paths/scalars + shard-location staleness; release the lock before any await.
|
||||
let (ecx_path, collection, seed_errs, cached_locations, cache_refreshed_at, data_shards, total_shards) = {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!("EC volume id {} not found", vid.0)],
|
||||
)
|
||||
}
|
||||
};
|
||||
// full scan means verifying the index as well
|
||||
let (_, errs) = ecv.scrub_index();
|
||||
// Bind to locals so the inner RwLock/Mutex guards drop before the block ends.
|
||||
let cached_locations = ecv.shard_locations.read().unwrap().clone();
|
||||
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
|
||||
let data_shards = ecv.data_shards as usize;
|
||||
let total_shards = (ecv.data_shards + ecv.parity_shards) as usize;
|
||||
(
|
||||
ecv.ecx_file_name(),
|
||||
ecv.collection.clone(),
|
||||
errs,
|
||||
cached_locations,
|
||||
cache_refreshed_at,
|
||||
data_shards,
|
||||
total_shards,
|
||||
)
|
||||
};
|
||||
let mut errs = seed_errs;
|
||||
|
||||
// Refresh the shard-location cache once up front (mirrors Go's
|
||||
// cachedLookupEcShardLocations). A partial reply (< data_shards locations, a
|
||||
// master mid-recovery) or a failed lookup is a hard, retryable error — never
|
||||
// overwrite a good cache with a partial map or storm a down master per needle.
|
||||
if needs_refresh(&cached_locations, cache_refreshed_at, data_shards, total_shards) {
|
||||
match cached_lookup_ec_shard_locations(state, vid).await {
|
||||
Ok(fresh) => {
|
||||
if write_back_shard_locations(state, vid, fresh, data_shards).is_none() {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!(
|
||||
"failed to locate shard via master grpc: fewer than {} data-shard locations returned",
|
||||
data_shards
|
||||
)],
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!("failed to locate shard via master grpc: {}", e)],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hoist the post-refresh shard-location map once; it is stable for the whole
|
||||
// walk, so per-needle snapshots no longer clone it.
|
||||
let locations: HashMap<ShardId, Vec<String>> = {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!("EC volume id {} not found", vid.0)],
|
||||
)
|
||||
}
|
||||
};
|
||||
let map = ecv.shard_locations.read().unwrap().clone();
|
||||
map
|
||||
};
|
||||
|
||||
// Walk the .ecx (private fd, no lock) for the row count + live (id, offset, size).
|
||||
let mut count: i64 = 0;
|
||||
let mut needles: Vec<(NeedleId, Offset, Size)> = Vec::new();
|
||||
match fs::File::open(&ecx_path) {
|
||||
Ok(mut f) => {
|
||||
if let Err(e) = crate::storage::idx::walk_index_file(&mut f, 0, |id, offset, size| {
|
||||
count += 1;
|
||||
// Skip ALL deleted entries: -1 tombstones (runtime delete folded
|
||||
// into .ecx) and -originalSize entries (a needle deleted on the
|
||||
// regular volume before EC encode). get_actual_size uses the raw
|
||||
// signed size, so a negative would yield empty intervals
|
||||
// (false-positive) or an under-16-byte buffer (parse panic).
|
||||
if !size.is_deleted() {
|
||||
needles.push((id, offset, size));
|
||||
}
|
||||
Ok(())
|
||||
}) {
|
||||
errs.push(format!("walk ECX file {}: {}", ecx_path, e));
|
||||
}
|
||||
}
|
||||
Err(e) => errs.push(format!("open ECX file {}: {}", ecx_path, e)),
|
||||
}
|
||||
|
||||
// reads for EC chunks can hit the same shard repeatedly, so dedupe broken shards
|
||||
let mut broken_shards: HashMap<ShardId, crate::pb::volume_server_pb::EcShardInfo> = HashMap::new();
|
||||
|
||||
for (id, offset, size) in needles {
|
||||
// Per-needle snapshot under the lock from the RAW .ecx (offset, size) so
|
||||
// logically-deleted needles are still verified; lock dropped before await.
|
||||
let snapshot = match scrub_snapshot_under_lock(state, vid, offset, size) {
|
||||
Ok(s) => s,
|
||||
// Volume unmounted mid-scan: abort with an error rather than skipping
|
||||
// every remaining needle, which would report a false-CLEAN result.
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
errs.push(format!("EC volume {} unmounted during scrub: {}", vid.0, e));
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Read each interval local-then-remote WITHOUT reconstructing: we verify
|
||||
// the shards are valid, we do not heal them. Locations refreshed above.
|
||||
let n_intervals = snapshot.intervals.len();
|
||||
let mut data: Vec<u8> = Vec::with_capacity(snapshot.actual_size);
|
||||
for (i, res) in snapshot.intervals.iter().enumerate() {
|
||||
match res {
|
||||
IntervalResult::Local(buf) => data.extend_from_slice(buf),
|
||||
IntervalResult::NeedRemote {
|
||||
shard_id,
|
||||
shard_offset,
|
||||
size: ssize,
|
||||
} => {
|
||||
let sources: &[String] =
|
||||
locations.get(shard_id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
match read_remote_ec_shard_interval(
|
||||
state,
|
||||
sources,
|
||||
vid,
|
||||
id,
|
||||
*shard_id,
|
||||
*shard_offset,
|
||||
*ssize,
|
||||
snapshot.encode_ts_ns,
|
||||
)
|
||||
.await
|
||||
{
|
||||
// A deleted shard yields no bytes; zero-fill the interval so
|
||||
// the assembled needle reaches read_bytes -> SizeMismatch{0}
|
||||
// -> the delete-state suppression (mirrors Go's pre-zeroed buffer).
|
||||
Ok((_, true)) => data.resize(data.len() + *ssize, 0),
|
||||
Ok((buf, false)) => data.extend_from_slice(&buf),
|
||||
Err(_) => {
|
||||
errs.push(format!(
|
||||
"failed to read EC shard {} for needle {} on volume {} (interval {}/{})",
|
||||
shard_id, id.0, vid.0, i + 1, n_intervals
|
||||
));
|
||||
broken_shards.insert(
|
||||
*shard_id,
|
||||
crate::pb::volume_server_pb::EcShardInfo {
|
||||
shard_id: *shard_id as u32,
|
||||
size: *ssize as i64,
|
||||
collection: collection.clone(),
|
||||
volume_id: vid.0,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also fires when a chunk read broke out above (data is short).
|
||||
if data.len() != snapshot.actual_size {
|
||||
errs.push(format!(
|
||||
"expected {} bytes for needle {}, got {}",
|
||||
snapshot.actual_size,
|
||||
id.0,
|
||||
data.len()
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut n = Needle::default();
|
||||
if let Err(e) = n.read_bytes(&data, 0, snapshot.size_for_parse, snapshot.version) {
|
||||
// A delete-state disagreement between the index and the reassembled
|
||||
// header (live index vs zero header size) is not corruption.
|
||||
let delete_state_disagrees = matches!(
|
||||
&e,
|
||||
NeedleError::SizeMismatch { found, .. }
|
||||
if snapshot.size_for_parse.is_deleted() != (found.0 == 0)
|
||||
);
|
||||
if !delete_state_disagrees || force_deleted_needles_check {
|
||||
errs.push(format!("needle {} on EC volume {}: {}", id.0, vid.0, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mirror Go CmpEcShardInfo: sort by (volume_id, shard_id).
|
||||
let mut broken: Vec<crate::pb::volume_server_pb::EcShardInfo> =
|
||||
broken_shards.into_values().collect();
|
||||
broken.sort_by(|a, b| a.volume_id.cmp(&b.volume_id).then(a.shard_id.cmp(&b.shard_id)));
|
||||
|
||||
(count, broken, errs)
|
||||
}
|
||||
|
||||
fn snapshot_under_lock(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
@@ -207,38 +441,81 @@ fn snapshot_under_lock(
|
||||
// Reuse EcVolume::locate_needle for offset/size resolution AND
|
||||
// the per-needle shard-interval math — it's the same routine the
|
||||
// local-only read path uses, so we stay byte-identical on the
|
||||
// shard-size + interval boundaries.
|
||||
// shard-size + interval boundaries. locate_needle applies the runtime
|
||||
// delete mask, which is correct for serving reads.
|
||||
let (offset, size, intervals) = match ecv.locate_needle(needle_id)? {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
};
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Some)
|
||||
}
|
||||
|
||||
/// Like `snapshot_under_lock`, but locates intervals from the RAW .ecx
|
||||
/// (offset, size) the FULL-scrub walk supplies — NOT `locate_needle`, which
|
||||
/// masks runtime-deleted needles. EC deletes are logical (the shard bytes stay
|
||||
/// until re-encode), so the scrub must still byte-verify them, matching Go's
|
||||
/// `Store.ScrubEcVolume` which walks the unmasked index.
|
||||
fn scrub_snapshot_under_lock(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
) -> io::Result<ScrubSnapshot> {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
// Volume unmounted mid-scan: a distinct NotFound so the caller aborts
|
||||
// with an error rather than silently skipping (which would false-CLEAN).
|
||||
None => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("EC volume {} not found (unmounted mid-scan)", vid.0),
|
||||
))
|
||||
}
|
||||
};
|
||||
let intervals = ecv.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
|
||||
if intervals.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"no intervals for needle",
|
||||
));
|
||||
}
|
||||
let actual = get_actual_size(size, ecv.version);
|
||||
Ok(ScrubSnapshot {
|
||||
version: ecv.version,
|
||||
actual_size: get_actual_size(size, ecv.version) as usize,
|
||||
size_for_parse: size,
|
||||
intervals: read_local_intervals(ecv, &intervals),
|
||||
encode_ts_ns: ecv.encode_ts_ns,
|
||||
})
|
||||
}
|
||||
|
||||
// Phase A.local: for each interval read the local shard if we
|
||||
// hold it; otherwise fall through to remote. We accumulate the
|
||||
// results in interval order so the assembly step is just a
|
||||
// concat.
|
||||
/// Scalars + locally-read intervals for the FULL scrub. Unlike `Snapshot` it
|
||||
/// omits the shard-location cache: the scrub hoists the refreshed map once up
|
||||
/// front instead of cloning it per needle.
|
||||
struct ScrubSnapshot {
|
||||
version: Version,
|
||||
actual_size: usize,
|
||||
size_for_parse: Size,
|
||||
intervals: Vec<IntervalResult>,
|
||||
encode_ts_ns: i64,
|
||||
}
|
||||
|
||||
/// Read any locally-held shard intervals, marking the rest `NeedRemote`. Shared
|
||||
/// by the read-path `build_snapshot` and the scrub snapshot.
|
||||
fn read_local_intervals(
|
||||
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
|
||||
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
|
||||
) -> Vec<IntervalResult> {
|
||||
let mut interval_results = Vec::with_capacity(intervals.len());
|
||||
for interval in &intervals {
|
||||
for interval in intervals {
|
||||
let (shard_id, shard_offset) = interval.to_shard_id_and_offset(ecv.data_shards);
|
||||
let buf_size = interval.size as usize;
|
||||
let local = ecv
|
||||
.shards
|
||||
.get(shard_id as usize)
|
||||
.and_then(|s| s.as_ref());
|
||||
let local = ecv.shards.get(shard_id as usize).and_then(|s| s.as_ref());
|
||||
match local {
|
||||
Some(shard) => {
|
||||
let mut buf = vec![0u8; buf_size];
|
||||
match shard.read_at(&mut buf, shard_offset as u64) {
|
||||
Ok(n) if n == buf_size => {
|
||||
interval_results.push(IntervalResult::Local(buf));
|
||||
}
|
||||
Ok(n) if n == buf_size => interval_results.push(IntervalResult::Local(buf)),
|
||||
_ => interval_results.push(IntervalResult::NeedRemote {
|
||||
shard_id,
|
||||
shard_offset,
|
||||
@@ -253,11 +530,29 @@ fn snapshot_under_lock(
|
||||
}),
|
||||
}
|
||||
}
|
||||
interval_results
|
||||
}
|
||||
|
||||
/// Read local intervals, then snapshot the scalars + shard-location cache so the
|
||||
/// read path can drop the store lock before awaiting remote reads.
|
||||
fn build_snapshot(
|
||||
ecv: &crate::storage::erasure_coding::ec_volume::EcVolume,
|
||||
offset: Offset,
|
||||
size: Size,
|
||||
intervals: &[crate::storage::erasure_coding::ec_locate::Interval],
|
||||
) -> io::Result<Snapshot> {
|
||||
if intervals.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"no intervals for needle",
|
||||
));
|
||||
}
|
||||
let actual = get_actual_size(size, ecv.version);
|
||||
let interval_results = read_local_intervals(ecv, intervals);
|
||||
let cached_locations = ecv.shard_locations.read().unwrap().clone();
|
||||
let cache_refreshed_at = *ecv.shard_locations_refresh_time.lock().unwrap();
|
||||
|
||||
Ok(Some(Snapshot {
|
||||
Ok(Snapshot {
|
||||
data_shards: ecv.data_shards,
|
||||
parity_shards: ecv.parity_shards,
|
||||
version: ecv.version,
|
||||
@@ -268,7 +563,7 @@ fn snapshot_under_lock(
|
||||
cached_locations,
|
||||
cache_refreshed_at,
|
||||
encode_ts_ns: ecv.encode_ts_ns,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Master `LookupEcVolume` freshness rules — match Go's
|
||||
@@ -349,19 +644,29 @@ async fn cached_lookup_ec_shard_locations(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
|
||||
/// cache. Returns the merged map on success, or `None` when the reply is
|
||||
/// incomplete (and was therefore NOT written) or the volume is gone.
|
||||
///
|
||||
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
|
||||
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
|
||||
/// partial, not ground truth — Go aborts the lookup with a retryable error and
|
||||
/// leaves the cache + refresh time untouched. Returning `None` without writing
|
||||
/// does the same, so a previously-complete cache is never clobbered with a
|
||||
/// partial map. On a complete reply the write is a per-shard MERGE (see
|
||||
/// `merge_shard_locations`), not a full replace.
|
||||
fn write_back_shard_locations(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
) {
|
||||
let store = state.store.read().unwrap();
|
||||
if let Some(ecv) = store.find_ec_volume(vid) {
|
||||
// Atomic swap + freshness stamp so a concurrent reader sees
|
||||
// either the prior cache or the fresh one — never an
|
||||
// intermediate half-replaced map with the freshness flag
|
||||
// already flipped.
|
||||
ecv.replace_shard_locations(locations);
|
||||
data_shards: usize,
|
||||
) -> Option<HashMap<ShardId, Vec<String>>> {
|
||||
if locations.len() < data_shards {
|
||||
return None;
|
||||
}
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = store.find_ec_volume(vid)?;
|
||||
Some(ecv.merge_shard_locations(locations))
|
||||
}
|
||||
|
||||
/// Build a SeaweedFS-style `host:httpPort.grpcPort` address from a
|
||||
@@ -393,7 +698,7 @@ async fn fetch_one_interval(
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
// Direct peer read against the cached locations for this shard.
|
||||
if let Some(sources) = shard_locations.get(&shard_id) {
|
||||
if !sources.is_empty() {
|
||||
@@ -409,7 +714,9 @@ async fn fetch_one_interval(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(buf) => return Ok(buf),
|
||||
// A deleted needle short-circuits: don't reconstruct (every shard
|
||||
// would report deleted), let the caller return "deleted".
|
||||
Ok((buf, is_deleted)) => return Ok((buf, is_deleted)),
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
"direct read ec shard {}.{} from {:?} failed: {} — will reconstruct",
|
||||
@@ -425,7 +732,7 @@ async fn fetch_one_interval(
|
||||
|
||||
// Reconstruct: fan-out reads to every other shard at the same
|
||||
// (shard_offset, size). Mirrors `recoverOneRemoteEcShardInterval`.
|
||||
recover_one_remote_ec_shard_interval(
|
||||
let buf = recover_one_remote_ec_shard_interval(
|
||||
state,
|
||||
vid,
|
||||
needle_id,
|
||||
@@ -437,7 +744,8 @@ async fn fetch_one_interval(
|
||||
parity_shards,
|
||||
expected_encode_ts_ns,
|
||||
)
|
||||
.await
|
||||
.await?;
|
||||
Ok((buf, false))
|
||||
}
|
||||
|
||||
async fn read_remote_ec_shard_interval(
|
||||
@@ -449,7 +757,7 @@ async fn read_remote_ec_shard_interval(
|
||||
shard_offset: i64,
|
||||
size: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
let mut last_err: Option<io::Error> = None;
|
||||
for src in sources {
|
||||
match do_read_remote_ec_shard_interval(
|
||||
@@ -464,7 +772,7 @@ async fn read_remote_ec_shard_interval(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(buf) => return Ok(buf),
|
||||
Ok(res) => return Ok(res),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
@@ -485,7 +793,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
shard_offset: i64,
|
||||
size: usize,
|
||||
expected_encode_ts_ns: i64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
) -> io::Result<(Vec<u8>, bool)> {
|
||||
let grpc_addr =
|
||||
parse_grpc_address(source).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
|
||||
let endpoint = build_grpc_endpoint(&grpc_addr, state.outgoing_grpc_tls.as_ref())
|
||||
@@ -534,6 +842,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
let mut stream = resp.into_inner();
|
||||
|
||||
let mut out = Vec::with_capacity(size);
|
||||
let mut is_deleted = false;
|
||||
while let Some(msg) = stream
|
||||
.message()
|
||||
.await
|
||||
@@ -551,10 +860,23 @@ async fn do_read_remote_ec_shard_interval(
|
||||
),
|
||||
));
|
||||
}
|
||||
if msg.is_deleted {
|
||||
is_deleted = true;
|
||||
}
|
||||
if !msg.data.is_empty() {
|
||||
out.extend_from_slice(&msg.data);
|
||||
}
|
||||
}
|
||||
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
|
||||
// at read time and answers is_deleted with no payload. Signal the deletion to
|
||||
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
|
||||
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
|
||||
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
|
||||
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
|
||||
// into Reed-Solomon. Exempt from the short-read guard below.
|
||||
if is_deleted {
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
if out.len() < size {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
@@ -569,7 +891,7 @@ async fn do_read_remote_ec_shard_interval(
|
||||
));
|
||||
}
|
||||
out.truncate(size);
|
||||
Ok(out)
|
||||
Ok((out, false))
|
||||
}
|
||||
|
||||
async fn recover_one_remote_ec_shard_interval(
|
||||
@@ -653,8 +975,11 @@ async fn recover_one_remote_ec_shard_interval(
|
||||
|
||||
for (sid, res) in results {
|
||||
match res {
|
||||
Ok(buf) => {
|
||||
if (sid as usize) < total_shards {
|
||||
// Exclude a deleted shard from reconstruction (Go gates on a full
|
||||
// read): feeding the empty/zero buffer into Reed-Solomon would
|
||||
// corrupt the recovered shard.
|
||||
Ok((buf, is_deleted)) => {
|
||||
if !is_deleted && (sid as usize) < total_shards {
|
||||
bufs[sid as usize] = Some(buf);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::sync::Arc;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars;
|
||||
use crate::storage::erasure_coding::ec_shard::{
|
||||
EcVolumeShard, DATA_SHARDS_COUNT, ERASURE_CODING_LARGE_BLOCK_SIZE,
|
||||
ERASURE_CODING_SMALL_BLOCK_SIZE,
|
||||
@@ -38,6 +39,10 @@ pub struct DiskLocation {
|
||||
ec_volumes: HashMap<VolumeId, EcVolume>,
|
||||
pub is_disk_space_low: Arc<AtomicBool>,
|
||||
pub available_space: AtomicU64,
|
||||
// Physical filesystem capacity from the latest check_disk_space probe, reported
|
||||
// to the master so balancing can see real disk fullness, not just slot counts.
|
||||
pub disk_total_bytes: AtomicU64,
|
||||
pub disk_free_bytes: AtomicU64,
|
||||
pub min_free_space: MinFreeSpace,
|
||||
}
|
||||
|
||||
@@ -74,6 +79,8 @@ impl DiskLocation {
|
||||
ec_volumes: HashMap::new(),
|
||||
is_disk_space_low: Arc::new(AtomicBool::new(false)),
|
||||
available_space: AtomicU64::new(0),
|
||||
disk_total_bytes: AtomicU64::new(0),
|
||||
disk_free_bytes: AtomicU64::new(0),
|
||||
min_free_space,
|
||||
})
|
||||
}
|
||||
@@ -395,6 +402,12 @@ impl DiskLocation {
|
||||
for i in 0..MAX_SHARD_COUNT {
|
||||
rm_if_present(format!("{}.ec{:02}", base, i))?;
|
||||
}
|
||||
|
||||
// Remove the bitrot checksum sidecars from both the data and idx dirs.
|
||||
remove_bitrot_sidecars(&base)?;
|
||||
if self.idx_directory != self.directory {
|
||||
remove_bitrot_sidecars(&idx_base)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -655,6 +668,8 @@ impl DiskLocation {
|
||||
};
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
self.available_space.store(free, Ordering::Relaxed);
|
||||
self.disk_total_bytes.store(total, Ordering::Relaxed);
|
||||
self.disk_free_bytes.store(free, Ordering::Relaxed);
|
||||
|
||||
// Update resource gauges
|
||||
crate::metrics::RESOURCE_GAUGE
|
||||
|
||||
@@ -0,0 +1,920 @@
|
||||
//! EC bitrot detection — checksum sidecar.
|
||||
//!
|
||||
//! A per-volume sidecar file stores a CRC32C (Castagnoli) checksum for every
|
||||
//! fixed-size block of every EC shard, so a scrub (and the reconstruction path)
|
||||
//! can detect silent disk corruption in any shard — including cold parity shards
|
||||
//! that are never read during normal serving.
|
||||
//!
|
||||
//! The sidecar is OPTIONAL: an absent or generation-mismatched sidecar simply
|
||||
//! means "feature off" for that generation, so old binaries, JSON-only nodes,
|
||||
//! and rollback deployments ignore it and degrade gracefully.
|
||||
//!
|
||||
//! On-disk layout of `<base>.ecsum` (legacy/generation 0) and `<base>.ecsum.v<N>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! [ magic(4) | format_version(2) | payload_len(4) | payload_crc32c(4) ] [ proto payload ]
|
||||
//! ```
|
||||
//!
|
||||
//! All header fields are BIG-ENDIAN. The header's `payload_crc32c` lets a loader
|
||||
//! detect corruption of the sidecar itself BEFORE trusting any contents, so a
|
||||
//! rotted sidecar can never be mistaken for shard corruption. This format is
|
||||
//! byte-identical to the Go implementation in
|
||||
//! `weed/storage/erasure_coding/ec_bitrot.go`.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use prost::Message;
|
||||
|
||||
use crate::pb::volume_server_pb::{
|
||||
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums, EcShardConfig,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_shard::MAX_SHARD_COUNT;
|
||||
use crate::storage::needle::crc::CRC;
|
||||
|
||||
/// Canonical extension for the checksum sidecar. Generation 0 (legacy/fresh
|
||||
/// encode) uses `<base>.ecsum`; vacuum generation N uses `<base>.ecsum.v<N>`,
|
||||
/// mirroring the `.vif`/`.ecx` versioned convention.
|
||||
pub const BITROT_SIDECAR_EXT: &str = ".ecsum";
|
||||
|
||||
/// Default checksum granularity (16 MiB). It is a power-of-two multiple of
|
||||
/// `ERASURE_CODING_SMALL_BLOCK_SIZE` (1 MiB) and keeps the sidecar tiny
|
||||
/// (~11 KB for a 30 GB volume) while localizing corruption to a 16 MiB region.
|
||||
pub const DEFAULT_BITROT_BLOCK_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Caps the block granularity so a loaded sidecar cannot force a huge
|
||||
/// scrub/verify scratch buffer. Power-of-two multiple of 1 MiB.
|
||||
pub const MAX_BITROT_BLOCK_SIZE: u32 = 64 * 1024 * 1024;
|
||||
|
||||
/// Magic "ECSU".
|
||||
pub const BITROT_MAGIC: u32 = 0x4543_5355;
|
||||
/// On-disk format version.
|
||||
pub const BITROT_FORMAT_VERSION: u16 = 1;
|
||||
/// Header size: magic(4) + version(2) + payload_len(4) + payload_crc32c(4).
|
||||
pub const BITROT_HEADER_SIZE: usize = 14;
|
||||
|
||||
/// Resolved protection state of an EC volume's active generation after loading
|
||||
/// and validating its sidecar.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BitrotStatus {
|
||||
/// No sidecar, or a sidecar that does not describe the active generation.
|
||||
/// The generation is unprotected; this is NOT corruption.
|
||||
Off,
|
||||
/// A complete, well-formed, generation-matching sidecar is loaded.
|
||||
On,
|
||||
/// A generation-matching sidecar that is malformed, incomplete, or
|
||||
/// self-integrity-failed. The generation is unprotected pending repair of
|
||||
/// the sidecar, and an integrity alarm should fire. The rebuild path treats
|
||||
/// this as fail-closed.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BitrotStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let s = match self {
|
||||
BitrotStatus::On => "on",
|
||||
BitrotStatus::Invalid => "invalid",
|
||||
BitrotStatus::Off => "off",
|
||||
};
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned by [`load_bitrot_sidecar`]. A self-integrity failure is a
|
||||
/// sidecar-integrity problem (the caller maps it to [`BitrotStatus::Invalid`]),
|
||||
/// never a shard-corruption signal.
|
||||
#[derive(Debug)]
|
||||
pub enum BitrotLoadError {
|
||||
/// File missing or other underlying I/O error.
|
||||
Io(io::Error),
|
||||
/// File shorter than the fixed header.
|
||||
TooShort(usize),
|
||||
/// Header magic did not match.
|
||||
BadMagic(u32),
|
||||
/// Header format version is unsupported.
|
||||
UnsupportedVersion(u16),
|
||||
/// Header payload_len disagrees with the actual payload length.
|
||||
LengthMismatch { header: u32, actual: usize },
|
||||
/// Header payload_crc32c disagrees with the computed CRC32C of the payload.
|
||||
CrcMismatch { header: u32, computed: u32 },
|
||||
/// Protobuf payload failed to decode.
|
||||
Decode(prost::DecodeError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BitrotLoadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
BitrotLoadError::Io(e) => write!(f, "bitrot sidecar io error: {}", e),
|
||||
BitrotLoadError::TooShort(n) => {
|
||||
write!(f, "bitrot sidecar too short ({} bytes)", n)
|
||||
}
|
||||
BitrotLoadError::BadMagic(m) => write!(f, "bitrot sidecar bad magic {:#x}", m),
|
||||
BitrotLoadError::UnsupportedVersion(v) => {
|
||||
write!(f, "bitrot sidecar unsupported format version {}", v)
|
||||
}
|
||||
BitrotLoadError::LengthMismatch { header, actual } => write!(
|
||||
f,
|
||||
"bitrot sidecar length mismatch: header {}, actual {}",
|
||||
header, actual
|
||||
),
|
||||
BitrotLoadError::CrcMismatch { header, computed } => write!(
|
||||
f,
|
||||
"bitrot sidecar self-integrity CRC mismatch: header {:#x}, computed {:#x}",
|
||||
header, computed
|
||||
),
|
||||
BitrotLoadError::Decode(e) => write!(f, "unmarshal bitrot sidecar: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for BitrotLoadError {}
|
||||
|
||||
impl From<io::Error> for BitrotLoadError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
BitrotLoadError::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the sidecar path for a base file name and EC generation. Generation
|
||||
/// 0 is the un-suffixed legacy path; generation N>0 is the versioned path,
|
||||
/// consistent with how `.vif`/`.ecx` are versioned by the 2PC switch.
|
||||
pub fn bitrot_sidecar_path(base: &str, generation: u32) -> String {
|
||||
if generation == 0 {
|
||||
format!("{}{}", base, BITROT_SIDECAR_EXT)
|
||||
} else {
|
||||
format!("{}{}.v{}", base, BITROT_SIDECAR_EXT, generation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the bitrot checksum sidecars for a base file name: the legacy
|
||||
/// `<base>.ecsum` (generation 0) and any versioned `<base>.ecsum.v<N>`.
|
||||
///
|
||||
/// Already-gone is success; returns the first real removal failure (and surfaces
|
||||
/// a directory-scan error) so a stale sidecar left behind is not reported as
|
||||
/// cleaned. Mirrors Go's `RemoveBitrotSidecars` / `removeBitrotSidecars`.
|
||||
pub fn remove_bitrot_sidecars(base: &str) -> io::Result<()> {
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
let rm = |path: std::path::PathBuf| -> io::Result<()> {
|
||||
match fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
};
|
||||
let mut first_err: Option<io::Error> = None;
|
||||
let mut record = |res: io::Result<()>| {
|
||||
if let Err(e) = res {
|
||||
if first_err.is_none() {
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
record(rm(format!("{}{}", base, BITROT_SIDECAR_EXT).into()));
|
||||
let path = Path::new(base);
|
||||
if let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) {
|
||||
let prefix = format!("{}{}.v", fname.to_string_lossy(), BITROT_SIDECAR_EXT);
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_name().to_string_lossy().starts_with(&prefix) {
|
||||
record(rm(entry.path()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a fresh random per-encode identity used to detect a stale sidecar
|
||||
/// left behind by an in-place re-encode.
|
||||
pub fn new_encode_uuid() -> Vec<u8> {
|
||||
use rand::RngCore;
|
||||
let mut b = vec![0u8; 16];
|
||||
rand::thread_rng().fill_bytes(&mut b);
|
||||
b
|
||||
}
|
||||
|
||||
/// Reports whether `block_size` is a power of two in [1 MiB, MAX_BITROT_BLOCK_SIZE].
|
||||
pub fn is_pow2_multiple_of_1mib(block_size: u32) -> bool {
|
||||
block_size >= (1 << 20) && block_size <= MAX_BITROT_BLOCK_SIZE && block_size.count_ones() == 1
|
||||
}
|
||||
|
||||
/// Returns ceil(covered_size / block_size).
|
||||
fn expected_block_count(covered_size: i64, block_size: i64) -> usize {
|
||||
if block_size <= 0 {
|
||||
return 0;
|
||||
}
|
||||
((covered_size + block_size - 1) / block_size) as usize
|
||||
}
|
||||
|
||||
/// Packs a slice of u32 into little-endian bytes.
|
||||
fn pack_u32_le(vals: &[u32]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(vals.len() * 4);
|
||||
for v in vals {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Unpacks little-endian bytes into a Vec<u32>. Trailing bytes (len % 4) are
|
||||
/// ignored, matching the Go implementation's `len(b)/4` truncation.
|
||||
fn unpack_u32_le(b: &[u8]) -> Vec<u32> {
|
||||
let n = b.len() / 4;
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
out.push(u32::from_le_bytes([
|
||||
b[i * 4],
|
||||
b[i * 4 + 1],
|
||||
b[i * 4 + 2],
|
||||
b[i * 4 + 3],
|
||||
]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Accumulates the per-block CRC32C of a single shard's byte stream as it is
|
||||
/// written. Tolerates arbitrary chunk sizes that cross block boundaries, so it
|
||||
/// works for both small encode buffers and the larger rebuild buffers.
|
||||
pub struct ShardChecksumBuilder {
|
||||
block_size: i64,
|
||||
cur: CRC,
|
||||
cur_len: i64,
|
||||
total: i64,
|
||||
blocks: Vec<u32>,
|
||||
}
|
||||
|
||||
impl ShardChecksumBuilder {
|
||||
/// Creates a builder over a given block size in bytes.
|
||||
pub fn new(block_size: i64) -> Self {
|
||||
ShardChecksumBuilder {
|
||||
block_size,
|
||||
cur: CRC(0),
|
||||
cur_len: 0,
|
||||
total: 0,
|
||||
blocks: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds a chunk of arbitrary size, splitting it across block boundaries.
|
||||
pub fn write(&mut self, mut p: &[u8]) {
|
||||
while !p.is_empty() {
|
||||
let room = self.block_size - self.cur_len;
|
||||
let n = (p.len() as i64).min(room) as usize;
|
||||
self.cur = self.cur.update(&p[..n]);
|
||||
self.cur_len += n as i64;
|
||||
self.total += n as i64;
|
||||
p = &p[n..];
|
||||
if self.cur_len == self.block_size {
|
||||
self.blocks.push(self.cur.0);
|
||||
self.cur = CRC(0);
|
||||
self.cur_len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Flushes any partial last block and returns the covered size and the
|
||||
/// packed little-endian u32 CRC array.
|
||||
pub fn finalize(mut self) -> (i64, Vec<u8>) {
|
||||
if self.cur_len > 0 {
|
||||
self.blocks.push(self.cur.0);
|
||||
self.cur = CRC(0);
|
||||
self.cur_len = 0;
|
||||
}
|
||||
(self.total, pack_u32_le(&self.blocks))
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomically writes `prot` to `path`, wrapped in the on-disk header with a
|
||||
/// CRC32C over the serialized payload (temp file + rename).
|
||||
pub fn save_bitrot_sidecar(path: &str, prot: &EcBitrotProtection) -> io::Result<()> {
|
||||
// The header records payload_len as a uint32 and the buffer allocation below
|
||||
// adds it to a constant. Bound the payload well under any overflow (a real
|
||||
// manifest is a few KB) so neither the length field nor the buffer can wrap.
|
||||
// Check the encoded length BEFORE serializing so an oversized manifest never
|
||||
// allocates a huge buffer. Mirrors Go's SaveBitrotSidecar maxBitrotPayloadSize.
|
||||
const MAX_BITROT_PAYLOAD_SIZE: usize = 1 << 30; // 1 GiB, vastly above any real sidecar
|
||||
let payload_len = prot.encoded_len();
|
||||
if payload_len > MAX_BITROT_PAYLOAD_SIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("bitrot sidecar payload too large: {} bytes", payload_len),
|
||||
));
|
||||
}
|
||||
let payload = prot.encode_to_vec();
|
||||
let mut buf = Vec::with_capacity(BITROT_HEADER_SIZE + payload.len());
|
||||
buf.extend_from_slice(&BITROT_MAGIC.to_be_bytes());
|
||||
buf.extend_from_slice(&BITROT_FORMAT_VERSION.to_be_bytes());
|
||||
buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||
buf.extend_from_slice(&CRC::new(&payload).0.to_be_bytes());
|
||||
buf.extend_from_slice(&payload);
|
||||
|
||||
let tmp = format!("{}.tmp", path);
|
||||
{
|
||||
let mut f = File::create(&tmp)?;
|
||||
f.write_all(&buf)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
if let Err(e) = std::fs::rename(&tmp, path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads and self-integrity-checks a sidecar file. Returns the parsed message,
|
||||
/// or an error if the file is missing, truncated, has a bad magic/version, or
|
||||
/// fails the payload CRC. A self-integrity failure is a sidecar-integrity
|
||||
/// problem (caller maps it to [`BitrotStatus::Invalid`]), never a shard
|
||||
/// corruption signal.
|
||||
pub fn load_bitrot_sidecar(path: &str) -> Result<EcBitrotProtection, BitrotLoadError> {
|
||||
let mut data = Vec::new();
|
||||
File::open(path)?.read_to_end(&mut data)?;
|
||||
if data.len() < BITROT_HEADER_SIZE {
|
||||
return Err(BitrotLoadError::TooShort(data.len()));
|
||||
}
|
||||
let magic = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
|
||||
if magic != BITROT_MAGIC {
|
||||
return Err(BitrotLoadError::BadMagic(magic));
|
||||
}
|
||||
let ver = u16::from_be_bytes([data[4], data[5]]);
|
||||
if ver != BITROT_FORMAT_VERSION {
|
||||
return Err(BitrotLoadError::UnsupportedVersion(ver));
|
||||
}
|
||||
let payload_len = u32::from_be_bytes([data[6], data[7], data[8], data[9]]);
|
||||
let want_crc = u32::from_be_bytes([data[10], data[11], data[12], data[13]]);
|
||||
let payload = &data[BITROT_HEADER_SIZE..];
|
||||
if payload_len as usize != payload.len() {
|
||||
return Err(BitrotLoadError::LengthMismatch {
|
||||
header: payload_len,
|
||||
actual: payload.len(),
|
||||
});
|
||||
}
|
||||
let got = CRC::new(payload).0;
|
||||
if got != want_crc {
|
||||
return Err(BitrotLoadError::CrcMismatch {
|
||||
header: want_crc,
|
||||
computed: got,
|
||||
});
|
||||
}
|
||||
EcBitrotProtection::decode(payload).map_err(BitrotLoadError::Decode)
|
||||
}
|
||||
|
||||
/// Performs the disk-free manifest/syntax checks that every loader runs:
|
||||
/// supported algorithm, valid block size, exactly one entry per shard id in the
|
||||
/// active layout (no duplicates, no out-of-range ids), positive covered_size,
|
||||
/// and a packed-CRC count consistent with covered_size.
|
||||
///
|
||||
/// It does NOT compare covered_size against on-disk shard lengths — that is a
|
||||
/// per-node physical check done only for locally-held shards.
|
||||
pub fn validate_manifest(
|
||||
prot: &EcBitrotProtection,
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> Result<(), String> {
|
||||
if prot.algorithm != ChecksumAlgorithm::ChecksumCrc32c as i32 {
|
||||
return Err(format!("unsupported checksum algorithm {}", prot.algorithm));
|
||||
}
|
||||
if !is_pow2_multiple_of_1mib(prot.block_size) {
|
||||
return Err(format!(
|
||||
"invalid block_size {} (must be a power-of-two multiple of 1 MiB, at most {})",
|
||||
prot.block_size, MAX_BITROT_BLOCK_SIZE
|
||||
));
|
||||
}
|
||||
let bs = prot.block_size as i64;
|
||||
let total = data_shards + parity_shards;
|
||||
if total == 0 || total > MAX_SHARD_COUNT {
|
||||
return Err(format!(
|
||||
"invalid active layout: data={} parity={}",
|
||||
data_shards, parity_shards
|
||||
));
|
||||
}
|
||||
if prot.shards.len() != total {
|
||||
return Err(format!(
|
||||
"incomplete manifest: {} shard entries, expected {}",
|
||||
prot.shards.len(),
|
||||
total
|
||||
));
|
||||
}
|
||||
let mut seen = vec![false; MAX_SHARD_COUNT];
|
||||
for s in &prot.shards {
|
||||
if s.shard_id >= total as u32 {
|
||||
return Err(format!(
|
||||
"shard id {} out of range [0,{})",
|
||||
s.shard_id, total
|
||||
));
|
||||
}
|
||||
if seen[s.shard_id as usize] {
|
||||
return Err(format!("duplicate shard id {}", s.shard_id));
|
||||
}
|
||||
seen[s.shard_id as usize] = true;
|
||||
if s.covered_size <= 0 {
|
||||
return Err(format!(
|
||||
"shard {} has non-positive covered_size {}",
|
||||
s.shard_id, s.covered_size
|
||||
));
|
||||
}
|
||||
let want_count = expected_block_count(s.covered_size, bs);
|
||||
if s.block_crc32c.len() != want_count * 4 {
|
||||
return Err(format!(
|
||||
"shard {} crc count mismatch: {} bytes, expected {} (covered_size={} block_size={})",
|
||||
s.shard_id,
|
||||
s.block_crc32c.len(),
|
||||
want_count * 4,
|
||||
s.covered_size,
|
||||
prot.block_size
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves the protection status of a loaded-or-missing sidecar against the
|
||||
/// active generation and layout. `loaded` is the result of attempting to load
|
||||
/// the sidecar at the active generation's path.
|
||||
///
|
||||
/// - missing sidecar (NotFound) => [`BitrotStatus::Off`]
|
||||
/// - load/self-integrity failure => [`BitrotStatus::Invalid`]
|
||||
/// - generation mismatch => [`BitrotStatus::Off`]
|
||||
/// - manifest validation failure => [`BitrotStatus::Invalid`]
|
||||
/// - otherwise => [`BitrotStatus::On`]
|
||||
pub fn resolve_status(
|
||||
loaded: &Result<EcBitrotProtection, BitrotLoadError>,
|
||||
active_generation: u32,
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> BitrotStatus {
|
||||
match loaded {
|
||||
Err(BitrotLoadError::Io(e)) if e.kind() == io::ErrorKind::NotFound => BitrotStatus::Off,
|
||||
Err(_) => BitrotStatus::Invalid,
|
||||
Ok(prot) => {
|
||||
if prot.generation != active_generation {
|
||||
return BitrotStatus::Off;
|
||||
}
|
||||
if validate_manifest(prot, data_shards, parity_shards).is_err() {
|
||||
return BitrotStatus::Invalid;
|
||||
}
|
||||
BitrotStatus::On
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the [`EcShardChecksums`] entry for a shard id, or `None`.
|
||||
pub fn shard_checksums(prot: &EcBitrotProtection, shard_id: u32) -> Option<&EcShardChecksums> {
|
||||
prot.shards.iter().find(|s| s.shard_id == shard_id)
|
||||
}
|
||||
|
||||
/// Reads a shard file at `path` in `block_size` chunks and compares each block's
|
||||
/// CRC32C against the manifest entry. Returns the list of mismatching block
|
||||
/// indices (empty == clean), or a fatal `io::Error` for genuine I/O problems.
|
||||
///
|
||||
/// A length mismatch (truncation or unexpected trailing bytes) is itself shard
|
||||
/// corruption: every block index is reported as mismatched so the caller treats
|
||||
/// the shard as bad. It does not interpret the result — the caller (scrub /
|
||||
/// rebuild) arbitrates shard-vs-sidecar via Reed-Solomon before acting.
|
||||
pub fn verify_shard_file_blocks(
|
||||
path: &str,
|
||||
entry: &EcShardChecksums,
|
||||
block_size: i64,
|
||||
) -> io::Result<Vec<usize>> {
|
||||
let f = File::open(path)?;
|
||||
let file_size = f.metadata()?.len() as i64;
|
||||
let want = unpack_u32_le(&entry.block_crc32c);
|
||||
|
||||
if file_size != entry.covered_size {
|
||||
// Length drift is shard corruption: report every block as mismatched.
|
||||
return Ok((0..want.len()).collect());
|
||||
}
|
||||
|
||||
let mut mismatched = Vec::new();
|
||||
let mut buf = vec![0u8; block_size.max(1) as usize];
|
||||
let mut offset: i64 = 0;
|
||||
for (i, want_crc) in want.iter().enumerate() {
|
||||
let to_read = (entry.covered_size - offset).min(block_size);
|
||||
if to_read <= 0 {
|
||||
break;
|
||||
}
|
||||
let to_read = to_read as usize;
|
||||
read_full_at(&f, &mut buf[..to_read], offset as u64)?;
|
||||
if CRC::new(&buf[..to_read]).0 != *want_crc {
|
||||
mismatched.push(i);
|
||||
}
|
||||
offset += to_read as i64;
|
||||
}
|
||||
Ok(mismatched)
|
||||
}
|
||||
|
||||
/// Reads exactly `buf.len()` bytes from `f` at `offset`, erroring on early EOF.
|
||||
fn read_full_at(f: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
|
||||
let mut total = 0usize;
|
||||
while total < buf.len() {
|
||||
#[cfg(unix)]
|
||||
let n = {
|
||||
use std::os::unix::fs::FileExt;
|
||||
f.read_at(&mut buf[total..], offset + total as u64)?
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let n = {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut fc = f.try_clone()?;
|
||||
fc.seek(SeekFrom::Start(offset + total as u64))?;
|
||||
fc.read(&mut buf[total..])?
|
||||
};
|
||||
if n == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"short read on shard block",
|
||||
));
|
||||
}
|
||||
total += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Builds the `EcShardConfig` proto for the given layout. The bitrot sidecar
|
||||
/// carries its own top-level encode_uuid, so the nested config leaves it empty.
|
||||
pub fn ec_shard_config(data_shards: u32, parity_shards: u32) -> EcShardConfig {
|
||||
EcShardConfig {
|
||||
data_shards,
|
||||
parity_shards,
|
||||
encode_ts_ns: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Cross-binary byte-exact proof: CANONICAL_HEX equals `canonicalInteropHex`
|
||||
/// in weed/storage/erasure_coding/ec_bitrot_interop_test.go (the Go reference
|
||||
/// asserts the same constant). Both binaries port the same format, so a
|
||||
/// sidecar written by either must be byte-identical; this pins the Rust side
|
||||
/// of that guarantee. If you change the format, regenerate and update BOTH.
|
||||
#[test]
|
||||
fn test_byte_exact_go_interop() {
|
||||
const CANONICAL_HEX: &str = "45435355000100000039cc1b826a080110808080082204080a10042a0a108080401a04040302012a0c0801108080401a04080706053210000102030405060708090a0b0c0d0e0f";
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(EcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
encode_ts_ns: 0,
|
||||
}),
|
||||
shards: vec![
|
||||
EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: 1024 * 1024,
|
||||
block_crc32c: pack_u32_le(&[0x0102_0304]),
|
||||
},
|
||||
EcShardChecksums {
|
||||
shard_id: 1,
|
||||
covered_size: 1024 * 1024,
|
||||
block_crc32c: pack_u32_le(&[0x0506_0708]),
|
||||
},
|
||||
],
|
||||
encode_uuid: (0..16u8).collect(),
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("ecsum_interop_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("v1.ecsum");
|
||||
let path = path.to_str().unwrap();
|
||||
save_bitrot_sidecar(path, &prot).unwrap();
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
|
||||
assert_eq!(hex, CANONICAL_HEX, "Rust .ecsum bytes drifted from the Go canonical form");
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sidecar_path_generations() {
|
||||
assert_eq!(bitrot_sidecar_path("/d/1", 0), "/d/1.ecsum");
|
||||
assert_eq!(bitrot_sidecar_path("/d/1", 3), "/d/1.ecsum.v3");
|
||||
}
|
||||
|
||||
/// Mirrors Go's TestRemoveBitrotSidecars: legacy + versioned sidecars go,
|
||||
/// unrelated files (a shard, a longer-vid sidecar) survive, absent is success.
|
||||
#[test]
|
||||
fn test_remove_bitrot_sidecars() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let base = tmp.path().join("5").to_str().unwrap().to_string();
|
||||
for p in [
|
||||
format!("{}.ecsum", base),
|
||||
format!("{}.ecsum.v1", base),
|
||||
format!("{}.ecsum.v7", base),
|
||||
] {
|
||||
std::fs::write(&p, b"x").unwrap();
|
||||
}
|
||||
let keep_shard = format!("{}.ec00", base);
|
||||
let keep_other_vid = format!("{}0.ecsum", base);
|
||||
std::fs::write(&keep_shard, b"x").unwrap();
|
||||
std::fs::write(&keep_other_vid, b"x").unwrap();
|
||||
|
||||
remove_bitrot_sidecars(&base).unwrap();
|
||||
|
||||
for p in [
|
||||
format!("{}.ecsum", base),
|
||||
format!("{}.ecsum.v1", base),
|
||||
format!("{}.ecsum.v7", base),
|
||||
] {
|
||||
assert!(!std::path::Path::new(&p).exists(), "{} should be removed", p);
|
||||
}
|
||||
assert!(std::path::Path::new(&keep_shard).exists());
|
||||
assert!(std::path::Path::new(&keep_other_vid).exists());
|
||||
|
||||
// Already-gone is success.
|
||||
remove_bitrot_sidecars(&base).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_pow2_multiple_of_1mib() {
|
||||
assert!(is_pow2_multiple_of_1mib(1 << 20)); // 1 MiB
|
||||
assert!(is_pow2_multiple_of_1mib(16 * 1024 * 1024)); // 16 MiB default
|
||||
assert!(is_pow2_multiple_of_1mib(1 << 25));
|
||||
assert!(is_pow2_multiple_of_1mib(MAX_BITROT_BLOCK_SIZE)); // 64 MiB boundary
|
||||
assert!(!is_pow2_multiple_of_1mib(0));
|
||||
assert!(!is_pow2_multiple_of_1mib(1 << 19)); // 512 KiB, too small
|
||||
assert!(!is_pow2_multiple_of_1mib(3 << 20)); // 3 MiB, not pow2
|
||||
assert!(!is_pow2_multiple_of_1mib(128 * 1024 * 1024)); // pow2 but > MAX_BITROT_BLOCK_SIZE
|
||||
assert!(!is_pow2_multiple_of_1mib(DEFAULT_BITROT_BLOCK_SIZE as u32 + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expected_block_count() {
|
||||
assert_eq!(expected_block_count(0, 16), 0);
|
||||
assert_eq!(expected_block_count(1, 16), 1);
|
||||
assert_eq!(expected_block_count(16, 16), 1);
|
||||
assert_eq!(expected_block_count(17, 16), 2);
|
||||
assert_eq!(expected_block_count(32, 16), 2);
|
||||
assert_eq!(expected_block_count(100, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pack_unpack_roundtrip() {
|
||||
let vals = vec![0x0102_0304u32, 0xdead_beef, 0, u32::MAX];
|
||||
let packed = pack_u32_le(&vals);
|
||||
assert_eq!(packed.len(), 16);
|
||||
// Verify little-endian byte order of the first entry.
|
||||
assert_eq!(&packed[0..4], &[0x04, 0x03, 0x02, 0x01]);
|
||||
assert_eq!(unpack_u32_le(&packed), vals);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builder_block_boundaries() {
|
||||
// block_size = 4; feed 10 bytes in chunks that cross boundaries.
|
||||
let mut b = ShardChecksumBuilder::new(4);
|
||||
let data = b"0123456789";
|
||||
b.write(&data[0..3]); // partial block 0
|
||||
b.write(&data[3..7]); // completes block 0 (idx 3), fills block 1
|
||||
b.write(&data[7..10]); // partial block 2
|
||||
let (covered, packed) = b.finalize();
|
||||
assert_eq!(covered, 10);
|
||||
let crcs = unpack_u32_le(&packed);
|
||||
// ceil(10/4) = 3 blocks
|
||||
assert_eq!(crcs.len(), 3);
|
||||
// Compare against direct per-block CRCs.
|
||||
assert_eq!(crcs[0], CRC::new(&data[0..4]).0);
|
||||
assert_eq!(crcs[1], CRC::new(&data[4..8]).0);
|
||||
assert_eq!(crcs[2], CRC::new(&data[8..10]).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builder_exact_block_multiple() {
|
||||
let mut b = ShardChecksumBuilder::new(4);
|
||||
b.write(b"01234567"); // exactly 2 blocks, no partial
|
||||
let (covered, packed) = b.finalize();
|
||||
assert_eq!(covered, 8);
|
||||
assert_eq!(unpack_u32_le(&packed).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_save_load_roundtrip() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp
|
||||
.path()
|
||||
.join("vol.ecsum")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
|
||||
let mut builder = ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64);
|
||||
builder.write(b"hello world");
|
||||
let (covered, packed) = builder.finalize();
|
||||
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards: vec![EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: covered,
|
||||
block_crc32c: packed,
|
||||
}],
|
||||
encode_uuid: new_encode_uuid(),
|
||||
};
|
||||
|
||||
save_bitrot_sidecar(&path, &prot).unwrap();
|
||||
let loaded = load_bitrot_sidecar(&path).unwrap();
|
||||
assert_eq!(loaded, prot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_rejects_bad_magic() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp.path().join("bad.ecsum").to_str().unwrap().to_string();
|
||||
std::fs::write(&path, vec![0u8; BITROT_HEADER_SIZE + 4]).unwrap();
|
||||
match load_bitrot_sidecar(&path) {
|
||||
Err(BitrotLoadError::BadMagic(_)) => {}
|
||||
other => panic!("expected BadMagic, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_rejects_corrupted_payload() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp
|
||||
.path()
|
||||
.join("corrupt.ecsum")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards: vec![EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: 5,
|
||||
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
|
||||
}],
|
||||
encode_uuid: vec![0u8; 16],
|
||||
};
|
||||
save_bitrot_sidecar(&path, &prot).unwrap();
|
||||
|
||||
// Flip a byte in the payload (after the 14-byte header).
|
||||
let mut data = std::fs::read(&path).unwrap();
|
||||
let last = data.len() - 1;
|
||||
data[last] ^= 0xff;
|
||||
std::fs::write(&path, &data).unwrap();
|
||||
|
||||
match load_bitrot_sidecar(&path) {
|
||||
Err(BitrotLoadError::CrcMismatch { .. }) => {}
|
||||
other => panic!("expected CrcMismatch, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_missing_is_notfound() {
|
||||
let res = load_bitrot_sidecar("/nonexistent/path/x.ecsum");
|
||||
match res {
|
||||
Err(BitrotLoadError::Io(e)) => assert_eq!(e.kind(), io::ErrorKind::NotFound),
|
||||
other => panic!("expected Io(NotFound), got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
fn good_manifest() -> EcBitrotProtection {
|
||||
let mut shards = Vec::new();
|
||||
for id in 0..14u32 {
|
||||
shards.push(EcShardChecksums {
|
||||
shard_id: id,
|
||||
covered_size: 5,
|
||||
block_crc32c: pack_u32_le(&[CRC::new(b"hello").0]),
|
||||
});
|
||||
}
|
||||
EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_shard_config(10, 4)),
|
||||
shards,
|
||||
encode_uuid: vec![0u8; 16],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_manifest_ok() {
|
||||
assert!(validate_manifest(&good_manifest(), 10, 4).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_wrong_algorithm() {
|
||||
let mut m = good_manifest();
|
||||
m.algorithm = ChecksumAlgorithm::ChecksumNone as i32;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_bad_block_size() {
|
||||
let mut m = good_manifest();
|
||||
m.block_size = 3 << 20;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_incomplete() {
|
||||
let mut m = good_manifest();
|
||||
m.shards.pop();
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_duplicate_shard_id() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[1].shard_id = 0;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_out_of_range_id() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[13].shard_id = 14;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_nonpositive_covered_size() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[0].covered_size = 0;
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_rejects_crc_count_mismatch() {
|
||||
let mut m = good_manifest();
|
||||
m.shards[0].block_crc32c = vec![0u8; 8]; // 2 entries but covered_size=5 => want 1
|
||||
assert!(validate_manifest(&m, 10, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_status() {
|
||||
// Missing => Off.
|
||||
let notfound: Result<EcBitrotProtection, BitrotLoadError> = Err(BitrotLoadError::Io(
|
||||
io::Error::new(io::ErrorKind::NotFound, "x"),
|
||||
));
|
||||
assert_eq!(resolve_status(¬found, 0, 10, 4), BitrotStatus::Off);
|
||||
|
||||
// Integrity failure => Invalid.
|
||||
let bad: Result<EcBitrotProtection, BitrotLoadError> =
|
||||
Err(BitrotLoadError::BadMagic(0));
|
||||
assert_eq!(resolve_status(&bad, 0, 10, 4), BitrotStatus::Invalid);
|
||||
|
||||
// Generation mismatch => Off.
|
||||
let mut m = good_manifest();
|
||||
m.generation = 7;
|
||||
let ok: Result<EcBitrotProtection, BitrotLoadError> = Ok(m);
|
||||
assert_eq!(resolve_status(&ok, 0, 10, 4), BitrotStatus::Off);
|
||||
|
||||
// Matching + valid => On.
|
||||
let ok2: Result<EcBitrotProtection, BitrotLoadError> = Ok(good_manifest());
|
||||
assert_eq!(resolve_status(&ok2, 0, 10, 4), BitrotStatus::On);
|
||||
|
||||
// Matching generation but invalid manifest => Invalid.
|
||||
let mut bad_m = good_manifest();
|
||||
bad_m.shards.pop();
|
||||
let ok3: Result<EcBitrotProtection, BitrotLoadError> = Ok(bad_m);
|
||||
assert_eq!(resolve_status(&ok3, 0, 10, 4), BitrotStatus::Invalid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_verify_shard_file_blocks() {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp.path().join("s.ec00").to_str().unwrap().to_string();
|
||||
let block_size: i64 = 4;
|
||||
let data = b"0123456789"; // 10 bytes, 3 blocks
|
||||
std::fs::write(&path, data).unwrap();
|
||||
|
||||
let mut b = ShardChecksumBuilder::new(block_size);
|
||||
b.write(data);
|
||||
let (covered, packed) = b.finalize();
|
||||
let entry = EcShardChecksums {
|
||||
shard_id: 0,
|
||||
covered_size: covered,
|
||||
block_crc32c: packed,
|
||||
};
|
||||
|
||||
// Clean file => no mismatches.
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert!(mm.is_empty());
|
||||
|
||||
// Corrupt block index 1 (bytes 4..8).
|
||||
let mut corrupt = data.to_vec();
|
||||
corrupt[5] ^= 0xff;
|
||||
std::fs::write(&path, &corrupt).unwrap();
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert_eq!(mm, vec![1]);
|
||||
|
||||
// Truncation => all blocks mismatched.
|
||||
std::fs::write(&path, b"012").unwrap();
|
||||
let mm = verify_shard_file_blocks(&path, &entry, block_size).unwrap();
|
||||
assert_eq!(mm, vec![0, 1, 2]);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,12 @@ use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
use reed_solomon_erasure::galois_8::ReedSolomon;
|
||||
|
||||
use crate::pb::volume_server_pb::{
|
||||
ChecksumAlgorithm, EcBitrotProtection, EcShardChecksums,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_bitrot::{
|
||||
self, ShardChecksumBuilder, DEFAULT_BITROT_BLOCK_SIZE,
|
||||
};
|
||||
use crate::storage::erasure_coding::ec_shard::*;
|
||||
use crate::storage::idx;
|
||||
use crate::storage::types::*;
|
||||
@@ -52,12 +58,21 @@ pub fn write_ec_files(
|
||||
shard.create()?;
|
||||
}
|
||||
|
||||
// Per-shard bitrot checksum builders: accumulate a CRC32C for every
|
||||
// DEFAULT_BITROT_BLOCK_SIZE block of each shard's byte stream as it is
|
||||
// written, so the resulting `.ecsum` sidecar can later detect silent
|
||||
// corruption in any shard (including cold parity).
|
||||
let mut builders: Vec<ShardChecksumBuilder> = (0..total_shards)
|
||||
.map(|_| ShardChecksumBuilder::new(DEFAULT_BITROT_BLOCK_SIZE as i64))
|
||||
.collect();
|
||||
|
||||
// Encode in large blocks, then small blocks
|
||||
encode_dat_file(
|
||||
&dat_file,
|
||||
dat_size,
|
||||
&rs,
|
||||
&mut shards,
|
||||
&mut builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -67,12 +82,52 @@ pub fn write_ec_files(
|
||||
shard.close();
|
||||
}
|
||||
|
||||
// Write the generation-0 bitrot sidecar (`<base>.ecsum`). Finalizing each
|
||||
// builder yields covered_size (== total bytes written to that shard) and
|
||||
// the packed little-endian CRC32C array.
|
||||
let mut shard_checksums: Vec<EcShardChecksums> = Vec::with_capacity(total_shards);
|
||||
for (i, builder) in builders.into_iter().enumerate() {
|
||||
let (covered_size, packed) = builder.finalize();
|
||||
shard_checksums.push(EcShardChecksums {
|
||||
shard_id: i as u32,
|
||||
covered_size,
|
||||
block_crc32c: packed,
|
||||
});
|
||||
}
|
||||
let prot = EcBitrotProtection {
|
||||
algorithm: ChecksumAlgorithm::ChecksumCrc32c as i32,
|
||||
block_size: DEFAULT_BITROT_BLOCK_SIZE as u32,
|
||||
generation: 0,
|
||||
ec_shard_config: Some(ec_bitrot::ec_shard_config(
|
||||
data_shards as u32,
|
||||
parity_shards as u32,
|
||||
)),
|
||||
shards: shard_checksums,
|
||||
encode_uuid: ec_bitrot::new_encode_uuid(),
|
||||
};
|
||||
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
|
||||
if let Err(e) = ec_bitrot::save_bitrot_sidecar(&sidecar_path, &prot) {
|
||||
// A failed sidecar must not fail the encode — the shards are already
|
||||
// written and valid. The volume simply runs with bitrot protection
|
||||
// off for this generation until the sidecar is regenerated.
|
||||
tracing::warn!(
|
||||
volume_id = volume_id.0,
|
||||
path = %sidecar_path,
|
||||
error = %e,
|
||||
"ec encode: failed to write bitrot sidecar; protection off for this generation",
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rebuild missing EC shard files from existing shards using Reed-Solomon reconstruct.
|
||||
///
|
||||
/// This does not require the `.dat` file, only the existing `.ecXX` shard files.
|
||||
///
|
||||
/// `additional_dirs` lists sibling disk locations to search for existing shards when
|
||||
/// they are not found in `dir`. This is required on multi-disk volume servers where
|
||||
/// shards for the same volume may be spread across disks.
|
||||
pub fn rebuild_ec_files(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
@@ -80,6 +135,7 @@ pub fn rebuild_ec_files(
|
||||
missing_shard_ids: &[u32],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
additional_dirs: &[&str],
|
||||
) -> io::Result<()> {
|
||||
if missing_shard_ids.is_empty() {
|
||||
return Ok(());
|
||||
@@ -93,7 +149,9 @@ pub fn rebuild_ec_files(
|
||||
.map(|i| EcVolumeShard::new(dir, collection, volume_id, i))
|
||||
.collect();
|
||||
|
||||
// Determine the exact shard size from the first available existing shard
|
||||
// Determine the exact shard size from the first available existing shard.
|
||||
// When a shard is not found in `dir`, search `additional_dirs` (sibling disks
|
||||
// on the same volume server) before failing — mirrors Go's findShardFile logic.
|
||||
let mut shard_size = 0;
|
||||
for (i, shard) in shards.iter_mut().enumerate() {
|
||||
if !missing_shard_ids.contains(&(i as u32)) {
|
||||
@@ -103,10 +161,26 @@ pub fn rebuild_ec_files(
|
||||
shard_size = size;
|
||||
}
|
||||
} else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("missing non-rebuild shard {}", i),
|
||||
));
|
||||
// Try sibling disk locations before giving up.
|
||||
let mut found = false;
|
||||
for &other_dir in additional_dirs {
|
||||
let mut alt = EcVolumeShard::new(other_dir, collection, volume_id, i as u8);
|
||||
if let Ok(_) = alt.open() {
|
||||
let size = alt.file_size();
|
||||
if size > shard_size {
|
||||
shard_size = size;
|
||||
}
|
||||
*shard = alt;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("missing non-rebuild shard {}", i),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +258,12 @@ pub fn rebuild_ec_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify EC shards by computing parity against the existing data and identifying corrupted shards.
|
||||
/// Reed-Solomon parity check over the locally-held shards: recompute parity from
|
||||
/// the data shards and flag any shard whose bytes disagree. Wired into FULL
|
||||
/// (scrub mode 2) as a TEMPORARY local parity/cold-region check — the per-needle
|
||||
/// FULL walk only reads live data-shard intervals, so on its own it can't catch
|
||||
/// bitrot in a parity shard or an unwalked region. Move to mode 4 (CHECKSUM) and
|
||||
/// drop it from mode 2 once the `.ecsum` subsystem lands.
|
||||
pub fn verify_ec_shards(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
@@ -331,11 +410,16 @@ fn write_sorted_ecx_from_idx(idx_path: &str, ecx_path: &str) -> io::Result<()> {
|
||||
/// content from the EC data shards, walks through needle headers to extract
|
||||
/// (needle_id, offset, size) entries, deduplicates them, and writes a sorted
|
||||
/// .ecx index file.
|
||||
///
|
||||
/// `additional_dirs` lists sibling disk locations to search for data shards when
|
||||
/// they are not found in `dir` — mirrors the same fallback used by rebuild_ec_files,
|
||||
/// required on multi-disk volume servers where shards may be spread across disks.
|
||||
pub fn rebuild_ecx_file(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
data_shards: usize,
|
||||
additional_dirs: &[&str],
|
||||
) -> io::Result<()> {
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
@@ -343,21 +427,34 @@ pub fn rebuild_ecx_file(
|
||||
let base = volume_file_name(dir, collection, volume_id);
|
||||
let ecx_path = format!("{}.ecx", base);
|
||||
|
||||
// Open data shards to read logical .dat content
|
||||
// Open data shards to read logical .dat content. When a shard isn't found
|
||||
// in `dir`, search `additional_dirs` (sibling disks on the same volume
|
||||
// server) before giving up.
|
||||
let mut shards: Vec<EcVolumeShard> = (0..data_shards as u8)
|
||||
.map(|i| EcVolumeShard::new(dir, collection, volume_id, i))
|
||||
.collect();
|
||||
|
||||
for shard in &mut shards {
|
||||
for (i, shard) in shards.iter_mut().enumerate() {
|
||||
if let Err(_) = shard.open() {
|
||||
// If a data shard is missing, we can't rebuild ecx
|
||||
for s in &mut shards {
|
||||
s.close();
|
||||
let mut found = false;
|
||||
for &other_dir in additional_dirs {
|
||||
let mut alt = EcVolumeShard::new(other_dir, collection, volume_id, i as u8);
|
||||
if alt.open().is_ok() {
|
||||
*shard = alt;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
// If a data shard is missing, we can't rebuild ecx
|
||||
for s in &mut shards {
|
||||
s.close();
|
||||
}
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("cannot open data shard for ecx rebuild"),
|
||||
));
|
||||
}
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("cannot open data shard for ecx rebuild"),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,6 +587,7 @@ fn encode_dat_file(
|
||||
dat_size: i64,
|
||||
rs: &ReedSolomon,
|
||||
shards: &mut [EcVolumeShard],
|
||||
builders: &mut [ShardChecksumBuilder],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<()> {
|
||||
@@ -507,6 +605,7 @@ fn encode_dat_file(
|
||||
large_block_size,
|
||||
rs,
|
||||
shards,
|
||||
builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -526,6 +625,7 @@ fn encode_dat_file(
|
||||
small_block_size,
|
||||
rs,
|
||||
shards,
|
||||
builders,
|
||||
data_shards,
|
||||
parity_shards,
|
||||
)?;
|
||||
@@ -543,6 +643,7 @@ fn encode_one_batch(
|
||||
block_size: usize,
|
||||
rs: &ReedSolomon,
|
||||
shards: &mut [EcVolumeShard],
|
||||
builders: &mut [ShardChecksumBuilder],
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
) -> io::Result<()> {
|
||||
@@ -596,9 +697,11 @@ fn encode_one_batch(
|
||||
)
|
||||
})?;
|
||||
|
||||
// Write all shard buffers to files
|
||||
// Write all shard buffers to files and feed the same bytes to each
|
||||
// shard's bitrot checksum builder, keeping covered_size == on-disk length.
|
||||
for (i, buf) in buffers.iter().enumerate() {
|
||||
shards[i].write_all(buf)?;
|
||||
builders[i].write(buf);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -666,6 +769,84 @@ mod tests {
|
||||
assert!(std::path::Path::new(&ecx_path).exists());
|
||||
}
|
||||
|
||||
fn make_volume_with_needles(n: u64) -> TempDir {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=n {
|
||||
// Larger payloads so encoded shards span multiple bitrot blocks
|
||||
// would require huge data; small payloads are fine for correctness.
|
||||
let data = format!("test data for needle {} {}", i, "x".repeat(64));
|
||||
let mut needle = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut needle, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
tmp
|
||||
}
|
||||
|
||||
/// Encode-time capture writes a valid generation-0 `.ecsum` sidecar whose
|
||||
/// recorded checksums match the actual on-disk shards.
|
||||
#[test]
|
||||
fn test_encode_writes_valid_bitrot_sidecar() {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
|
||||
let tmp = make_volume_with_needles(5);
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_ec_files(dir, dir, "", VolumeId(1), 10, 4).unwrap();
|
||||
|
||||
let base = format!("{}/1", dir);
|
||||
let sidecar_path = ec_bitrot::bitrot_sidecar_path(&base, 0);
|
||||
assert!(
|
||||
std::path::Path::new(&sidecar_path).exists(),
|
||||
"generation-0 .ecsum sidecar should exist after encode"
|
||||
);
|
||||
|
||||
let prot = ec_bitrot::load_bitrot_sidecar(&sidecar_path).unwrap();
|
||||
ec_bitrot::validate_manifest(&prot, 10, 4).unwrap();
|
||||
assert_eq!(prot.generation, 0);
|
||||
assert_eq!(prot.shards.len(), 14);
|
||||
assert_eq!(prot.encode_uuid.len(), 16);
|
||||
assert_eq!(prot.block_size, ec_bitrot::DEFAULT_BITROT_BLOCK_SIZE as u32);
|
||||
|
||||
// Every shard's recorded covered_size must equal its on-disk length and
|
||||
// its block CRCs must verify clean.
|
||||
let bs = prot.block_size as i64;
|
||||
for entry in &prot.shards {
|
||||
let path = format!("{}.ec{:02}", base, entry.shard_id);
|
||||
let on_disk = std::fs::metadata(&path).unwrap().len() as i64;
|
||||
assert_eq!(
|
||||
entry.covered_size, on_disk,
|
||||
"covered_size must equal on-disk length for shard {}",
|
||||
entry.shard_id
|
||||
);
|
||||
let mm = ec_bitrot::verify_shard_file_blocks(&path, entry, bs).unwrap();
|
||||
assert!(
|
||||
mm.is_empty(),
|
||||
"shard {} should verify clean, got mismatches {:?}",
|
||||
entry.shard_id,
|
||||
mm
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// encode_sample_volume writes a small volume and EC-encodes it, returning
|
||||
// the dir path so a test can drop/truncate shards and rebuild.
|
||||
fn encode_sample_volume(tmp: &TempDir) -> String {
|
||||
@@ -717,7 +898,7 @@ mod tests {
|
||||
|
||||
// Rebuild a different (genuinely missing) shard.
|
||||
std::fs::remove_file(format!("{}/1.ec07", dir)).unwrap();
|
||||
let res = rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4);
|
||||
let res = rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4, &[]);
|
||||
assert!(res.is_err(), "truncated input shard must abort the rebuild");
|
||||
}
|
||||
|
||||
@@ -730,7 +911,7 @@ mod tests {
|
||||
|
||||
let dropped = format!("{}/1.ec07", dir);
|
||||
std::fs::remove_file(&dropped).unwrap();
|
||||
rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4).unwrap();
|
||||
rebuild_ec_files(&dir, "", VolumeId(1), &[7], 10, 4, &[]).unwrap();
|
||||
assert!(
|
||||
std::path::Path::new(&dropped).exists(),
|
||||
"rebuilt shard .ec07 should exist"
|
||||
@@ -741,6 +922,124 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// Multi-disk rebuild: shards for the same volume are split across two
|
||||
// directories (simulating a volume server with two disk locations). The
|
||||
// shard to rebuild is in the primary dir; some of the input shards needed
|
||||
// for RS reconstruction exist only in the secondary dir. Passing the
|
||||
// secondary dir via `additional_dirs` must allow the rebuild to succeed
|
||||
// where it would previously return "missing non-rebuild shard N".
|
||||
#[test]
|
||||
fn test_rebuild_ec_files_multi_disk() {
|
||||
let tmp_primary = TempDir::new().unwrap();
|
||||
let tmp_secondary = TempDir::new().unwrap();
|
||||
let primary = tmp_primary.path().to_str().unwrap().to_string();
|
||||
let secondary = tmp_secondary.path().to_str().unwrap().to_string();
|
||||
|
||||
// Encode into primary dir first (all 14 shards land there).
|
||||
let dir = encode_sample_volume(&tmp_primary);
|
||||
assert_eq!(dir, primary);
|
||||
|
||||
// Simulate a multi-disk layout: move shards 0, 4, 8 to the secondary
|
||||
// dir, as if the master had placed them on a different disk.
|
||||
let moved_shards: &[u8] = &[0, 4, 8];
|
||||
for &shard_id in moved_shards {
|
||||
let src = format!("{}/1.ec{:02}", primary, shard_id);
|
||||
let dst = format!("{}/1.ec{:02}", secondary, shard_id);
|
||||
std::fs::rename(&src, &dst).unwrap();
|
||||
}
|
||||
|
||||
// Remove shard 7 from primary — this is the shard we want to rebuild.
|
||||
let missing_path = format!("{}/1.ec07", primary);
|
||||
std::fs::remove_file(&missing_path).unwrap();
|
||||
|
||||
// Without additional_dirs the rebuild must fail: shards 0, 4, 8 are
|
||||
// not in primary and shard 7 cannot be reconstructed without them.
|
||||
let res = rebuild_ec_files(&primary, "", VolumeId(1), &[7], 10, 4, &[]);
|
||||
assert!(
|
||||
res.is_err(),
|
||||
"rebuild without additional_dirs must fail when input shards are on another disk"
|
||||
);
|
||||
assert!(
|
||||
!std::path::Path::new(&missing_path).exists(),
|
||||
"failed rebuild must not leave a partial shard file behind"
|
||||
);
|
||||
|
||||
// With additional_dirs pointing at the secondary, the rebuild must succeed.
|
||||
rebuild_ec_files(
|
||||
&primary,
|
||||
"",
|
||||
VolumeId(1),
|
||||
&[7],
|
||||
10,
|
||||
4,
|
||||
&[secondary.as_str()],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
std::path::Path::new(&missing_path).exists(),
|
||||
"rebuilt shard .ec07 should exist in primary dir"
|
||||
);
|
||||
assert!(
|
||||
std::fs::metadata(&missing_path).unwrap().len() > 0,
|
||||
"rebuilt shard must be non-empty"
|
||||
);
|
||||
}
|
||||
|
||||
// Multi-disk .ecx rebuild: data shards (0-9) needed to reconstruct the
|
||||
// logical .dat content are split across two directories, as on a
|
||||
// multi-disk volume server. Passing the secondary dir via
|
||||
// `additional_dirs` must allow rebuild_ecx_file to find them and
|
||||
// succeed where it would previously fail with
|
||||
// "cannot open data shard for ecx rebuild".
|
||||
#[test]
|
||||
fn test_rebuild_ecx_file_multi_disk() {
|
||||
let tmp_primary = TempDir::new().unwrap();
|
||||
let tmp_secondary = TempDir::new().unwrap();
|
||||
let primary = tmp_primary.path().to_str().unwrap().to_string();
|
||||
let secondary = tmp_secondary.path().to_str().unwrap().to_string();
|
||||
|
||||
let dir = encode_sample_volume(&tmp_primary);
|
||||
assert_eq!(dir, primary);
|
||||
|
||||
// Move some data shards (0-9) to the secondary dir, simulating a
|
||||
// multi-disk layout where not all data shards landed on the same disk.
|
||||
let moved_shards: &[u8] = &[1, 3, 6];
|
||||
for &shard_id in moved_shards {
|
||||
let src = format!("{}/1.ec{:02}", primary, shard_id);
|
||||
let dst = format!("{}/1.ec{:02}", secondary, shard_id);
|
||||
std::fs::rename(&src, &dst).unwrap();
|
||||
}
|
||||
|
||||
// Delete the existing .ecx to force a rebuild.
|
||||
let ecx_path = format!("{}/1.ecx", primary);
|
||||
std::fs::remove_file(&ecx_path).unwrap();
|
||||
|
||||
// Without additional_dirs, rebuild must fail: shards 1, 3, 6 are not
|
||||
// in primary and the full logical .dat content can't be reconstructed.
|
||||
let res = rebuild_ecx_file(&primary, "", VolumeId(1), 10, &[]);
|
||||
assert!(
|
||||
res.is_err(),
|
||||
"ecx rebuild without additional_dirs must fail when data shards are on another disk"
|
||||
);
|
||||
assert!(
|
||||
!std::path::Path::new(&ecx_path).exists(),
|
||||
"failed ecx rebuild must not leave a partial .ecx file behind"
|
||||
);
|
||||
|
||||
// With additional_dirs pointing at the secondary, the rebuild must succeed.
|
||||
rebuild_ecx_file(&primary, "", VolumeId(1), 10, &[secondary.as_str()]).unwrap();
|
||||
|
||||
assert!(
|
||||
std::path::Path::new(&ecx_path).exists(),
|
||||
"rebuilt .ecx should exist in primary dir"
|
||||
);
|
||||
assert!(
|
||||
std::fs::metadata(&ecx_path).unwrap().len() > 0,
|
||||
"rebuilt .ecx must be non-empty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reed_solomon_basic() {
|
||||
let data_shards = 10;
|
||||
|
||||
@@ -109,6 +109,17 @@ impl EcVolumeShard {
|
||||
self.ecd_file_size
|
||||
}
|
||||
|
||||
/// Protobuf descriptor for this shard. Mirrors Go's ToEcShardInfo.
|
||||
pub fn to_ec_shard_info(&self) -> crate::pb::volume_server_pb::EcShardInfo {
|
||||
crate::pb::volume_server_pb::EcShardInfo {
|
||||
shard_id: self.shard_id as u32,
|
||||
size: self.file_size(),
|
||||
collection: self.collection.clone(),
|
||||
volume_id: self.volume_id.0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the shard file.
|
||||
pub fn close(&mut self) {
|
||||
if let Some(ref file) = self.ecd_file {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! EcVolume: an erasure-coded volume with up to 14 shards.
|
||||
//! EcVolume: an erasure-coded volume with up to MAX_SHARD_COUNT shards.
|
||||
//!
|
||||
//! Each EcVolume has a sorted index (.ecx) and a deletion journal (.ecj).
|
||||
//! Shards (.ec00-.ec13) may be distributed across multiple servers.
|
||||
@@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use crate::pb::master_pb;
|
||||
use crate::storage::erasure_coding::ec_locate;
|
||||
use crate::storage::erasure_coding::ec_shard::*;
|
||||
use crate::storage::needle::needle::{get_actual_size, Needle};
|
||||
use crate::storage::needle::needle::{get_actual_size, Needle, NeedleError};
|
||||
use crate::storage::types::*;
|
||||
|
||||
/// An erasure-coded volume managing its local shards and index.
|
||||
@@ -22,7 +22,7 @@ pub struct EcVolume {
|
||||
pub dir: String,
|
||||
pub dir_idx: String,
|
||||
pub version: Version,
|
||||
pub shards: Vec<Option<EcVolumeShard>>, // indexed by ShardId (0..14)
|
||||
pub shards: Vec<Option<EcVolumeShard>>, // indexed by ShardId (0..MAX_SHARD_COUNT)
|
||||
pub dat_file_size: i64,
|
||||
pub data_shards: u32,
|
||||
pub parity_shards: u32,
|
||||
@@ -61,6 +61,13 @@ pub struct EcVolume {
|
||||
/// served from a shard of a different encode run is rejected (server- and
|
||||
/// client-side); 0 for a pre-feature volume, which is treated leniently.
|
||||
pub encode_ts_ns: i64,
|
||||
/// Active-generation EC bitrot checksum sidecar (`<base>.ecsum`), loaded and
|
||||
/// validated at mount. `None` unless `bitrot_status == On`.
|
||||
pub(crate) bitrot: Option<crate::pb::volume_server_pb::EcBitrotProtection>,
|
||||
/// Resolved protection state of the loaded sidecar. Cached alongside `bitrot`
|
||||
/// so `bitrot_protection()` can return the `Off`/`Invalid` distinction without
|
||||
/// re-reading, mirroring Go's `EcVolume.bitrotStatus`.
|
||||
pub(crate) bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
|
||||
}
|
||||
|
||||
/// Locate the `.vif` for a (collection, vid) by preferring the data dir
|
||||
@@ -106,7 +113,7 @@ pub fn read_ec_shard_config(
|
||||
if let Some(ec) = vif_info.ec_shard_config {
|
||||
if ec.data_shards > 0
|
||||
&& ec.parity_shards > 0
|
||||
&& (ec.data_shards + ec.parity_shards) <= TOTAL_SHARDS_COUNT as u32
|
||||
&& (ec.data_shards + ec.parity_shards) <= MAX_SHARD_COUNT as u32
|
||||
{
|
||||
data_shards = ec.data_shards;
|
||||
parity_shards = ec.parity_shards;
|
||||
@@ -191,6 +198,8 @@ impl EcVolume {
|
||||
shard_locations_refresh_time: std::sync::Mutex::new(None),
|
||||
expire_at_sec,
|
||||
encode_ts_ns,
|
||||
bitrot: None,
|
||||
bitrot_status: crate::storage::erasure_coding::ec_bitrot::BitrotStatus::Off,
|
||||
};
|
||||
|
||||
// Open .ecx file (sorted index) in read/write mode for in-place deletion marking.
|
||||
@@ -237,9 +246,189 @@ impl EcVolume {
|
||||
// Seed the in-memory deleted set from the journal.
|
||||
vol.load_deleted_needles_from_ecj()?;
|
||||
|
||||
// Load the generation-0 EC bitrot checksum sidecar (optional; best-effort).
|
||||
vol.load_active_bitrot_sidecar();
|
||||
|
||||
Ok(vol)
|
||||
}
|
||||
|
||||
/// Load the generation-0 checksum sidecar into `self.bitrot`/`self.bitrot_status`.
|
||||
/// OSS only produces generation-0 (fresh-encode) sidecars, mirroring Go's
|
||||
/// `loadActiveBitrotSidecar`.
|
||||
fn load_active_bitrot_sidecar(&mut self) {
|
||||
self.load_bitrot_for_generation(0);
|
||||
}
|
||||
|
||||
/// Load and validate the sidecar describing `generation`, setting
|
||||
/// `self.bitrot`/`self.bitrot_status`. Absent or generation/config-mismatched
|
||||
/// => `Off` (protection off, not corruption); self-integrity or manifest
|
||||
/// failure => `Invalid` with a warning (protection off pending repair); usable
|
||||
/// => `On`. Mirrors Go's `loadBitrotForGeneration`.
|
||||
fn load_bitrot_for_generation(&mut self, generation: u32) {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
let base = self.base_name();
|
||||
let path = ec_bitrot::bitrot_sidecar_path(&base, generation);
|
||||
let loaded = ec_bitrot::load_bitrot_sidecar(&path);
|
||||
let status = ec_bitrot::resolve_status(
|
||||
&loaded,
|
||||
generation,
|
||||
self.data_shards as usize,
|
||||
self.parity_shards as usize,
|
||||
);
|
||||
self.bitrot = None;
|
||||
self.bitrot_status = status;
|
||||
match status {
|
||||
ec_bitrot::BitrotStatus::On => self.bitrot = loaded.ok(),
|
||||
ec_bitrot::BitrotStatus::Off => {}
|
||||
ec_bitrot::BitrotStatus::Invalid => {
|
||||
tracing::warn!(
|
||||
volume_id = self.volume_id.0,
|
||||
path = %path,
|
||||
generation,
|
||||
"ec volume: bitrot sidecar present but invalid; protection off pending repair",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The active-generation bitrot protection AND its status (cached at mount),
|
||||
/// mirroring Go's `EcVolume.BitrotProtection()`. Preserves the distinction
|
||||
/// `checksum_scrub` needs: an absent/generation-mismatched sidecar is `Off`
|
||||
/// (a clean no-op), a present-but-malformed one is `Invalid` (a real integrity
|
||||
/// error). Returns `Some(prot)` only for `On`.
|
||||
pub(crate) fn bitrot_protection(
|
||||
&self,
|
||||
) -> (
|
||||
Option<crate::pb::volume_server_pb::EcBitrotProtection>,
|
||||
crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
|
||||
) {
|
||||
(self.bitrot.clone(), self.bitrot_status)
|
||||
}
|
||||
|
||||
/// Read-only EC bitrot checksum scrub of the LOCAL shards of this volume's
|
||||
/// active generation.
|
||||
///
|
||||
/// Loads the active-generation `.ecsum` sidecar and, for each locally-held
|
||||
/// shard, reads the on-disk shard file in `block_size` chunks and compares
|
||||
/// each block's CRC32C against the sidecar. Returns
|
||||
/// `(blocks_scanned, mismatched_shards, errors)`.
|
||||
///
|
||||
/// If more than `parity_shards` shards mismatch wholesale (i.e. every block
|
||||
/// of those shards is wrong — the signature of a stale/wrong sidecar rather
|
||||
/// than localized disk rot), the result is classified as a suspect sidecar:
|
||||
/// `mismatched_shards` is cleared and an integrity note is added to `errors`
|
||||
/// instead. A genuine multi-shard disk failure of that magnitude is
|
||||
/// already unrecoverable, so treating it as a sidecar-integrity issue avoids
|
||||
/// raising false shard-corruption alarms.
|
||||
///
|
||||
/// This method NEVER deletes or mutates anything — it is purely diagnostic.
|
||||
pub fn checksum_scrub(&self) -> (u64, Vec<u32>, Vec<String>) {
|
||||
use crate::storage::erasure_coding::ec_bitrot;
|
||||
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
|
||||
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
|
||||
// Resolve the active-generation protection AND its status, mirroring
|
||||
// Go's `ChecksumScrub` (`prot, status := ecv.BitrotProtection()`):
|
||||
// - BitrotOff => sidecars are OPTIONAL; an absent (or generation/
|
||||
// config-mismatched) sidecar simply means protection is not enabled
|
||||
// for this generation. Return a CLEAN, EMPTY result — NOT an error —
|
||||
// so legacy/intentionally-unprotected volumes are never reported
|
||||
// broken. (Go: `case BitrotOff: return 0, nil, nil`.)
|
||||
// - BitrotInvalid => the sidecar is PRESENT but malformed/unverifiable
|
||||
// (self-integrity or manifest failure). That is the only status that
|
||||
// yields an integrity error here.
|
||||
// - BitrotOn => scan local shards against it.
|
||||
let prot = match self.bitrot_protection() {
|
||||
(_, BitrotStatus::Off) => {
|
||||
// Unprotected generation: nothing to verify. Not an error.
|
||||
return (0, Vec::new(), Vec::new());
|
||||
}
|
||||
(_, BitrotStatus::Invalid) => {
|
||||
return (
|
||||
0,
|
||||
Vec::new(),
|
||||
vec![format!(
|
||||
"EC volume {} bitrot sidecar is malformed/unverifiable (sidecar integrity)",
|
||||
self.volume_id.0
|
||||
)],
|
||||
);
|
||||
}
|
||||
(Some(p), BitrotStatus::On) => p,
|
||||
(None, BitrotStatus::On) => {
|
||||
// Unreachable: BitrotOn always carries a loaded sidecar. Treat a
|
||||
// missing payload defensively as protection off (clean no-op).
|
||||
return (0, Vec::new(), Vec::new());
|
||||
}
|
||||
};
|
||||
|
||||
let block_size = prot.block_size as i64;
|
||||
let generation = prot.generation;
|
||||
let base = self.base_name();
|
||||
|
||||
let mut blocks_scanned: u64 = 0;
|
||||
let mut mismatched_shards: Vec<u32> = Vec::new();
|
||||
// Track shards whose blocks ALL mismatch (wholesale) to detect a
|
||||
// stale/wrong sidecar.
|
||||
let mut wholesale_mismatch = 0usize;
|
||||
|
||||
for (i, slot) in self.shards.iter().enumerate() {
|
||||
if slot.is_none() {
|
||||
continue; // not local
|
||||
}
|
||||
let shard_id = i as u32;
|
||||
let Some(entry) = ec_bitrot::shard_checksums(&prot, shard_id) else {
|
||||
errors.push(format!(
|
||||
"EC volume {} shard {} present but missing from sidecar manifest",
|
||||
self.volume_id.0, shard_id
|
||||
));
|
||||
continue;
|
||||
};
|
||||
|
||||
// Resolve the on-disk shard file path for the active generation,
|
||||
// mirroring EcVolumeShard::reopen_against_generation's convention.
|
||||
let path = if generation == 0 {
|
||||
format!("{}.ec{:02}", base, shard_id)
|
||||
} else {
|
||||
format!("{}.ec{:02}.v{}", base, shard_id, generation)
|
||||
};
|
||||
|
||||
let expected_blocks = entry.block_crc32c.len() / 4;
|
||||
match ec_bitrot::verify_shard_file_blocks(&path, entry, block_size) {
|
||||
Ok(mismatched) => {
|
||||
blocks_scanned += expected_blocks as u64;
|
||||
if !mismatched.is_empty() {
|
||||
mismatched_shards.push(shard_id);
|
||||
if expected_blocks > 0 && mismatched.len() == expected_blocks {
|
||||
wholesale_mismatch += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(format!(
|
||||
"EC volume {} shard {} scrub read error: {}",
|
||||
self.volume_id.0, shard_id, e
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If more shards mismatch wholesale than parity can mask, the sidecar
|
||||
// itself is the likely culprit (stale generation / wrong volume), so
|
||||
// suppress the shard-corruption verdict and flag a sidecar-integrity
|
||||
// issue instead.
|
||||
if wholesale_mismatch > self.parity_shards as usize {
|
||||
errors.push(format!(
|
||||
"EC volume {}: {} shards mismatch wholesale (> {} parity); suspect stale/wrong sidecar, not shard corruption",
|
||||
self.volume_id.0, wholesale_mismatch, self.parity_shards
|
||||
));
|
||||
mismatched_shards.clear();
|
||||
}
|
||||
|
||||
mismatched_shards.sort_unstable();
|
||||
(blocks_scanned, mismatched_shards, errors)
|
||||
}
|
||||
|
||||
/// Walk the .ecj journal and populate `deleted_needles`. Called once
|
||||
/// from `new()` under exclusive ownership of the just-constructed
|
||||
/// EcVolume, so locking is not strictly required — but we take the
|
||||
@@ -464,10 +653,10 @@ impl EcVolume {
|
||||
/// against a half-populated cache and return NotFound for the
|
||||
/// not-yet-inserted shards.
|
||||
///
|
||||
/// Callers populating the whole cache atomically should use
|
||||
/// [`Self::replace_shard_locations`] instead — it swaps the
|
||||
/// entire map under the write lock and advances the refresh
|
||||
/// timestamp in one step.
|
||||
/// Callers writing back a whole `LookupEcVolume` reply should use
|
||||
/// [`Self::merge_shard_locations`] instead — it upserts the reply's
|
||||
/// shards under the write lock and advances the refresh timestamp in
|
||||
/// one step, retaining cached shards the reply omits.
|
||||
pub fn set_shard_locations(&self, shard_id: ShardId, locations: Vec<String>) {
|
||||
self.shard_locations
|
||||
.write()
|
||||
@@ -486,6 +675,29 @@ impl EcVolume {
|
||||
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
|
||||
}
|
||||
|
||||
/// Merge a fresh `LookupEcVolume` reply into the shard-locations cache and
|
||||
/// stamp the refresh time, returning a clone of the resulting map.
|
||||
///
|
||||
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
|
||||
/// id present in the reply overwrites its cached entry, while shard ids absent
|
||||
/// from the reply keep their previously-cached locations — so a reply that
|
||||
/// passes the data-shard completeness guard but omits a shard already in cache
|
||||
/// does not drop that shard's known location (unlike a full replace).
|
||||
pub fn merge_shard_locations(
|
||||
&self,
|
||||
locations: HashMap<ShardId, Vec<String>>,
|
||||
) -> HashMap<ShardId, Vec<String>> {
|
||||
let merged = {
|
||||
let mut guard = self.shard_locations.write().unwrap();
|
||||
for (shard_id, addrs) in locations {
|
||||
guard.insert(shard_id, addrs);
|
||||
}
|
||||
guard.clone()
|
||||
};
|
||||
*self.shard_locations_refresh_time.lock().unwrap() = Some(std::time::Instant::now());
|
||||
merged
|
||||
}
|
||||
|
||||
/// Get a cloned list of server addresses for a given shard ID.
|
||||
pub fn get_shard_locations(&self, shard_id: ShardId) -> Vec<String> {
|
||||
self.shard_locations
|
||||
@@ -546,6 +758,26 @@ impl EcVolume {
|
||||
}
|
||||
|
||||
/// Locate the EC shard intervals needed to read a needle.
|
||||
/// Locate the EC shard intervals covering a needle at `actual_offset` whose
|
||||
/// index size is `size`. Mirrors Go's EcVolume.LocateEcShardNeedleInterval.
|
||||
pub fn locate_ec_shard_needle_interval(
|
||||
&self,
|
||||
actual_offset: i64,
|
||||
size: Size,
|
||||
) -> Vec<ec_locate::Interval> {
|
||||
// shardSize = datFileSize / DataShards when known, else ecdFileSize - 1
|
||||
// (shards are padded to the small block size; the -1 avoids an
|
||||
// off-by-one in the large-block row count).
|
||||
let shard_size = if self.dat_file_size > 0 {
|
||||
self.dat_file_size / self.data_shards as i64
|
||||
} else {
|
||||
self.shard_file_size() - 1
|
||||
};
|
||||
// locate_data wants the on-disk size (header+body+checksum+timestamp+padding).
|
||||
let actual = get_actual_size(size, self.version);
|
||||
ec_locate::locate_data(actual_offset, Size(actual as i32), shard_size, self.data_shards)
|
||||
}
|
||||
|
||||
pub fn locate_needle(
|
||||
&self,
|
||||
needle_id: NeedleId,
|
||||
@@ -559,25 +791,7 @@ impl EcVolume {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Match Go's LocateEcShardNeedleInterval: shardSize = shard.ecdFileSize - 1
|
||||
// Shards are usually padded to ErasureCodingSmallBlockSize, so subtract 1
|
||||
// to avoid off-by-one in large block row count calculation.
|
||||
// If datFileSize is known, use datFileSize / DataShards instead.
|
||||
let shard_size = if self.dat_file_size > 0 {
|
||||
self.dat_file_size / self.data_shards as i64
|
||||
} else {
|
||||
self.shard_file_size() - 1
|
||||
};
|
||||
// Pass the actual on-disk size (header+body+checksum+timestamp+padding)
|
||||
// to locate_data, matching Go: types.Size(needle.GetActualSize(size, version))
|
||||
let actual = get_actual_size(size, self.version);
|
||||
let intervals = ec_locate::locate_data(
|
||||
offset.to_actual_offset(),
|
||||
Size(actual as i32),
|
||||
shard_size,
|
||||
self.data_shards,
|
||||
);
|
||||
|
||||
let intervals = self.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
|
||||
Ok(Some((offset, size, intervals)))
|
||||
}
|
||||
|
||||
@@ -708,97 +922,186 @@ impl EcVolume {
|
||||
/// Matches Go's `(ev *EcVolume) ScrubIndex()` → `idx.CheckIndexFile()`.
|
||||
/// Returns (entry_count, errors).
|
||||
pub fn scrub_index(&self) -> (u64, Vec<String>) {
|
||||
let ecx_file = match self.ecx_file.as_ref() {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
return (
|
||||
0,
|
||||
vec![format!(
|
||||
"no ECX file associated with EC volume {}",
|
||||
self.volume_id.0
|
||||
)],
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
if self.ecx_file_size == 0 {
|
||||
if self.ecx_file.is_none() {
|
||||
return (
|
||||
0,
|
||||
vec![format!(
|
||||
"zero-size ECX file for EC volume {}",
|
||||
"no ECX file associated with EC volume {}",
|
||||
self.volume_id.0
|
||||
)],
|
||||
);
|
||||
}
|
||||
if self.ecx_file_size == 0 {
|
||||
return (
|
||||
0,
|
||||
vec![format!("zero-size ECX file for EC volume {}", self.volume_id.0)],
|
||||
);
|
||||
}
|
||||
|
||||
let entry_count = self.ecx_file_size as usize / NEEDLE_MAP_ENTRY_SIZE;
|
||||
let mut entries: Vec<(usize, NeedleId, i64, Size)> = Vec::with_capacity(entry_count);
|
||||
let mut errs: Vec<String> = Vec::new();
|
||||
let mut entry_buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
// Walk a private fd so the structural scan never moves the shared
|
||||
// ecx_file cursor (the cached handle is read positionally elsewhere).
|
||||
let ecx_path = self.ecx_file_name();
|
||||
let mut ecx_file = match File::open(&ecx_path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return (0, vec![format!("open ECX file {}: {}", ecx_path, e)]),
|
||||
};
|
||||
crate::storage::idx::check_index_file(&mut ecx_file, self.ecx_file_size, self.version)
|
||||
}
|
||||
|
||||
// Walk all entries
|
||||
for i in 0..entry_count {
|
||||
let file_offset = (i * NEEDLE_MAP_ENTRY_SIZE) as u64;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::FileExt;
|
||||
if let Err(e) = ecx_file.read_exact_at(&mut entry_buf, file_offset) {
|
||||
errs.push(format!("read ecx entry {}: {}", i, e));
|
||||
/// ScrubLocal verifies each needle against the LOCAL shards only; it cannot
|
||||
/// CRC-check a needle whose intervals span shards held on other servers.
|
||||
/// Mirrors Go's EcVolume.ScrubLocal. Returns (rows walked, broken shards, errors).
|
||||
pub fn scrub_local(
|
||||
&self,
|
||||
) -> (u64, Vec<crate::pb::volume_server_pb::EcShardInfo>, Vec<String>) {
|
||||
// Local scan also verifies the index.
|
||||
let (_, mut errs) = self.scrub_index();
|
||||
|
||||
let mut broken_shards: HashSet<ShardId> = HashSet::new();
|
||||
let mut count: u64 = 0;
|
||||
|
||||
let ecx_path = self.ecx_file_name();
|
||||
let mut ecx_file = match File::open(&ecx_path) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
errs.push(format!("open ECX file {}: {}", ecx_path, e));
|
||||
return (count, Vec::new(), errs);
|
||||
}
|
||||
};
|
||||
|
||||
// Reused across every needle/chunk to avoid a per-chunk allocation.
|
||||
let mut chunk_buf: Vec<u8> = Vec::new();
|
||||
let walk = crate::storage::idx::walk_index_file(&mut ecx_file, 0, |id, offset, size| {
|
||||
count += 1;
|
||||
if size.is_tombstone() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let locations = self.locate_ec_shard_needle_interval(offset.to_actual_offset(), size);
|
||||
// A needle is verifiable locally only if every shard it spans is local;
|
||||
// when any is remote, skip the reassembly buffer entirely.
|
||||
let has_remote_chunks = locations.iter().any(|iv| {
|
||||
let (sid, _) = iv.to_shard_id_and_offset(self.data_shards);
|
||||
self.shards.get(sid as usize).and_then(|s| s.as_ref()).is_none()
|
||||
});
|
||||
let mut read: i64 = 0;
|
||||
let mut data: Vec<u8> = if has_remote_chunks {
|
||||
Vec::new()
|
||||
} else {
|
||||
Vec::with_capacity(get_actual_size(size, self.version) as usize)
|
||||
};
|
||||
let mut local_shard_ids: Vec<ShardId> = Vec::new();
|
||||
|
||||
for (i, iv) in locations.iter().enumerate() {
|
||||
let (sid, soffset) = iv.to_shard_id_and_offset(self.data_shards);
|
||||
let ssize = iv.size;
|
||||
let shard = match self.shards.get(sid as usize).and_then(|s| s.as_ref()) {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
// Shard is not local; we can't verify it without decoding.
|
||||
read += ssize;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
local_shard_ids.push(sid);
|
||||
|
||||
if soffset + ssize > shard.file_size() {
|
||||
broken_shards.insert(sid);
|
||||
errs.push(format!(
|
||||
"local shard {} for needle {} is too short ({}), cannot read chunk {}/{}",
|
||||
sid,
|
||||
id.0,
|
||||
shard.file_size(),
|
||||
i + 1,
|
||||
locations.len()
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
chunk_buf.resize(ssize as usize, 0);
|
||||
match shard.read_at(&mut chunk_buf, soffset as u64) {
|
||||
Err(e) => {
|
||||
broken_shards.insert(sid);
|
||||
errs.push(format!(
|
||||
"failed to read chunk {}/{} for needle {} from local shard {} at offset {}: {}",
|
||||
i + 1,
|
||||
locations.len(),
|
||||
id.0,
|
||||
sid,
|
||||
soffset,
|
||||
e
|
||||
));
|
||||
continue;
|
||||
}
|
||||
Ok(got) if got as i64 != ssize => {
|
||||
broken_shards.insert(sid);
|
||||
errs.push(format!(
|
||||
"expected {} bytes for chunk {}/{} for needle {} from local shard {}, got {}",
|
||||
ssize,
|
||||
i + 1,
|
||||
locations.len(),
|
||||
id.0,
|
||||
sid,
|
||||
got
|
||||
));
|
||||
continue;
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
|
||||
if !has_remote_chunks {
|
||||
data.extend_from_slice(&chunk_buf);
|
||||
}
|
||||
read += ssize;
|
||||
}
|
||||
let (key, offset, size) = idx_entry_from_bytes(&entry_buf);
|
||||
entries.push((i, key, offset.to_actual_offset(), size));
|
||||
}
|
||||
|
||||
// Sort by offset, then size
|
||||
entries.sort_by(|a, b| a.2.cmp(&b.2).then(a.3 .0.cmp(&b.3 .0)));
|
||||
local_shard_ids.sort_unstable();
|
||||
|
||||
// Check for overlapping needles
|
||||
for i in 1..entries.len() {
|
||||
let (idx, id, offset, size) = entries[i];
|
||||
let (_, last_id, last_offset, last_size) = entries[i - 1];
|
||||
|
||||
let actual_size =
|
||||
crate::storage::needle::needle::get_actual_size(size, self.version);
|
||||
let end = if actual_size != 0 {
|
||||
offset + actual_size - 1
|
||||
} else {
|
||||
offset
|
||||
};
|
||||
|
||||
let last_actual_size =
|
||||
crate::storage::needle::needle::get_actual_size(last_size, self.version);
|
||||
let last_end = if last_actual_size != 0 {
|
||||
last_offset + last_actual_size - 1
|
||||
} else {
|
||||
last_offset
|
||||
};
|
||||
|
||||
if offset <= last_end {
|
||||
errs.push(format!(
|
||||
"needle {} (#{}) at [{}-{}] overlaps needle {} at [{}-{}]",
|
||||
id.0,
|
||||
idx + 1,
|
||||
offset,
|
||||
end,
|
||||
last_id.0,
|
||||
last_offset,
|
||||
last_end
|
||||
let want = get_actual_size(size, self.version);
|
||||
if read != want {
|
||||
// Like Go, returning from the walk callback aborts the scan.
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!(
|
||||
"expected {} bytes for needle {} on volume {}, got {}",
|
||||
want, id.0, self.volume_id.0, read
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
// Only a fully-local needle can be reassembled and CRC-checked.
|
||||
if !has_remote_chunks {
|
||||
let mut n = Needle::default();
|
||||
if let Err(e) = n.read_bytes(&data, 0, size, self.version) {
|
||||
// A delete-state disagreement between the .ecx index and the reassembled
|
||||
// on-disk header (live index vs zero header size) is not corruption.
|
||||
let delete_state_disagrees = matches!(
|
||||
&e,
|
||||
NeedleError::SizeMismatch { found, .. } if size.is_deleted() != (found.0 == 0)
|
||||
);
|
||||
if !delete_state_disagrees {
|
||||
errs.push(format!(
|
||||
"needle {} on volume {}, shards {:?}: {}",
|
||||
id.0, self.volume_id.0, local_shard_ids, e
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = walk {
|
||||
// Go appends the walk/callback error verbatim.
|
||||
errs.push(e.to_string());
|
||||
}
|
||||
|
||||
// Verify file size matches entry count
|
||||
let expected_size = entry_count as i64 * NEEDLE_MAP_ENTRY_SIZE as i64;
|
||||
if expected_size != self.ecx_file_size {
|
||||
errs.push(format!(
|
||||
"expected an index file of size {}, got {}",
|
||||
expected_size, self.ecx_file_size
|
||||
));
|
||||
}
|
||||
let mut broken: Vec<crate::pb::volume_server_pb::EcShardInfo> = broken_shards
|
||||
.iter()
|
||||
.filter_map(|sid| self.shards.get(*sid as usize).and_then(|s| s.as_ref()))
|
||||
.map(|s| s.to_ec_shard_info())
|
||||
.collect();
|
||||
broken.sort_by(|a, b| a.shard_id.cmp(&b.shard_id));
|
||||
|
||||
(entries.len() as u64, errs)
|
||||
(count, broken, errs)
|
||||
}
|
||||
|
||||
// ---- Deletion ----
|
||||
@@ -1150,6 +1453,21 @@ impl EcVolume {
|
||||
let _ = fs::remove_file(format!("{}.ecj", data_base));
|
||||
let _ = fs::remove_file(format!("{}.vif", data_base));
|
||||
}
|
||||
// Go's Destroy() also removes bitrot checksum sidecars so a later
|
||||
// volume-id reuse cannot load stale protection, and so
|
||||
// collection.delete does not leave orphaned <base>.ecsum files.
|
||||
// ecx_actual_dir is always one of these two dirs.
|
||||
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(
|
||||
&self.base_name(),
|
||||
);
|
||||
if self.dir_idx != self.dir {
|
||||
let idx_base = crate::storage::volume::volume_file_name(
|
||||
&self.dir_idx,
|
||||
&self.collection,
|
||||
self.volume_id,
|
||||
);
|
||||
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base);
|
||||
}
|
||||
self.ecx_file = None;
|
||||
self.ecj_file = None;
|
||||
}
|
||||
@@ -1160,6 +1478,194 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// `destroy()` must remove co-located `.ecsum` sidecars (Go Destroy parity).
|
||||
/// Without this, `collection.delete` leaves orphaned bitrot files that
|
||||
/// inflate EC-health scanners after the shards are gone.
|
||||
#[test]
|
||||
fn test_destroy_removes_bitrot_sidecar() {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::volume::Volume;
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"ec1c",
|
||||
VolumeId(2074),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=3 {
|
||||
let data = format!("needle {}", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
crate::storage::erasure_coding::ec_encoder::write_ec_files(
|
||||
dir,
|
||||
dir,
|
||||
"ec1c",
|
||||
VolumeId(2074),
|
||||
10,
|
||||
4,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let base = crate::storage::volume::volume_file_name(dir, "ec1c", VolumeId(2074));
|
||||
let ecsum = format!("{}.ecsum", base);
|
||||
assert!(
|
||||
std::path::Path::new(&ecsum).exists(),
|
||||
"precondition: encode must write generation-0 .ecsum"
|
||||
);
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ec00", base)).exists(),
|
||||
"precondition: encode must write shards"
|
||||
);
|
||||
|
||||
let mut vol = EcVolume::new(dir, dir, "ec1c", VolumeId(2074)).unwrap();
|
||||
// Mount at least one local shard so destroy's shard loop has work.
|
||||
vol.add_shard(EcVolumeShard::new(dir, "ec1c", VolumeId(2074), 0))
|
||||
.unwrap();
|
||||
vol.destroy();
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ec00", base)).exists(),
|
||||
"destroy should remove shards"
|
||||
);
|
||||
assert!(
|
||||
!std::path::Path::new(&ecsum).exists(),
|
||||
"destroy should remove co-located .ecsum (Go Destroy parity)"
|
||||
);
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecx", base)).exists(),
|
||||
"destroy should remove .ecx"
|
||||
);
|
||||
}
|
||||
|
||||
/// Mounting an EC volume loads and validates its generation-0 `.ecsum`
|
||||
/// sidecar, so `bitrot_protection()` reports `On` with the parsed manifest.
|
||||
#[test]
|
||||
fn test_mount_loads_bitrot_sidecar() {
|
||||
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::volume::Volume;
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=5 {
|
||||
let data = format!("test data for needle {}", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
crate::storage::erasure_coding::ec_encoder::write_ec_files(dir, dir, "", VolumeId(1), 10, 4)
|
||||
.unwrap();
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
assert!(
|
||||
vol.bitrot.is_some(),
|
||||
"mount should load the generation-0 .ecsum sidecar"
|
||||
);
|
||||
let (prot, status) = vol.bitrot_protection();
|
||||
assert_eq!(status, BitrotStatus::On);
|
||||
assert_eq!(prot.unwrap().shards.len(), 14);
|
||||
}
|
||||
|
||||
/// CHECKSUM scrub verifies clean shards against the sidecar and flags a shard
|
||||
/// whose bytes are corrupted after encode.
|
||||
#[test]
|
||||
fn test_checksum_scrub_clean_and_detects_corruption() {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::volume::Volume;
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
for i in 1..=8 {
|
||||
let data = format!("test data for needle {} with a bit more length", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
crate::storage::erasure_coding::ec_encoder::write_ec_files(dir, dir, "", VolumeId(1), 10, 4)
|
||||
.unwrap();
|
||||
|
||||
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
for id in 0..14u8 {
|
||||
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), id))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Clean scrub: no mismatches, no errors, blocks scanned > 0.
|
||||
let (scanned, broken, errs) = vol.checksum_scrub();
|
||||
assert!(errs.is_empty(), "unexpected scrub errors: {:?}", errs);
|
||||
assert!(broken.is_empty(), "unexpected mismatches: {:?}", broken);
|
||||
assert!(scanned > 0, "scrub should scan at least one block");
|
||||
|
||||
// Corrupt one byte of shard 3 on disk; re-scrub must report shard 3.
|
||||
let shard3 = format!("{}/1.ec03", dir);
|
||||
let mut bytes = std::fs::read(&shard3).unwrap();
|
||||
assert!(!bytes.is_empty());
|
||||
bytes[0] ^= 0xFF;
|
||||
std::fs::write(&shard3, &bytes).unwrap();
|
||||
|
||||
let (_, broken2, _) = vol.checksum_scrub();
|
||||
assert!(
|
||||
broken2.contains(&3),
|
||||
"corrupted shard 3 should be flagged, got {:?}",
|
||||
broken2
|
||||
);
|
||||
}
|
||||
|
||||
fn write_ecx_file(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
@@ -1292,10 +1798,11 @@ mod tests {
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_ecx_file(dir, "pics", VolumeId(1), &[]);
|
||||
|
||||
// data + parity exceeds MAX_SHARD_COUNT, so the config is rejected.
|
||||
let vif = crate::storage::volume::VifVolumeInfo {
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 10,
|
||||
data_shards: 20,
|
||||
parity_shards: 20,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
@@ -1311,4 +1818,150 @@ mod tests {
|
||||
assert_eq!(vol.data_shards, DATA_SHARDS_COUNT as u32);
|
||||
assert_eq!(vol.parity_shards, PARITY_SHARDS_COUNT as u32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ec_volume_wide_ratio_vif_config() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_ecx_file(dir, "pics", VolumeId(1), &[]);
|
||||
|
||||
// A wider-than-default ratio within MAX_SHARD_COUNT must load as-is.
|
||||
let vif = crate::storage::volume::VifVolumeInfo {
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 16,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let base = crate::storage::volume::volume_file_name(dir, "pics", VolumeId(1));
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string_pretty(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "pics", VolumeId(1)).unwrap();
|
||||
assert_eq!(vol.data_shards, 16);
|
||||
assert_eq!(vol.parity_shards, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_local_skips_tombstones() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(-1))];
|
||||
write_ecx_file(dir, "", VolumeId(1), &entries);
|
||||
|
||||
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
let (count, broken, errs) = vol.scrub_local();
|
||||
assert_eq!(count, 1);
|
||||
assert!(broken.is_empty(), "{:?}", broken);
|
||||
assert!(errs.is_empty(), "{:?}", errs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_local_clean_when_no_local_shards() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
|
||||
write_ecx_file(dir, "", VolumeId(1), &entries);
|
||||
|
||||
// dat_file_size makes the shard-size math well-defined.
|
||||
let vif = crate::storage::volume::VifVolumeInfo {
|
||||
dat_file_size: 14000,
|
||||
..Default::default()
|
||||
};
|
||||
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string_pretty(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// No shard files present: nothing to verify locally, so no errors.
|
||||
let vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
let (count, broken, errs) = vol.scrub_local();
|
||||
assert_eq!(count, 1);
|
||||
assert!(broken.is_empty(), "{:?}", broken);
|
||||
assert!(errs.is_empty(), "{:?}", errs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_local_suppresses_delete_state_disagreement() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
// Live index entry (size > 0) whose reassembled on-disk header reports size 0
|
||||
// (deleted-on-shards but live-in-index) — a delete-state disagreement, not corruption.
|
||||
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
|
||||
write_ecx_file(dir, "", VolumeId(1), &entries);
|
||||
|
||||
let vif = crate::storage::volume::VifVolumeInfo {
|
||||
dat_file_size: 14000,
|
||||
..Default::default()
|
||||
};
|
||||
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string_pretty(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Shard 0 holds the needle's bytes; all-zero so the parsed header size is 0.
|
||||
let mut shard0 = EcVolumeShard::new(dir, "", VolumeId(1), 0);
|
||||
shard0.create().unwrap();
|
||||
shard0.write_all(&[0u8; 256]).unwrap();
|
||||
shard0.close();
|
||||
|
||||
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), 0))
|
||||
.unwrap();
|
||||
|
||||
let (count, broken, errs) = vol.scrub_local();
|
||||
assert_eq!(count, 1);
|
||||
assert!(broken.is_empty(), "{:?}", broken);
|
||||
assert!(
|
||||
errs.is_empty(),
|
||||
"delete-state disagreement must be suppressed, got {:?}",
|
||||
errs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_local_reports_genuine_size_corruption() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let entries = vec![(NeedleId(1), Offset::from_actual_offset(0), Size(100))];
|
||||
write_ecx_file(dir, "", VolumeId(1), &entries);
|
||||
|
||||
let vif = crate::storage::volume::VifVolumeInfo {
|
||||
dat_file_size: 14000,
|
||||
..Default::default()
|
||||
};
|
||||
let base = crate::storage::volume::volume_file_name(dir, "", VolumeId(1));
|
||||
std::fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string_pretty(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// On-disk header reports a non-zero size (50) that disagrees with the live
|
||||
// index size (100): genuine corruption, not a delete-state race — must report.
|
||||
let mut bytes = vec![0u8; 256];
|
||||
bytes[15] = 50; // header size field (big-endian u32) = 50
|
||||
let mut shard0 = EcVolumeShard::new(dir, "", VolumeId(1), 0);
|
||||
shard0.create().unwrap();
|
||||
shard0.write_all(&bytes).unwrap();
|
||||
shard0.close();
|
||||
|
||||
let mut vol = EcVolume::new(dir, dir, "", VolumeId(1)).unwrap();
|
||||
vol.add_shard(EcVolumeShard::new(dir, "", VolumeId(1), 0))
|
||||
.unwrap();
|
||||
|
||||
let (_count, _broken, errs) = vol.scrub_local();
|
||||
assert!(
|
||||
!errs.is_empty(),
|
||||
"a non-zero size mismatch is genuine corruption and must be reported"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Encodes a volume's .dat file into 10 data + 4 parity shards using
|
||||
//! Reed-Solomon erasure coding. Can reconstruct from any 10 of 14 shards.
|
||||
|
||||
pub mod ec_bitrot;
|
||||
pub mod ec_decoder;
|
||||
pub mod ec_encoder;
|
||||
pub mod ec_locate;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//!
|
||||
//! Each entry: NeedleId(8) + Offset(5) + Size(4) = 17 bytes.
|
||||
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::types::*;
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
|
||||
@@ -36,6 +37,76 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify the integrity of an .idx/.ecx index file: walk every entry, sort by
|
||||
/// (offset, size), flag overlapping needles, and check the file is a whole
|
||||
/// number of entries. Mirrors Go's `idx.CheckIndexFile`. No data-file reads.
|
||||
pub fn check_index_file<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
idx_file_size: i64,
|
||||
version: Version,
|
||||
) -> (u64, Vec<String>) {
|
||||
let mut errs = Vec::new();
|
||||
// (walk index, id, actual offset, size)
|
||||
let mut entries: Vec<(usize, NeedleId, i64, Size)> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
if let Err(e) = walk_index_file(reader, 0, |id, offset, size| {
|
||||
entries.push((i, id, offset.to_actual_offset(), size));
|
||||
i += 1;
|
||||
Ok(())
|
||||
}) {
|
||||
errs.push(format!("walk index file: {}", e));
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| a.2.cmp(&b.2).then(a.3 .0.cmp(&b.3 .0)));
|
||||
|
||||
// Offset-0 logical tombstones (remote-tier deletes) occupy no physical extent,
|
||||
// so they cannot overlap anything — exclude them from the overlap check. They
|
||||
// are still counted below for the index-size check.
|
||||
let physical: Vec<(usize, NeedleId, i64, Size)> = entries
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|e| !(e.2 == 0 && e.3.is_deleted()))
|
||||
.collect();
|
||||
|
||||
for j in 1..physical.len() {
|
||||
let (index, id, offset, size) = physical[j];
|
||||
let (_, last_id, last_offset, last_size) = physical[j - 1];
|
||||
|
||||
let end = match get_actual_size(size, version) {
|
||||
0 => offset,
|
||||
s => offset + s - 1,
|
||||
};
|
||||
let last_end = match get_actual_size(last_size, version) {
|
||||
0 => last_offset,
|
||||
s => last_offset + s - 1,
|
||||
};
|
||||
|
||||
if offset <= last_end {
|
||||
errs.push(format!(
|
||||
"needle {} (#{}) at [{}-{}] overlaps needle {} at [{}-{}]",
|
||||
id.0,
|
||||
index + 1,
|
||||
offset,
|
||||
end,
|
||||
last_id.0,
|
||||
last_offset,
|
||||
last_end
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let count = entries.len() as u64;
|
||||
let expected = count as i64 * NEEDLE_MAP_ENTRY_SIZE as i64;
|
||||
if expected != idx_file_size {
|
||||
errs.push(format!(
|
||||
"expected an index file of size {}, got {}",
|
||||
idx_file_size, expected
|
||||
));
|
||||
}
|
||||
|
||||
(count, errs)
|
||||
}
|
||||
|
||||
/// Write a single index entry to a writer.
|
||||
pub fn write_index_entry<W: io::Write>(
|
||||
writer: &mut W,
|
||||
@@ -96,6 +167,67 @@ mod tests {
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
|
||||
fn idx_bytes(entries: &[(NeedleId, Offset, Size)]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
for (key, offset, size) in entries {
|
||||
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_entry_to_bytes(&mut buf, *key, *offset, *size);
|
||||
data.extend_from_slice(&buf);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_index_file_clean() {
|
||||
let data = idx_bytes(&[
|
||||
(NeedleId(1), Offset::from_actual_offset(0), Size(50)),
|
||||
(NeedleId(2), Offset::from_actual_offset(100_000), Size(50)),
|
||||
]);
|
||||
let size = data.len() as i64;
|
||||
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
|
||||
assert_eq!(count, 2);
|
||||
assert!(errs.is_empty(), "{:?}", errs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_index_file_detects_overlap() {
|
||||
let data = idx_bytes(&[
|
||||
(NeedleId(1), Offset::from_actual_offset(0), Size(100)),
|
||||
(NeedleId(2), Offset::from_actual_offset(8), Size(100)),
|
||||
]);
|
||||
let size = data.len() as i64;
|
||||
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(errs.len(), 1, "{:?}", errs);
|
||||
assert!(errs[0].contains("overlaps"), "{:?}", errs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_index_file_ignores_offset0_tombstone() {
|
||||
// A live needle near the start plus an offset-0 logical tombstone (remote-tier
|
||||
// delete) must NOT be flagged as overlapping; the tombstone row still counts.
|
||||
let data = idx_bytes(&[
|
||||
(NeedleId(1), Offset::from_actual_offset(8), Size(100)),
|
||||
(NeedleId(2), Offset::from_actual_offset(0), Size(-1)),
|
||||
]);
|
||||
let size = data.len() as i64;
|
||||
let (count, errs) = check_index_file(&mut Cursor::new(data), size, Version(3));
|
||||
assert_eq!(count, 2, "tombstone row is still counted: {:?}", errs);
|
||||
assert!(errs.is_empty(), "offset-0 tombstone must not overlap: {:?}", errs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_check_index_file_detects_size_mismatch() {
|
||||
let data = idx_bytes(&[(NeedleId(1), Offset::from_actual_offset(0), Size(50))]);
|
||||
let claimed = data.len() as i64 + 5;
|
||||
let (_count, errs) = check_index_file(&mut Cursor::new(data), claimed, Version(3));
|
||||
assert!(
|
||||
errs.iter().any(|e| e.contains("expected an index file")),
|
||||
"{:?}",
|
||||
errs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_write_index_entry() {
|
||||
let mut buf = Vec::new();
|
||||
|
||||
@@ -712,7 +712,7 @@ fn format_needle_id_cookie(key: NeedleId, cookie: Cookie) -> String {
|
||||
/// Parse "needle_id_cookie_hex" or "needle_id_cookie_hex_delta" into (NeedleId, Cookie).
|
||||
/// Matches Go's ParsePath + ParseNeedleIdCookie: supports an optional `_delta` suffix
|
||||
/// where delta is a decimal number added to the NeedleId (used for sub-file addressing).
|
||||
/// Rejects strings that are too short or too long.
|
||||
/// Rejects strings that are too short or too long, and deltas that overflow the needle id.
|
||||
pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
|
||||
// Go ParsePath: check for "_" suffix containing a decimal delta
|
||||
let (hex_part, delta) = if let Some(underscore_pos) = s.rfind('_') {
|
||||
@@ -743,23 +743,22 @@ pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
|
||||
let needle_id_hex = &hex_part[..split];
|
||||
let cookie_hex = &hex_part[split..];
|
||||
|
||||
let needle_id_bytes = hex::decode(needle_id_hex).map_err(|e| format!("Parse needleId error: {}", e))?;
|
||||
let cookie_bytes = hex::decode(cookie_hex).map_err(|e| format!("Parse cookie error: {}", e))?;
|
||||
|
||||
// Pad needle id to 8 bytes
|
||||
let mut nid_buf = [0u8; 8];
|
||||
if needle_id_bytes.len() > 8 {
|
||||
return Err(format!("KeyHash is too long."));
|
||||
}
|
||||
let start = 8 - needle_id_bytes.len();
|
||||
nid_buf[start..].copy_from_slice(&needle_id_bytes);
|
||||
|
||||
let mut key = NeedleId::from_bytes(&nid_buf[0..8]);
|
||||
let cookie = Cookie::from_bytes(&cookie_bytes[0..4]);
|
||||
// Go parses both with strconv.ParseUint, which accepts odd-length hex
|
||||
let mut key = NeedleId(
|
||||
u64::from_str_radix(needle_id_hex, 16)
|
||||
.map_err(|e| format!("Parse needleId error: {}", e))?,
|
||||
);
|
||||
let cookie = Cookie(
|
||||
u32::from_str_radix(cookie_hex, 16).map_err(|e| format!("Parse cookie error: {}", e))?,
|
||||
);
|
||||
|
||||
// Apply delta if present (Go: n.Id += Uint64ToNeedleId(d))
|
||||
if let Some(d) = delta {
|
||||
key = NeedleId(key.0.wrapping_add(d));
|
||||
key = NeedleId(
|
||||
key.0
|
||||
.checked_add(d)
|
||||
.ok_or_else(|| format!("delta {} overflows needle id {:x}", d, key.0))?,
|
||||
);
|
||||
}
|
||||
|
||||
Ok((key, cookie))
|
||||
@@ -941,4 +940,25 @@ mod tests {
|
||||
assert_eq!(key, NeedleId(1));
|
||||
assert_eq!(cookie, Cookie(0x12345678));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_rejects_delta_overflow() {
|
||||
assert!(parse_needle_id_cookie("ffffffffffffffff00000000_1").is_err());
|
||||
let (key, _) = parse_needle_id_cookie("fffffffffffffffe00000000_1").unwrap();
|
||||
assert_eq!(key, NeedleId(u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_odd_length_needle_id() {
|
||||
// Go's shell formats purge fids with strconv.FormatUint, which does not
|
||||
// pad the needle id hex to an even length.
|
||||
let (key, cookie) = parse_needle_id_cookie("100000000").unwrap();
|
||||
assert_eq!(key, NeedleId(1));
|
||||
assert_eq!(cookie, Cookie(0));
|
||||
|
||||
let fid = FileId::parse("3,12300000000").unwrap();
|
||||
assert_eq!(fid.volume_id, VolumeId(3));
|
||||
assert_eq!(fid.key, NeedleId(0x123));
|
||||
assert_eq!(fid.cookie, Cookie(0));
|
||||
}
|
||||
}
|
||||
@@ -934,46 +934,108 @@ impl Store {
|
||||
|
||||
/// Delete EC shard files from disk.
|
||||
pub fn delete_ec_shards(&mut self, vid: VolumeId, collection: &str, shard_ids: &[u32]) {
|
||||
// Delete shard files from disk
|
||||
for loc in &self.locations {
|
||||
// Delete shard files from disk, tracking which locations actually held one.
|
||||
let mut deleted_at = vec![false; self.locations.len()];
|
||||
for (i, loc) in self.locations.iter().enumerate() {
|
||||
for &shard_id in shard_ids {
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id as u8);
|
||||
let path = shard.file_name();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
if std::fs::remove_file(shard.file_name()).is_ok() {
|
||||
deleted_at[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also unmount if mounted
|
||||
self.unmount_ec_shards(vid, shard_ids);
|
||||
|
||||
// Per-disk: when this delete removed the location's last shards, the local
|
||||
// bitrot sidecar is orphaned — remove it (Go deleteEcShardIdsForEachLocation
|
||||
// when found && existingShardCount == 0). The `deleted_at` gate keeps a
|
||||
// delete that never touched a disk from stripping a sidecar it does not
|
||||
// own: a shared -dir.idx sibling with surviving shards, or an ec.rebuild
|
||||
// index-prep copy that lands .ecx/.ecsum before any shard.
|
||||
for (i, loc) in self.locations.iter().enumerate() {
|
||||
if !deleted_at[i] || Self::location_has_ec_shards(loc, collection, vid) {
|
||||
continue;
|
||||
}
|
||||
let data_base =
|
||||
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
|
||||
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&data_base);
|
||||
if loc.idx_directory != loc.directory {
|
||||
// A single -dir.idx is shared by every location: leave the idx-base
|
||||
// sidecar alone while any sibling still holds shards of this volume.
|
||||
let idx_in_use = self.locations.iter().any(|other| {
|
||||
other.idx_directory == loc.idx_directory
|
||||
&& Self::location_has_ec_shards(other, collection, vid)
|
||||
});
|
||||
if !idx_in_use {
|
||||
let idx_base = crate::storage::volume::volume_file_name(
|
||||
&loc.idx_directory,
|
||||
collection,
|
||||
vid,
|
||||
);
|
||||
let _ =
|
||||
crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If all shards are gone, remove .ecx and .ecj files from both idx and data dirs
|
||||
let all_gone = self.check_all_ec_shards_deleted(vid, collection);
|
||||
if all_gone {
|
||||
for loc in &self.locations {
|
||||
let idx_base =
|
||||
crate::storage::volume::volume_file_name(&loc.idx_directory, collection, vid);
|
||||
let data_base =
|
||||
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
|
||||
let _ = std::fs::remove_file(format!("{}.ecx", idx_base));
|
||||
let _ = std::fs::remove_file(format!("{}.ecj", idx_base));
|
||||
// Also try data directory in case .ecx/.ecj were created before -dir.idx
|
||||
if loc.idx_directory != loc.directory {
|
||||
let data_base =
|
||||
crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
|
||||
let _ = std::fs::remove_file(format!("{}.ecx", data_base));
|
||||
let _ = std::fs::remove_file(format!("{}.ecj", data_base));
|
||||
}
|
||||
// A shard-only disk also drops its stale .vif (Go
|
||||
// removeEcSharedIndexFiles): a live .idx means this disk still
|
||||
// hosts the source volume and the .vif belongs to it. Unexpected
|
||||
// stat errors count as present so a transient failure never
|
||||
// strips a live volume's .vif.
|
||||
let has_idx = [&idx_base, &data_base].iter().any(|base| {
|
||||
match std::fs::metadata(format!("{}.idx", base)) {
|
||||
Ok(_) => true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(_) => true,
|
||||
}
|
||||
});
|
||||
if !has_idx {
|
||||
let _ = std::fs::remove_file(format!("{}.vif", data_base));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True if `loc` still has any on-disk EC shard for this volume. An
|
||||
/// unexpected stat error (permission, I/O) counts as "exists" so a
|
||||
/// transient failure never classifies live shards as gone and deletes
|
||||
/// their sidecar or shared index.
|
||||
fn location_has_ec_shards(loc: &DiskLocation, collection: &str, vid: VolumeId) -> bool {
|
||||
for shard_id in 0..MAX_SHARD_COUNT as u8 {
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
|
||||
match std::fs::metadata(shard.file_name()) {
|
||||
Ok(_) => return true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(_) => return true,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Check if all EC shard files have been deleted for a volume.
|
||||
/// Uses MAX_SHARD_COUNT to support non-standard EC configurations.
|
||||
fn check_all_ec_shards_deleted(&self, vid: VolumeId, collection: &str) -> bool {
|
||||
for loc in &self.locations {
|
||||
for shard_id in 0..MAX_SHARD_COUNT as u8 {
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
|
||||
if std::path::Path::new(&shard.file_name()).exists() {
|
||||
return false;
|
||||
}
|
||||
if Self::location_has_ec_shards(loc, collection, vid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
@@ -1682,6 +1744,116 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Deleting a disk's last shard removes that disk's now-orphaned `.ecsum`;
|
||||
/// a disk this delete never changed keeps its sidecar. Disk 0 models
|
||||
/// ec.rebuild's index-prep state (`.ecsum` landed, no shards yet) — an
|
||||
/// unrelated shard delete must not strip its just-copied protection.
|
||||
#[test]
|
||||
fn test_delete_ec_shards_sidecar_gated_on_local_delete() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(2);
|
||||
let collection = "c";
|
||||
let vid = VolumeId(7);
|
||||
|
||||
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ecsum", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec00", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecsum", base1), b"x").unwrap();
|
||||
|
||||
// Disk 1 still has .ec01 afterwards: both sidecars survive.
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base0)).exists());
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base1)).exists());
|
||||
|
||||
// Disk 1's last shard goes: its sidecar is orphaned and removed, but
|
||||
// disk 0 was never touched by either delete and keeps its sidecar.
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
assert!(!std::path::Path::new(&format!("{}.ec01", base1)).exists());
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", base1)).exists(),
|
||||
"orphaned sidecar should be removed with the disk's last shard"
|
||||
);
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecsum", base0)).exists(),
|
||||
"a delete that removed nothing on this disk must not strip its sidecar"
|
||||
);
|
||||
}
|
||||
|
||||
/// With one -dir.idx shared by every location, emptying disk 0 must not
|
||||
/// remove the idx-base sidecar while disk 1 still holds shards; it goes
|
||||
/// only when the last location sharing the idx dir is emptied too.
|
||||
#[test]
|
||||
fn test_delete_ec_shards_preserves_shared_idx_sidecar() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let idx = tmp.path().join("idx");
|
||||
std::fs::create_dir_all(&idx).unwrap();
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
for i in 0..2 {
|
||||
let path = tmp.path().join(format!("data{}", i));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
store
|
||||
.add_location(
|
||||
path.to_str().unwrap(),
|
||||
idx.to_str().unwrap(),
|
||||
100,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(0.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let collection = "c";
|
||||
let vid = VolumeId(7);
|
||||
|
||||
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
let idx_base = volume_file_name(&store.locations[0].idx_directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecsum", idx_base), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar must survive while a sibling disk still has shards"
|
||||
);
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar should go with the last location's last shard"
|
||||
);
|
||||
}
|
||||
|
||||
/// When the node's last shard goes, a shard-only disk also drops its stale
|
||||
/// .vif (Go removeEcSharedIndexFiles); a disk with a live .idx still hosts
|
||||
/// the source volume and keeps its .vif.
|
||||
#[test]
|
||||
fn test_delete_ec_shards_vif_removal_gated_on_idx() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(2);
|
||||
let collection = "c";
|
||||
let vid = VolumeId(7);
|
||||
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
let base1 = volume_file_name(&store.locations[1].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.vif", base0), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.vif", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.idx", base1), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0, 1]);
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.vif", base0)).exists(),
|
||||
"shard-only disk should drop its stale .vif with the node's last shard"
|
||||
);
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.vif", base1)).exists(),
|
||||
"a disk with a live .idx keeps its .vif"
|
||||
);
|
||||
}
|
||||
|
||||
/// An already-mounted EC volume on disk 1 must win over a stray
|
||||
/// `.ecx` on disk 2. Protects the post-startup steady state from
|
||||
/// being perturbed by leftover index files from a prior failed move.
|
||||
|
||||
@@ -1866,236 +1866,346 @@ impl Volume {
|
||||
// needle map's max_needle_end accumulator, so we don't pay for a
|
||||
// second linear scan of the .idx here.
|
||||
|
||||
// Check last 10 index entries (matching Go's CheckVolumeDataIntegrity).
|
||||
// Go starts healthyIndexSize = indexSize and reduces on EOF.
|
||||
// On success: break (err != ErrorSizeMismatch when err == nil).
|
||||
// On EOF: set healthyIndexSize = position of corrupt entry, continue.
|
||||
// On ErrorSizeMismatch: continue (try next entry).
|
||||
// After loop: if healthyIndexSize < indexSize → error.
|
||||
// Verify the needle physically last in the .dat (the highest offset)
|
||||
// and that the .dat ends exactly at it. The .idx is not always in .dat
|
||||
// append order: weed fix and other rebuilds could rewrite it sorted by
|
||||
// key, which puts the highest-key needle last instead of the .dat-tail
|
||||
// needle. Picking the last file-position entry there compares a
|
||||
// mid-file needle's tail against the full .dat size and falsely flips
|
||||
// the volume read-only on every load. Mirrors Go's
|
||||
// findDatTailEntryOffset + doCheckAndFixVolumeData.
|
||||
let mut idx_file = File::open(&idx_path)?;
|
||||
let max_entries = std::cmp::min(10, idx_size / NEEDLE_MAP_ENTRY_SIZE as i64);
|
||||
let mut healthy_index_size: i64 = idx_size;
|
||||
let tail_entry_pos = self.find_dat_tail_entry_offset(&mut idx_file, idx_size, version)?;
|
||||
if tail_entry_pos < 0 {
|
||||
// pre-allocated / all-zero index, nothing to verify against the .dat
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for i in 1..=max_entries {
|
||||
let entry_offset = idx_size - i * NEEDLE_MAP_ENTRY_SIZE as i64;
|
||||
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_file.seek(SeekFrom::Start(entry_offset as u64))?;
|
||||
idx_file.read_exact(&mut buf)?;
|
||||
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_file.seek(SeekFrom::Start(tail_entry_pos as u64))?;
|
||||
idx_file.read_exact(&mut buf)?;
|
||||
let (key, offset, size) = idx_entry_from_bytes(&buf);
|
||||
if offset.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
if size.is_deleted() {
|
||||
// Deletion tombstone: the .idx carries TombstoneFileSize (-1) but
|
||||
// the appended needle in .dat carries Size=0, so verify with
|
||||
// Size=0 — comparing against -1 would mismatch the on-disk header
|
||||
// and send every volume with a trailing deletion read-only.
|
||||
self.verify_deleted_needle_integrity(offset.to_actual_offset(), key, version)
|
||||
} else {
|
||||
self.verify_needle_integrity(offset.to_actual_offset(), key, size, version)
|
||||
}
|
||||
}
|
||||
|
||||
let (key, offset, size) = idx_entry_from_bytes(&buf);
|
||||
if offset.is_zero() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let actual_offset = offset.to_actual_offset() as u64;
|
||||
|
||||
// Read needle header at the offset
|
||||
let mut header = [0u8; NEEDLE_HEADER_SIZE];
|
||||
match self.read_exact_at_backend(&mut header, actual_offset) {
|
||||
Ok(()) => {}
|
||||
Err(VolumeError::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
|
||||
// Match Go: on EOF, mark this entry as corrupt and continue
|
||||
// checking earlier entries (healthyIndexSize tracks the boundary).
|
||||
healthy_index_size = entry_offset;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
let (_cookie, needle_id, needle_size) = Needle::parse_header(&header);
|
||||
|
||||
// Verify the needle ID matches the index entry
|
||||
if !key.is_empty() && needle_id != key {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"index key {:?} does not match needle Id {:?} at offset {}",
|
||||
key, needle_id, actual_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
// For non-deleted entries, verify the size matches
|
||||
if !size.is_deleted() && size.0 > 0 && needle_size.0 != size.0 {
|
||||
// Try with MaxPossibleVolumeSize offset adjustment (Go parity)
|
||||
let alt_offset = actual_offset + MAX_POSSIBLE_VOLUME_SIZE as u64;
|
||||
let mut alt_header = [0u8; NEEDLE_HEADER_SIZE];
|
||||
if self
|
||||
.read_exact_at_backend(&mut alt_header, alt_offset)
|
||||
.is_ok()
|
||||
{
|
||||
let (_, _, alt_size) = Needle::parse_header(&alt_header);
|
||||
if alt_size.0 == size.0 {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Match Go: ErrorSizeMismatch breaks out of the loop
|
||||
break;
|
||||
}
|
||||
|
||||
// If V3, try to read the append timestamp from the last verified entry.
|
||||
// Go reads AppendAtNs from both live and deleted (tombstone) entries
|
||||
// via verifyNeedleIntegrity and verifyDeletedNeedleIntegrity.
|
||||
if version == VERSION_3 {
|
||||
// For tombstones (deleted), body size on disk is 0.
|
||||
// For live entries, body size is size.0.
|
||||
let body_size = if size.is_deleted() { 0u64 } else { size.0 as u64 };
|
||||
let ts_offset =
|
||||
actual_offset + NEEDLE_HEADER_SIZE as u64 + body_size + 4; // skip checksum
|
||||
let mut ts_buf = [0u8; 8];
|
||||
if self.read_exact_at_backend(&mut ts_buf, ts_offset).is_ok() {
|
||||
let ts = u64::from_be_bytes(ts_buf);
|
||||
if ts > 0 {
|
||||
self.last_append_at_ns = ts;
|
||||
}
|
||||
/// .idx file position of the entry whose needle is physically last in the
|
||||
/// .dat (highest offset). The common case — an append-ordered .idx — is
|
||||
/// resolved in O(1): the last entry's on-disk end equals the .dat size. A
|
||||
/// key-sorted .idx (e.g. legacy weed fix output) falls back to a single
|
||||
/// linear scan for the maximum offset. Returns -1 when no entry has a
|
||||
/// non-zero offset (a pre-allocated / all-zero index).
|
||||
fn find_dat_tail_entry_offset(
|
||||
&self,
|
||||
idx_file: &mut File,
|
||||
idx_size: i64,
|
||||
version: Version,
|
||||
) -> Result<i64, VolumeError> {
|
||||
if let Ok(dat_size) = self.dat_file_size() {
|
||||
if dat_size > 0 {
|
||||
let last_pos = idx_size - NEEDLE_MAP_ENTRY_SIZE as i64;
|
||||
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_file.seek(SeekFrom::Start(last_pos as u64))?;
|
||||
idx_file.read_exact(&mut buf)?;
|
||||
let (_, offset, size) = idx_entry_from_bytes(&buf);
|
||||
if !offset.is_zero() && needle_disk_end(offset, size, version) == dat_size as i64 {
|
||||
return Ok(last_pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Match Go: if healthyIndexSize < indexSize, trailing entries are corrupt
|
||||
if healthy_index_size < idx_size {
|
||||
// Slow path: scan the whole .idx for the entry at the maximum offset.
|
||||
// Tombstone entries are not skipped: a trailing deletion is a real
|
||||
// on-disk record and can be the needle physically last in the .dat.
|
||||
let mut max_entry_pos: i64 = -1;
|
||||
let mut max_actual_offset: i64 = -1;
|
||||
let mut entry_pos: i64 = 0;
|
||||
let mut buf = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_file.seek(SeekFrom::Start(0))?;
|
||||
let mut reader = io::BufReader::new(idx_file);
|
||||
while entry_pos < idx_size {
|
||||
reader.read_exact(&mut buf)?;
|
||||
let (_, offset, _) = idx_entry_from_bytes(&buf);
|
||||
if !offset.is_zero() {
|
||||
let ao = offset.to_actual_offset();
|
||||
if ao > max_actual_offset {
|
||||
max_actual_offset = ao;
|
||||
max_entry_pos = entry_pos;
|
||||
}
|
||||
}
|
||||
entry_pos += NEEDLE_MAP_ENTRY_SIZE as i64;
|
||||
}
|
||||
Ok(max_entry_pos)
|
||||
}
|
||||
|
||||
/// Verify the live needle at the .dat tail: its header must match the
|
||||
/// .idx entry and the .dat must end exactly at its on-disk end. Extra
|
||||
/// bytes mean an unindexed trailing record (a torn append); appending
|
||||
/// after one would place the next needle at an offset the 8-byte .idx
|
||||
/// encoding may not represent, so the volume is quarantined read-only
|
||||
/// instead. Mirrors Go's verifyNeedleIntegrity.
|
||||
fn verify_needle_integrity(
|
||||
&mut self,
|
||||
actual_offset: i64,
|
||||
key: NeedleId,
|
||||
size: Size,
|
||||
version: Version,
|
||||
) -> Result<(), VolumeError> {
|
||||
let mut header = [0u8; NEEDLE_HEADER_SIZE];
|
||||
self.read_exact_at_backend(&mut header, actual_offset as u64)?;
|
||||
let (_cookie, needle_id, needle_size) = Needle::parse_header(&header);
|
||||
|
||||
let mut checked_offset = actual_offset;
|
||||
let mut checked_id = needle_id;
|
||||
if needle_size != size {
|
||||
// Go parity: on a size mismatch, retry past the 32GB offset
|
||||
// wrap-around before giving up.
|
||||
let alt_offset = actual_offset + MAX_POSSIBLE_VOLUME_SIZE as i64;
|
||||
let mut alt_header = [0u8; NEEDLE_HEADER_SIZE];
|
||||
self.read_exact_at_backend(&mut alt_header, alt_offset as u64)
|
||||
.map_err(|_| size_mismatch_error(actual_offset, needle_id, needle_size, size))?;
|
||||
let (_, alt_id, alt_size) = Needle::parse_header(&alt_header);
|
||||
if alt_size != size {
|
||||
return Err(size_mismatch_error(actual_offset, needle_id, needle_size, size));
|
||||
}
|
||||
checked_offset = alt_offset;
|
||||
checked_id = alt_id;
|
||||
}
|
||||
|
||||
if !key.is_empty() && checked_id != key {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"healthy index size {} is less than expected {}",
|
||||
healthy_index_size, idx_size
|
||||
"index key {:?} does not match needle Id {:?} at offset {}",
|
||||
key, checked_id, checked_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
if version == VERSION_3 {
|
||||
let ts_offset =
|
||||
checked_offset as u64 + NEEDLE_HEADER_SIZE as u64 + size.0 as u64 + 4; // skip checksum
|
||||
let mut ts_buf = [0u8; 8];
|
||||
self.read_exact_at_backend(&mut ts_buf, ts_offset)?;
|
||||
let ts = u64::from_be_bytes(ts_buf);
|
||||
if ts > 0 {
|
||||
self.last_append_at_ns = ts;
|
||||
}
|
||||
}
|
||||
|
||||
self.verify_dat_ends_at(checked_offset + get_actual_size(size, version))
|
||||
}
|
||||
|
||||
/// Scrub the volume index by verifying each needle map entry against the dat file.
|
||||
/// For each entry, reads only the 16-byte needle header at the given offset to verify:
|
||||
/// correct needle ID, correct cookie (non-zero), and valid size.
|
||||
/// Does NOT read/verify the full needle data or CRC.
|
||||
/// Returns (files_checked, broken_needles) tuple.
|
||||
/// Verify the deletion tombstone at the .dat tail. Tombstones are appended
|
||||
/// with DataSize=0, so the on-disk header carries Size=0; verify with that
|
||||
/// and then require the .dat to end exactly at the tombstone. Mirrors Go's
|
||||
/// verifyDeletedNeedleIntegrity.
|
||||
fn verify_deleted_needle_integrity(
|
||||
&mut self,
|
||||
actual_offset: i64,
|
||||
key: NeedleId,
|
||||
version: Version,
|
||||
) -> Result<(), VolumeError> {
|
||||
let record_size = get_actual_size(Size(0), version) as usize;
|
||||
let mut record = vec![0u8; record_size];
|
||||
self.read_exact_at_backend(&mut record, actual_offset as u64)?;
|
||||
|
||||
let mut n = Needle::default();
|
||||
n.read_bytes(&record, actual_offset, Size(0), version)
|
||||
.map_err(|e| {
|
||||
VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("read tombstone at offset {}: {}", actual_offset, e),
|
||||
))
|
||||
})?;
|
||||
if !key.is_empty() && n.id != key {
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"index key {:?} does not match needle Id {:?} at offset {}",
|
||||
key, n.id, actual_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
if n.append_at_ns > 0 {
|
||||
self.last_append_at_ns = n.append_at_ns;
|
||||
}
|
||||
|
||||
self.verify_dat_ends_at(actual_offset + get_actual_size(Size(0), version))
|
||||
}
|
||||
|
||||
/// The checked needle is the one physically last in the .dat, so the file
|
||||
/// must end exactly at it; extra bytes mean an unindexed trailing record.
|
||||
fn verify_dat_ends_at(&self, file_tail_offset: i64) -> Result<(), VolumeError> {
|
||||
let file_size = self.dat_file_size().map_err(VolumeError::Io)? as i64;
|
||||
if file_size == file_tail_offset {
|
||||
return Ok(());
|
||||
}
|
||||
let dat_path = self.file_name(".dat");
|
||||
if file_size > file_tail_offset {
|
||||
warn!(
|
||||
"data file {} actual {} bytes expected {} bytes!",
|
||||
dat_path, file_size, file_tail_offset
|
||||
);
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"data file {} actual {} bytes expected {} bytes",
|
||||
dat_path, file_size, file_tail_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
warn!(
|
||||
"data file {} has {} bytes, less than expected {} bytes!",
|
||||
dat_path, file_size, file_tail_offset
|
||||
);
|
||||
Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"data file {} has {} bytes, less than expected {} bytes",
|
||||
dat_path, file_size, file_tail_offset
|
||||
),
|
||||
)))
|
||||
}
|
||||
|
||||
/// Open the on-disk .idx for scrubbing and apply Go openIndex's zero-size
|
||||
/// guard: a zero-size index is only legal for a pre-allocated volume whose
|
||||
/// .dat is superblock-only; an empty index over a populated .dat is
|
||||
/// corruption. Returns the open file + size, or the messages to report.
|
||||
fn open_index_for_scrub(&self) -> Result<(File, i64), Vec<String>> {
|
||||
let idx_path = self.file_name(".idx");
|
||||
let idx_file =
|
||||
File::open(&idx_path).map_err(|e| vec![format!("open index file {}: {}", idx_path, e)])?;
|
||||
let idx_file_size = idx_file
|
||||
.metadata()
|
||||
.map_err(|e| vec![format!("stat index file {}: {}", idx_path, e)])?
|
||||
.len() as i64;
|
||||
if idx_file_size == 0 {
|
||||
match self.dat_file_size() {
|
||||
Ok(dat_size) if dat_size > SUPER_BLOCK_SIZE as u64 => {
|
||||
return Err(vec![format!(
|
||||
"zero-size IDX file for volume {} with store size {}",
|
||||
self.id.0, dat_size
|
||||
)]);
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
return Err(vec![format!(
|
||||
"stat data file for volume {}: {}",
|
||||
self.id.0, e
|
||||
)])
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((idx_file, idx_file_size))
|
||||
}
|
||||
|
||||
/// Scrub the volume index: verify the on-disk .idx for overlapping needles
|
||||
/// and a size that is a whole number of entries. Mirrors Go's Volume.ScrubIndex
|
||||
/// → idx.CheckIndexFile. Index-only; does not read the .dat.
|
||||
pub fn scrub_index(&self) -> Result<(u64, Vec<String>), VolumeError> {
|
||||
if self.dat_file.is_none() && self.remote_dat_file.is_none() {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
let (mut idx_file, idx_file_size) = match self.open_index_for_scrub() {
|
||||
Ok(v) => v,
|
||||
Err(msgs) => return Ok((0, msgs)),
|
||||
};
|
||||
Ok(crate::storage::idx::check_index_file(
|
||||
&mut idx_file,
|
||||
idx_file_size,
|
||||
self.version(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Scrub the volume: walk the on-disk .idx (every physical row, including
|
||||
/// superseded and deleted entries), CRC-verify each live needle, and reconcile
|
||||
/// the .dat size against the needles it indexes. Mirrors Go's Volume.Scrub →
|
||||
/// scrubVolumeData. Returns (rows_walked, broken_needles).
|
||||
pub fn scrub(&self) -> Result<(u64, Vec<String>), VolumeError> {
|
||||
// Matches Go's scrubVolumeData: a volume with no data backend can't be
|
||||
// scrubbed (and a zero dat_size would flag every needle out of range).
|
||||
if !self.has_data_backend() {
|
||||
return Err(VolumeError::NotFound);
|
||||
}
|
||||
let nm = self.nm_or_not_found()?;
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
let (mut idx_file, idx_file_size) = match self.open_index_for_scrub() {
|
||||
Ok(v) => v,
|
||||
Err(msgs) => return Ok((0, msgs)),
|
||||
};
|
||||
|
||||
let version = self.version();
|
||||
let dat_size = self.dat_file_size().map_err(VolumeError::Io)?;
|
||||
|
||||
let mut files_checked: u64 = 0;
|
||||
let mut broken = Vec::new();
|
||||
// Full scrub also runs the index structural check.
|
||||
let (_, mut broken) =
|
||||
crate::storage::idx::check_index_file(&mut idx_file, idx_file_size, version);
|
||||
|
||||
for (needle_id, nv) in nm.iter_entries() {
|
||||
if nv.offset.is_zero() || nv.size.is_deleted() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let offset = nv.offset.to_actual_offset();
|
||||
if offset < 0 || offset as u64 >= dat_size {
|
||||
broken.push(format!(
|
||||
"needle {} offset {} out of range (dat_size={})",
|
||||
needle_id.0, offset, dat_size
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read only the 16-byte needle header to verify ID, cookie, and size
|
||||
let mut header_buf = [0u8; NEEDLE_HEADER_SIZE];
|
||||
match self.read_exact_at_backend(&mut header_buf, offset as u64) {
|
||||
Ok(()) => {
|
||||
let (cookie, id, size) = Needle::parse_header(&header_buf);
|
||||
if id != needle_id {
|
||||
broken.push(format!(
|
||||
"needle {} header id mismatch: expected {}, got {}",
|
||||
needle_id.0, needle_id.0, id.0
|
||||
));
|
||||
} else if cookie.0 == 0 {
|
||||
broken.push(format!(
|
||||
"needle {} has zero cookie at offset {}",
|
||||
needle_id.0, offset
|
||||
));
|
||||
} else if size.0 <= 0 && !nv.size.is_deleted() {
|
||||
broken.push(format!(
|
||||
"needle {} has invalid size {} at offset {}",
|
||||
needle_id.0, size.0, offset
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
broken.push(format!("needle {} read header error: {}", needle_id.0, e));
|
||||
}
|
||||
}
|
||||
|
||||
files_checked += 1;
|
||||
}
|
||||
|
||||
Ok((files_checked, broken))
|
||||
}
|
||||
|
||||
/// Scrub the volume by reading and verifying all needles.
|
||||
/// Returns (files_checked, broken_needles) tuple.
|
||||
/// Each needle is read from disk and its CRC checksum is verified.
|
||||
pub fn scrub(&self) -> Result<(u64, Vec<String>), VolumeError> {
|
||||
if self.dat_file.is_none() && self.remote_dat_file.is_none() {
|
||||
return Err(VolumeError::NotFound);
|
||||
}
|
||||
let nm = self.nm_or_not_found()?;
|
||||
|
||||
let dat_size = self.dat_file_size().map_err(|e| VolumeError::Io(e))?;
|
||||
let version = self.version();
|
||||
|
||||
let mut files_checked: u64 = 0;
|
||||
let mut broken = Vec::new();
|
||||
let mut count: u64 = 0;
|
||||
let mut total_read: i64 = 0;
|
||||
|
||||
for (needle_id, nv) in nm.iter_entries() {
|
||||
if nv.offset.is_zero() {
|
||||
continue;
|
||||
let walk = crate::storage::idx::walk_index_file(&mut idx_file, 0, |needle_id, offset, size| {
|
||||
count += 1;
|
||||
// A remote-tier delete records an offset-0 tombstone with no physical
|
||||
// .dat bytes, so it must not contribute to total_read.
|
||||
if offset.is_zero() && size.is_deleted() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Accumulate actual needle size for ALL entries including deleted ones
|
||||
// (matches Go: deleted needles still occupy space in the .dat file).
|
||||
total_read += get_actual_size(nv.size, version);
|
||||
|
||||
if nv.size.is_deleted() {
|
||||
continue;
|
||||
// Deleted needles still occupy .dat space: count their size, don't read.
|
||||
total_read += get_actual_size(size, version);
|
||||
if size.is_deleted() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let offset = nv.offset.to_actual_offset();
|
||||
if offset < 0 || offset as u64 >= dat_size {
|
||||
let actual_offset = offset.to_actual_offset();
|
||||
if actual_offset < 0 || actual_offset as u64 >= dat_size {
|
||||
broken.push(format!(
|
||||
"needle {} offset {} out of range (dat_size={})",
|
||||
needle_id.0, offset, dat_size
|
||||
needle_id.0, actual_offset, dat_size
|
||||
));
|
||||
continue;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Read and verify the needle (read_needle_data_at checks CRC via read_bytes/read_tail)
|
||||
// Lock held above; read directly via the unlocked path (matches Go).
|
||||
let mut n = Needle {
|
||||
id: needle_id,
|
||||
..Needle::default()
|
||||
};
|
||||
match self.read_needle_data_at(&mut n, offset, nv.size) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
broken.push(format!("needle {} error: {}", needle_id.0, e));
|
||||
}
|
||||
let mut read_option = ReadOption::default();
|
||||
if let Err(e) =
|
||||
self.read_needle_data_at_unlocked(&mut n, actual_offset, size, &mut read_option)
|
||||
{
|
||||
broken.push(format!(
|
||||
"failed to read needle {} on volume {}: {}",
|
||||
needle_id.0, self.id.0, e
|
||||
));
|
||||
}
|
||||
|
||||
files_checked += 1;
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = walk {
|
||||
broken.push(format!("walk index file: {}", e));
|
||||
}
|
||||
|
||||
// Validate total data size against .dat file size (matches Go's scrubVolumeData)
|
||||
let expected_size = total_read + SUPER_BLOCK_SIZE as i64;
|
||||
if (dat_size as i64) < expected_size {
|
||||
// Reconcile the physical .dat size against the needles read.
|
||||
let want_size = total_read + SUPER_BLOCK_SIZE as i64;
|
||||
if (dat_size as i64) < want_size {
|
||||
broken.push(format!(
|
||||
"dat file size {} is smaller than expected {} (total_read {} + super_block {})",
|
||||
dat_size, expected_size, total_read, SUPER_BLOCK_SIZE
|
||||
"data file for volume {} is smaller ({}) than the {} needles it contains ({})",
|
||||
self.id.0, dat_size, count, want_size
|
||||
));
|
||||
} else if dat_size as i64 != expected_size {
|
||||
} else if dat_size as i64 != want_size {
|
||||
broken.push(format!(
|
||||
"warning: dat file size {} does not match expected {} (total_read {} + super_block {})",
|
||||
dat_size, expected_size, total_read, SUPER_BLOCK_SIZE
|
||||
"data file size for volume {} ({}) doesn't match the size for {} needles read ({})",
|
||||
self.id.0, dat_size, count, want_size
|
||||
));
|
||||
}
|
||||
|
||||
Ok((files_checked, broken))
|
||||
Ok((count, broken))
|
||||
}
|
||||
|
||||
/// Scan raw needle entries from the .dat file starting at `from_offset`.
|
||||
@@ -3423,6 +3533,24 @@ impl Volume {
|
||||
// ============================================================================
|
||||
|
||||
/// Generate volume file base name: dir/collection_id or dir/id
|
||||
/// Byte offset just past the needle's on-disk record. Deletion tombstones
|
||||
/// carry TombstoneFileSize (-1) in the .idx but are written with DataSize=0,
|
||||
/// so their on-disk record is sized as 0. Mirrors Go's needleDiskEnd.
|
||||
fn needle_disk_end(offset: Offset, size: Size, version: Version) -> i64 {
|
||||
let on_disk_size = if size.is_deleted() { Size(0) } else { size };
|
||||
offset.to_actual_offset() + get_actual_size(on_disk_size, version)
|
||||
}
|
||||
|
||||
fn size_mismatch_error(offset: i64, id: NeedleId, found: Size, expected: Size) -> VolumeError {
|
||||
VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"entry not found: offset {} found id {:?} size {}, expected size {}",
|
||||
offset, id, found.0, expected.0
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn volume_file_name(dir: &str, collection: &str, id: VolumeId) -> String {
|
||||
if collection.is_empty() {
|
||||
format!("{}/{}", dir, id.0)
|
||||
@@ -3883,6 +4011,150 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn write_three_needles(dir: &str) {
|
||||
let mut v = make_test_volume(dir);
|
||||
for i in 1..=3u64 {
|
||||
let data = format!("data {}", i);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(i),
|
||||
cookie: Cookie(i as u32),
|
||||
data: data.as_bytes().to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
fn reload_volume(dir: &str) -> Volume {
|
||||
Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// A torn shutdown can leave bytes in the .dat past the last indexed
|
||||
// needle. Appending after such a tail would place the next needle at an
|
||||
// offset the 8-byte-unit .idx encoding may not represent, so the load
|
||||
// check must quarantine the volume read-only, matching Go's
|
||||
// verifyNeedleIntegrity "actual N bytes expected M bytes" behavior.
|
||||
#[test]
|
||||
fn test_integrity_detects_unindexed_dat_tail() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_three_needles(dir);
|
||||
|
||||
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
|
||||
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
|
||||
f.write_all(&[0xFFu8; 100]).unwrap();
|
||||
f.sync_all().unwrap();
|
||||
drop(f);
|
||||
|
||||
let v = reload_volume(dir);
|
||||
assert!(
|
||||
v.is_no_write_or_delete(),
|
||||
"volume with unindexed .dat tail must load read-only"
|
||||
);
|
||||
}
|
||||
|
||||
// Same torn tail, but with a deletion tombstone as the last indexed
|
||||
// record — the tombstone path must also verify the .dat ends at it.
|
||||
#[test]
|
||||
fn test_integrity_detects_tail_after_tombstone() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
{
|
||||
let mut v = make_test_volume(dir);
|
||||
let data = b"data 1".to_vec();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: data.clone(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.delete_needle(&mut Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
}
|
||||
|
||||
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
|
||||
let mut f = OpenOptions::new().append(true).open(&dat_path).unwrap();
|
||||
f.write_all(&[0xFFu8; 64]).unwrap();
|
||||
f.sync_all().unwrap();
|
||||
drop(f);
|
||||
|
||||
let v = reload_volume(dir);
|
||||
assert!(
|
||||
v.is_no_write_or_delete(),
|
||||
"volume with unindexed tail after tombstone must load read-only"
|
||||
);
|
||||
}
|
||||
|
||||
// A key-sorted .idx (legacy weed fix output) puts the highest-key needle
|
||||
// last by file position, not the .dat-tail needle. The check must find
|
||||
// the true tail entry via the max-offset scan instead of falsely flipping
|
||||
// a healthy volume read-only.
|
||||
#[test]
|
||||
fn test_integrity_key_sorted_idx_no_false_readonly() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_three_needles(dir);
|
||||
|
||||
// Swap the last two .idx entries so the file-position-last entry
|
||||
// references a mid-file needle.
|
||||
let idx_path = volume_file_name(dir, "", VolumeId(1)) + ".idx";
|
||||
let content = fs::read(&idx_path).unwrap();
|
||||
assert_eq!(content.len(), 3 * NEEDLE_MAP_ENTRY_SIZE);
|
||||
let mut swapped = content.clone();
|
||||
swapped[NEEDLE_MAP_ENTRY_SIZE..2 * NEEDLE_MAP_ENTRY_SIZE]
|
||||
.copy_from_slice(&content[2 * NEEDLE_MAP_ENTRY_SIZE..]);
|
||||
swapped[2 * NEEDLE_MAP_ENTRY_SIZE..]
|
||||
.copy_from_slice(&content[NEEDLE_MAP_ENTRY_SIZE..2 * NEEDLE_MAP_ENTRY_SIZE]);
|
||||
fs::write(&idx_path, swapped).unwrap();
|
||||
|
||||
let v = reload_volume(dir);
|
||||
assert!(
|
||||
!v.is_no_write_or_delete(),
|
||||
"healthy volume with key-sorted .idx must not load read-only"
|
||||
);
|
||||
}
|
||||
|
||||
// A .dat truncated mid-needle (crash during append) must quarantine.
|
||||
#[test]
|
||||
fn test_integrity_detects_truncated_dat_tail() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
write_three_needles(dir);
|
||||
|
||||
let dat_path = volume_file_name(dir, "", VolumeId(1)) + ".dat";
|
||||
let len = fs::metadata(&dat_path).unwrap().len();
|
||||
let f = OpenOptions::new().write(true).open(&dat_path).unwrap();
|
||||
f.set_len(len - 5).unwrap();
|
||||
f.sync_all().unwrap();
|
||||
drop(f);
|
||||
|
||||
let v = reload_volume(dir);
|
||||
assert!(
|
||||
v.is_no_write_or_delete(),
|
||||
"volume with truncated .dat tail must load read-only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_empty_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "zero-size volume without index"
|
||||
@@ -3914,6 +4186,107 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_overwritten_volume_scrubs_clean() {
|
||||
// An overwrite/delete appends a second .dat record + .idx row. Walking
|
||||
// the on-disk .idx (not the deduped map) makes total_read match the
|
||||
// physical .dat, so a healthy overwritten volume is NOT flagged broken.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
for (id, body) in [(1u64, "first version"), (1, "second version"), (2, "other")] {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data: body.as_bytes().to_vec(),
|
||||
data_size: body.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
}
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let (count, broken) = v.scrub().unwrap();
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"overwritten volume should scrub clean, got {:?}",
|
||||
broken
|
||||
);
|
||||
assert_eq!(count, 3, "scrub must count every .idx row");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_ignores_offset0_tombstone() {
|
||||
// A remote-tier delete appends an offset-0 tombstone to the .idx with no
|
||||
// physical .dat bytes; it must not flag the volume (neither the size
|
||||
// reconcile nor the structural overlap check).
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
let data = b"needle data".to_vec();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: data.clone(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
// Append an offset-0 logical tombstone to the on-disk .idx.
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(v.file_name(".idx"))
|
||||
.unwrap();
|
||||
crate::storage::idx::write_index_entry(&mut f, NeedleId(2), Offset::from_actual_offset(0), Size(-1))
|
||||
.unwrap();
|
||||
f.sync_all().unwrap();
|
||||
drop(f);
|
||||
|
||||
let (count, broken) = v.scrub().unwrap();
|
||||
assert!(
|
||||
broken.is_empty(),
|
||||
"offset-0 tombstone must not flag the volume, got {:?}",
|
||||
broken
|
||||
);
|
||||
assert_eq!(count, 2, "both .idx rows are walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_index_flags_zero_size_idx_with_data() {
|
||||
// A populated .dat with an empty .idx is corruption — the pre-allocated
|
||||
// exception only covers a superblock-only .dat.
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
|
||||
let data = b"needle data".to_vec();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: data.clone(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
assert!(v.dat_file_size().unwrap() > SUPER_BLOCK_SIZE as u64);
|
||||
|
||||
// Truncate the .idx to zero while the .dat keeps its needle.
|
||||
std::fs::File::create(v.file_name(".idx")).unwrap();
|
||||
|
||||
let (count, broken) = v.scrub_index().unwrap();
|
||||
assert_eq!(count, 0);
|
||||
assert!(
|
||||
broken.iter().any(|e| e.contains("zero-size IDX file")),
|
||||
"expected zero-size IDX error, got {:?}",
|
||||
broken
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scrub_healthy_volume() {
|
||||
// Mirror of Go's TestScrubVolumeData "healthy volume" case: a volume
|
||||
|
||||
@@ -38,10 +38,27 @@ fn test_state_with_whitelist(whitelist: Vec<String>) -> (Arc<VolumeServerState>,
|
||||
fn test_state_with_guard(
|
||||
whitelist: Vec<String>,
|
||||
signing_key: Vec<u8>,
|
||||
) -> (Arc<VolumeServerState>, TempDir) {
|
||||
build_test_state(whitelist, signing_key, None, String::new())
|
||||
}
|
||||
|
||||
/// Build a test state with volume 1 created using the given replica placement
|
||||
/// (e.g. "001" for a two-copy volume) and master URL. An empty master URL plus
|
||||
/// a None placement is the single-copy default used by most tests.
|
||||
fn build_test_state(
|
||||
whitelist: Vec<String>,
|
||||
signing_key: Vec<u8>,
|
||||
replication: Option<&str>,
|
||||
master_url: String,
|
||||
) -> (Arc<VolumeServerState>, TempDir) {
|
||||
let tmp = TempDir::new().expect("failed to create temp dir");
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
let replica_placement = replication.map(|s| {
|
||||
seaweed_volume::storage::super_block::ReplicaPlacement::from_string(s)
|
||||
.expect("invalid replica placement")
|
||||
});
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
@@ -57,7 +74,7 @@ fn test_state_with_guard(
|
||||
.add_volume(
|
||||
VolumeId(1),
|
||||
"",
|
||||
None,
|
||||
replica_placement,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
@@ -100,7 +117,7 @@ fn test_state_with_guard(
|
||||
),
|
||||
read_mode: seaweed_volume::config::ReadMode::Local,
|
||||
allow_untrusted_remote_endpoints: false,
|
||||
master_url: String::new(),
|
||||
master_url,
|
||||
master_urls: Vec::new(),
|
||||
seed_master_set: std::collections::HashSet::new(),
|
||||
current_master_url: tokio::sync::RwLock::new(String::new()),
|
||||
@@ -678,3 +695,242 @@ async fn admin_router_serves_volume_ui_static_assets() {
|
||||
let body = body_bytes(response).await;
|
||||
assert!(body.len() > 1000);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Replicated (fan-out) writes
|
||||
//
|
||||
// A chunked S3 upload has the gateway write every replica holder directly with
|
||||
// `type=replicate` instead of relaying through the primary volume. Each holder
|
||||
// must accept the copy and store it locally without re-replicating. These tests
|
||||
// pin that contract on the Rust volume server.
|
||||
// ============================================================================
|
||||
|
||||
/// Raw-body `type=replicate` write is stored and reads back.
|
||||
#[tokio::test]
|
||||
async fn replicate_write_raw_body_is_stored() {
|
||||
let (state, _tmp) = test_state();
|
||||
let uri = "/1,01637037d6?type=replicate";
|
||||
let payload = b"fan-out replica bytes";
|
||||
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.body(Body::from(payload.to_vec()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CREATED);
|
||||
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/1,01637037d6")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(body_bytes(response).await, payload);
|
||||
}
|
||||
|
||||
/// Multipart `type=replicate` write (the shape the Go gateway uploader sends)
|
||||
/// is stored and reads back.
|
||||
#[tokio::test]
|
||||
async fn replicate_write_multipart_body_is_stored() {
|
||||
let (state, _tmp) = test_state();
|
||||
let boundary = "----replicateboundary";
|
||||
let payload = b"fan-out replica bytes";
|
||||
let mut body = Vec::new();
|
||||
body.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
|
||||
body.extend_from_slice(
|
||||
b"Content-Disposition: form-data; name=\"file\"; filename=\"chunk\"\r\n",
|
||||
);
|
||||
body.extend_from_slice(b"Content-Type: application/octet-stream\r\n\r\n");
|
||||
body.extend_from_slice(payload);
|
||||
body.extend_from_slice(format!("\r\n--{}--\r\n", boundary).as_bytes());
|
||||
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/1,01637037d6?type=replicate")
|
||||
.header(
|
||||
"Content-Type",
|
||||
format!("multipart/form-data; boundary={}", boundary),
|
||||
)
|
||||
.body(Body::from(body))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CREATED);
|
||||
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/1,01637037d6")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(body_bytes(response).await, payload);
|
||||
}
|
||||
|
||||
/// On a multi-copy volume, a `type=replicate` write must store locally without
|
||||
/// re-replicating: it must not contact the master, even an unreachable one.
|
||||
/// A plain write to the same volume does attempt replication and fails against
|
||||
/// the dead master, which proves the `type=replicate` flag is what suppresses
|
||||
/// the fan-out (not a disabled replication path).
|
||||
#[tokio::test]
|
||||
async fn replicate_write_does_not_re_replicate() {
|
||||
// Port 0 is rejected by the socket layer immediately, so a stray lookup
|
||||
// fails fast instead of hanging on a connect timeout in firewalled CI.
|
||||
let dead_master = "127.0.0.1:0".to_string();
|
||||
let (state, _tmp) = build_test_state(Vec::new(), Vec::new(), Some("001"), dead_master);
|
||||
|
||||
// type=replicate: stored locally, no master lookup -> 201.
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/1,01637037d6?type=replicate")
|
||||
.body(Body::from(b"replicated copy".to_vec()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
StatusCode::CREATED,
|
||||
"replicate write must not depend on the master"
|
||||
);
|
||||
|
||||
// plain write: tries to fan out to the dead master and fails.
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/1,02637037d7")
|
||||
.body(Body::from(b"primary copy".to_vec()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"plain write to a multi-copy volume must attempt replication"
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Chunk-manifest expansion resolves chunks on EC volumes
|
||||
//
|
||||
// A chunked object whose data chunks live on an EC-encoded volume must expand
|
||||
// by reconstruct-on-read from the shards, not by a local regular-volume lookup
|
||||
// (which finds nothing once the volume is EC-encoded). Mirrors Go's
|
||||
// ChunkedFileReader, which resolves every chunk through the master.
|
||||
// ============================================================================
|
||||
|
||||
#[tokio::test]
|
||||
async fn chunk_manifest_expands_chunk_stored_on_ec_volume() {
|
||||
use seaweed_volume::storage::erasure_coding::ec_encoder::write_ec_files;
|
||||
use seaweed_volume::storage::needle::needle::{FileId, Needle};
|
||||
use seaweed_volume::storage::types::{Cookie, NeedleId};
|
||||
use seaweed_volume::storage::volume::Volume;
|
||||
|
||||
let (state, tmp) = test_state();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
|
||||
// A chunk large enough to be worth EC-encoding; its bytes are the payload we
|
||||
// expect the manifest GET to return.
|
||||
let chunk_data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||
let chunk_nid = NeedleId(0x2a);
|
||||
let chunk_cookie = Cookie(0x1234abcd);
|
||||
|
||||
// Build regular volume 2 holding the chunk, then EC-encode it and mount all
|
||||
// 14 shards locally so reconstruct-on-read is a pure local read.
|
||||
{
|
||||
let mut v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
"",
|
||||
VolumeId(2),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut n = Needle {
|
||||
id: chunk_nid,
|
||||
cookie: chunk_cookie,
|
||||
data: chunk_data.clone(),
|
||||
data_size: chunk_data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
v.close();
|
||||
}
|
||||
write_ec_files(dir, dir, "", VolumeId(2), 10, 4).unwrap();
|
||||
// Volume 2 was built standalone (never registered in the store), so it only
|
||||
// exists as EC shards — the chunk resolves through the EC path, as it would
|
||||
// after ec.encode retired the regular volume.
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
let shard_ids: Vec<u32> = (0..14).collect();
|
||||
store.mount_ec_shards(VolumeId(2), "", &shard_ids).unwrap();
|
||||
}
|
||||
|
||||
// Write the chunk-manifest needle to regular volume 1.
|
||||
let chunk_fid = FileId::new(VolumeId(2), chunk_nid, chunk_cookie).to_string();
|
||||
let manifest = format!(
|
||||
r#"{{"name":"big.bin","mime":"application/octet-stream","size":{},"chunks":[{{"fid":"{}","offset":0,"size":{}}}]}}"#,
|
||||
chunk_data.len(),
|
||||
chunk_fid,
|
||||
chunk_data.len()
|
||||
);
|
||||
let manifest_nid = NeedleId(0x7);
|
||||
let manifest_cookie = Cookie(0x55667788);
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
let mut n = Needle {
|
||||
id: manifest_nid,
|
||||
cookie: manifest_cookie,
|
||||
data: manifest.into_bytes(),
|
||||
..Needle::default()
|
||||
};
|
||||
n.data_size = n.data.len() as u32;
|
||||
n.set_is_chunk_manifest();
|
||||
store.write_volume_needle(VolumeId(1), &mut n).unwrap();
|
||||
}
|
||||
|
||||
// GET the manifest object; expect the reconstructed chunk bytes.
|
||||
let manifest_fid = FileId::new(VolumeId(1), manifest_nid, manifest_cookie).to_string();
|
||||
let app = build_admin_router(state.clone());
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/{}", manifest_fid))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(body_bytes(response).await, chunk_data);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
module seaweedfs-rdma-sidecar
|
||||
|
||||
go 1.25.0
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
github.com/seaweedfs/seaweedfs v0.0.0-00010101000000-000000000000
|
||||
github.com/sirupsen/logrus v1.9.4-0.20230606125235-dd1b4c2e81af
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/spf13/cobra v1.8.0
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1
|
||||
)
|
||||
@@ -12,15 +12,15 @@ require (
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cognusion/imaging v1.0.2 // indirect
|
||||
github.com/cognusion/imaging v1.0.3 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.2 // indirect
|
||||
github.com/prometheus/common v0.67.5 // indirect
|
||||
github.com/prometheus/procfs v0.20.1 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/seaweedfs/goexif v1.0.3 // indirect
|
||||
@@ -33,12 +33,12 @@ require (
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/image v0.38.0 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
google.golang.org/grpc v1.79.3 // indirect
|
||||
golang.org/x/image v0.43.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 // indirect
|
||||
google.golang.org/grpc v1.81.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
|
||||
@@ -2,11 +2,9 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cognusion/imaging v1.0.2 h1:BQwBV8V8eF3+dwffp8Udl9xF1JKh5Z0z5JkJwAi98Mc=
|
||||
github.com/cognusion/imaging v1.0.2/go.mod h1:mj7FvH7cT2dlFogQOSUQRtotBxJ4gFQ2ySMSmBm5dSk=
|
||||
github.com/cognusion/imaging v1.0.3 h1:nHyIeEVDV8JkBbuhgx8iSBW72W8rHbDEyruA0Jh7Lnk=
|
||||
github.com/cognusion/imaging v1.0.3/go.mod h1:38tFLFhGK81ORThZG8dVXPtp1uhd+3xM1WXuMn+unOA=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
@@ -17,8 +15,8 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -27,8 +25,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
|
||||
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -39,15 +37,14 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.67.2 h1:PcBAckGFTIHt2+L3I33uNRTlKTplNzFctXcWhPyAEN8=
|
||||
github.com/prometheus/common v0.67.2/go.mod h1:63W3KZb1JOKgcjlIr64WW/LvFGAqKPj0atm+knVGEko=
|
||||
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
|
||||
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
@@ -57,8 +54,8 @@ github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDc
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
|
||||
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
|
||||
github.com/sirupsen/logrus v1.9.4-0.20230606125235-dd1b4c2e81af h1:Sp5TG9f7K39yfB+If0vjp97vuT74F72r8hfRpP8jLU0=
|
||||
github.com/sirupsen/logrus v1.9.4-0.20230606125235-dd1b4c2e81af/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
@@ -72,8 +69,6 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
@@ -84,42 +79,40 @@ github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAh
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
|
||||
golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
|
||||
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 h1:ndE4FoJqsIceKP2oYSnUZqhTdYufCYYkqwtFzfrhI7w=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4 h1:tEkOQcXgF6dH1G+MVKZrfpYvozGrzb91k6ha7jireSM=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260427160629-7cedc36a6bc4/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
|
||||
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -34,14 +34,18 @@ type FuseTestFramework struct {
|
||||
|
||||
// TestConfig holds configuration for FUSE tests
|
||||
type TestConfig struct {
|
||||
Collection string
|
||||
Replication string
|
||||
ChunkSizeMB int
|
||||
CacheSizeMB int
|
||||
NumVolumes int
|
||||
EnableDebug bool
|
||||
MountOptions []string
|
||||
SkipCleanup bool // for debugging failed tests
|
||||
Collection string
|
||||
Replication string
|
||||
ChunkSizeMB int
|
||||
CacheSizeMB int
|
||||
NumVolumes int
|
||||
EnableDebug bool
|
||||
// MountGlobalOptions are glog flags (-v, -logtostderr, ...) registered on
|
||||
// weed's global flagset; they must precede the subcommand name or the
|
||||
// mount process dies at flag parsing.
|
||||
MountGlobalOptions []string
|
||||
MountOptions []string
|
||||
SkipCleanup bool // for debugging failed tests
|
||||
}
|
||||
|
||||
// DefaultTestConfig returns a default configuration for FUSE tests
|
||||
@@ -82,35 +86,47 @@ func NewFuseTestFramework(t *testing.T, config *TestConfig) *FuseTestFramework {
|
||||
}
|
||||
}
|
||||
|
||||
// freePort asks the OS for a free TCP port in a range where the gRPC
|
||||
// offset (port + 10000) won't collide with well-known ports.
|
||||
// Stay below the Linux ephemeral floor (32768) so the kernel does not
|
||||
// reuse the chosen port for an outbound connection between close() here
|
||||
// and re-bind in the child "weed mini" process.
|
||||
// grpcPortOffset mirrors weed's HTTP->gRPC port convention (gRPC = HTTP + offset);
|
||||
// "weed mount" derives the filer gRPC port from the filer HTTP address the same way.
|
||||
const grpcPortOffset = 10000
|
||||
|
||||
// freePort returns a free filer HTTP port whose gRPC sibling (port+grpcPortOffset)
|
||||
// is also free. Both must stay below the Linux ephemeral floor (32768): a gRPC port
|
||||
// above it can be transiently grabbed by an outbound connection, forcing mini to
|
||||
// relocate its filer gRPC port while "weed mount" keeps dialing HTTP+10000 — the
|
||||
// mount then never connects and the test times out. Capping HTTP at 22000 keeps the
|
||||
// gRPC port at or below 32000.
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
const (
|
||||
minServicePort = 20000
|
||||
maxServicePort = 32000
|
||||
maxServicePort = 22000
|
||||
)
|
||||
|
||||
portCount := maxServicePort - minServicePort + 1
|
||||
start := minServicePort + int(time.Now().UnixNano()%int64(portCount))
|
||||
|
||||
for attempt := 0; attempt < 512; attempt++ {
|
||||
for attempt := 0; attempt < portCount; attempt++ {
|
||||
port := minServicePort + (start-minServicePort+attempt)%portCount
|
||||
l, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
|
||||
if err != nil {
|
||||
continue
|
||||
if portIsFree(port) && portIsFree(port+grpcPortOffset) {
|
||||
return port
|
||||
}
|
||||
l.Close()
|
||||
return port
|
||||
}
|
||||
|
||||
t.Fatalf("failed to allocate port <= %d after repeated attempts", maxServicePort)
|
||||
t.Fatalf("failed to allocate a free HTTP/gRPC port pair in [%d,%d]", minServicePort, maxServicePort)
|
||||
return 0
|
||||
}
|
||||
|
||||
// portIsFree reports whether a TCP port can currently be bound on 127.0.0.1.
|
||||
func portIsFree(port int) bool {
|
||||
l, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
l.Close()
|
||||
return true
|
||||
}
|
||||
|
||||
// Setup starts "weed mini" and mounts the FUSE filesystem.
|
||||
func (f *FuseTestFramework) Setup(config *TestConfig) error {
|
||||
if f.isSetup {
|
||||
@@ -246,19 +262,20 @@ func (f *FuseTestFramework) copyLogsForCI() {
|
||||
|
||||
// startMini starts "weed mini" which runs master+volume+filer in one process.
|
||||
func (f *FuseTestFramework) startMini(config *TestConfig) error {
|
||||
args := []string{
|
||||
"mini",
|
||||
"-dir=" + f.dataDir,
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-filer.port=" + strconv.Itoa(f.filerPort),
|
||||
"-s3=false",
|
||||
"-webdav=false",
|
||||
"-admin.ui=false",
|
||||
}
|
||||
var args []string
|
||||
if config.EnableDebug {
|
||||
args = append(args, "-v=4")
|
||||
}
|
||||
args = append(args,
|
||||
"mini",
|
||||
"-dir="+f.dataDir,
|
||||
"-ip=127.0.0.1",
|
||||
"-ip.bind=127.0.0.1",
|
||||
"-filer.port="+strconv.Itoa(f.filerPort),
|
||||
"-s3=false",
|
||||
"-webdav=false",
|
||||
"-admin.ui=false",
|
||||
)
|
||||
|
||||
proc, err := f.startProcess("mini", args)
|
||||
if err != nil {
|
||||
@@ -270,14 +287,18 @@ func (f *FuseTestFramework) startMini(config *TestConfig) error {
|
||||
|
||||
// mountFuse mounts the SeaweedFS FUSE filesystem
|
||||
func (f *FuseTestFramework) mountFuse(config *TestConfig) error {
|
||||
args := []string{
|
||||
args := append([]string{}, config.MountGlobalOptions...)
|
||||
if config.EnableDebug {
|
||||
args = append(args, "-v=4")
|
||||
}
|
||||
args = append(args,
|
||||
"mount",
|
||||
"-filer=127.0.0.1:" + strconv.Itoa(f.filerPort),
|
||||
"-dir=" + f.mountPoint,
|
||||
"-filer=127.0.0.1:"+strconv.Itoa(f.filerPort),
|
||||
"-dir="+f.mountPoint,
|
||||
"-filer.path=/",
|
||||
"-dirAutoCreate",
|
||||
"-allowOthers=false",
|
||||
}
|
||||
)
|
||||
|
||||
if config.Collection != "" {
|
||||
args = append(args, "-collection="+config.Collection)
|
||||
@@ -291,9 +312,6 @@ func (f *FuseTestFramework) mountFuse(config *TestConfig) error {
|
||||
if config.CacheSizeMB > 0 {
|
||||
args = append(args, fmt.Sprintf("-cacheCapacityMB=%d", config.CacheSizeMB))
|
||||
}
|
||||
if config.EnableDebug {
|
||||
args = append(args, "-v=4")
|
||||
}
|
||||
|
||||
args = append(args, config.MountOptions...)
|
||||
|
||||
@@ -333,11 +351,19 @@ func (f *FuseTestFramework) waitForService(addr string, timeout time.Duration) e
|
||||
return fmt.Errorf("service at %s not ready within timeout", addr)
|
||||
}
|
||||
|
||||
// waitForMount waits for the FUSE mount to be ready
|
||||
// waitForMount waits for the FUSE mount to be ready. A stat/ReadDir probe
|
||||
// alone is not enough: the bare mount point directory passes both before the
|
||||
// mount process finishes starting, letting tests race ahead and write to the
|
||||
// local disk underneath the mount. The mount point's device ID differing from
|
||||
// its parent's confirms a filesystem is actually mounted there.
|
||||
func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
|
||||
parentDev, err := deviceID(filepath.Dir(f.mountPoint))
|
||||
if err != nil {
|
||||
return fmt.Errorf("stat mount point parent: %v", err)
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := os.Stat(f.mountPoint); err == nil {
|
||||
if dev, err := deviceID(f.mountPoint); err == nil && dev != parentDev {
|
||||
if _, err := os.ReadDir(f.mountPoint); err == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -347,6 +373,15 @@ func (f *FuseTestFramework) waitForMount(timeout time.Duration) error {
|
||||
return fmt.Errorf("mount point not ready within timeout")
|
||||
}
|
||||
|
||||
// deviceID returns the device ID of the filesystem containing path.
|
||||
func deviceID(path string) (uint64, error) {
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Stat(path, &st); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint64(st.Dev), nil
|
||||
}
|
||||
|
||||
// findWeedBinary locates the weed binary.
|
||||
func findWeedBinary() string {
|
||||
if p, err := exec.LookPath("weed"); err == nil {
|
||||
|
||||
@@ -79,6 +79,15 @@ func writeBufferCapConfig(debugPort int) *TestConfig {
|
||||
CacheSizeMB: 100, // read cache (unrelated)
|
||||
NumVolumes: 3,
|
||||
EnableDebug: false,
|
||||
// Route glog to stderr so the framework's process log capture
|
||||
// actually contains something — by default weed sends glog to
|
||||
// /tmp/weed.* files which the CI artifact upload step never
|
||||
// sees. Critical for diagnosing upload/saveToStorage errors
|
||||
// on Linux runs.
|
||||
MountGlobalOptions: []string{
|
||||
"-logtostderr=true",
|
||||
"-v=2",
|
||||
},
|
||||
MountOptions: []string{
|
||||
// 16 MiB total write buffer ⇒ up to 8 chunks in flight
|
||||
// across every open file handle on this mount. Large
|
||||
@@ -88,13 +97,6 @@ func writeBufferCapConfig(debugPort int) *TestConfig {
|
||||
"-writeBufferSizeMB=16",
|
||||
"-debug=true",
|
||||
fmt.Sprintf("-debug.port=%d", debugPort),
|
||||
// Route glog to stderr so the framework's process log
|
||||
// capture actually contains something — by default weed
|
||||
// sends glog to /tmp/weed.* files which the CI artifact
|
||||
// upload step never sees. Critical for diagnosing
|
||||
// upload/saveToStorage errors on Linux runs.
|
||||
"-logtostderr=true",
|
||||
"-v=2",
|
||||
},
|
||||
SkipCleanup: false,
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
module github.com/seaweedfs/seaweedfs/test/kafka/kafka-client-loadtest
|
||||
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.7
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/IBM/sarama v1.46.1
|
||||
@@ -35,7 +33,7 @@ require (
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
)
|
||||
@@ -84,8 +84,8 @@ go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
@@ -93,8 +93,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
@@ -105,8 +105,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package master_cold_start
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
// The very first write against a fresh cluster must succeed in one shot: the
|
||||
// assign that triggers volume growth waits for it instead of shedding itself
|
||||
// with "volume growth in progress". No client retries — a single request per
|
||||
// assign, like a plain HTTP client.
|
||||
func TestColdStartFirstWrite(t *testing.T) {
|
||||
c := StartCluster(t, 3)
|
||||
|
||||
// Each subtest uses its own replication so its volume layout starts cold.
|
||||
t.Run("http_assign_and_write", func(t *testing.T) {
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
resp, err := client.Get(c.MasterURL() + "/dir/assign?replication=002")
|
||||
if err != nil {
|
||||
t.Fatalf("dir/assign: %v", err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("dir/assign returned %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
var assign struct {
|
||||
Fid string `json:"fid"`
|
||||
Url string `json:"url"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &assign); err != nil {
|
||||
t.Fatalf("parse assign response %q: %v", body, err)
|
||||
}
|
||||
if assign.Error != "" || assign.Fid == "" {
|
||||
t.Fatalf("assign failed: %s", body)
|
||||
}
|
||||
|
||||
content := []byte("cold start write")
|
||||
if err := uploadAndReadBack(client, assign.Url, assign.Fid, content); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("grpc_assign", func(t *testing.T) {
|
||||
grpcDialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
err := pb.WithMasterClient(context.Background(), false, pb.ServerAddress(c.MasterAddress()), grpcDialOption, false,
|
||||
func(client master_pb.SeaweedClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
resp, err := client.Assign(ctx, &master_pb.AssignRequest{Count: 1, Replication: "001"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Error != "" || resp.Fid == "" {
|
||||
return fmt.Errorf("assign failed: %+v", resp)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("single grpc assign on cold cluster: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// uploadAndReadBack writes content to the assigned fid and reads it back.
|
||||
func uploadAndReadBack(client *http.Client, volumeUrl, fid string, content []byte) error {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
part, err := writer.CreateFormFile("file", "cold_start.txt")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
part.Write(content)
|
||||
writer.Close()
|
||||
|
||||
target := fmt.Sprintf("http://%s/%s", volumeUrl, fid)
|
||||
req, err := http.NewRequest(http.MethodPost, target, &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upload to %s: %w", target, err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("upload to %s returned %d: %s", target, resp.StatusCode, body)
|
||||
}
|
||||
|
||||
resp, err = client.Get(target)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read back %s: %w", target, err)
|
||||
}
|
||||
got, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("read back %s returned %d", target, resp.StatusCode)
|
||||
}
|
||||
if !bytes.Equal(got, content) {
|
||||
return fmt.Errorf("read back %s: got %q, want %q", target, got, content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// Package master_cold_start boots a fresh master plus empty volume servers
|
||||
// and exercises the very first write against the cluster. The first assign
|
||||
// triggers volume growth server-side; it must succeed within a single
|
||||
// request, without client retries.
|
||||
package master_cold_start
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
waitTimeout = 30 * time.Second
|
||||
waitTick = 200 * time.Millisecond
|
||||
)
|
||||
|
||||
type process struct {
|
||||
name string
|
||||
cmd *exec.Cmd
|
||||
logFile string
|
||||
}
|
||||
|
||||
// Cluster is one fresh master plus n empty volume servers.
|
||||
type Cluster struct {
|
||||
t testing.TB
|
||||
weedBinary string
|
||||
baseDir string
|
||||
|
||||
masterPort int
|
||||
masterGrpcPort int
|
||||
procs []*process
|
||||
}
|
||||
|
||||
// StartCluster boots a master and volumeServerCount empty volume servers,
|
||||
// then waits for all of them to register with the master.
|
||||
func StartCluster(t testing.TB, volumeServerCount int) *Cluster {
|
||||
t.Helper()
|
||||
|
||||
weedBinary, err := findOrBuildWeedBinary()
|
||||
if err != nil {
|
||||
t.Fatalf("resolve weed binary: %v", err)
|
||||
}
|
||||
|
||||
baseDir, err := os.MkdirTemp("", "seaweedfs_master_cold_start_it_")
|
||||
if err != nil {
|
||||
t.Fatalf("create temp dir: %v", err)
|
||||
}
|
||||
logsDir := filepath.Join(baseDir, "logs")
|
||||
os.MkdirAll(logsDir, 0o755)
|
||||
|
||||
ports, err := testutil.AllocateMiniPorts(1 + volumeServerCount)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
|
||||
c := &Cluster{
|
||||
t: t,
|
||||
weedBinary: weedBinary,
|
||||
baseDir: baseDir,
|
||||
masterPort: ports[0],
|
||||
masterGrpcPort: ports[0] + testutil.GrpcPortOffset,
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
c.StopAll()
|
||||
if t.Failed() {
|
||||
c.DumpLogs()
|
||||
t.Logf("cold-start logs kept at %s", baseDir)
|
||||
} else {
|
||||
os.RemoveAll(baseDir)
|
||||
}
|
||||
})
|
||||
|
||||
masterDir := filepath.Join(baseDir, "master")
|
||||
os.MkdirAll(masterDir, 0o755)
|
||||
c.startProcess("master", filepath.Join(logsDir, "master.log"),
|
||||
"master",
|
||||
"-ip=127.0.0.1",
|
||||
"-port="+strconv.Itoa(c.masterPort),
|
||||
"-port.grpc="+strconv.Itoa(c.masterGrpcPort),
|
||||
"-mdir="+masterDir,
|
||||
"-volumeSizeLimitMB=32",
|
||||
"-defaultReplication=000",
|
||||
)
|
||||
if err := c.waitForMaster(waitTimeout); err != nil {
|
||||
t.Fatalf("master not ready: %v", err)
|
||||
}
|
||||
|
||||
for i := 0; i < volumeServerCount; i++ {
|
||||
volDir := filepath.Join(baseDir, fmt.Sprintf("vol%d", i))
|
||||
os.MkdirAll(volDir, 0o755)
|
||||
name := fmt.Sprintf("volume%d", i)
|
||||
c.startProcess(name, filepath.Join(logsDir, name+".log"),
|
||||
"volume",
|
||||
"-ip=127.0.0.1",
|
||||
"-port="+strconv.Itoa(ports[1+i]),
|
||||
"-port.grpc="+strconv.Itoa(ports[1+i]+testutil.GrpcPortOffset),
|
||||
"-dir="+volDir,
|
||||
"-max=10",
|
||||
"-mserver=127.0.0.1:"+strconv.Itoa(c.masterPort),
|
||||
)
|
||||
}
|
||||
if err := c.waitForVolumeServers(volumeServerCount, waitTimeout); err != nil {
|
||||
t.Fatalf("volume servers not registered: %v", err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Cluster) startProcess(name, logFile string, args ...string) {
|
||||
c.t.Helper()
|
||||
f, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
c.t.Fatalf("create log for %s: %v", name, err)
|
||||
}
|
||||
defer f.Close() // the child owns its own descriptor after Start
|
||||
cmd := exec.Command(c.weedBinary, args...)
|
||||
cmd.Dir = c.baseDir
|
||||
cmd.Stdout = f
|
||||
cmd.Stderr = f
|
||||
if err := cmd.Start(); err != nil {
|
||||
c.t.Fatalf("start %s: %v", name, err)
|
||||
}
|
||||
c.procs = append(c.procs, &process{name: name, cmd: cmd, logFile: logFile})
|
||||
}
|
||||
|
||||
// StopAll interrupts every process, volume servers first so the master does
|
||||
// not log reconnect noise.
|
||||
func (c *Cluster) StopAll() {
|
||||
for i := len(c.procs) - 1; i >= 0; i-- {
|
||||
p := c.procs[i]
|
||||
if p.cmd.Process == nil {
|
||||
continue
|
||||
}
|
||||
_ = p.cmd.Process.Signal(os.Interrupt)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- p.cmd.Wait() }()
|
||||
select {
|
||||
case <-time.After(10 * time.Second):
|
||||
_ = p.cmd.Process.Kill()
|
||||
<-done
|
||||
case <-done:
|
||||
}
|
||||
}
|
||||
c.procs = nil
|
||||
}
|
||||
|
||||
// MasterURL returns the master HTTP endpoint.
|
||||
func (c *Cluster) MasterURL() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d", c.masterPort)
|
||||
}
|
||||
|
||||
// MasterAddress returns "127.0.0.1:port" for the master HTTP port.
|
||||
func (c *Cluster) MasterAddress() string {
|
||||
return fmt.Sprintf("127.0.0.1:%d", c.masterPort)
|
||||
}
|
||||
|
||||
func (c *Cluster) waitForMaster(timeout time.Duration) error {
|
||||
client := &http.Client{Timeout: 1 * time.Second}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get(c.MasterURL() + "/cluster/status")
|
||||
if err == nil {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
var cs struct {
|
||||
IsLeader bool `json:"IsLeader"`
|
||||
}
|
||||
if json.Unmarshal(body, &cs) == nil && cs.IsLeader {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
time.Sleep(waitTick)
|
||||
}
|
||||
return fmt.Errorf("master did not become leader within %v", timeout)
|
||||
}
|
||||
|
||||
// waitForVolumeServers polls /dir/status until want data nodes are registered
|
||||
// with free volume slots.
|
||||
func (c *Cluster) waitForVolumeServers(want int, timeout time.Duration) error {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
deadline := time.Now().Add(timeout)
|
||||
var last string
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get(c.MasterURL() + "/dir/status")
|
||||
if err == nil {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
var status struct {
|
||||
Topology struct {
|
||||
Max int64 `json:"Max"`
|
||||
DataCenters []struct {
|
||||
Racks []struct {
|
||||
DataNodes []struct {
|
||||
Url string `json:"Url"`
|
||||
} `json:"DataNodes"`
|
||||
} `json:"Racks"`
|
||||
} `json:"DataCenters"`
|
||||
} `json:"Topology"`
|
||||
}
|
||||
if json.Unmarshal(body, &status) == nil {
|
||||
nodes := 0
|
||||
for _, dc := range status.Topology.DataCenters {
|
||||
for _, rack := range dc.Racks {
|
||||
nodes += len(rack.DataNodes)
|
||||
}
|
||||
}
|
||||
if nodes >= want && status.Topology.Max > 0 {
|
||||
return nil
|
||||
}
|
||||
last = fmt.Sprintf("%d/%d nodes, %d slots", nodes, want, status.Topology.Max)
|
||||
}
|
||||
}
|
||||
time.Sleep(waitTick)
|
||||
}
|
||||
return fmt.Errorf("volume servers not registered within %v (%s)", timeout, last)
|
||||
}
|
||||
|
||||
// DumpLogs prints the tail of every process log.
|
||||
func (c *Cluster) DumpLogs() {
|
||||
logsDir := filepath.Join(c.baseDir, "logs")
|
||||
entries, _ := os.ReadDir(logsDir)
|
||||
for _, e := range entries {
|
||||
c.t.Logf("=== %s tail ===\n%s", e.Name(), tailFile(filepath.Join(logsDir, e.Name())))
|
||||
}
|
||||
}
|
||||
|
||||
func tailFile(path string) string {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "(no log)"
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
lines := make([]string, 0, 50)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
if len(lines) > 50 {
|
||||
lines = lines[1:]
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func findOrBuildWeedBinary() (string, error) {
|
||||
if fromEnv := os.Getenv("WEED_BINARY"); fromEnv != "" {
|
||||
if isExecutableFile(fromEnv) {
|
||||
return fromEnv, nil
|
||||
}
|
||||
return "", fmt.Errorf("WEED_BINARY not executable: %s", fromEnv)
|
||||
}
|
||||
|
||||
repoRoot := ""
|
||||
if _, file, _, ok := runtime.Caller(0); ok {
|
||||
repoRoot = filepath.Clean(filepath.Join(filepath.Dir(file), "..", ".."))
|
||||
}
|
||||
if repoRoot == "" {
|
||||
return "", fmt.Errorf("unable to detect repository root")
|
||||
}
|
||||
|
||||
binDir := filepath.Join(os.TempDir(), "seaweedfs_master_cold_start_it_bin")
|
||||
os.MkdirAll(binDir, 0o755)
|
||||
binPath := filepath.Join(binDir, "weed")
|
||||
if isExecutableFile(binPath) {
|
||||
return binPath, nil
|
||||
}
|
||||
|
||||
cmd := exec.Command("go", "build", "-o", binPath, ".")
|
||||
cmd.Dir = filepath.Join(repoRoot, "weed")
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &out
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", fmt.Errorf("build weed binary: %w\n%s", err, out.String())
|
||||
}
|
||||
return binPath, nil
|
||||
}
|
||||
|
||||
func isExecutableFile(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
return false
|
||||
}
|
||||
return info.Mode().Perm()&0o111 != 0
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
v2config "github.com/aws/aws-sdk-go-v2/config"
|
||||
v2creds "github.com/aws/aws-sdk-go-v2/credentials"
|
||||
s3v2 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
s3v2types "github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestListBucketsPaginationAndOwnerIndex exercises ListBuckets pagination
|
||||
// (max-buckets, continuation-token, prefix) and the owner-index path that
|
||||
// serves non-admin identities without scanning all buckets.
|
||||
func TestListBucketsPaginationAndOwnerIndex(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
s3Config := `{
|
||||
"identities": [
|
||||
{"name": "admin", "credentials": [{"accessKey": "admin", "secretKey": "admin"}], "actions": ["Admin"]},
|
||||
{"name": "alice", "credentials": [{"accessKey": "alice", "secretKey": "alice_secret"}],
|
||||
"actions": ["Admin:alice-b1", "Admin:alice-b2", "Admin:alice-b3"]},
|
||||
{"name": "carol", "credentials": [{"accessKey": "carol", "secretKey": "carol_secret"}],
|
||||
"actions": ["List:alice-b1"]},
|
||||
{"name": "bob", "credentials": [{"accessKey": "bob", "secretKey": "bob_secret"}],
|
||||
"actions": ["Read:alice-b1"]}
|
||||
]
|
||||
}`
|
||||
configPath := filepath.Join(t.TempDir(), "s3.json")
|
||||
require.NoError(t, os.WriteFile(configPath, []byte(s3Config), 0644))
|
||||
|
||||
cluster, err := startMiniCluster(t, "-s3.config="+configPath)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
ctx := context.Background()
|
||||
newClient := func(key, secret string) *s3v2.Client {
|
||||
cfg, err := v2config.LoadDefaultConfig(ctx,
|
||||
v2config.WithRegion("us-east-1"),
|
||||
v2config.WithCredentialsProvider(v2creds.NewStaticCredentialsProvider(key, secret, "")),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return s3v2.NewFromConfig(cfg, func(o *s3v2.Options) {
|
||||
o.BaseEndpoint = aws.String(cluster.s3Endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
admin := newClient("admin", "admin")
|
||||
alice := newClient("alice", "alice_secret")
|
||||
carol := newClient("carol", "carol_secret")
|
||||
bob := newClient("bob", "bob_secret")
|
||||
|
||||
// Non-admin listings use the owner index once the backfill marker exists.
|
||||
markerURL := fmt.Sprintf("http://127.0.0.1:%d/buckets/.system/owners/.complete", cluster.filerPort)
|
||||
require.Eventually(t, func() bool {
|
||||
resp, err := http.Get(markerURL)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode == http.StatusOK
|
||||
}, 15*time.Second, 200*time.Millisecond, "owner index backfill marker")
|
||||
|
||||
aliceBuckets := []string{"alice-b1", "alice-b2", "alice-b3"}
|
||||
for _, b := range aliceBuckets {
|
||||
_, err := alice.CreateBucket(ctx, &s3v2.CreateBucketInput{Bucket: aws.String(b)})
|
||||
require.NoError(t, err, "alice create %s", b)
|
||||
}
|
||||
var adminBuckets []string
|
||||
for i := 0; i < 5; i++ {
|
||||
name := fmt.Sprintf("admin-b%d", i)
|
||||
adminBuckets = append(adminBuckets, name)
|
||||
_, err := admin.CreateBucket(ctx, &s3v2.CreateBucketInput{Bucket: aws.String(name)})
|
||||
require.NoError(t, err, "admin create %s", name)
|
||||
}
|
||||
|
||||
t.Run("OwnerSeesOwnBuckets", func(t *testing.T) {
|
||||
out, err := alice.ListBuckets(ctx, &s3v2.ListBucketsInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aliceBuckets, bucketNames(out.Buckets))
|
||||
assert.Nil(t, out.ContinuationToken)
|
||||
})
|
||||
|
||||
t.Run("OwnerPagination", func(t *testing.T) {
|
||||
page1, err := alice.ListBuckets(ctx, &s3v2.ListBucketsInput{MaxBuckets: aws.Int32(2)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aliceBuckets[:2], bucketNames(page1.Buckets))
|
||||
require.NotNil(t, page1.ContinuationToken)
|
||||
|
||||
page2, err := alice.ListBuckets(ctx, &s3v2.ListBucketsInput{
|
||||
MaxBuckets: aws.Int32(2),
|
||||
ContinuationToken: page1.ContinuationToken,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aliceBuckets[2:], bucketNames(page2.Buckets))
|
||||
assert.Nil(t, page2.ContinuationToken)
|
||||
})
|
||||
|
||||
t.Run("OwnerPrefix", func(t *testing.T) {
|
||||
out, err := alice.ListBuckets(ctx, &s3v2.ListBucketsInput{Prefix: aws.String("alice-b2")})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"alice-b2"}, bucketNames(out.Buckets))
|
||||
})
|
||||
|
||||
t.Run("GrantedListVisible", func(t *testing.T) {
|
||||
out, err := carol.ListBuckets(ctx, &s3v2.ListBucketsInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"alice-b1"}, bucketNames(out.Buckets))
|
||||
})
|
||||
|
||||
t.Run("ReadGrantNotVisible", func(t *testing.T) {
|
||||
out, err := bob.ListBuckets(ctx, &s3v2.ListBucketsInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, bucketNames(out.Buckets))
|
||||
})
|
||||
|
||||
t.Run("AdminPaginatesAll", func(t *testing.T) {
|
||||
var all []string
|
||||
var token *string
|
||||
for pages := 0; ; pages++ {
|
||||
require.Less(t, pages, 10, "runaway pagination")
|
||||
out, err := admin.ListBuckets(ctx, &s3v2.ListBucketsInput{MaxBuckets: aws.Int32(3), ContinuationToken: token})
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, len(out.Buckets), 3)
|
||||
all = append(all, bucketNames(out.Buckets)...)
|
||||
if out.ContinuationToken == nil {
|
||||
break
|
||||
}
|
||||
token = out.ContinuationToken
|
||||
}
|
||||
assert.Equal(t, append(append([]string{}, adminBuckets...), aliceBuckets...), all)
|
||||
})
|
||||
|
||||
t.Run("AdminPrefix", func(t *testing.T) {
|
||||
out, err := admin.ListBuckets(ctx, &s3v2.ListBucketsInput{Prefix: aws.String("admin-")})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, adminBuckets, bucketNames(out.Buckets))
|
||||
})
|
||||
|
||||
t.Run("InvalidMaxBuckets", func(t *testing.T) {
|
||||
_, err := admin.ListBuckets(ctx, &s3v2.ListBucketsInput{MaxBuckets: aws.Int32(0)})
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("IndexEntriesOnFiler", func(t *testing.T) {
|
||||
indexURL := fmt.Sprintf("http://127.0.0.1:%d/buckets/.system/owners/alice/?limit=100", cluster.filerPort)
|
||||
req, err := http.NewRequest(http.MethodGet, indexURL, nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
for _, b := range aliceBuckets {
|
||||
assert.Contains(t, string(body), b)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DeleteRemovesFromListing", func(t *testing.T) {
|
||||
_, err := alice.DeleteBucket(ctx, &s3v2.DeleteBucketInput{Bucket: aws.String("alice-b2")})
|
||||
require.NoError(t, err)
|
||||
out, err := alice.ListBuckets(ctx, &s3v2.ListBucketsInput{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"alice-b1", "alice-b3"}, bucketNames(out.Buckets))
|
||||
})
|
||||
|
||||
t.Run("HiddenSystemBucket", func(t *testing.T) {
|
||||
_, err := admin.HeadBucket(ctx, &s3v2.HeadBucketInput{Bucket: aws.String(".system")})
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func bucketNames(buckets []s3v2types.Bucket) (names []string) {
|
||||
for _, b := range buckets {
|
||||
names = append(names, aws.ToString(b.Name))
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
// Package admin contains integration tests for the admin UI's Iceberg
|
||||
// catalog and data-preview pages. Tests start a real weed mini cluster
|
||||
// (with the admin UI enabled), create a table bucket, namespace, and table
|
||||
// via the S3 Tables manager, populate real Parquet data files, manifests,
|
||||
// and snapshots via S3 and the filer gRPC API, and then assert on the HTML
|
||||
// the admin server renders.
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/apache/iceberg-go/table"
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/command"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cluster lifecycle (mirrors test/s3tables/maintenance)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type testCluster struct {
|
||||
dataDir string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
filerGrpcPort int
|
||||
s3Port int
|
||||
adminPort int
|
||||
s3Endpoint string
|
||||
adminEndpoint string
|
||||
isRunning bool
|
||||
}
|
||||
|
||||
var shared *testCluster
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
flag.Parse()
|
||||
if testing.Short() {
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
testDir, err := os.MkdirTemp("", "seaweed-admin-iceberg-*")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "SKIP: failed to create temp dir: %v\n", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
cluster, err := startCluster(testDir)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "SKIP: failed to start cluster: %v\n", err)
|
||||
os.RemoveAll(testDir)
|
||||
os.Exit(0)
|
||||
}
|
||||
shared = cluster
|
||||
|
||||
code := m.Run()
|
||||
shared.stop()
|
||||
os.RemoveAll(testDir)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func startCluster(testDir string) (*testCluster, error) {
|
||||
ports, err := testutil.AllocatePorts(10)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
masterPort, masterGrpc := ports[0], ports[1]
|
||||
volumePort, volumeGrpc := ports[2], ports[3]
|
||||
filerPort, filerGrpc := ports[4], ports[5]
|
||||
s3Port, s3Grpc := ports[6], ports[7]
|
||||
adminPort, adminGrpc := ports[8], ports[9]
|
||||
|
||||
// Empty security.toml disables JWT auth.
|
||||
if err := os.WriteFile(filepath.Join(testDir, "security.toml"), []byte("# test\n"), 0644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if os.Getenv("AWS_ACCESS_KEY_ID") == "" {
|
||||
os.Setenv("AWS_ACCESS_KEY_ID", "admin")
|
||||
}
|
||||
if os.Getenv("AWS_SECRET_ACCESS_KEY") == "" {
|
||||
os.Setenv("AWS_SECRET_ACCESS_KEY", "admin")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
c := &testCluster{
|
||||
dataDir: testDir,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
filerGrpcPort: filerGrpc,
|
||||
s3Port: s3Port,
|
||||
adminPort: adminPort,
|
||||
s3Endpoint: fmt.Sprintf("http://127.0.0.1:%d", s3Port),
|
||||
adminEndpoint: fmt.Sprintf("http://127.0.0.1:%d", adminPort),
|
||||
}
|
||||
|
||||
// Set on the package global before the goroutine starts so the mini
|
||||
// command picks it up; cleared in stop(). The global is how the mini
|
||||
// harness receives its cancellation context in tests.
|
||||
command.MiniClusterCtx = ctx //nolint:fatcontext // test harness handoff, not a per-request context
|
||||
|
||||
c.wg.Add(1)
|
||||
go func() {
|
||||
defer c.wg.Done()
|
||||
oldDir, _ := os.Getwd()
|
||||
oldArgs := os.Args
|
||||
defer func() { os.Chdir(oldDir); os.Args = oldArgs }()
|
||||
os.Chdir(testDir)
|
||||
|
||||
args := []string{
|
||||
"-dir=" + testDir,
|
||||
"-master.dir=" + testDir,
|
||||
"-master.port=" + strconv.Itoa(masterPort),
|
||||
"-master.port.grpc=" + strconv.Itoa(masterGrpc),
|
||||
"-volume.port=" + strconv.Itoa(volumePort),
|
||||
"-volume.port.grpc=" + strconv.Itoa(volumeGrpc),
|
||||
"-volume.port.public=" + strconv.Itoa(volumePort),
|
||||
"-volume.publicUrl=127.0.0.1:" + strconv.Itoa(volumePort),
|
||||
"-filer.port=" + strconv.Itoa(filerPort),
|
||||
"-filer.port.grpc=" + strconv.Itoa(filerGrpc),
|
||||
"-s3.port=" + strconv.Itoa(s3Port),
|
||||
"-s3.port.grpc=" + strconv.Itoa(s3Grpc),
|
||||
"-admin.port=" + strconv.Itoa(adminPort),
|
||||
"-admin.port.grpc=" + strconv.Itoa(adminGrpc),
|
||||
"-webdav.port=0",
|
||||
"-master.volumeSizeLimitMB=32",
|
||||
"-ip=127.0.0.1",
|
||||
"-master.peers=none",
|
||||
"-s3.iam.readOnly=false",
|
||||
}
|
||||
os.Args = append([]string{"weed"}, args...)
|
||||
glog.MaxSize = 1024 * 1024
|
||||
for _, cmd := range command.Commands {
|
||||
if cmd.Name() == "mini" && cmd.Run != nil {
|
||||
cmd.Flag.Parse(os.Args[1:])
|
||||
cmd.Run(cmd, cmd.Flag.Args())
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err := waitReady(c.s3Endpoint, 30*time.Second); err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if err := waitReady(c.adminEndpoint, 30*time.Second); err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
c.isRunning = true
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *testCluster) stop() {
|
||||
command.MiniClusterCtx = nil //nolint:fatcontext // clearing the test harness handoff
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
if c.isRunning {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { c.wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
|
||||
func (c *testCluster) filerConn(t *testing.T) filer_pb.SeaweedFilerClient {
|
||||
t.Helper()
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", c.filerGrpcPort)
|
||||
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { conn.Close() })
|
||||
return filer_pb.NewSeaweedFilerClient(conn)
|
||||
}
|
||||
|
||||
func waitReady(endpoint string, timeout time.Duration) error {
|
||||
client := &http.Client{Timeout: 1 * time.Second}
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get(endpoint)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("timeout waiting for %s", endpoint)
|
||||
}
|
||||
|
||||
func randomSuffix() string {
|
||||
b := make([]byte, 4)
|
||||
rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Catalog and table population
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type previewRow struct {
|
||||
ID int64 `parquet:"id"`
|
||||
Name string `parquet:"name"`
|
||||
}
|
||||
|
||||
func buildParquet(t *testing.T, rows []previewRow) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
writer := parquet.NewGenericWriter[previewRow](&buf)
|
||||
_, err := writer.Write(rows)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func newS3Client(t *testing.T, endpoint string) *s3.Client {
|
||||
t.Helper()
|
||||
cfg, err := config.LoadDefaultConfig(context.Background(),
|
||||
config.WithRegion("us-east-1"),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("admin", "admin", "")),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
}
|
||||
|
||||
type catalogFixture struct {
|
||||
bucket string
|
||||
namespace string
|
||||
table string
|
||||
snap1ID int64
|
||||
snap2ID int64
|
||||
file1Path string // manifest-listed location of the first data file (relative)
|
||||
file2Path string // manifest-listed location of the second data file (s3:// URI)
|
||||
}
|
||||
|
||||
// setupCatalog creates a table bucket, namespace, and two tables via the S3
|
||||
// Tables manager: "events" with two snapshots backed by real Parquet files,
|
||||
// and "empty" with no Iceberg metadata.
|
||||
func setupCatalog(t *testing.T, client filer_pb.SeaweedFilerClient) catalogFixture {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
fx := catalogFixture{
|
||||
bucket: "admin-ui-" + randomSuffix(),
|
||||
namespace: "analytics",
|
||||
table: "events",
|
||||
snap1ID: 3001,
|
||||
snap2ID: 3002,
|
||||
}
|
||||
fx.file1Path = "data/p1.parquet"
|
||||
fx.file2Path = fmt.Sprintf("s3://%s/%s/%s/data/p2.parquet", fx.bucket, fx.namespace, fx.table)
|
||||
|
||||
mgr := s3tables.NewManager()
|
||||
mgr.SetAccountID(s3_constants.AccountAdminId)
|
||||
mc := s3tables.NewManagerClient(client)
|
||||
exec := func(op string, req, resp interface{}) {
|
||||
t.Helper()
|
||||
require.NoError(t, mgr.Execute(ctx, mc, op, req, resp, s3_constants.AccountAdminId), "s3tables %s", op)
|
||||
}
|
||||
|
||||
var bucketResp s3tables.CreateTableBucketResponse
|
||||
exec("CreateTableBucket", &s3tables.CreateTableBucketRequest{Name: fx.bucket}, &bucketResp)
|
||||
exec("CreateNamespace", &s3tables.CreateNamespaceRequest{TableBucketARN: bucketResp.ARN, Namespace: []string{fx.namespace}}, &s3tables.CreateNamespaceResponse{})
|
||||
exec("CreateTable", &s3tables.CreateTableRequest{TableBucketARN: bucketResp.ARN, Namespace: []string{fx.namespace}, Name: fx.table, Format: "ICEBERG"}, &s3tables.CreateTableResponse{})
|
||||
exec("CreateTable", &s3tables.CreateTableRequest{TableBucketARN: bucketResp.ARN, Namespace: []string{fx.namespace}, Name: "empty", Format: "ICEBERG"}, &s3tables.CreateTableResponse{})
|
||||
|
||||
// Upload real Parquet data files via S3 so they are chunk-backed entries.
|
||||
s3Client := newS3Client(t, shared.s3Endpoint)
|
||||
tableKey := path.Join(fx.namespace, fx.table)
|
||||
rows1 := []previewRow{{1, "p1-row-1"}, {2, "p1-row-2"}, {3, "p1-row-3"}, {4, "p1-row-4"}, {5, "p1-row-5"}}
|
||||
rows2 := []previewRow{{6, "p2-row-6"}, {7, "p2-row-7"}, {8, "p2-row-8"}}
|
||||
parquet1 := buildParquet(t, rows1)
|
||||
parquet2 := buildParquet(t, rows2)
|
||||
putObject(t, s3Client, fx.bucket, path.Join(tableKey, "data/p1.parquet"), parquet1)
|
||||
putObject(t, s3Client, fx.bucket, path.Join(tableKey, "data/p2.parquet"), parquet2)
|
||||
|
||||
// Build table metadata with two snapshots. Snapshot 2's manifest list is
|
||||
// cumulative (both manifests) as engines write it.
|
||||
location := fmt.Sprintf("s3://%s/%s/%s", fx.bucket, fx.namespace, fx.table)
|
||||
schema := iceberg.NewSchema(0,
|
||||
iceberg.NestedField{ID: 1, Type: iceberg.PrimitiveTypes.Int64, Name: "id", Required: true},
|
||||
iceberg.NestedField{ID: 2, Type: iceberg.PrimitiveTypes.String, Name: "name", Required: false},
|
||||
)
|
||||
meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, table.UnsortedSortOrder, location, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
baseMs := time.Now().UnixMilli() + 100
|
||||
snap1 := table.Snapshot{SnapshotID: fx.snap1ID, SequenceNumber: 1, TimestampMs: baseMs, ManifestList: "metadata/snap-3001.avro"}
|
||||
snap2 := table.Snapshot{SnapshotID: fx.snap2ID, ParentSnapshotID: &fx.snap1ID, SequenceNumber: 2, TimestampMs: baseMs + 1, ManifestList: "metadata/snap-3002.avro"}
|
||||
|
||||
builder, err := table.MetadataBuilderFromBase(meta, location)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, builder.AddSnapshot(&snap1))
|
||||
require.NoError(t, builder.AddSnapshot(&snap2))
|
||||
require.NoError(t, builder.SetSnapshotRef(table.MainBranch, fx.snap2ID, table.BranchRef))
|
||||
meta, err = builder.Build()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Write manifests and manifest lists into the table's metadata directory.
|
||||
metaDir := path.Join(s3tables.TablesPath, fx.bucket, fx.namespace, fx.table, "metadata")
|
||||
spec := meta.PartitionSpec()
|
||||
version := meta.Version()
|
||||
|
||||
mf1 := writeManifest(t, ctx, client, metaDir, "manifest-3001.avro", version, spec, schema, fx.snap1ID, fx.file1Path, int64(len(rows1)), int64(len(parquet1)))
|
||||
mf2 := writeManifest(t, ctx, client, metaDir, "manifest-3002.avro", version, spec, schema, fx.snap2ID, fx.file2Path, int64(len(rows2)), int64(len(parquet2)))
|
||||
|
||||
list1 := writeManifestList(t, ctx, client, metaDir, "snap-3001.avro", version, fx.snap1ID, nil, 1, []iceberg.ManifestFile{mf1})
|
||||
// Re-read snapshot 1's list so mf1 carries its assigned sequence number,
|
||||
// which the cumulative snapshot 2 list requires.
|
||||
assigned, err := iceberg.ReadManifestList(bytes.NewReader(list1))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, assigned, 1)
|
||||
writeManifestList(t, ctx, client, metaDir, "snap-3002.avro", version, fx.snap2ID, &fx.snap1ID, 2, []iceberg.ManifestFile{assigned[0], mf2})
|
||||
|
||||
// Point the table's catalog xattr at the new metadata.
|
||||
fullJSON, err := json.Marshal(meta)
|
||||
require.NoError(t, err)
|
||||
writeFile(t, ctx, client, metaDir, "v2.metadata.json", fullJSON)
|
||||
updateTableMetadataXattr(t, ctx, client, fx, fullJSON)
|
||||
|
||||
// Snapshot timestamps sit slightly in the future; let them pass.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
return fx
|
||||
}
|
||||
|
||||
func putObject(t *testing.T, client *s3.Client, bucket, key string, body []byte) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(body),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func writeManifest(t *testing.T, ctx context.Context, client filer_pb.SeaweedFilerClient, metaDir, name string, version int, spec iceberg.PartitionSpec, schema *iceberg.Schema, snapID int64, dataFilePath string, recordCount, fileSize int64) iceberg.ManifestFile {
|
||||
t.Helper()
|
||||
dfBuilder, err := iceberg.NewDataFileBuilder(
|
||||
spec, iceberg.EntryContentData,
|
||||
dataFilePath, iceberg.ParquetFile,
|
||||
map[int]any{}, nil, nil, recordCount, fileSize,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
entry := iceberg.NewManifestEntry(iceberg.EntryStatusADDED, &snapID, nil, nil, dfBuilder.Build())
|
||||
|
||||
var buf bytes.Buffer
|
||||
mf, err := iceberg.WriteManifest(path.Join("metadata", name), &buf, version, spec, schema, snapID, []iceberg.ManifestEntry{entry})
|
||||
require.NoError(t, err)
|
||||
writeFile(t, ctx, client, metaDir, name, buf.Bytes())
|
||||
return mf
|
||||
}
|
||||
|
||||
func writeManifestList(t *testing.T, ctx context.Context, client filer_pb.SeaweedFilerClient, metaDir, name string, version int, snapID int64, parent *int64, seqNum int64, files []iceberg.ManifestFile) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, iceberg.WriteManifestList(version, &buf, snapID, parent, &seqNum, 0, files))
|
||||
writeFile(t, ctx, client, metaDir, name, buf.Bytes())
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, ctx context.Context, client filer_pb.SeaweedFilerClient, dir, name string, content []byte) {
|
||||
t.Helper()
|
||||
resp, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: time.Now().Unix(), Crtime: time.Now().Unix(),
|
||||
FileMode: uint32(0644), FileSize: uint64(len(content)),
|
||||
},
|
||||
Content: content,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "writeFile(%s, %s)", dir, name)
|
||||
require.Empty(t, resp.Error, "writeFile(%s, %s)", dir, name)
|
||||
}
|
||||
|
||||
func updateTableMetadataXattr(t *testing.T, ctx context.Context, client filer_pb.SeaweedFilerClient, fx catalogFixture, fullJSON []byte) {
|
||||
t.Helper()
|
||||
nsDir := path.Join(s3tables.TablesPath, fx.bucket, fx.namespace)
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: nsDir, Name: fx.table})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.Entry)
|
||||
|
||||
var internalMeta map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(resp.Entry.Extended[s3tables.ExtendedKeyMetadata], &internalMeta))
|
||||
metaObj := map[string]json.RawMessage{}
|
||||
if raw, ok := internalMeta["metadata"]; ok {
|
||||
require.NoError(t, json.Unmarshal(raw, &metaObj))
|
||||
}
|
||||
metaObj["fullMetadata"] = fullJSON
|
||||
metaJSON, err := json.Marshal(metaObj)
|
||||
require.NoError(t, err)
|
||||
internalMeta["metadata"] = metaJSON
|
||||
internalMeta["metadataVersion"] = json.RawMessage("2")
|
||||
internalMeta["metadataLocation"] = json.RawMessage(`"metadata/v2.metadata.json"`)
|
||||
xattr, err := json.Marshal(internalMeta)
|
||||
require.NoError(t, err)
|
||||
|
||||
resp.Entry.Extended[s3tables.ExtendedKeyMetadata] = xattr
|
||||
resp.Entry.Extended[s3tables.ExtendedKeyMetadataVersion] = []byte("2")
|
||||
_, err = client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{Directory: nsDir, Entry: resp.Entry})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Page fetching
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func fetchPage(t *testing.T, pagePath string) string {
|
||||
t.Helper()
|
||||
resp, err := (&http.Client{Timeout: 30 * time.Second}).Get(shared.adminEndpoint + pagePath)
|
||||
require.NoError(t, err, "GET %s", pagePath)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "GET %s: %s", pagePath, string(body))
|
||||
return string(body)
|
||||
}
|
||||
|
||||
// fetchPageUntil re-fetches a page until the predicate passes, tolerating the
|
||||
// admin server's filer-discovery delay right after startup.
|
||||
func fetchPageUntil(t *testing.T, pagePath string, predicate func(string) bool) string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
var body string
|
||||
for time.Now().Before(deadline) {
|
||||
body = fetchPage(t, pagePath)
|
||||
if predicate(body) {
|
||||
return body
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func tablePagePath(fx catalogFixture, tableName, suffix string) string {
|
||||
return fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces/%s/tables/%s%s",
|
||||
url.PathEscape(fx.bucket), url.PathEscape(fx.namespace), url.PathEscape(tableName), suffix)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Integration tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestAdminIcebergPages(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
client := shared.filerConn(t)
|
||||
fx := setupCatalog(t, client)
|
||||
|
||||
t.Run("CatalogBrowsing", func(t *testing.T) {
|
||||
buckets := fetchPageUntil(t, "/object-store/s3tables/buckets", func(body string) bool {
|
||||
return strings.Contains(body, fx.bucket)
|
||||
})
|
||||
assert.Contains(t, buckets, fx.bucket)
|
||||
|
||||
namespaces := fetchPage(t, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces", url.PathEscape(fx.bucket)))
|
||||
assert.Contains(t, namespaces, fx.namespace)
|
||||
|
||||
tables := fetchPage(t, fmt.Sprintf("/object-store/s3tables/buckets/%s/namespaces/%s/tables", url.PathEscape(fx.bucket), url.PathEscape(fx.namespace)))
|
||||
assert.Contains(t, tables, fx.table)
|
||||
assert.Contains(t, tables, "empty")
|
||||
})
|
||||
|
||||
t.Run("TableDetails", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, ""))
|
||||
assert.Contains(t, body, "Browse Data")
|
||||
assert.Contains(t, body, "/data")
|
||||
assert.Contains(t, body, ">id<")
|
||||
assert.Contains(t, body, ">name<")
|
||||
assert.Contains(t, body, strconv.FormatInt(fx.snap1ID, 10))
|
||||
assert.Contains(t, body, strconv.FormatInt(fx.snap2ID, 10))
|
||||
})
|
||||
|
||||
t.Run("DataPreviewCurrentSnapshot", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data"))
|
||||
assert.Contains(t, body, "Showing 8 row(s) from 2 data file(s).")
|
||||
assert.Contains(t, body, "p1-row-1")
|
||||
assert.Contains(t, body, "p2-row-8")
|
||||
assert.Contains(t, body, fx.file1Path)
|
||||
assert.Contains(t, body, fx.file2Path)
|
||||
assert.Contains(t, body, "current")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewOldSnapshot", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data?snapshot="+strconv.FormatInt(fx.snap1ID, 10)))
|
||||
assert.Contains(t, body, "Showing 5 row(s) from 1 data file(s).")
|
||||
assert.Contains(t, body, "p1-row-5")
|
||||
assert.NotContains(t, body, "p2-row-6")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewSingleFile", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data?file="+url.QueryEscape(fx.file2Path)))
|
||||
assert.Contains(t, body, "Showing 3 row(s) from 1 data file(s).")
|
||||
assert.Contains(t, body, "p2-row-6")
|
||||
assert.NotContains(t, body, "p1-row-1")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewRowLimit", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data?limit=3"))
|
||||
assert.Contains(t, body, "Showing 3 row(s) from 1 data file(s).")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewUnknownFile", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data?file="+url.QueryEscape("s3://elsewhere/x.parquet")))
|
||||
assert.Contains(t, body, "Requested data file is not part of this snapshot.")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewUnknownSnapshot", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, fx.table, "/data?snapshot=42"))
|
||||
assert.Contains(t, body, "Snapshot 42 not found.")
|
||||
})
|
||||
|
||||
t.Run("DataPreviewTableWithoutMetadata", func(t *testing.T) {
|
||||
body := fetchPage(t, tablePagePath(fx, "empty", "/data"))
|
||||
assert.Contains(t, body, "Table has no Iceberg metadata.")
|
||||
})
|
||||
}
|
||||
+3
-3
@@ -1,17 +1,17 @@
|
||||
module seaweedfs-sftp-tests
|
||||
|
||||
go 1.24.0
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/pkg/sftp v1.13.7
|
||||
github.com/stretchr/testify v1.10.0
|
||||
golang.org/x/crypto v0.45.0
|
||||
golang.org/x/crypto v0.52.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
+6
-6
@@ -17,8 +17,8 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
@@ -37,15 +37,15 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package sftp
|
||||
|
||||
import (
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestScopedUserCannotAccessSiblingPrefix verifies that a permission entry
|
||||
// for /tenants/alice does not leak onto sibling paths such as
|
||||
// /tenants/alice-archive that merely share the string prefix.
|
||||
func TestScopedUserCannotAccessSiblingPrefix(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
config := DefaultTestConfig()
|
||||
config.EnableDebug = testing.Verbose()
|
||||
|
||||
fw := NewSftpTestFramework(t, config)
|
||||
require.NoError(t, fw.Setup(config))
|
||||
defer fw.Cleanup()
|
||||
|
||||
// admin seeds both tenants
|
||||
admin, adminConn, err := fw.ConnectSFTP("admin", "adminpassword")
|
||||
require.NoError(t, err)
|
||||
defer adminConn.Close()
|
||||
defer admin.Close()
|
||||
|
||||
require.NoError(t, admin.MkdirAll("/tenants/alice"))
|
||||
require.NoError(t, admin.MkdirAll("/tenants/alice-archive"))
|
||||
secret, err := admin.Create("/tenants/alice-archive/secret.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = secret.Write([]byte("SIBLING-SECRET"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, secret.Close())
|
||||
|
||||
scoped, scopedConn, err := fw.ConnectSFTP("scoped", "scopedpassword")
|
||||
require.NoError(t, err)
|
||||
defer scopedConn.Close()
|
||||
defer scoped.Close()
|
||||
|
||||
// positive control: the scoped user can write within its own prefix
|
||||
own, err := scoped.Create("/tenants/alice/own.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = own.Write([]byte("ok"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, own.Close())
|
||||
|
||||
// reading the sibling tenant's file must fail
|
||||
if f, err := scoped.Open("/tenants/alice-archive/secret.txt"); err == nil {
|
||||
data, _ := io.ReadAll(f)
|
||||
f.Close()
|
||||
t.Fatalf("ACL for /tenants/alice read sibling /tenants/alice-archive: %q", data)
|
||||
}
|
||||
|
||||
// overwriting the sibling tenant's file must fail
|
||||
if f, err := scoped.Create("/tenants/alice-archive/secret.txt"); err == nil {
|
||||
f.Write([]byte("OVERWRITTEN-BY-SCOPED-USER"))
|
||||
f.Close()
|
||||
t.Fatal("ACL for /tenants/alice overwrote sibling /tenants/alice-archive")
|
||||
}
|
||||
|
||||
// the sibling file is intact
|
||||
f, err := admin.Open("/tenants/alice-archive/secret.txt")
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(f)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
require.Equal(t, "SIBLING-SECRET", string(data))
|
||||
}
|
||||
Vendored
+11
@@ -31,6 +31,17 @@
|
||||
},
|
||||
"Uid": 1002,
|
||||
"Gid": 1002
|
||||
},
|
||||
{
|
||||
"Username": "scoped",
|
||||
"Password": "scopedpassword",
|
||||
"PublicKeys": [],
|
||||
"HomeDir": "/",
|
||||
"Permissions": {
|
||||
"/tenants/alice": ["read", "write", "list"]
|
||||
},
|
||||
"Uid": 1003,
|
||||
"Gid": 1003
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
+21
-4
@@ -11,6 +11,23 @@ import (
|
||||
// GrpcPortOffset is the offset weed mini uses to derive gRPC ports from HTTP ports.
|
||||
const GrpcPortOffset = 10000
|
||||
|
||||
// linuxEphemeralPortFloor is the Linux default ip_local_port_range lower bound.
|
||||
// Ports at or above it can be claimed as the source port of a transient
|
||||
// outbound connection during mini's own startup (e.g. volume dialing master
|
||||
// gRPC) in the window between allocation and the listener bind, surfacing as
|
||||
// "bind: address already in use".
|
||||
const linuxEphemeralPortFloor = 32768
|
||||
|
||||
// miniPortMin/miniPortMax bound the random HTTP port range for weed mini.
|
||||
// The cap keeps both the HTTP port and its +GrpcPortOffset gRPC counterpart
|
||||
// below linuxEphemeralPortFloor, out of the range the kernel draws ephemeral
|
||||
// source ports from, so the steal above cannot happen. Deriving the cap from
|
||||
// GrpcPortOffset keeps the two in lockstep if the offset ever changes.
|
||||
const (
|
||||
miniPortMin = 10000
|
||||
miniPortMax = linuxEphemeralPortFloor - GrpcPortOffset
|
||||
)
|
||||
|
||||
// miniDefaultPorts are the weed mini flag defaults (see weed/command/mini.go).
|
||||
// A test only overrides services it uses; unspecified services still bind
|
||||
// these defaults, so allocation must avoid handing them out (or any value
|
||||
@@ -83,8 +100,8 @@ func MustAllocatePorts(t *testing.T, count int) []int {
|
||||
// wrong port and hang.
|
||||
func AllocateMiniPorts(count int) ([]int, error) {
|
||||
const (
|
||||
minPort = 10000
|
||||
maxPort = 55000
|
||||
minPort = miniPortMin
|
||||
maxPort = miniPortMax
|
||||
)
|
||||
reserved := reservedMiniPorts()
|
||||
ports := make([]int, 0, count)
|
||||
@@ -155,8 +172,8 @@ func MustFreeMiniPort(t *testing.T, name string) int {
|
||||
// allocated, so a mini gRPC port cannot be recycled as a regular port mid-batch.
|
||||
func AllocatePortSet(miniCount, regularCount int) (mini []int, regular []int, err error) {
|
||||
const (
|
||||
minPort = 10000
|
||||
maxPort = 55000
|
||||
minPort = miniPortMin
|
||||
maxPort = miniPortMax
|
||||
)
|
||||
reserved := reservedMiniPorts()
|
||||
mini = make([]int, 0, miniCount)
|
||||
|
||||
@@ -25,6 +25,27 @@ func TestAllocateMiniPortsAvoidsMiniDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// AllocateMiniPorts must keep every port it hands out, and that port's gRPC
|
||||
// counterpart, below 32768 - the Linux default ip_local_port_range floor.
|
||||
// A real failure: filer was allocated 44204, then lost the bind to a transient
|
||||
// outbound connection that had grabbed 44204 as an ephemeral source port
|
||||
// during mini startup ("bind: address already in use").
|
||||
func TestAllocateMiniPortsBelowEphemeralFloor(t *testing.T) {
|
||||
const ephemeralFloor = linuxEphemeralPortFloor
|
||||
for iter := 0; iter < 200; iter++ {
|
||||
ports, err := AllocateMiniPorts(4)
|
||||
if err != nil {
|
||||
t.Fatalf("iter %d: AllocateMiniPorts: %v", iter, err)
|
||||
}
|
||||
for _, p := range ports {
|
||||
if p+GrpcPortOffset >= ephemeralFloor {
|
||||
t.Fatalf("iter %d: port %d (gRPC %d) reaches the ephemeral range floor %d",
|
||||
iter, p, p+GrpcPortOffset, ephemeralFloor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocatePortSetNoGrpcCollision(t *testing.T) {
|
||||
// Run a few iterations to catch the OS-recycles-just-closed-port race
|
||||
// that previously hit regular ports when the mini gRPC offset was freed
|
||||
|
||||
@@ -119,7 +119,7 @@ func TestBatchDeleteCookieMismatchAndSkipCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchDeleteMixedStatusesAndMismatchStopsProcessing(t *testing.T) {
|
||||
func TestBatchDeleteMixedStatusesAndMismatchContinuesProcessing(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
@@ -188,29 +188,32 @@ func TestBatchDeleteMixedStatusesAndMismatchStopsProcessing(t *testing.T) {
|
||||
}
|
||||
|
||||
wrongCookieB := framework.NewFileID(volumeID, needleB, cookieB+1)
|
||||
stopResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
|
||||
mismatchContinueResp, err := client.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
|
||||
FileIds: []string{wrongCookieB, fidC},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BatchDelete mismatch-stop request failed: %v", err)
|
||||
t.Fatalf("BatchDelete mismatch-continue request failed: %v", err)
|
||||
}
|
||||
if len(stopResp.GetResults()) != 1 {
|
||||
t.Fatalf("BatchDelete mismatch-stop expected 1 result due early break, got %d", len(stopResp.GetResults()))
|
||||
if len(mismatchContinueResp.GetResults()) != 2 {
|
||||
t.Fatalf("BatchDelete mismatch-continue expected 2 results, got %d", len(mismatchContinueResp.GetResults()))
|
||||
}
|
||||
if stopResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
|
||||
t.Fatalf("BatchDelete mismatch-stop expected 400, got %d", stopResp.GetResults()[0].GetStatus())
|
||||
if mismatchContinueResp.GetResults()[0].GetStatus() != http.StatusBadRequest {
|
||||
t.Fatalf("BatchDelete mismatch-continue result[0] expected 400, got %d", mismatchContinueResp.GetResults()[0].GetStatus())
|
||||
}
|
||||
if mismatchContinueResp.GetResults()[1].GetStatus() != http.StatusAccepted {
|
||||
t.Fatalf("BatchDelete mismatch-continue result[1] expected 202, got %d", mismatchContinueResp.GetResults()[1].GetStatus())
|
||||
}
|
||||
|
||||
readB := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidB)
|
||||
_ = framework.ReadAllAndClose(t, readB)
|
||||
if readB.StatusCode != http.StatusOK {
|
||||
t.Fatalf("fidB should remain after cookie mismatch path, got %d", readB.StatusCode)
|
||||
t.Fatalf("fidB should remain after cookie mismatch, got %d", readB.StatusCode)
|
||||
}
|
||||
|
||||
readC := framework.ReadBytes(t, httpClient, cluster.VolumeAdminURL(), fidC)
|
||||
_ = framework.ReadAllAndClose(t, readC)
|
||||
if readC.StatusCode != http.StatusOK {
|
||||
t.Fatalf("fidC should remain when batch processing stops on mismatch, got %d", readC.StatusCode)
|
||||
if readC.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("fidC should be deleted when processing continues past a mismatch, got %d", readC.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -311,9 +311,7 @@ func (s *AdminServer) getFilerNodesStatus() []FilerNode {
|
||||
|
||||
// Get filer nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -352,9 +350,7 @@ func (s *AdminServer) getMessageBrokerNodesStatus() []MessageBrokerNode {
|
||||
|
||||
// Get message broker nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -393,9 +389,7 @@ func (s *AdminServer) getS3NodesStatus() []S3Node {
|
||||
|
||||
// Get S3 nodes from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,16 +14,38 @@ const (
|
||||
adminLockClientName = "admin-plugin"
|
||||
)
|
||||
|
||||
const (
|
||||
// A competing shell client polls the master once a second, while a local
|
||||
// re-acquire would win immediately. Leave the lock free for slightly more
|
||||
// than one poll interval so a waiting operator gets it first.
|
||||
defaultAdminLockYieldWindow = 2 * time.Second
|
||||
// After the lock has been held continuously for this long (overlapping
|
||||
// reference-counted holds can keep it held indefinitely), new Acquire
|
||||
// calls wait for a full release so shell clients are not starved.
|
||||
defaultAdminLockFairnessWindow = time.Minute
|
||||
)
|
||||
|
||||
// adminLocker is the subset of exclusive_locks.ExclusiveLocker the manager uses.
|
||||
type adminLocker interface {
|
||||
RequestLock(clientName string)
|
||||
ReleaseLock()
|
||||
SetMessage(message string)
|
||||
}
|
||||
|
||||
// AdminLockManager coordinates exclusive admin locks with reference counting.
|
||||
// It is safe for concurrent use.
|
||||
type AdminLockManager struct {
|
||||
locker *exclusive_locks.ExclusiveLocker
|
||||
clientName string
|
||||
locker adminLocker
|
||||
clientName string
|
||||
yieldWindow time.Duration
|
||||
fairnessWindow time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
acquiring bool
|
||||
releasing bool
|
||||
holdCount int
|
||||
heldSince time.Time
|
||||
|
||||
lastAcquiredAt time.Time
|
||||
lastReleasedAt time.Time
|
||||
@@ -40,13 +62,19 @@ func NewAdminLockManager(masterClient *wdclient.MasterClient, clientName string)
|
||||
clientName = adminLockClientName
|
||||
}
|
||||
manager := &AdminLockManager{
|
||||
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
|
||||
clientName: clientName,
|
||||
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
|
||||
clientName: clientName,
|
||||
yieldWindow: defaultAdminLockYieldWindow,
|
||||
fairnessWindow: defaultAdminLockFairnessWindow,
|
||||
}
|
||||
manager.cond = sync.NewCond(&manager.mu)
|
||||
return manager
|
||||
}
|
||||
|
||||
// Acquire takes the shared cluster lock, reference counted so overlapping
|
||||
// admin-side holders piggyback on one lease. It must not be called while the
|
||||
// caller's own call stack already holds the lock: once the fairness window
|
||||
// makes new acquires wait for a full release, a nested Acquire deadlocks.
|
||||
func (m *AdminLockManager) Acquire(reason string) (func(), error) {
|
||||
if m == nil || m.locker == nil {
|
||||
return func() {}, nil
|
||||
@@ -57,18 +85,28 @@ func (m *AdminLockManager) Acquire(reason string) (func(), error) {
|
||||
m.locker.SetMessage(reason)
|
||||
m.currentReason = reason
|
||||
}
|
||||
for m.acquiring {
|
||||
for m.acquiring || m.releasing || (m.holdCount > 0 && time.Since(m.heldSince) > m.fairnessWindow) {
|
||||
m.cond.Wait()
|
||||
}
|
||||
if m.holdCount == 0 {
|
||||
m.acquiring = true
|
||||
m.waitingSince = time.Now().UTC()
|
||||
m.waitingReason = reason
|
||||
yield := time.Duration(0)
|
||||
if !m.lastReleasedAt.IsZero() {
|
||||
if since := time.Since(m.lastReleasedAt); since < m.yieldWindow {
|
||||
yield = m.yieldWindow - since
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if yield > 0 {
|
||||
time.Sleep(yield)
|
||||
}
|
||||
m.locker.RequestLock(m.clientName)
|
||||
m.mu.Lock()
|
||||
m.acquiring = false
|
||||
m.holdCount = 1
|
||||
m.heldSince = time.Now()
|
||||
m.lastAcquiredAt = time.Now().UTC()
|
||||
m.waitingSince = time.Time{}
|
||||
m.waitingReason = ""
|
||||
@@ -96,14 +134,22 @@ func (m *AdminLockManager) Release() {
|
||||
}
|
||||
m.holdCount--
|
||||
shouldRelease := m.holdCount == 0
|
||||
if shouldRelease {
|
||||
// Block new acquires until ReleaseLock completes: a RequestLock
|
||||
// issued while the locker still considers itself locked would no-op
|
||||
// and leave a hold with no live lease.
|
||||
m.releasing = true
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
if shouldRelease {
|
||||
m.locker.ReleaseLock()
|
||||
m.mu.Lock()
|
||||
m.releasing = false
|
||||
m.lastReleasedAt = time.Now().UTC()
|
||||
m.currentReason = ""
|
||||
m.cond.Broadcast()
|
||||
m.mu.Unlock()
|
||||
m.locker.ReleaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeAdminLocker struct {
|
||||
releaseDelay time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
requests []time.Time
|
||||
releases []time.Time // recorded when ReleaseLock returns
|
||||
}
|
||||
|
||||
func (f *fakeAdminLocker) RequestLock(clientName string) {
|
||||
f.mu.Lock()
|
||||
f.requests = append(f.requests, time.Now())
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *fakeAdminLocker) ReleaseLock() {
|
||||
if f.releaseDelay > 0 {
|
||||
time.Sleep(f.releaseDelay)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.releases = append(f.releases, time.Now())
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *fakeAdminLocker) SetMessage(message string) {}
|
||||
|
||||
func (f *fakeAdminLocker) counts() (int, int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.requests), len(f.releases)
|
||||
}
|
||||
|
||||
func newTestLockManager(locker adminLocker, yieldWindow, fairnessWindow time.Duration) *AdminLockManager {
|
||||
m := &AdminLockManager{
|
||||
locker: locker,
|
||||
clientName: "test",
|
||||
yieldWindow: yieldWindow,
|
||||
fairnessWindow: fairnessWindow,
|
||||
}
|
||||
m.cond = sync.NewCond(&m.mu)
|
||||
return m
|
||||
}
|
||||
|
||||
func TestAdminLockManagerRefCountsOverlappingHolds(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
locker := &fakeAdminLocker{}
|
||||
m := newTestLockManager(locker, defaultAdminLockYieldWindow, defaultAdminLockFairnessWindow)
|
||||
|
||||
release1, _ := m.Acquire("a")
|
||||
release2, _ := m.Acquire("b")
|
||||
|
||||
if requests, releases := locker.counts(); requests != 1 || releases != 0 {
|
||||
t.Fatalf("expected one lease request while overlapping, got requests=%d releases=%d", requests, releases)
|
||||
}
|
||||
|
||||
release1()
|
||||
if _, releases := locker.counts(); releases != 0 {
|
||||
t.Fatalf("lock released while still held by another caller")
|
||||
}
|
||||
release2()
|
||||
if _, releases := locker.counts(); releases != 1 {
|
||||
t.Fatalf("expected one release after last holder, got %d", releases)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLockManagerYieldsBeforeReacquire(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
locker := &fakeAdminLocker{}
|
||||
m := newTestLockManager(locker, 100*time.Millisecond, defaultAdminLockFairnessWindow)
|
||||
|
||||
release, _ := m.Acquire("first")
|
||||
release()
|
||||
release, _ = m.Acquire("second")
|
||||
release()
|
||||
|
||||
locker.mu.Lock()
|
||||
gap := locker.requests[1].Sub(locker.releases[0])
|
||||
locker.mu.Unlock()
|
||||
if gap < 90*time.Millisecond {
|
||||
t.Fatalf("re-acquire did not yield to competing clients: gap=%v", gap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLockManagerFairnessWindowForcesFullRelease(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
locker := &fakeAdminLocker{}
|
||||
m := newTestLockManager(locker, 20*time.Millisecond, 50*time.Millisecond)
|
||||
|
||||
release1, _ := m.Acquire("long-hold")
|
||||
m.mu.Lock()
|
||||
m.heldSince = time.Now().Add(-time.Second)
|
||||
m.mu.Unlock()
|
||||
|
||||
acquired := make(chan func(), 1)
|
||||
go func() {
|
||||
release2, _ := m.Acquire("late-joiner")
|
||||
acquired <- release2
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-acquired:
|
||||
t.Fatalf("late acquire joined a hold older than the fairness window")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
|
||||
release1()
|
||||
|
||||
select {
|
||||
case release2 := <-acquired:
|
||||
release2()
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("late acquire did not proceed after full release")
|
||||
}
|
||||
|
||||
if requests, releases := locker.counts(); requests != 2 || releases != 2 {
|
||||
t.Fatalf("expected a full release/re-acquire cycle, got requests=%d releases=%d", requests, releases)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLockManagerAcquireWaitsForReleaseInFlight(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
locker := &fakeAdminLocker{releaseDelay: 50 * time.Millisecond}
|
||||
m := newTestLockManager(locker, time.Millisecond, defaultAdminLockFairnessWindow)
|
||||
|
||||
release1, _ := m.Acquire("first")
|
||||
releaseDone := make(chan struct{})
|
||||
go func() {
|
||||
release1()
|
||||
close(releaseDone)
|
||||
}()
|
||||
// Let the release enter the slow ReleaseLock before re-acquiring.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
release2, _ := m.Acquire("second")
|
||||
<-releaseDone
|
||||
release2()
|
||||
|
||||
locker.mu.Lock()
|
||||
defer locker.mu.Unlock()
|
||||
if len(locker.requests) != 2 || len(locker.releases) != 2 {
|
||||
t.Fatalf("unexpected lease traffic: requests=%d releases=%d", len(locker.requests), len(locker.releases))
|
||||
}
|
||||
if locker.requests[1].Before(locker.releases[0]) {
|
||||
t.Fatalf("RequestLock ran while ReleaseLock was still in flight")
|
||||
}
|
||||
}
|
||||
+153
-28
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
clustermaintenance "github.com/seaweedfs/seaweedfs/weed/cluster/maintenance"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -32,7 +33,10 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/lifecycle_xml"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks"
|
||||
|
||||
@@ -73,6 +77,27 @@ func (s *AdminServer) getFilerConfig() (*FilerConfig, error) {
|
||||
return config, err
|
||||
}
|
||||
|
||||
// getFilerConf reads filer.conf so callers can inspect per-path rules such as
|
||||
// the read-only flag that quota enforcement toggles. A missing filer.conf
|
||||
// yields an empty (all-writable) config rather than an error.
|
||||
func (s *AdminServer) getFilerConf() (*filer.FilerConf, error) {
|
||||
fc := filer.NewFilerConf()
|
||||
err := s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
content, err := filer.ReadInsideFiler(context.Background(), client, filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(content) > 0 {
|
||||
return fc.LoadFromBytes(content)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return fc, err
|
||||
}
|
||||
|
||||
// getCollectionName returns the collection name for a bucket, prefixed with filer group if configured
|
||||
func getCollectionName(filerGroup, bucketName string) string {
|
||||
if filerGroup != "" {
|
||||
@@ -85,6 +110,7 @@ type AdminServer struct {
|
||||
masterClient *wdclient.MasterClient
|
||||
templateFS http.FileSystem
|
||||
dataDir string
|
||||
filerGroup string
|
||||
grpcDialOption grpc.DialOption
|
||||
cacheExpiration time.Duration
|
||||
lastCacheUpdate time.Time
|
||||
@@ -134,13 +160,13 @@ type AdminServer struct {
|
||||
|
||||
// Type definitions moved to types.go
|
||||
|
||||
func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
|
||||
func NewAdminServer(masters string, filerGroup string, templateFS http.FileSystem, dataDir string, icebergPort int) *AdminServer {
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.admin")
|
||||
|
||||
// Create master client with multiple master support
|
||||
masterClient := wdclient.NewMasterClient(
|
||||
grpcDialOption,
|
||||
"", // filerGroup - not needed for admin
|
||||
filerGroup,
|
||||
"admin", // clientType
|
||||
"", // clientHost - not needed for admin
|
||||
"", // dataCenter - not needed for admin
|
||||
@@ -162,6 +188,7 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
|
||||
masterClient: masterClient,
|
||||
templateFS: templateFS,
|
||||
dataDir: dataDir,
|
||||
filerGroup: filerGroup,
|
||||
grpcDialOption: grpcDialOption,
|
||||
cacheExpiration: defaultCacheTimeout,
|
||||
filerCacheExpiration: defaultFilerCacheTimeout,
|
||||
@@ -293,6 +320,13 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *AdminServer) listClusterNodesRequest(clientType string) *master_pb.ListClusterNodesRequest {
|
||||
return &master_pb.ListClusterNodesRequest{
|
||||
ClientType: clientType,
|
||||
FilerGroup: s.filerGroup,
|
||||
}
|
||||
}
|
||||
|
||||
// vacuumToggler abstracts the master's vacuum enable/disable for testing.
|
||||
type vacuumToggler interface {
|
||||
disableVacuum() error
|
||||
@@ -661,6 +695,12 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
glog.Warningf("Failed to get filer configuration, using defaults: %v", err)
|
||||
}
|
||||
|
||||
// Read filer.conf so we can surface the read-only flag quota enforcement sets
|
||||
fc, err := s.getFilerConf()
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to read filer.conf for bucket read-only state: %v", err)
|
||||
}
|
||||
|
||||
// Now list buckets from the filer and match with collection data
|
||||
err = s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Paginate through all buckets in the buckets directory
|
||||
@@ -759,19 +799,24 @@ func (s *AdminServer) GetS3Buckets() ([]S3Bucket, error) {
|
||||
createdAt = time.Unix(resp.Entry.Attributes.Crtime, 0)
|
||||
lastModified = time.Unix(resp.Entry.Attributes.Mtime, 0)
|
||||
}
|
||||
readOnly := fc.MatchStorageRule(filerConfig.BucketsPath + "/" + bucketName + "/").ReadOnly
|
||||
lifecycleRuleCount, lifecycleEnabledCount := extractLifecycleCountsFromEntry(resp.Entry)
|
||||
bucket := S3Bucket{
|
||||
Name: bucketName,
|
||||
CreatedAt: createdAt,
|
||||
LogicalSize: logicalSize,
|
||||
PhysicalSize: physicalSize,
|
||||
LastModified: lastModified,
|
||||
Quota: quota,
|
||||
QuotaEnabled: quotaEnabled,
|
||||
VersioningStatus: versioningStatus,
|
||||
ObjectLockEnabled: objectLockEnabled,
|
||||
ObjectLockMode: objectLockMode,
|
||||
ObjectLockDuration: objectLockDuration,
|
||||
Owner: owner,
|
||||
Name: bucketName,
|
||||
CreatedAt: createdAt,
|
||||
LogicalSize: logicalSize,
|
||||
PhysicalSize: physicalSize,
|
||||
LastModified: lastModified,
|
||||
Quota: quota,
|
||||
QuotaEnabled: quotaEnabled,
|
||||
ReadOnly: readOnly,
|
||||
VersioningStatus: versioningStatus,
|
||||
ObjectLockEnabled: objectLockEnabled,
|
||||
ObjectLockMode: objectLockMode,
|
||||
ObjectLockDuration: objectLockDuration,
|
||||
Owner: owner,
|
||||
LifecycleRuleCount: lifecycleRuleCount,
|
||||
LifecycleEnabledCount: lifecycleEnabledCount,
|
||||
}
|
||||
buckets = append(buckets, bucket)
|
||||
}
|
||||
@@ -820,6 +865,13 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
details.Bucket.PhysicalSize = data.PhysicalSize
|
||||
}
|
||||
|
||||
// Surface the read-only flag quota enforcement sets in filer.conf
|
||||
if fc, err := s.getFilerConf(); err != nil {
|
||||
glog.Warningf("Failed to read filer.conf for bucket read-only state: %v", err)
|
||||
} else {
|
||||
details.Bucket.ReadOnly = fc.MatchStorageRule(filerConfig.BucketsPath + "/" + bucketName + "/").ReadOnly
|
||||
}
|
||||
|
||||
err = s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Get bucket info
|
||||
bucketResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
@@ -869,6 +921,7 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
details.Bucket.ObjectLockMode = objectLockMode
|
||||
details.Bucket.ObjectLockDuration = objectLockDuration
|
||||
details.Bucket.Owner = owner
|
||||
details.Bucket.LifecycleRuleCount, details.Bucket.LifecycleEnabledCount = extractLifecycleCountsFromEntry(bucketResp.Entry)
|
||||
|
||||
return nil
|
||||
})
|
||||
@@ -880,6 +933,68 @@ func (s *AdminServer) GetBucketDetails(bucketName string) (*BucketDetails, error
|
||||
return details, nil
|
||||
}
|
||||
|
||||
// GetBucketLifecycle returns the lifecycle configuration stored on a bucket's filer entry
|
||||
func (s *AdminServer) GetBucketLifecycle(bucketName string) (*BucketLifecycle, error) {
|
||||
filerConfig, err := s.getFilerConfig()
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to get filer configuration, using defaults: %v", err)
|
||||
}
|
||||
|
||||
lifecycle := &BucketLifecycle{
|
||||
Bucket: bucketName,
|
||||
Rules: []BucketLifecycleRule{},
|
||||
}
|
||||
|
||||
err = s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: filerConfig.BucketsPath,
|
||||
Name: bucketName,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("bucket not found: %w", err)
|
||||
}
|
||||
|
||||
xmlBytes := resp.Entry.Extended[scheduler.BucketLifecycleConfigurationXMLKey]
|
||||
if len(xmlBytes) == 0 {
|
||||
return nil
|
||||
}
|
||||
rules, err := lifecycle_xml.ParseCanonical(xmlBytes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse lifecycle configuration: %w", err)
|
||||
}
|
||||
lifecycle.XML = string(xmlBytes)
|
||||
for _, rule := range rules {
|
||||
lifecycle.Rules = append(lifecycle.Rules, toBucketLifecycleRule(rule))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return lifecycle, nil
|
||||
}
|
||||
|
||||
func toBucketLifecycleRule(rule *s3lifecycle.Rule) BucketLifecycleRule {
|
||||
out := BucketLifecycleRule{
|
||||
ID: rule.ID,
|
||||
Status: rule.Status,
|
||||
Prefix: rule.Prefix,
|
||||
Tags: rule.FilterTags,
|
||||
SizeGreaterThan: rule.FilterSizeGreaterThan,
|
||||
SizeLessThan: rule.FilterSizeLessThan,
|
||||
ExpirationDays: rule.ExpirationDays,
|
||||
ExpiredObjectDeleteMarker: rule.ExpiredObjectDeleteMarker,
|
||||
NoncurrentVersionExpirationDays: rule.NoncurrentVersionExpirationDays,
|
||||
NewerNoncurrentVersions: rule.NewerNoncurrentVersions,
|
||||
AbortMultipartDays: rule.AbortMPUDaysAfterInitiation,
|
||||
}
|
||||
if !rule.ExpirationDate.IsZero() {
|
||||
out.ExpirationDate = rule.ExpirationDate.Format(time.DateOnly)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// CreateS3Bucket creates a new S3 bucket
|
||||
func (s *AdminServer) CreateS3Bucket(bucketName string) error {
|
||||
return s.CreateS3BucketWithQuota(bucketName, 0, false)
|
||||
@@ -1112,9 +1227,7 @@ func (s *AdminServer) GetClusterFilers() (*ClusterFilersData, error) {
|
||||
|
||||
// Get filer information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1159,9 +1272,7 @@ func (s *AdminServer) GetClusterBrokers() (*ClusterBrokersData, error) {
|
||||
|
||||
// Get broker information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1206,9 +1317,7 @@ func (s *AdminServer) GetClusterS3Servers() (*ClusterS3ServersData, error) {
|
||||
|
||||
// Get S3 server information from master using ListClusterNodes
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1419,8 +1528,8 @@ func (s *AdminServer) RunPluginDetectionWithReport(
|
||||
|
||||
// DispatchPluginProposals dispatches a batch of proposals using the same
|
||||
// capacity-aware dispatch logic as the scheduler loop (executor reservation with
|
||||
// backoff, per-job retry on transient errors). The plugin lock must already be
|
||||
// held by the caller.
|
||||
// backoff, per-job retry on transient errors). The dispatch takes the cluster
|
||||
// admin lock around each job itself; callers must not hold it.
|
||||
func (s *AdminServer) DispatchPluginProposals(
|
||||
ctx context.Context,
|
||||
jobType string,
|
||||
@@ -1642,9 +1751,7 @@ func (s *AdminServer) UpdateTopicRetention(namespace, name string, enabled bool,
|
||||
// Get broker information from master
|
||||
var brokerAddress string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1774,6 +1881,24 @@ func extractVersioningFromEntry(entry *filer_pb.Entry) string {
|
||||
return s3api.GetVersioningStatus(entry)
|
||||
}
|
||||
|
||||
func extractLifecycleCountsFromEntry(entry *filer_pb.Entry) (ruleCount, enabledCount int) {
|
||||
xmlBytes := entry.Extended[scheduler.BucketLifecycleConfigurationXMLKey]
|
||||
if len(xmlBytes) == 0 {
|
||||
return
|
||||
}
|
||||
rules, err := lifecycle_xml.ParseCanonical(xmlBytes)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, rule := range rules {
|
||||
ruleCount++
|
||||
if rule.Status == s3lifecycle.StatusEnabled {
|
||||
enabledCount++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetConfigPersistence returns the config persistence manager
|
||||
func (as *AdminServer) GetConfigPersistence() *ConfigPersistence {
|
||||
return as.configPersistence
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
)
|
||||
|
||||
func TestListClusterNodesRequestIncludesFilerGroup(t *testing.T) {
|
||||
server := &AdminServer{filerGroup: "tenant-a"}
|
||||
|
||||
req := server.listClusterNodesRequest(cluster.FilerType)
|
||||
|
||||
if req.ClientType != cluster.FilerType {
|
||||
t.Fatalf("ClientType = %q, want %q", req.ClientType, cluster.FilerType)
|
||||
}
|
||||
if req.FilerGroup != "tenant-a" {
|
||||
t.Fatalf("FilerGroup = %q, want %q", req.FilerGroup, "tenant-a")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListClusterNodesRequestKeepsDefaultFilerGroupEmpty(t *testing.T) {
|
||||
server := &AdminServer{}
|
||||
|
||||
req := server.listClusterNodesRequest(cluster.FilerType)
|
||||
|
||||
if req.FilerGroup != "" {
|
||||
t.Fatalf("FilerGroup = %q, want empty", req.FilerGroup)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
@@ -84,6 +85,23 @@ func (s *AdminServer) ShowBucketDetails(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusOK, details)
|
||||
}
|
||||
|
||||
// ShowBucketLifecycle returns the lifecycle configuration for a specific bucket
|
||||
func (s *AdminServer) ShowBucketLifecycle(w http.ResponseWriter, r *http.Request) {
|
||||
bucketName := mux.Vars(r)["bucket"]
|
||||
if bucketName == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Bucket name is required")
|
||||
return
|
||||
}
|
||||
|
||||
lifecycle, err := s.GetBucketLifecycle(bucketName)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get bucket lifecycle: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, lifecycle)
|
||||
}
|
||||
|
||||
// CreateBucket creates a new S3 bucket
|
||||
func (s *AdminServer) CreateBucket(w http.ResponseWriter, r *http.Request) {
|
||||
var req CreateBucketRequest
|
||||
@@ -397,6 +415,14 @@ func (s *AdminServer) SetBucketQuota(bucketName string, quotaBytes int64, quotaE
|
||||
return fmt.Errorf("failed to update bucket quota: %w", err)
|
||||
}
|
||||
|
||||
if quota <= 0 {
|
||||
// with no active quota, quota enforcement can no longer clear a
|
||||
// read-only flag it turned on, so lift it here
|
||||
if _, err := filer.ClearBucketReadOnly(context.Background(), client, "/buckets", bucketName); err != nil {
|
||||
return fmt.Errorf("failed to clear bucket read-only flag: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
@@ -55,6 +57,20 @@ func (s *AdminServer) GetGrpcDialOption() grpc.DialOption {
|
||||
return s.grpcDialOption
|
||||
}
|
||||
|
||||
// VolumeServerReadJwt mints a per-fileId Bearer token for reads against a
|
||||
// volume server when jwt.signing.read.key is configured. The volume servers
|
||||
// are unaware of jwt.filer_signing.read.key — that one only gates the filer
|
||||
// HTTP surface, which this code path doesn't touch.
|
||||
func VolumeServerReadJwt(fileId string) string {
|
||||
v := util.GetViper()
|
||||
signingKey := security.SigningKey(v.GetString("jwt.signing.read.key"))
|
||||
if len(signingKey) == 0 {
|
||||
return ""
|
||||
}
|
||||
expiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
|
||||
return string(security.GenJwtForVolumeServer(signingKey, expiresAfterSec, fileId))
|
||||
}
|
||||
|
||||
// GetFilerAddress returns a filer address, discovering from masters if needed
|
||||
func (s *AdminServer) GetFilerAddress() string {
|
||||
// Discover filers from masters
|
||||
@@ -76,9 +92,7 @@ func (s *AdminServer) getDiscoveredFilers() []string {
|
||||
// Discover filers from masters
|
||||
var filers []string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.FilerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.FilerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -150,10 +150,19 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
var totalMaxVolumes int64
|
||||
var totalSize int64
|
||||
var totalFiles int64
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports per disk; the slot-based estimate overstates capacity
|
||||
// when maxVolumeCount is configured higher than the disk holds.
|
||||
var diskCapacity int64
|
||||
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
totalVolumes += diskInfo.VolumeCount
|
||||
totalMaxVolumes += diskInfo.MaxVolumeCount
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
diskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(resp.VolumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Sum up individual volume information
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
@@ -198,7 +207,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
Volumes: int(totalVolumes),
|
||||
MaxVolumes: int(totalMaxVolumes),
|
||||
DiskUsage: totalSize,
|
||||
DiskCapacity: totalMaxVolumes * int64(resp.VolumeSizeLimitMb) * 1024 * 1024,
|
||||
DiskCapacity: diskCapacity,
|
||||
LastHeartbeat: time.Now(),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/apache/iceberg-go"
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
const (
|
||||
icebergPreviewDefaultRows = 50
|
||||
icebergPreviewMaxRows = 200
|
||||
icebergPreviewMaxFiles = 5
|
||||
icebergPreviewMaxManifests = 100
|
||||
icebergPreviewMaxListed = 500
|
||||
icebergPreviewMaxCellChars = 200
|
||||
icebergPreviewMaxMetaBytes = 64 << 20
|
||||
)
|
||||
|
||||
type IcebergDataFileInfo struct {
|
||||
Path string `json:"path"`
|
||||
Format string `json:"format"`
|
||||
RecordCount int64 `json:"record_count"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
}
|
||||
|
||||
// IcebergDataPreviewData backs the table data-preview page. PreviewError and
|
||||
// PreviewNotes report per-snapshot problems without failing the whole page.
|
||||
type IcebergDataPreviewData struct {
|
||||
Username string `json:"username"`
|
||||
CatalogName string `json:"catalog_name"`
|
||||
NamespaceName string `json:"namespace_name"`
|
||||
TableName string `json:"table_name"`
|
||||
BucketARN string `json:"bucket_arn"`
|
||||
SnapshotID int64 `json:"snapshot_id"`
|
||||
SnapshotTime time.Time `json:"snapshot_time"`
|
||||
CurrentSnapshotID int64 `json:"current_snapshot_id"`
|
||||
Snapshots []IcebergSnapshotInfo `json:"snapshots"`
|
||||
Columns []string `json:"columns"`
|
||||
Rows [][]string `json:"rows"`
|
||||
RowLimit int `json:"row_limit"`
|
||||
ScannedFiles int `json:"scanned_files"`
|
||||
SelectedFile string `json:"selected_file"`
|
||||
DataFiles []IcebergDataFileInfo `json:"data_files"`
|
||||
TotalDataFiles int `json:"total_data_files"`
|
||||
TotalRecords int64 `json:"total_records"`
|
||||
HasDeletes bool `json:"has_deletes"`
|
||||
PreviewNotes []string `json:"preview_notes,omitempty"`
|
||||
PreviewError string `json:"preview_error,omitempty"`
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
// GetIcebergTableDataPreview walks the selected snapshot's manifests and reads
|
||||
// sample rows from its Parquet data files. snapshotID 0 means the current
|
||||
// snapshot; selectedFile restricts the preview to one manifest-listed file.
|
||||
func (s *AdminServer) GetIcebergTableDataPreview(ctx context.Context, catalogName, bucketArn, namespace, tableName string, snapshotID int64, selectedFile string, rowLimit int) (IcebergDataPreviewData, error) {
|
||||
if rowLimit < 1 {
|
||||
rowLimit = icebergPreviewDefaultRows
|
||||
}
|
||||
if rowLimit > icebergPreviewMaxRows {
|
||||
rowLimit = icebergPreviewMaxRows
|
||||
}
|
||||
|
||||
data := IcebergDataPreviewData{
|
||||
CatalogName: catalogName,
|
||||
NamespaceName: namespace,
|
||||
TableName: tableName,
|
||||
BucketARN: bucketArn,
|
||||
RowLimit: rowLimit,
|
||||
SelectedFile: selectedFile,
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
namespaceParts, err := parseNamespaceInput(namespace)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
var resp s3tables.GetTableResponse
|
||||
req := &s3tables.GetTableRequest{TableBucketARN: bucketArn, Namespace: namespaceParts, Name: tableName}
|
||||
if err := s.executeS3TablesOperation(ctx, "GetTable", req, &resp); err != nil {
|
||||
return data, err
|
||||
}
|
||||
if resp.Metadata == nil || len(resp.Metadata.FullMetadata) == 0 {
|
||||
data.PreviewError = "Table has no Iceberg metadata."
|
||||
return data, nil
|
||||
}
|
||||
var full icebergFullMetadata
|
||||
if err := json.Unmarshal(resp.Metadata.FullMetadata, &full); err != nil {
|
||||
data.PreviewError = fmt.Sprintf("Failed to parse Iceberg metadata: %v", err)
|
||||
return data, nil
|
||||
}
|
||||
data.Snapshots = snapshotsFromFullMetadata(full.Snapshots)
|
||||
data.CurrentSnapshotID = full.CurrentSnapshotID
|
||||
|
||||
snap := selectPreviewSnapshot(full, snapshotID)
|
||||
if snap == nil {
|
||||
if snapshotID != 0 {
|
||||
data.PreviewError = fmt.Sprintf("Snapshot %d not found.", snapshotID)
|
||||
} else {
|
||||
data.PreviewError = "Table has no snapshots yet."
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
data.SnapshotID = snap.SnapshotID
|
||||
if snap.TimestampMs > 0 {
|
||||
data.SnapshotTime = time.Unix(0, snap.TimestampMs*int64(time.Millisecond))
|
||||
}
|
||||
if snap.ManifestList == "" {
|
||||
data.PreviewError = "Snapshot has no manifest list."
|
||||
return data, nil
|
||||
}
|
||||
|
||||
dataFiles, hasDeletes, notes, err := s.listIcebergDataFiles(ctx, catalogName, namespace, tableName, snap.ManifestList)
|
||||
if err != nil {
|
||||
data.PreviewError = fmt.Sprintf("Failed to read snapshot manifests: %v", err)
|
||||
return data, nil
|
||||
}
|
||||
data.HasDeletes = hasDeletes
|
||||
data.PreviewNotes = notes
|
||||
data.TotalDataFiles = len(dataFiles)
|
||||
for _, f := range dataFiles {
|
||||
data.TotalRecords += f.RecordCount
|
||||
}
|
||||
data.DataFiles = dataFiles
|
||||
if len(dataFiles) > icebergPreviewMaxListed {
|
||||
data.DataFiles = dataFiles[:icebergPreviewMaxListed]
|
||||
data.PreviewNotes = append(data.PreviewNotes, fmt.Sprintf("Listing first %d of %d data files.", icebergPreviewMaxListed, len(dataFiles)))
|
||||
}
|
||||
|
||||
toScan := dataFiles
|
||||
if selectedFile != "" {
|
||||
toScan = nil
|
||||
for _, f := range dataFiles {
|
||||
if f.Path == selectedFile {
|
||||
toScan = []IcebergDataFileInfo{f}
|
||||
break
|
||||
}
|
||||
}
|
||||
if toScan == nil {
|
||||
data.PreviewError = "Requested data file is not part of this snapshot."
|
||||
return data, nil
|
||||
}
|
||||
}
|
||||
if len(toScan) == 0 {
|
||||
data.PreviewNotes = append(data.PreviewNotes, "Snapshot contains no data files.")
|
||||
return data, nil
|
||||
}
|
||||
|
||||
for _, f := range toScan {
|
||||
if len(data.Rows) >= rowLimit || data.ScannedFiles >= icebergPreviewMaxFiles {
|
||||
break
|
||||
}
|
||||
if !strings.EqualFold(f.Format, string(iceberg.ParquetFile)) {
|
||||
data.PreviewNotes = append(data.PreviewNotes, fmt.Sprintf("Skipped %s: %s preview is not supported.", path.Base(f.Path), f.Format))
|
||||
continue
|
||||
}
|
||||
filerPath, err := icebergLocationToFilerPath(f.Path, catalogName, namespace, tableName)
|
||||
if err != nil {
|
||||
data.PreviewNotes = append(data.PreviewNotes, fmt.Sprintf("Skipped %s: %v", path.Base(f.Path), err))
|
||||
continue
|
||||
}
|
||||
cols, rows, err := s.readParquetRows(ctx, filerPath, rowLimit-len(data.Rows))
|
||||
if err != nil {
|
||||
data.PreviewNotes = append(data.PreviewNotes, fmt.Sprintf("Failed to read %s: %v", path.Base(f.Path), err))
|
||||
data.ScannedFiles++
|
||||
continue
|
||||
}
|
||||
if data.Columns == nil {
|
||||
data.Columns = cols
|
||||
} else if !slices.Equal(data.Columns, cols) {
|
||||
data.PreviewNotes = append(data.PreviewNotes, fmt.Sprintf("Skipped %s: column layout differs from the first file.", path.Base(f.Path)))
|
||||
continue
|
||||
}
|
||||
data.Rows = append(data.Rows, rows...)
|
||||
data.ScannedFiles++
|
||||
}
|
||||
if hasDeletes {
|
||||
data.PreviewNotes = append(data.PreviewNotes, "Snapshot has row-level delete files; the preview shows raw data-file rows without applying deletes.")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func selectPreviewSnapshot(full icebergFullMetadata, snapshotID int64) *icebergSnapshot {
|
||||
if snapshotID != 0 {
|
||||
for i := range full.Snapshots {
|
||||
if full.Snapshots[i].SnapshotID == snapshotID {
|
||||
return &full.Snapshots[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return selectSnapshotForMetrics(full)
|
||||
}
|
||||
|
||||
func (s *AdminServer) listIcebergDataFiles(ctx context.Context, bucketName, namespaceDir, tableName, manifestListLocation string) (files []IcebergDataFileInfo, hasDeletes bool, notes []string, err error) {
|
||||
listPath, err := icebergLocationToFilerPath(manifestListLocation, bucketName, namespaceDir, tableName)
|
||||
if err != nil {
|
||||
return nil, false, nil, err
|
||||
}
|
||||
listBytes, err := s.readFilerFileContent(ctx, listPath)
|
||||
if err != nil {
|
||||
return nil, false, nil, fmt.Errorf("read manifest list %s: %w", manifestListLocation, err)
|
||||
}
|
||||
manifests, err := iceberg.ReadManifestList(bytes.NewReader(listBytes))
|
||||
if err != nil {
|
||||
return nil, false, nil, fmt.Errorf("parse manifest list: %w", err)
|
||||
}
|
||||
|
||||
scanned := 0
|
||||
for _, mf := range manifests {
|
||||
if mf.ManifestContent() != iceberg.ManifestContentData {
|
||||
hasDeletes = true
|
||||
continue
|
||||
}
|
||||
if scanned >= icebergPreviewMaxManifests {
|
||||
notes = append(notes, fmt.Sprintf("Scanned first %d of %d manifests.", icebergPreviewMaxManifests, len(manifests)))
|
||||
break
|
||||
}
|
||||
scanned++
|
||||
mfPath, err := icebergLocationToFilerPath(mf.FilePath(), bucketName, namespaceDir, tableName)
|
||||
if err != nil {
|
||||
notes = append(notes, fmt.Sprintf("Skipped manifest %s: %v", path.Base(mf.FilePath()), err))
|
||||
continue
|
||||
}
|
||||
mfBytes, err := s.readFilerFileContent(ctx, mfPath)
|
||||
if err != nil {
|
||||
notes = append(notes, fmt.Sprintf("Failed to read manifest %s: %v", path.Base(mf.FilePath()), err))
|
||||
continue
|
||||
}
|
||||
entries, err := iceberg.ReadManifest(mf, bytes.NewReader(mfBytes), true)
|
||||
if err != nil {
|
||||
notes = append(notes, fmt.Sprintf("Failed to parse manifest %s: %v", path.Base(mf.FilePath()), err))
|
||||
continue
|
||||
}
|
||||
for _, entry := range entries {
|
||||
df := entry.DataFile()
|
||||
files = append(files, IcebergDataFileInfo{
|
||||
Path: df.FilePath(),
|
||||
Format: string(df.FileFormat()),
|
||||
RecordCount: df.Count(),
|
||||
SizeBytes: df.FileSizeBytes(),
|
||||
})
|
||||
}
|
||||
}
|
||||
return files, hasDeletes, notes, nil
|
||||
}
|
||||
|
||||
// icebergLocationToFilerPath maps an Iceberg file location (s3://bucket/...,
|
||||
// an absolute filer path, or a table-relative path like data/x.parquet) to a
|
||||
// filer path, which must stay under the table-buckets root.
|
||||
func icebergLocationToFilerPath(location, bucketName, namespaceDir, tableName string) (string, error) {
|
||||
p := location
|
||||
if idx := strings.Index(p, "://"); idx >= 0 {
|
||||
p = path.Join(s3tables.TablesPath, p[idx+3:])
|
||||
} else if strings.HasPrefix(p, "/") {
|
||||
p = path.Clean(p)
|
||||
} else {
|
||||
tableDir := path.Join(s3tables.TablesPath, bucketName, namespaceDir, tableName)
|
||||
p = path.Join(tableDir, p)
|
||||
if !strings.HasPrefix(p, tableDir+"/") {
|
||||
return "", fmt.Errorf("location %q resolves outside the table directory", location)
|
||||
}
|
||||
}
|
||||
p = path.Clean(p)
|
||||
if !strings.HasPrefix(p, s3tables.TablesPath+"/") {
|
||||
return "", fmt.Errorf("location %q resolves outside %s", location, s3tables.TablesPath)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *AdminServer) lookupFilerEntry(ctx context.Context, fullPath string) (*filer_pb.Entry, error) {
|
||||
dir, name := path.Dir(fullPath), path.Base(fullPath)
|
||||
var entry *filer_pb.Entry
|
||||
err := s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entry = resp.Entry
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entry == nil {
|
||||
return nil, fmt.Errorf("not found: %s", fullPath)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func (s *AdminServer) readFilerFileContent(ctx context.Context, fullPath string) ([]byte, error) {
|
||||
entry, err := s.lookupFilerEntry(ctx, fullPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(entry.Content) > 0 || len(entry.GetChunks()) == 0 {
|
||||
return entry.Content, nil
|
||||
}
|
||||
size := int64(filer.FileSize(entry))
|
||||
if size > icebergPreviewMaxMetaBytes {
|
||||
return nil, fmt.Errorf("file too large to load (%d bytes)", size)
|
||||
}
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(ctx, s.GetMasterClient(), VolumeServerReadJwt, entry.GetChunks(), 0, size, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := streamFn(&buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (s *AdminServer) readParquetRows(ctx context.Context, fullPath string, want int) ([]string, [][]string, error) {
|
||||
entry, err := s.lookupFilerEntry(ctx, fullPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var readerAt io.ReaderAt
|
||||
var size int64
|
||||
if len(entry.Content) > 0 || len(entry.GetChunks()) == 0 {
|
||||
readerAt = bytes.NewReader(entry.Content)
|
||||
size = int64(len(entry.Content))
|
||||
} else {
|
||||
size = int64(filer.FileSize(entry))
|
||||
readerAt = &filerChunkReaderAt{ctx: ctx, server: s, chunks: entry.GetChunks(), size: size}
|
||||
}
|
||||
|
||||
pf, err := parquet.OpenFile(readerAt, size, parquet.SkipPageIndex(true), parquet.SkipBloomFilters(true))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open parquet: %w", err)
|
||||
}
|
||||
leafColumns := pf.Schema().Columns()
|
||||
cols := make([]string, len(leafColumns))
|
||||
for i, c := range leafColumns {
|
||||
cols[i] = strings.Join(c, ".")
|
||||
}
|
||||
|
||||
reader := parquet.NewReader(pf)
|
||||
defer reader.Close()
|
||||
rowBuf := make([]parquet.Row, 32)
|
||||
var out [][]string
|
||||
for len(out) < want {
|
||||
n, readErr := reader.ReadRows(rowBuf)
|
||||
for i := 0; i < n && len(out) < want; i++ {
|
||||
out = append(out, formatParquetRow(rowBuf[i], len(cols)))
|
||||
}
|
||||
if readErr != nil {
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, nil, readErr
|
||||
}
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return cols, out, nil
|
||||
}
|
||||
|
||||
func formatParquetRow(row parquet.Row, columnCount int) []string {
|
||||
cells := make([]string, columnCount)
|
||||
seen := make([]bool, columnCount)
|
||||
for _, v := range row {
|
||||
ci := v.Column()
|
||||
if ci < 0 || ci >= columnCount {
|
||||
continue
|
||||
}
|
||||
cell := formatParquetValue(v)
|
||||
if seen[ci] {
|
||||
cells[ci] += ", " + cell
|
||||
} else {
|
||||
cells[ci] = cell
|
||||
seen[ci] = true
|
||||
}
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
func formatParquetValue(v parquet.Value) string {
|
||||
if v.IsNull() {
|
||||
return ""
|
||||
}
|
||||
switch v.Kind() {
|
||||
case parquet.ByteArray, parquet.FixedLenByteArray:
|
||||
b := v.ByteArray()
|
||||
if utf8.Valid(b) {
|
||||
return truncateCell(string(b))
|
||||
}
|
||||
return truncateCell(fmt.Sprintf("0x%x", b))
|
||||
default:
|
||||
return truncateCell(v.String())
|
||||
}
|
||||
}
|
||||
|
||||
func truncateCell(s string) string {
|
||||
if len(s) <= icebergPreviewMaxCellChars {
|
||||
return s
|
||||
}
|
||||
cut := icebergPreviewMaxCellChars
|
||||
for cut > 0 && !utf8.RuneStart(s[cut]) {
|
||||
cut--
|
||||
}
|
||||
return s[:cut] + "…"
|
||||
}
|
||||
|
||||
// filerChunkReaderAt serves random-access reads over a chunked filer entry by
|
||||
// issuing ranged volume-server reads, carrying the read JWT when configured.
|
||||
type filerChunkReaderAt struct {
|
||||
ctx context.Context
|
||||
server *AdminServer
|
||||
chunks []*filer_pb.FileChunk
|
||||
size int64
|
||||
}
|
||||
|
||||
func (r *filerChunkReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if off < 0 {
|
||||
return 0, fmt.Errorf("negative offset: %d", off)
|
||||
}
|
||||
if off >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
want := int64(len(p))
|
||||
if off+want > r.size {
|
||||
want = r.size - off
|
||||
}
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(r.ctx, r.server.GetMasterClient(), VolumeServerReadJwt, r.chunks, off, want, 0)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Write straight into p; a bytes.Buffer wrapping p would silently
|
||||
// allocate a fresh backing array if it ever grew, dropping bytes the
|
||||
// caller expects in p.
|
||||
w := &sliceWriter{dst: p}
|
||||
if err := streamFn(w); err != nil {
|
||||
return w.n, err
|
||||
}
|
||||
if w.n < len(p) {
|
||||
return w.n, io.EOF
|
||||
}
|
||||
return w.n, nil
|
||||
}
|
||||
|
||||
// sliceWriter writes into a fixed destination slice, discarding any overflow.
|
||||
type sliceWriter struct {
|
||||
dst []byte
|
||||
n int
|
||||
}
|
||||
|
||||
func (w *sliceWriter) Write(p []byte) (int, error) {
|
||||
c := copy(w.dst[w.n:], p)
|
||||
w.n += c
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/parquet-go/parquet-go"
|
||||
)
|
||||
|
||||
func TestIcebergLocationToFilerPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
location string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{location: "s3://warehouse/ns/tbl/data/f1.parquet", want: "/buckets/warehouse/ns/tbl/data/f1.parquet"},
|
||||
{location: "s3a://warehouse/ns/tbl/metadata/snap-1.avro", want: "/buckets/warehouse/ns/tbl/metadata/snap-1.avro"},
|
||||
{location: "/buckets/warehouse/ns/tbl/data/f1.parquet", want: "/buckets/warehouse/ns/tbl/data/f1.parquet"},
|
||||
{location: "data/f1.parquet", want: "/buckets/warehouse/ns/tbl/data/f1.parquet"},
|
||||
{location: "metadata/v3.metadata.json", want: "/buckets/warehouse/ns/tbl/metadata/v3.metadata.json"},
|
||||
{location: "s3://warehouse/../../etc/passwd", wantErr: true},
|
||||
{location: "/etc/passwd", wantErr: true},
|
||||
{location: "../../../etc/passwd", wantErr: true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got, err := icebergLocationToFilerPath(tc.location, "warehouse", "ns", "tbl")
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("icebergLocationToFilerPath(%q) = %q, want error", tc.location, got)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("icebergLocationToFilerPath(%q): %v", tc.location, err)
|
||||
continue
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Errorf("icebergLocationToFilerPath(%q) = %q, want %q", tc.location, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatParquetRow(t *testing.T) {
|
||||
type record struct {
|
||||
ID int64 `parquet:"id"`
|
||||
Name string `parquet:"name"`
|
||||
Score float64 `parquet:"score"`
|
||||
Blob []byte `parquet:"blob"`
|
||||
Note *string `parquet:"note,optional"`
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
w := parquet.NewGenericWriter[record](&buf)
|
||||
note := "hello"
|
||||
if _, err := w.Write([]record{
|
||||
{ID: 1, Name: "alpha", Score: 1.5, Blob: []byte{0xff, 0xfe}, Note: ¬e},
|
||||
{ID: 2, Name: "beta", Score: -2.25, Blob: []byte("text"), Note: nil},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pf, err := parquet.OpenFile(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leafColumns := pf.Schema().Columns()
|
||||
cols := make([]string, len(leafColumns))
|
||||
for i, c := range leafColumns {
|
||||
cols[i] = strings.Join(c, ".")
|
||||
}
|
||||
|
||||
reader := parquet.NewReader(pf)
|
||||
defer reader.Close()
|
||||
rows := make([]parquet.Row, 4)
|
||||
n, err := reader.ReadRows(rows)
|
||||
if err != nil && err != io.EOF {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 2 {
|
||||
t.Fatalf("got %d rows, want 2", n)
|
||||
}
|
||||
|
||||
byName := func(cells []string, name string) string {
|
||||
for i, col := range cols {
|
||||
if col == name {
|
||||
return cells[i]
|
||||
}
|
||||
}
|
||||
t.Fatalf("column %q not found in %v", name, cols)
|
||||
return ""
|
||||
}
|
||||
|
||||
first := formatParquetRow(rows[0], len(cols))
|
||||
if got := byName(first, "id"); got != "1" {
|
||||
t.Errorf("id = %q, want 1", got)
|
||||
}
|
||||
if got := byName(first, "name"); got != "alpha" {
|
||||
t.Errorf("name = %q, want alpha", got)
|
||||
}
|
||||
if got := byName(first, "score"); got != "1.5" {
|
||||
t.Errorf("score = %q, want 1.5", got)
|
||||
}
|
||||
if got := byName(first, "blob"); got != "0xfffe" {
|
||||
t.Errorf("blob = %q, want 0xfffe", got)
|
||||
}
|
||||
if got := byName(first, "note"); got != "hello" {
|
||||
t.Errorf("note = %q, want hello", got)
|
||||
}
|
||||
|
||||
second := formatParquetRow(rows[1], len(cols))
|
||||
if got := byName(second, "blob"); got != "text" {
|
||||
t.Errorf("blob = %q, want text", got)
|
||||
}
|
||||
if got := byName(second, "note"); got != "" {
|
||||
t.Errorf("note = %q, want empty for null", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateCell(t *testing.T) {
|
||||
long := strings.Repeat("界", 200)
|
||||
got := truncateCell(long)
|
||||
if len(got) > icebergPreviewMaxCellChars+len("…") {
|
||||
t.Errorf("truncated cell too long: %d", len(got))
|
||||
}
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Errorf("truncated cell should end with ellipsis")
|
||||
}
|
||||
if short := truncateCell("abc"); short != "abc" {
|
||||
t.Errorf("short cell changed: %q", short)
|
||||
}
|
||||
}
|
||||
@@ -494,9 +494,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
|
||||
// First, try to find any broker from the cluster
|
||||
var brokers []string
|
||||
err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.BrokerType,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.BrokerType))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -524,7 +522,7 @@ func (s *AdminServer) findBrokerLeader() (string, error) {
|
||||
|
||||
// Try to find broker leader
|
||||
_, err := client.FindBrokerLeader(ctx, &mq_pb.FindBrokerLeaderRequest{
|
||||
FilerGroup: "",
|
||||
FilerGroup: s.filerGroup,
|
||||
})
|
||||
if err == nil {
|
||||
return nil // This broker is the leader
|
||||
|
||||
@@ -595,20 +595,15 @@ func (s *AdminServer) TriggerPluginDetectionAPI(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
|
||||
// RunPluginJobTypeAPI runs full workflow for one job type: detect then dispatch detected jobs.
|
||||
// RunPluginDetection and the dispatch path take the cluster admin lock
|
||||
// themselves (around detection and around each job), so no lock is held
|
||||
// across the whole workflow here.
|
||||
func (s *AdminServer) RunPluginJobTypeAPI(w http.ResponseWriter, r *http.Request) {
|
||||
jobType := strings.TrimSpace(mux.Vars(r)["jobType"])
|
||||
if jobType == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "jobType is required")
|
||||
return
|
||||
}
|
||||
releaseLock, err := s.acquirePluginLock(fmt.Sprintf("plugin detect+execute %s", jobType))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if releaseLock != nil {
|
||||
defer releaseLock()
|
||||
}
|
||||
|
||||
var req struct {
|
||||
ClusterContext json.RawMessage `json:"cluster_context"`
|
||||
@@ -805,9 +800,7 @@ func (s *AdminServer) buildDefaultPluginClusterContext() *plugin_pb.ClusterConte
|
||||
|
||||
s3Seen := map[string]struct{}{}
|
||||
if err := s.WithMasterClient(func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: cluster.S3Type,
|
||||
})
|
||||
resp, err := client.ListClusterNodes(context.Background(), s.listClusterNodesRequest(cluster.S3Type))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -79,11 +79,15 @@ type S3Bucket struct {
|
||||
LastModified time.Time `json:"last_modified"`
|
||||
Quota int64 `json:"quota"` // Quota in bytes, 0 means no quota
|
||||
QuotaEnabled bool `json:"quota_enabled"` // Whether quota is enabled
|
||||
ReadOnly bool `json:"read_only"` // Whether the bucket path is read-only in filer.conf (e.g. quota enforcement)
|
||||
VersioningStatus string `json:"versioning_status"` // Versioning status: "" (never enabled), "Enabled", or "Suspended"
|
||||
ObjectLockEnabled bool `json:"object_lock_enabled"` // Whether object lock is enabled
|
||||
ObjectLockMode string `json:"object_lock_mode"` // Object lock mode: "GOVERNANCE" or "COMPLIANCE"
|
||||
ObjectLockDuration int32 `json:"object_lock_duration"` // Default retention duration in days
|
||||
Owner string `json:"owner,omitempty"` // Bucket owner identity; empty means admin-only access
|
||||
|
||||
LifecycleRuleCount int `json:"lifecycle_rule_count"`
|
||||
LifecycleEnabledCount int `json:"lifecycle_enabled_count"`
|
||||
}
|
||||
|
||||
type S3Object struct {
|
||||
@@ -99,6 +103,27 @@ type BucketDetails struct {
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type BucketLifecycleRule struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Prefix string `json:"prefix,omitempty"`
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
SizeGreaterThan int64 `json:"size_greater_than,omitempty"`
|
||||
SizeLessThan int64 `json:"size_less_than,omitempty"`
|
||||
ExpirationDays int `json:"expiration_days,omitempty"`
|
||||
ExpirationDate string `json:"expiration_date,omitempty"`
|
||||
ExpiredObjectDeleteMarker bool `json:"expired_object_delete_marker,omitempty"`
|
||||
NoncurrentVersionExpirationDays int `json:"noncurrent_version_expiration_days,omitempty"`
|
||||
NewerNoncurrentVersions int `json:"newer_noncurrent_versions,omitempty"`
|
||||
AbortMultipartDays int `json:"abort_multipart_days,omitempty"`
|
||||
}
|
||||
|
||||
type BucketLifecycle struct {
|
||||
Bucket string `json:"bucket"`
|
||||
Rules []BucketLifecycleRule `json:"rules"`
|
||||
XML string `json:"xml,omitempty"`
|
||||
}
|
||||
|
||||
// ObjectStoreUser is defined in admin_data.go
|
||||
|
||||
// Volume management structures
|
||||
|
||||
@@ -471,7 +471,14 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
|
||||
// Process disk information
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
vs.MaxVolumes += int(diskInfo.MaxVolumeCount)
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024 // Use actual volume size limit
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports; the slot-based estimate overstates capacity when
|
||||
// maxVolumeCount is configured higher than the disk holds.
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
vs.DiskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Count regular volumes and calculate disk usage
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
|
||||
@@ -154,11 +154,11 @@ func (s *WorkerGrpcServer) Stop() error {
|
||||
s.running = false
|
||||
close(s.stopChan)
|
||||
|
||||
// Close all worker connections
|
||||
// Close all worker connections. Cancelling the context stops each
|
||||
// handleOutgoingMessages goroutine; the outgoing channel is never closed.
|
||||
s.connMutex.Lock()
|
||||
for _, conn := range s.connections {
|
||||
conn.cancel()
|
||||
s.safeCloseOutgoingChannel(conn, "Stop")
|
||||
}
|
||||
s.connections = make(map[string]*WorkerConnection)
|
||||
s.connMutex.Unlock()
|
||||
@@ -227,10 +227,9 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
s.connMutex.Lock()
|
||||
if oldConn, exists := s.connections[workerID]; exists {
|
||||
glog.Infof("Worker %s reconnected, cleaning up old connection", workerID)
|
||||
// Cancel old connection to stop its goroutines
|
||||
// Cancel old connection to stop its goroutines. Its handleOutgoingMessages
|
||||
// exits on the cancelled context; the outgoing channel is never closed.
|
||||
oldConn.cancel()
|
||||
// Don't close oldConn.outgoing here as it may cause panic in handleOutgoingMessages
|
||||
// Let the goroutine exit naturally when it detects context cancellation
|
||||
}
|
||||
s.connections[workerID] = conn
|
||||
s.connMutex.Unlock()
|
||||
@@ -255,11 +254,8 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- regResponse:
|
||||
if s.sendToWorker(conn, regResponse, 5*time.Second, "registration response") {
|
||||
glog.V(1).Infof("Registration response sent to worker %s", workerID)
|
||||
case <-time.After(5 * time.Second):
|
||||
glog.Errorf("Failed to send registration response to worker %s", workerID)
|
||||
}
|
||||
|
||||
// Handle incoming messages
|
||||
@@ -384,11 +380,7 @@ func (s *WorkerGrpcServer) handleHeartbeat(conn *WorkerConnection, heartbeat *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- response:
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("Failed to send heartbeat response to worker %s", conn.workerID)
|
||||
}
|
||||
s.sendToWorker(conn, response, time.Second, "heartbeat response")
|
||||
}
|
||||
|
||||
// handleTaskRequest processes task requests from workers
|
||||
@@ -435,11 +427,7 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- assignment:
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("Failed to send task assignment to worker %s", conn.workerID)
|
||||
}
|
||||
s.sendToWorker(conn, assignment, time.Second, "task assignment")
|
||||
} else {
|
||||
// Send explicit "No Task" response to prevent worker timeout
|
||||
// Workers expect a TaskAssignment message but will sleep if TaskId is empty
|
||||
@@ -452,11 +440,8 @@ func (s *WorkerGrpcServer) handleTaskRequest(conn *WorkerConnection, request *wo
|
||||
},
|
||||
}
|
||||
|
||||
select {
|
||||
case conn.outgoing <- noTaskAssignment:
|
||||
if s.sendToWorker(conn, noTaskAssignment, time.Second, "no-task response") {
|
||||
glog.V(4).Infof("Sent 'No Task' response to worker %s", conn.workerID)
|
||||
case <-time.After(time.Second):
|
||||
// If we can't send, the worker will eventually time out and reconnect, which is fine
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -596,14 +581,22 @@ func (s *WorkerGrpcServer) handleTaskLogResponse(conn *WorkerConnection, respons
|
||||
s.logRequestsMutex.Unlock()
|
||||
}
|
||||
|
||||
// safeCloseOutgoingChannel safely closes the outgoing channel for a worker connection.
|
||||
func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, source string) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
glog.V(1).Infof("%s: recovered from panic closing outgoing channel for worker %s: %v", source, conn.workerID, r)
|
||||
}
|
||||
}()
|
||||
close(conn.outgoing)
|
||||
// sendToWorker queues a message on conn.outgoing, which is deliberately never
|
||||
// closed: it has multiple concurrent senders, so closing it could panic one of
|
||||
// them with "send on closed channel". Teardown is signaled via conn.ctx instead;
|
||||
// handleOutgoingMessages drains the channel until that context is cancelled.
|
||||
// Returns false if the connection closed or the send timed out.
|
||||
func (s *WorkerGrpcServer) sendToWorker(conn *WorkerConnection, msg *worker_pb.AdminMessage, timeout time.Duration, description string) bool {
|
||||
select {
|
||||
case conn.outgoing <- msg:
|
||||
return true
|
||||
case <-conn.ctx.Done():
|
||||
glog.V(2).Infof("Dropped %s for worker %s: connection closed", description, conn.workerID)
|
||||
return false
|
||||
case <-time.After(timeout):
|
||||
glog.Warningf("Failed to send %s to worker %s: timeout", description, conn.workerID)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// unregisterWorker removes a worker connection
|
||||
@@ -628,12 +621,11 @@ func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection, event string
|
||||
s.connMutex.Unlock()
|
||||
stats_collect.AdminWorkerEventsTotal.WithLabelValues(event).Inc()
|
||||
|
||||
// Cancel context to signal goroutines to stop
|
||||
// Cancel context to signal goroutines to stop. The outgoing channel is
|
||||
// never closed (it has multiple senders); handleOutgoingMessages exits on
|
||||
// the cancelled context.
|
||||
conn.cancel()
|
||||
|
||||
// Safely close the outgoing channel with recover to handle potential double-close
|
||||
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
|
||||
|
||||
glog.V(1).Infof("Unregistered worker %s", conn.workerID)
|
||||
}
|
||||
|
||||
@@ -732,6 +724,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
|
||||
select {
|
||||
case conn.outgoing <- logRequest:
|
||||
glog.V(1).Infof("Log request sent to worker %s for task %s", workerID, taskID)
|
||||
case <-conn.ctx.Done():
|
||||
s.logRequestsMutex.Lock()
|
||||
if s.pendingLogRequests[requestKey] == requestContext {
|
||||
delete(s.pendingLogRequests, requestKey)
|
||||
}
|
||||
s.logRequestsMutex.Unlock()
|
||||
return nil, fmt.Errorf("worker %s connection closed", workerID)
|
||||
case <-time.After(logSendTimeout):
|
||||
// Clean up pending request on timeout
|
||||
s.logRequestsMutex.Lock()
|
||||
@@ -750,6 +749,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i
|
||||
}
|
||||
glog.V(1).Infof("Received %d log entries for task %s from worker %s", len(response.LogEntries), taskID, workerID)
|
||||
return response.LogEntries, nil
|
||||
case <-conn.ctx.Done():
|
||||
s.logRequestsMutex.Lock()
|
||||
if s.pendingLogRequests[requestKey] == requestContext {
|
||||
delete(s.pendingLogRequests, requestKey)
|
||||
}
|
||||
s.logRequestsMutex.Unlock()
|
||||
return nil, fmt.Errorf("worker %s connection closed", workerID)
|
||||
case <-time.After(logResponseTimeout):
|
||||
// Clean up pending request on timeout
|
||||
s.logRequestsMutex.Lock()
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
)
|
||||
|
||||
func newTestWorkerConn(bufferSize int) *WorkerConnection {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &WorkerConnection{
|
||||
workerID: "w-test",
|
||||
outgoing: make(chan *worker_pb.AdminMessage, bufferSize),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendToWorkerDropsOnCancelledContext verifies a send bails out via the
|
||||
// connection context instead of blocking for the full timeout once the
|
||||
// connection is torn down and its buffer is full.
|
||||
func TestSendToWorkerDropsOnCancelledContext(t *testing.T) {
|
||||
s := &WorkerGrpcServer{adminServer: &AdminServer{}}
|
||||
conn := newTestWorkerConn(1)
|
||||
|
||||
// Fill the buffer so the next send cannot enqueue.
|
||||
conn.outgoing <- &worker_pb.AdminMessage{}
|
||||
conn.cancel()
|
||||
|
||||
start := time.Now()
|
||||
if s.sendToWorker(conn, &worker_pb.AdminMessage{}, 5*time.Second, "heartbeat response") {
|
||||
t.Fatal("expected send to be dropped when context cancelled and buffer full")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("send blocked for %v; expected an immediate context-cancelled bail", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHeartbeatDuringUnregisterDoesNotPanic is a regression test for the
|
||||
// "panic: send on closed channel" crash: unregisterWorker (called from the
|
||||
// stale-connection cleanup routine) used to close conn.outgoing while the
|
||||
// WorkerStream goroutine was still sending heartbeat responses to it.
|
||||
func TestHeartbeatDuringUnregisterDoesNotPanic(t *testing.T) {
|
||||
s := &WorkerGrpcServer{
|
||||
adminServer: &AdminServer{},
|
||||
connections: make(map[string]*WorkerConnection),
|
||||
}
|
||||
conn := newTestWorkerConn(100)
|
||||
s.connections[conn.workerID] = conn
|
||||
|
||||
// Drain outgoing like handleOutgoingMessages would, until teardown.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-conn.ctx.Done():
|
||||
return
|
||||
case <-conn.outgoing:
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
s.handleHeartbeat(conn, &worker_pb.WorkerHeartbeat{})
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.unregisterWorker(conn, "test")
|
||||
}()
|
||||
|
||||
// Under the old close()-based teardown this would panic the sender goroutine
|
||||
// and crash the test binary.
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -114,6 +114,7 @@ func (h *AdminHandlers) registerUIRoutes(r *mux.Router) {
|
||||
r.HandleFunc("/object-store/s3tables/buckets/{bucket}/namespaces", h.ShowS3TablesNamespaces).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/s3tables/buckets/{bucket}/namespaces/{namespace}/tables", h.ShowS3TablesTables).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/s3tables/buckets/{bucket}/namespaces/{namespace}/tables/{table}", h.ShowS3TablesTableDetails).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/s3tables/buckets/{bucket}/namespaces/{namespace}/tables/{table}/data", h.ShowS3TablesTableData).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/iceberg", h.ShowIcebergCatalog).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/iceberg/{catalog}/namespaces", h.ShowIcebergNamespaces).Methods(http.MethodGet)
|
||||
r.HandleFunc("/object-store/iceberg/{catalog}/namespaces/{namespace}/tables", h.ShowIcebergTables).Methods(http.MethodGet)
|
||||
@@ -177,6 +178,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) {
|
||||
s3Api.Handle("/buckets", wrapWrite(h.adminServer.CreateBucket)).Methods(http.MethodPost)
|
||||
s3Api.Handle("/buckets/{bucket}", wrapWrite(h.adminServer.DeleteBucket)).Methods(http.MethodDelete)
|
||||
s3Api.HandleFunc("/buckets/{bucket}", h.adminServer.ShowBucketDetails).Methods(http.MethodGet)
|
||||
s3Api.HandleFunc("/buckets/{bucket}/lifecycle", h.adminServer.ShowBucketLifecycle).Methods(http.MethodGet)
|
||||
s3Api.Handle("/buckets/{bucket}/quota", wrapWrite(h.adminServer.UpdateBucketQuota)).Methods(http.MethodPut)
|
||||
s3Api.Handle("/buckets/{bucket}/owner", wrapWrite(h.adminServer.UpdateBucketOwner)).Methods(http.MethodPut)
|
||||
|
||||
@@ -442,6 +444,38 @@ func (h *AdminHandlers) ShowS3TablesTableDetails(w http.ResponseWriter, r *http.
|
||||
}
|
||||
}
|
||||
|
||||
// ShowS3TablesTableData renders sample rows and the data-file list of an Iceberg table snapshot.
|
||||
func (h *AdminHandlers) ShowS3TablesTableData(w http.ResponseWriter, r *http.Request) {
|
||||
bucketName := mux.Vars(r)["bucket"]
|
||||
namespace := mux.Vars(r)["namespace"]
|
||||
tableName := mux.Vars(r)["table"]
|
||||
arn, err := buildS3TablesBucketArn(bucketName)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
snapshotID, _ := strconv.ParseInt(query.Get("snapshot"), 10, 64)
|
||||
limit, _ := strconv.Atoi(query.Get("limit"))
|
||||
|
||||
username := h.getUsername(r)
|
||||
data, err := h.adminServer.GetIcebergTableDataPreview(r.Context(), bucketName, arn, namespace, tableName, snapshotID, query.Get("file"), limit)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get table data: "+err.Error())
|
||||
return
|
||||
}
|
||||
data.Username = username
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
component := app.IcebergTableData(data)
|
||||
viewCtx := layout.NewViewContext(r, username, dash.CSRFTokenFromContext(r.Context()))
|
||||
layoutComponent := layout.Layout(viewCtx, component)
|
||||
if err := layoutComponent.Render(r.Context(), w); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to render template: "+err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func buildS3TablesBucketArn(bucketName string) (string, error) {
|
||||
return s3tables.BuildBucketARN(s3tables.DefaultRegion, s3_constants.AccountAdminId, bucketName)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Admin upload chunk size, matching s3api so files split into the same fid-sized pieces.
|
||||
@@ -256,7 +255,7 @@ func (h *FileBrowserHandlers) streamEntryContent(ctx context.Context, entry *fil
|
||||
streamFn, err := filer.PrepareStreamContentWithThrottler(
|
||||
ctx,
|
||||
h.adminServer.GetMasterClient(),
|
||||
volumeServerReadJwt,
|
||||
dash.VolumeServerReadJwt,
|
||||
entry.GetChunks(),
|
||||
0,
|
||||
size,
|
||||
@@ -267,17 +266,3 @@ func (h *FileBrowserHandlers) streamEntryContent(ctx context.Context, entry *fil
|
||||
}
|
||||
return streamFn(w)
|
||||
}
|
||||
|
||||
// volumeServerReadJwt mints a per-fileId Bearer token for reads against a
|
||||
// volume server when jwt.signing.read.key is configured. The volume servers
|
||||
// are unaware of jwt.filer_signing.read.key — that one only gates the filer
|
||||
// HTTP surface, which this code path doesn't touch.
|
||||
func volumeServerReadJwt(fileId string) string {
|
||||
v := util.GetViper()
|
||||
signingKey := security.SigningKey(v.GetString("jwt.signing.read.key"))
|
||||
if len(signingKey) == 0 {
|
||||
return ""
|
||||
}
|
||||
expiresAfterSec := v.GetInt("jwt.signing.read.expires_after_seconds")
|
||||
return string(security.GenJwtForVolumeServer(signingKey, expiresAfterSec, fileId))
|
||||
}
|
||||
@@ -424,7 +424,13 @@ func (r *Plugin) acquireAdminLock(reason string) (func(), error) {
|
||||
if r == nil || r.lockManager == nil {
|
||||
return func() {}, nil
|
||||
}
|
||||
return r.lockManager.Acquire(reason)
|
||||
release, err := r.lockManager.Acquire(reason)
|
||||
if release == nil {
|
||||
// Lock manager implementations may return a nil release when
|
||||
// disabled; callers always invoke the release function.
|
||||
release = func() {}
|
||||
}
|
||||
return release, err
|
||||
}
|
||||
|
||||
// RunDetectionWithReport requests one detector worker and returns proposals with request metadata.
|
||||
|
||||
@@ -98,9 +98,11 @@ func (r *Plugin) laneSchedulerLoop(ls *schedulerLaneState) {
|
||||
// runLaneSchedulerIteration runs one scheduling pass for a single lane,
|
||||
// processing only the job types assigned to that lane.
|
||||
//
|
||||
// For lanes that require a lock (e.g. LaneDefault), all job types are
|
||||
// processed sequentially under one admin lock because their volume
|
||||
// management operations share global state.
|
||||
// For lanes that require a lock (e.g. LaneDefault), job types are processed
|
||||
// sequentially because their volume management operations share global
|
||||
// state, and the cluster admin lock is taken around each detection and each
|
||||
// dispatched job rather than the whole pass, so manual shell operations
|
||||
// sharing the same lock can interleave between jobs.
|
||||
//
|
||||
// For lanes that do not require a lock (e.g. LaneIceberg, LaneLifecycle),
|
||||
// each job type runs independently in its own goroutine so they do not
|
||||
@@ -122,7 +124,7 @@ func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool {
|
||||
}
|
||||
|
||||
if LaneRequiresLock(ls.lane) {
|
||||
return r.runLaneSchedulerIterationLocked(ls, jobTypes)
|
||||
return r.runLaneSchedulerIterationSequential(ls, jobTypes)
|
||||
}
|
||||
return r.runLaneSchedulerIterationConcurrent(ls, jobTypes)
|
||||
}
|
||||
@@ -162,21 +164,13 @@ func (r *Plugin) collectDueJobTypes(ls *schedulerLaneState, jobTypes []string) (
|
||||
return active, due
|
||||
}
|
||||
|
||||
// runLaneSchedulerIterationLocked processes job types sequentially under a
|
||||
// single admin lock. Used by the default lane where volume management
|
||||
// operations must be serialised.
|
||||
func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobTypes []string) bool {
|
||||
r.setLaneLoopState(ls, "", "waiting_for_lock")
|
||||
lockName := fmt.Sprintf("plugin scheduler:%s", ls.lane)
|
||||
releaseLock, err := r.acquireAdminLock(lockName)
|
||||
if err != nil {
|
||||
glog.Warningf("Plugin scheduler [%s] failed to acquire lock: %v", ls.lane, err)
|
||||
r.setLaneLoopState(ls, "", "idle")
|
||||
return false
|
||||
}
|
||||
if releaseLock != nil {
|
||||
defer releaseLock()
|
||||
}
|
||||
// runLaneSchedulerIterationSequential processes job types one at a time.
|
||||
// Used by the default lane where volume management operations must be
|
||||
// serialised. The cluster admin lock is not held across the pass;
|
||||
// runJobTypeIteration and dispatchScheduledProposals take it around each
|
||||
// detection and each job.
|
||||
func (r *Plugin) runLaneSchedulerIterationSequential(ls *schedulerLaneState, jobTypes []string) bool {
|
||||
r.setLaneLoopState(ls, "", "busy")
|
||||
|
||||
active, due := r.collectDueJobTypes(ls, jobTypes)
|
||||
hadJobs := false
|
||||
@@ -288,6 +282,30 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
return false
|
||||
}
|
||||
|
||||
// Detection plans against the live topology, so it runs under the shared
|
||||
// cluster admin lock; the lock is released as soon as detection returns.
|
||||
releaseDetectionLock := func() {}
|
||||
if LaneRequiresLock(JobTypeLane(jobType)) {
|
||||
r.setSchedulerLoopStateForJobType(jobType, "waiting_for_lock")
|
||||
release, lockErr := r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s detection", jobType))
|
||||
if lockErr != nil {
|
||||
r.recordSchedulerDetectionError(jobType, lockErr)
|
||||
r.appendActivity(JobActivity{
|
||||
JobType: jobType,
|
||||
Source: "admin_scheduler",
|
||||
Message: fmt.Sprintf("scheduled detection aborted: %v", lockErr),
|
||||
Stage: "failed",
|
||||
OccurredAt: timeToPtr(time.Now().UTC()),
|
||||
})
|
||||
r.recordSchedulerRunComplete(jobType, "error")
|
||||
return false
|
||||
}
|
||||
var releaseOnce sync.Once
|
||||
releaseDetectionLock = func() { releaseOnce.Do(release) }
|
||||
r.setSchedulerLoopStateForJobType(jobType, "detecting")
|
||||
}
|
||||
defer releaseDetectionLock()
|
||||
|
||||
detectionTimeout := policy.DetectionTimeout
|
||||
remaining := time.Until(start.Add(maxRuntime))
|
||||
if remaining <= 0 {
|
||||
@@ -311,6 +329,7 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
detectCtx, cancelDetect := context.WithTimeout(jobCtx, detectionTimeout)
|
||||
proposals, err := r.RunDetection(detectCtx, jobType, clusterContext, policy.MaxResults)
|
||||
cancelDetect()
|
||||
releaseDetectionLock()
|
||||
if err != nil {
|
||||
r.recordSchedulerDetectionError(jobType, err)
|
||||
stage := "failed"
|
||||
@@ -375,26 +394,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
|
||||
r.setSchedulerLoopStateForJobType(jobType, "executing")
|
||||
|
||||
// Scan proposals for the maximum estimated_runtime_seconds so the
|
||||
// execution phase gets enough time for large jobs (e.g. vacuum on
|
||||
// big volumes). If any proposal needs more time than the remaining
|
||||
// JobTypeMaxRuntime, extend the execution context accordingly.
|
||||
var maxEstimatedRuntime time.Duration
|
||||
for _, p := range filtered {
|
||||
if p.Parameters != nil {
|
||||
if est, ok := p.Parameters["estimated_runtime_seconds"]; ok {
|
||||
if v := est.GetInt64Value(); v > 0 {
|
||||
if d := time.Duration(v) * time.Second; d > maxEstimatedRuntime {
|
||||
maxEstimatedRuntime = d
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if maxEstimatedRuntime > maxEstimatedRuntimeCap {
|
||||
maxEstimatedRuntime = maxEstimatedRuntimeCap
|
||||
}
|
||||
|
||||
remaining = time.Until(start.Add(maxRuntime))
|
||||
if remaining <= 0 {
|
||||
r.appendActivity(JobActivity{
|
||||
@@ -408,17 +407,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
return detected
|
||||
}
|
||||
|
||||
// If the longest estimated job exceeds the remaining JobTypeMaxRuntime,
|
||||
// create a new execution context with enough headroom instead of using
|
||||
// jobCtx which would cancel too early.
|
||||
execCtx := jobCtx
|
||||
execCancel := context.CancelFunc(func() {})
|
||||
if maxEstimatedRuntime > 0 && maxEstimatedRuntime > remaining {
|
||||
execCtx, execCancel = context.WithTimeout(context.Background(), maxEstimatedRuntime)
|
||||
remaining = maxEstimatedRuntime
|
||||
}
|
||||
defer execCancel()
|
||||
|
||||
execPolicy := policy
|
||||
if execPolicy.ExecutionTimeout <= 0 {
|
||||
execPolicy.ExecutionTimeout = defaultScheduledExecutionTimeout
|
||||
@@ -427,10 +415,15 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
execPolicy.ExecutionTimeout = remaining
|
||||
}
|
||||
|
||||
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(execCtx, jobType, filtered, clusterContext, execPolicy)
|
||||
// jobCtx bounds how long this run keeps STARTING jobs; a started job
|
||||
// runs on its own estimated-runtime deadline (see
|
||||
// executeScheduledJobWithExecutor). Jobs still queued when the window
|
||||
// closes are canceled and re-proposed by a later detection, so one large
|
||||
// backlog cannot monopolise the lane for hours.
|
||||
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(jobCtx, jobType, filtered, clusterContext, execPolicy)
|
||||
|
||||
status := "success"
|
||||
if execCtx.Err() != nil {
|
||||
if jobCtx.Err() != nil {
|
||||
status = "timeout"
|
||||
} else if errorCount > 0 || canceledCount > 0 {
|
||||
status = "error"
|
||||
@@ -818,6 +811,11 @@ func (r *Plugin) dispatchScheduledProposals(
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// Volume management jobs mutate volume placement, so each one runs under
|
||||
// the shared cluster admin lock. Taking it per job instead of around the
|
||||
// whole dispatch lets manual shell operations interleave between jobs.
|
||||
jobsRequireLock := LaneRequiresLock(JobTypeLane(jobType))
|
||||
|
||||
jobQueue := make(chan *plugin_pb.JobSpec, len(proposals))
|
||||
for index, proposal := range proposals {
|
||||
job := buildScheduledJobSpec(jobType, proposal, index)
|
||||
@@ -900,7 +898,42 @@ func (r *Plugin) dispatchScheduledProposals(
|
||||
break
|
||||
}
|
||||
|
||||
var releaseJobLock func()
|
||||
if jobsRequireLock {
|
||||
var lockErr error
|
||||
releaseJobLock, lockErr = r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s job %s", jobType, job.JobId))
|
||||
if lockErr != nil {
|
||||
release()
|
||||
statsMu.Lock()
|
||||
errorCount++
|
||||
statsMu.Unlock()
|
||||
r.appendActivity(JobActivity{
|
||||
JobID: job.JobId,
|
||||
JobType: job.JobType,
|
||||
Source: "admin_scheduler",
|
||||
Message: fmt.Sprintf("scheduled execution lock failed: %v", lockErr),
|
||||
Stage: "failed",
|
||||
OccurredAt: timeToPtr(time.Now().UTC()),
|
||||
})
|
||||
break
|
||||
}
|
||||
// The lock may have been held by an operator for a
|
||||
// while; re-check the execution window.
|
||||
if ctx.Err() != nil {
|
||||
releaseJobLock()
|
||||
release()
|
||||
r.cancelQueuedJob(job, ctx.Err())
|
||||
statsMu.Lock()
|
||||
canceledCount++
|
||||
statsMu.Unlock()
|
||||
continue jobLoop
|
||||
}
|
||||
}
|
||||
|
||||
err := r.executeScheduledJobWithExecutor(ctx, executor, job, clusterContext, policy)
|
||||
if releaseJobLock != nil {
|
||||
releaseJobLock()
|
||||
}
|
||||
release()
|
||||
if errors.Is(err, errExecutorAtCapacity) {
|
||||
r.trackExecutionQueued(job)
|
||||
@@ -1164,10 +1197,6 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
parent := ctx
|
||||
if parent == nil {
|
||||
parent = context.Background()
|
||||
}
|
||||
// Use the job's estimated runtime if provided and larger than the
|
||||
// default execution timeout. This lets handlers like vacuum scale
|
||||
// the timeout based on volume size so large volumes are not killed.
|
||||
@@ -1185,7 +1214,11 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
}
|
||||
}
|
||||
}
|
||||
execCtx, cancel := context.WithTimeout(parent, timeout)
|
||||
// The attempt runs against its own deadline, detached from the
|
||||
// dispatch window (ctx): a job started near the end of the window
|
||||
// may run to completion; the window only stops further jobs from
|
||||
// starting.
|
||||
execCtx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
_, err := r.executeJobWithExecutor(execCtx, executor, job, clusterContext, int32(attempt))
|
||||
cancel()
|
||||
if err == nil {
|
||||
|
||||
@@ -664,6 +664,12 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
|
||||
t.Fatalf("SaveJobTypeConfig: %v", err)
|
||||
}
|
||||
|
||||
// Make the job type due immediately so the iteration reaches
|
||||
// detection; the lock is only taken around due work now.
|
||||
pluginSvc.schedulerMu.Lock()
|
||||
pluginSvc.nextDetectionAt[tt.jobType] = time.Now().UTC().Add(-time.Second)
|
||||
pluginSvc.schedulerMu.Unlock()
|
||||
|
||||
ls := pluginSvc.lanes[tt.lane]
|
||||
pluginSvc.runLaneSchedulerIteration(ls)
|
||||
|
||||
@@ -674,6 +680,61 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchScheduledProposalsLocksPerJob(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
jobType string
|
||||
wantLocks int
|
||||
}{
|
||||
{"DefaultLaneLocksEachJob", "volume_balance", 3},
|
||||
{"LifecycleLaneNeedsNoLock", "s3_lifecycle", 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
lm := &trackingLockManager{}
|
||||
pluginSvc, err := New(Options{LockManager: lm})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
// The worker has capabilities but no connected session, so each
|
||||
// job reserves capacity, fails to send, and moves on.
|
||||
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
|
||||
WorkerId: "worker-a",
|
||||
Capabilities: []*plugin_pb.JobTypeCapability{
|
||||
{JobType: tt.jobType, CanExecute: true, MaxExecutionConcurrency: 4},
|
||||
},
|
||||
})
|
||||
|
||||
policy := schedulerPolicy{
|
||||
ExecutionConcurrency: 1,
|
||||
PerWorkerConcurrency: 1,
|
||||
ExecutionTimeout: time.Second,
|
||||
ExecutorReserveBackoff: time.Millisecond,
|
||||
}
|
||||
proposals := []*plugin_pb.JobProposal{
|
||||
{ProposalId: "p1", JobType: tt.jobType, DedupeKey: "k1"},
|
||||
{ProposalId: "p2", JobType: tt.jobType, DedupeKey: "k2"},
|
||||
{ProposalId: "p3", JobType: tt.jobType, DedupeKey: "k3"},
|
||||
}
|
||||
|
||||
success, errors, canceled := pluginSvc.dispatchScheduledProposals(
|
||||
context.Background(), tt.jobType, proposals, &plugin_pb.ClusterContext{}, policy)
|
||||
if success != 0 || canceled != 0 || errors != 3 {
|
||||
t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", success, errors, canceled)
|
||||
}
|
||||
if got := lm.count(); got != tt.wantLocks {
|
||||
t.Fatalf("lock acquired %d times, want %d", got, tt.wantLocks)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- lane-scoped prune ----------
|
||||
|
||||
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
)
|
||||
|
||||
// SchedulerLane identifies an independent scheduling track. Each lane runs
|
||||
// its own goroutine, maintains its own detection timing, and acquires its
|
||||
// own admin lock so that workloads in different lanes never block each other.
|
||||
// its own goroutine and maintains its own detection timing so that
|
||||
// workloads in different lanes never block each other.
|
||||
type SchedulerLane string
|
||||
|
||||
const (
|
||||
@@ -39,17 +39,19 @@ var laneIdleSleep = map[SchedulerLane]time.Duration{
|
||||
}
|
||||
|
||||
// laneRequiresLock maps each lane to whether its job types must be
|
||||
// serialised under a single admin lock. The default lane needs this
|
||||
// because volume-management operations share global state. Other
|
||||
// lanes run each job type independently.
|
||||
// serialised and run under the shared cluster admin lock. The default
|
||||
// lane needs this because volume-management operations share global
|
||||
// state; the lock is taken around each detection and each job so manual
|
||||
// shell operations can interleave. Other lanes run each job type
|
||||
// independently without the lock.
|
||||
var laneRequiresLock = map[SchedulerLane]bool{
|
||||
LaneDefault: true,
|
||||
LaneIceberg: false,
|
||||
LaneLifecycle: false,
|
||||
}
|
||||
|
||||
// LaneRequiresLock returns true if the given lane needs a single admin
|
||||
// lock to serialise its job types. Unknown lanes default to true.
|
||||
// LaneRequiresLock returns true if the given lane serialises its job types
|
||||
// and runs them under the cluster admin lock. Unknown lanes default to true.
|
||||
func LaneRequiresLock(lane SchedulerLane) bool {
|
||||
if v, ok := laneRequiresLock[lane]; ok {
|
||||
return v
|
||||
|
||||
Loaded 100 of 430 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user