Compare commits

..
Author SHA1 Message Date
Chris Lu 9a5245e060 Merge remote-tracking branch 'origin/master' into fix-delete-offline-replica
# Conflicts:
#	weed/storage/store_mark_readonly_can_delete_test.go
2026-11-03 08:13:29 -08:00
Chris Lu aba3eab8d9 Merge branch 'master' into fix-delete-offline-replica 2026-11-02 17:47:28 -08:00
Chris LuandClaude Opus 5.5 3c69805f76 shell: keep the gRPC port in the printed volume.delete command
ServerAddress.String() drops a custom gRPC port, so the printed -node
would dial the HTTP port plus 10000. Print the full address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:12:44 -08:00
Chris LuandClaude Opus 5.5 1dcf721ce3 shell: name the copies a partial empty-volume delete leaves behind
Once some copies of a volume are deleted, a rerun of volume.deleteEmpty
skips the rest as under-replicated, and the shell keeps no state to
finish them. Log each copy whose delete failed with the volume.delete
command that removes it once it is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:09:47 -08:00
Chris LuandClaude Opus 5.5 440c50fc65 shell: delete an empty volume only when every copy is empty
volume.deleteEmpty judged each copy on its own, so it removed an empty
copy while another copy still held data or was offline, leaving that
one as the volume's only copy. Low-disk copies now report
readOnlyCanDelete and passed the check as well. Apply the master
sweep's rule: every copy is listed and every copy is empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:58:53 -08:00
Chris LuandClaude Opus 5.5 64f92bfa8a Merge branch 'master' into fix-delete-offline-replica
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:48:09 -08:00
Chris LuandClaude Opus 5.5 b0539a2387 master: keep the cleanup mark while a survivor is only read-only
A partly deleted empty volume lost its deleting mark when the next sweep
found a surviving copy read-only. Later sweeps then skipped the vid as
under-replicated, so the empty copy kept its slot after it became
deletable again. Only a copy that gained data or was written recently
clears the mark now; a read-only or missing copy just postpones the
cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 06:21:06 -08:00
Chris LuandClaude Opus 5.5 59cd87f23c master: finish a partly deleted empty volume in the next sweep
When one copy's VolumeDelete succeeded and another failed, the vid was
left with fewer copies than its replica placement, so every later sweep
skipped it as under-replicated and the empty copy kept its slot. The vid
now stays marked deleting after a partial delete, and the next sweep
finishes it. The mark is cleared once the vid is gone or stops being an
empty, quiet candidate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 06:07:21 -08:00
Chris LuandClaude Opus 5.5 db9b3145e2 master: keep under-replicated volumes out of empty-volume cleanup
The cleanup only looked at the copies the master lists. With a replica
offline the listed copies can be empty and quiet while the missing one
still holds data, and deleting them would leave that copy as the only
one when it returns. Low-disk replicas now report readOnlyCanDelete and
pass the eligibility check, which made this reachable for more volumes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 05:13:58 -08:00
Chris LuandClaude Opus 5.5 c446ea309b filer: retry deletes a low-disk replica could not record
A low-disk volume now counts as deletable, but appending the tombstone
can still fail with no space left on device. Treat that as retryable so
the deletion stays queued instead of being dropped after the other
replicas applied it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 05:13:58 -08:00
Chris LuandClaude Opus 5.5 504230ce1e volume(rust): report a low-disk volume as read-only but deletable
Mirrors the Go heartbeat: readOnlyCanDelete is set whenever the volume
is read-only without no_write_or_delete, which includes low disk space.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 04:42:33 -08:00
Chris LuandClaude Opus 5.5 1caae79f1a volume: report a low-disk volume as read-only but deletable
A volume is read-only while its disk is low on space, but it still
applies deletes; only noWriteOrDelete refuses them. The heartbeat set
readOnlyCanDelete from the operator mark alone, so the master listed a
low-disk replica as refusing deletes and the replica count check
rejected every delete on its volumes, on the healthy replicas too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 04:42:32 -08:00
Chris LuandClaude Opus 5.5 d33c543f91 filer: move exhausted deletion retries to dead letter queues
A deletion that still fails after the backed-off retries is no longer
dropped. It moves to a dead letter queue retried after 24 hours, then to a
second one retried after 48 hours, and is dropped only if that fails too.
The id stays in the durable deletion ledger the whole time, so a restart
replays it instead of losing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 19:37:48 -08:00
Chris LuandClaude Opus 5.5 ffccd8a4ed volume(rust): refuse a batch delete while a replica is offline
Mirrors the Go volume server: batch_delete checks that the master lists
every replica of a replicated volume before deleting, and answers 503
with the replica count error otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:43:19 -08:00
Chris LuandClaude Opus 5.5 7f25ccf119 filer: retry deletes refused for an offline replica
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:43:19 -08:00
Chris LuandClaude Opus 5.5 edae1ac31a volume: refuse a batch delete while a replica is offline
BatchDelete now applies the replica check the HTTP delete path already
uses: when the master lists fewer replicas than the volume's copy count,
the delete is refused with 503 instead of applied to the replicas that
remain. The caller retries, so the replica that was offline still gets
the delete once it returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:43:19 -08:00
784 changed files with 8672 additions and 78368 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ runs:
using: composite
steps:
- name: Install cosign
uses: sigstore/cosign-installer@v4.1.3
uses: sigstore/cosign-installer@v4.1.2
- name: Sign
shell: bash
+1 -25
View File
@@ -9,8 +9,6 @@ logs a warning rather than under-reporting.
import json
import os
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime
@@ -24,28 +22,6 @@ REPO = "seaweedfs/seaweedfs"
TOKEN = os.environ["GITHUB_TOKEN"]
OUT = os.environ.get("OUT", "note/star_history.svg")
PAGE_CAP = 400 # GitHub's hard limit on stargazer pagination
REQUEST_ATTEMPTS = 5
RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
def open_url(req):
for attempt in range(REQUEST_ATTEMPTS):
try:
return urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as error:
if error.code not in RETRYABLE_STATUS_CODES or attempt == REQUEST_ATTEMPTS - 1:
raise
retry_after = error.headers.get("Retry-After")
try:
delay = min(float(retry_after), 60) if retry_after else 2**attempt
except ValueError:
delay = 2**attempt
error.close()
except urllib.error.URLError:
if attempt == REQUEST_ATTEMPTS - 1:
raise
delay = 2**attempt
time.sleep(delay)
def fetch_stargazers():
@@ -62,7 +38,7 @@ def fetch_stargazers():
"User-Agent": "seaweedfs-star-history",
},
)
with open_url(req) as resp:
with urllib.request.urlopen(req) as resp:
batch = json.load(resp)
if not batch:
break
-75
View File
@@ -1,75 +0,0 @@
import importlib.util
import os
from pathlib import Path
import sys
import types
import unittest
from unittest.mock import patch
from urllib.error import HTTPError
def load_star_history():
matplotlib = types.ModuleType("matplotlib")
matplotlib.use = lambda backend: None
pyplot = types.ModuleType("matplotlib.pyplot")
dates = types.ModuleType("matplotlib.dates")
dates.AutoDateLocator = object
dates.DateFormatter = object
modules = {
"matplotlib": matplotlib,
"matplotlib.pyplot": pyplot,
"matplotlib.dates": dates,
}
with patch.dict(sys.modules, modules), patch.dict(os.environ, {"GITHUB_TOKEN": "test"}):
path = Path(__file__).with_name("star_history.py")
spec = importlib.util.spec_from_file_location("star_history", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
star_history = load_star_history()
class StarHistoryTests(unittest.TestCase):
def http_error(self, code):
return HTTPError("https://api.github.com", code, "error", {}, None)
@patch.object(star_history.time, "sleep")
@patch.object(star_history.urllib.request, "urlopen")
def test_retries_server_error(self, urlopen, sleep):
response = object()
urlopen.side_effect = [self.http_error(500), response]
result = star_history.open_url(object())
self.assertIs(result, response)
self.assertEqual(urlopen.call_count, 2)
sleep.assert_called_once_with(1)
@patch.object(star_history.time, "sleep")
@patch.object(star_history.urllib.request, "urlopen")
def test_does_not_retry_non_transient_http_error(self, urlopen, sleep):
error = self.http_error(404)
urlopen.side_effect = error
with self.assertRaises(HTTPError):
star_history.open_url(object())
urlopen.assert_called_once()
sleep.assert_not_called()
@patch.object(star_history.time, "sleep")
@patch.object(star_history.urllib.request, "urlopen")
def test_stops_after_retry_limit(self, urlopen, sleep):
urlopen.side_effect = self.http_error(500)
with self.assertRaises(HTTPError):
star_history.open_url(object())
self.assertEqual(urlopen.call_count, star_history.REQUEST_ATTEMPTS)
self.assertEqual(sleep.call_count, star_history.REQUEST_ATTEMPTS - 1)
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.3
uses: github/codeql-action/init@v4.39.1
# Override language selection by uncommenting this and choosing your languages
with:
languages: go
@@ -41,7 +41,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v4.39.3
uses: github/codeql-action/autobuild@v4.39.1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -55,4 +55,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.3
uses: github/codeql-action/analyze@v4.39.1
+2 -2
View File
@@ -180,14 +180,14 @@ jobs:
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.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.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -141,7 +141,7 @@ jobs:
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
+6 -6
View File
@@ -270,13 +270,13 @@ jobs:
buildkitd-config: /tmp/buildkitd.toml
- name: Login to Docker Hub
if: needs.setup.outputs.publish == 'true'
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.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.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -324,7 +324,7 @@ jobs:
fi
- name: Login to GHCR
if: needs.setup.outputs.publish == 'true'
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -434,7 +434,7 @@ jobs:
output: trivy-results.sarif
exit-code: '0'
- name: Upload Trivy scan results to GitHub Security
uses: github/codeql-action/upload-sarif@v4.39.3
uses: github/codeql-action/upload-sarif@v4.39.1
if: always()
with:
sarif_file: trivy-results.sarif
@@ -501,12 +501,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.8.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -58,7 +58,7 @@ jobs:
-
name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
@@ -262,7 +262,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.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -352,7 +352,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.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -374,7 +374,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.8.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
@@ -487,7 +487,7 @@ jobs:
variant: large_disk
steps:
- name: Login to GHCR
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -515,7 +515,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
uses: github/codeql-action/upload-sarif@v4.39.1
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
@@ -539,13 +539,13 @@ jobs:
latest_tag: latest_large_disk
steps:
- name: Login to Docker Hub
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v4.8.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -96,7 +96,7 @@ jobs:
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
- name: Login to Docker Hub
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
-3
View File
@@ -61,9 +61,6 @@ jobs:
restore-keys: |
${{ runner.os }}-buildx-e2e-
- name: Test APT mirror fallback
run: python3 test_apt_install.py
- name: Install dependencies
run: |
sudo rm -f /etc/apt/sources.list.d/azure-cli.list /etc/apt/sources.list.d/microsoft-prod.list
+1 -69
View File
@@ -37,13 +37,6 @@ jobs:
with:
version: v3.18.4
- uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Test vector chart resources
run: go test ./k8s/charts/seaweedfs/tests -count=1
- uses: actions/setup-python@v7
with:
python-version: '3.10'
@@ -1328,67 +1321,6 @@ jobs:
echo "$BOOL_FALSE" | grep -q -- '-status Suspended' || { echo "FAIL: bool false versioning did not Suspend the bucket"; exit 1; }
echo "Bucket versioning: YAML bool false suspends consistently with string \"false\""
echo "=== Testing bucket ttl, replication and disk in one fs.configure ==="
FS_CONFIGURE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=cfgbucket \
--set s3.createBuckets[0].ttl=7d \
--set-string s3.createBuckets[0].replication=001 \
--set s3.createBuckets[0].disk=ssd | grep 'fs.configure -locationPrefix=/buckets/cfgbucket/' || true)
echo "$FS_CONFIGURE" | grep -q -- '-ttl=7d -replication=001 -disk=ssd -apply' || { echo "FAIL: bucket fs.configure missing ttl/replication/disk: $FS_CONFIGURE"; exit 1; }
echo "Bucket fs.configure: ttl, replication and disk render together"
FS_CONFIGURE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=replbucket \
--set-string s3.createBuckets[0].replication=002 | grep 'fs.configure -locationPrefix=/buckets/replbucket/' || true)
echo "$FS_CONFIGURE" | grep -q -- '/buckets/replbucket/ -replication=002 -apply' || { echo "FAIL: replication-only bucket did not render fs.configure: $FS_CONFIGURE"; exit 1; }
echo "Bucket fs.configure: replication without ttl"
FS_CONFIGURE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=diskbucket \
--set s3.createBuckets[0].disk=ssd | grep 'fs.configure -locationPrefix=/buckets/diskbucket/' || true)
echo "$FS_CONFIGURE" | grep -q -- '/buckets/diskbucket/ -disk=ssd -apply' || { echo "FAIL: disk-only bucket did not render fs.configure: $FS_CONFIGURE"; exit 1; }
echo "Bucket fs.configure: disk without ttl"
if helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=numbucket \
--set s3.createBuckets[0].replication=0 >/dev/null 2>&1; then
echo "FAIL: a numeric replication should fail to render"; exit 1
fi
echo "Bucket fs.configure: numeric replication is rejected"
if helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=badbucket \
--set-string s3.createBuckets[0].replication=00O >/dev/null 2>&1; then
echo "FAIL: a non-digit replication should fail to render"; exit 1
fi
echo "Bucket fs.configure: non-digit replication is rejected"
if helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=bigbucket \
--set-string s3.createBuckets[0].replication=256 >/dev/null 2>&1; then
echo "FAIL: a replication above 255 should fail to render"; exit 1
fi
FS_CONFIGURE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=maxbucket \
--set-string s3.createBuckets[0].replication=255 | grep 'fs.configure -locationPrefix=/buckets/maxbucket/' || true)
echo "$FS_CONFIGURE" | grep -q -- '/buckets/maxbucket/ -replication=255 -apply' || { echo "FAIL: replication 255 should render: $FS_CONFIGURE"; exit 1; }
echo "Bucket fs.configure: replication is limited to 000-255"
FS_CONFIGURE=$(helm template test $CHART_DIR \
--set s3.enabled=true \
--set s3.createBuckets[0].name=nullbucket \
--set s3.createBuckets[0].ttl=7d \
--set s3.createBuckets[0].replication=null | grep 'fs.configure -locationPrefix=/buckets/nullbucket/' || true)
echo "$FS_CONFIGURE" | grep -q -- '/buckets/nullbucket/ -ttl=7d -apply' || { echo "FAIL: null replication should be treated as unset: $FS_CONFIGURE"; exit 1; }
echo "Bucket fs.configure: null replication is unset"
echo ""
echo "=== Testing hook Job labels ==="
# The hook Jobs were the only pods in the chart without the standard
@@ -2199,7 +2131,7 @@ jobs:
echo "IMAGE_TAG=$TAG" >> $GITHUB_ENV
- name: Create kind cluster
uses: helm/kind-action@v1.15.2
uses: helm/kind-action@v1.15.1
- name: Verify volume resize hook security contexts
run: |
-135
View File
@@ -1,135 +0,0 @@
name: "rust: vector desktop platforms"
on:
pull_request:
paths:
- 'seaweed-vector/**'
- 'seaweed-worker/**'
- 'seaweed-common/**'
- 'weed/pb/**'
- '.github/workflows/rust-vector-platforms.yml'
- 'install.sh'
- 'test/installer/**'
push:
tags: ['*']
workflow_dispatch:
permissions:
contents: read
concurrency:
group: vector-platforms-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
vector:
permissions:
contents: read
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15-intel
suffix: darwin_amd64
protoc: macos-x86_64
- runner: macos-latest
suffix: darwin_arm64
protoc: macos-aarch_64
- runner: windows-latest
suffix: windows_amd64
protoc: win32
runs-on: ${{ matrix.runner }}
timeout-minutes: 120
env:
CARGO_BUILD_JOBS: '2'
CARGO_PROFILE_TEST_DEBUG: '0'
SEAWEEDFS_COMMIT: ${{ github.sha }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- uses: actions/cache/restore@v6
id: cargo-cache
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-vector/target
key: vector-${{ matrix.suffix }}-${{ hashFiles('seaweed-vector/Cargo.lock') }}
restore-keys: vector-${{ matrix.suffix }}-
- name: Fetch dependencies
run: cargo fetch --locked --manifest-path seaweed-vector/Cargo.toml
- name: Select vendored protoc
env:
PROTOC_PACKAGE: protoc-bin-vendored-${{ matrix.protoc }}
run: |
python - <<'PY'
import os, pathlib, tomllib
lock=tomllib.loads(pathlib.Path('seaweed-vector/Cargo.lock').read_text())
name=os.environ['PROTOC_PACKAGE']
version=next(p['version'] for p in lock['package'] if p['name']==name)
cargo=pathlib.Path(os.environ.get('CARGO_HOME',pathlib.Path.home()/'.cargo'))
executable='protoc.exe' if os.name=='nt' else 'protoc'
path=next(cargo.glob(f'registry/src/*/{name}-{version}/bin/{executable}'))
with open(os.environ['GITHUB_ENV'],'a') as out: out.write(f'PROTOC={path}\n')
PY
- name: Build vector engine
id: cargo-build
run: cargo build --locked --release --manifest-path seaweed-vector/Cargo.toml -p weed-vector-server
- name: Test vector crates
run: cargo test --locked --release --manifest-path seaweed-vector/Cargo.toml --workspace
- name: Test installer
run: |
if [ "$RUNNER_OS" = "Windows" ]; then
BASH_BINARY="$(cygpath -w "$BASH")"
export BASH_BINARY
fi
python -m unittest discover -s test/installer
- name: Save compiled dependencies
if: ${{ always() && !startsWith(github.ref, 'refs/tags/') && steps.cargo-build.outcome == 'success' && steps.cargo-cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-vector/target
key: vector-${{ matrix.suffix }}-${{ hashFiles('seaweed-vector/Cargo.lock') }}
- name: Package engine
env:
ASSET_SUFFIX: ${{ matrix.suffix }}
run: |
python - <<'PY'
import hashlib, os, pathlib, tarfile, zipfile
suffix=os.environ['ASSET_SUFFIX']
binary='weed-vector.exe' if os.name=='nt' else 'weed-vector'
source=pathlib.Path('seaweed-vector/target/release')/binary
asset=f'weed-vector_{suffix}'+('.zip' if os.name=='nt' else '.tar.gz')
if os.name=='nt':
with zipfile.ZipFile(asset,'w',zipfile.ZIP_DEFLATED) as archive: archive.write(source,binary)
else:
with tarfile.open(asset,'w:gz') as archive: archive.add(source,arcname=binary)
digest=hashlib.md5(pathlib.Path(asset).read_bytes()).hexdigest()
pathlib.Path(asset+'.md5').write_text(f'{digest} {asset}\n')
PY
- uses: actions/upload-artifact@v7
with:
name: vector-${{ matrix.suffix }}
path: weed-vector_${{ matrix.suffix }}.*
release:
if: startsWith(github.ref, 'refs/tags/')
needs: vector
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v8
with:
pattern: vector-*
merge-multiple: true
- uses: softprops/action-gh-release@v3
with:
files: weed-vector_*
+4 -24
View File
@@ -76,32 +76,25 @@ jobs:
vectors-e2e:
name: S3 Vectors Integration (${{ matrix.volume }} volume${{ matrix.hardened && ', hardened' || '' }}${{ matrix.worker && ', worker' || '' }})
name: S3 Vectors Integration (${{ matrix.volume }} volume${{ matrix.hardened && ', hardened' || '' }})
runs-on: ubuntu-24.04
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
volume: [go, rust]
# Hardened: volume servers behind mutual TLS, every gRPC hop (master,
# volume, filer, gateway, engine) under mutual TLS, read JWTs
# required, and every chunk encrypted by the gateway.
# Hardened: volume servers behind mutual TLS, read JWTs required,
# and every chunk encrypted by the gateway.
hardened: ["", "1"]
worker: ["", "1"]
# Worker: the admin server and the Lance maintenance worker join the
# cluster, for the tests that build vector indexes through a job.
env:
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_BUILD_JOBS: "2"
CARGO_TARGET_DIR: ${{ github.workspace }}/seaweed-vector/target
VOLUME_SERVER_IMPL: ${{ matrix.volume }}
VECTOR_QUERY_MODE: single
VECTOR_FILER_GROUP: vectors-ci
VECTOR_TLS: ${{ matrix.hardened }}
VECTOR_READ_JWT: ${{ matrix.hardened }}
VECTOR_ENCRYPT_VOLUMES: ${{ matrix.hardened }}
VECTOR_WORKER: ${{ matrix.worker }}
steps:
- uses: actions/checkout@v7
with:
@@ -129,18 +122,6 @@ jobs:
run: |
go test ./weed/s3api/s3vectors -count=1
go test ./weed/command -run 'Vector|Vectors' -count=1
# The worker workspace has no protoc of its own for lance's build
# scripts; use the vendored one its lock names, as its own workflow does.
- name: Use the vendored protoc for the worker
if: matrix.worker == '1'
run: |
cd seaweed-worker
cargo fetch --locked
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build integration binaries
working-directory: test/s3vectors
# dev profile: correctness suite, no release codegen needed. weed-volume
@@ -149,7 +130,6 @@ jobs:
set -e
make ./weed ./weed-vector CARGO_PROFILE=dev
if [ "${{ matrix.volume }}" = "rust" ]; then make ./weed-volume CARGO_PROFILE=dev; fi
if [ "${{ matrix.worker }}" = "1" ]; then make ./weed-vector-cli ./weed-worker CARGO_PROFILE=dev; fi
- uses: actions/setup-python@v7
with:
python-version: "3.12"
@@ -173,7 +153,7 @@ jobs:
if: always()
uses: actions/upload-artifact@v7
with:
name: vectors-e2e-diagnostics-${{ matrix.volume }}${{ matrix.hardened && '-hardened' || '' }}${{ matrix.worker && '-worker' || '' }}
name: vectors-e2e-diagnostics-${{ matrix.volume }}${{ matrix.hardened && '-hardened' || '' }}
path: |
${{ runner.temp }}/vector-tests
${{ runner.temp }}/vector-results.xml
+1 -2
View File
@@ -147,7 +147,6 @@ telemetry/server/telemetry-server
__pycache__/
/test/s3vectors/weed
/test/s3vectors/weed-vector
/test/s3vectors/weed-vector-cli
/test/s3vectors/weed-worker
/test/s3vectors/weed-vector-worker
/test/s3vectors/weed-volume
.pytest_cache/
+3 -41
View File
@@ -17,9 +17,7 @@ SeaweedFS is a simple and highly scalable distributed file system. There are two
1. to store billions of files!
2. to serve the files fast!
One SeaweedFS cluster serves an S3 object store, a POSIX file system, a lakehouse with S3 Tables and a built-in Iceberg REST Catalog, and [vector search with S3 Vector Buckets](#vector-search-with-s3-vector-buckets), all on shared storage. Each blob is one disk read away, capacity grows by starting another volume server, and cloud storage can be cached or tiered transparently. Blob reads and writes have O(1) complexity and can run at the full speed supported by the underlying hardware.
![SeaweedFS feature overview: S3 objects, POSIX files, table buckets with an Iceberg REST Catalog and Lance namespace, and S3 Vector Buckets share one cluster of masters, filers, and volume servers, with cloud caching, tiering, and cross-cluster replication.](note/seaweedfs-features.svg)
One `weed` binary serves an S3 object store, a POSIX file system, and a lakehouse with S3 Tables, all over the same data. Each blob is one disk read away, capacity grows by starting another volume server, and cloud storage can be cached or tiered transparently. Both read and write operations have O(1) complexity and can run at the full speed supported by the underlying hardware.
- [Download Binaries for different platforms](https://github.com/seaweedfs/seaweedfs/releases/latest)
- [Wiki Documentation](https://github.com/seaweedfs/seaweedfs/wiki)
@@ -42,7 +40,6 @@ Table of Contents
* [Scalable](#scalable)
* [The most complete S3 API](#the-most-complete-s3-api)
* [A data warehouse with S3 Tables](#a-data-warehouse-with-s3-tables)
* [Vector search with S3 Vector Buckets](#vector-search-with-s3-vector-buckets)
* [A fast cache for cloud storage](#a-fast-cache-for-cloud-storage)
* [Active-active replication and more](#active-active-replication-and-more)
* [Architecture](#architecture)
@@ -207,13 +204,12 @@ On one laptop, [`weed benchmark`][Benchmarks] writes 1KB files at 15,700 per sec
## The most complete S3 API ##
The S3 gateway implements the object, bucket, S3 Tables, S3 Vectors, IAM, and STS APIs on one endpoint, so the AWS SDKs and CLI, rclone, restic, Spark, and Trino work unchanged. S3 Vectors uses the `weed-vector` service described [below](#vector-search-with-s3-vector-buckets).
The S3 gateway implements the object, bucket, S3 Tables, IAM, and STS APIs on one endpoint, so the AWS SDKs and CLI, rclone, restic, Spark, and Trino work unchanged.
| API | Operations |
| --- | --- |
| S3 bucket and object | 73 |
| S3 Tables | 36 |
| S3 Vectors | 19 |
| IAM | 39 |
| STS | 5 |
@@ -227,7 +223,7 @@ The full operation list is in [Amazon S3 API][AmazonS3API], and [Supported APIs
## A data warehouse with S3 Tables ##
SeaweedFS is a lakehouse in one system. [S3 Table Buckets][S3TableBucket] hold Apache Iceberg tables by default, or [Lance][LanceCatalog] tables for vectors and multimodal data, and the built-in [Iceberg REST Catalog][IcebergCatalog] and Lance namespace serve them directly. The S3 Tables API and Iceberg REST Catalog share the same namespaces, table metadata, and permissions. There is no Hive Metastore, Glue, or separate catalog service to deploy, secure, and back up.
SeaweedFS is a lakehouse in one system. [S3 Table Buckets][S3TableBucket] hold Apache Iceberg tables by default, or [Lance][LanceCatalog] tables for vectors and multimodal data, and the built-in [Iceberg REST Catalog][IcebergCatalog] and Lance namespace serve them directly. There is no Hive Metastore, Glue, or separate catalog service to deploy, secure, and back up.
* Query engines operate on the same tables at the same time: [Spark][SparkIceberg], [Trino][TrinoIceberg], [Dremio][DremioIceberg], [DuckDB][DuckDBIceberg], [Apache Doris][DorisIceberg], [RisingWave][RisingWaveIceberg], ClickHouse, and [LanceDB][LanceDB]. Catalog commits are atomic compare-and-swap, so concurrent writers are safe. [Lakekeeper][Lakekeeper] can front the same storage with STS-vended credentials. [OLake Go][OLake] is a high-performance, open-source EL (Extract–Load) platform that bridges operational databases and open lakehouse storage - writing Apache Iceberg tables or Parquet files on Amazon S3.
* [Automated table maintenance][IcebergMaintenance]: compaction, snapshot expiration, orphan file removal, and manifest rewriting, configured per bucket or table through the S3 Tables maintenance APIs, and the same for [Lance][LanceMaintenance].
@@ -236,40 +232,6 @@ SeaweedFS is a lakehouse in one system. [S3 Table Buckets][S3TableBucket] hold A
`S3_TABLE_BUCKET=warehouse ./weed mini -dir=./data` brings the whole stack up on a laptop.
## Vector search with S3 Vector Buckets ##
Keep embeddings alongside your objects and tables in the same SeaweedFS cluster. S3 Vector Buckets expose the AWS S3 Vectors API for semantic search, retrieval-augmented generation (RAG), and recommendations, using Lance tables on SeaweedFS storage.
* Create vector buckets and indexes; insert, retrieve, list, and delete vectors with the AWS SDKs or CLI pointed at your S3 endpoint.
* Find the nearest vectors with cosine or Euclidean distance, filter by metadata, and return distances and metadata with the results.
* Control access with `s3vectors:*` IAM actions and vector bucket policies; tag buckets and indexes for organization and access control.
Install the separate vector engine; the default installer installs only `weed`:
```bash
curl -fsSL https://raw.githubusercontent.com/seaweedfs/seaweedfs/master/install.sh | bash -s -- --component vector
```
Release 4.53 provides vector binaries for Linux amd64 and arm64. If your release has no binary for your platform, build from [source](seaweed-vector). From a directory where you want a new checkout:
```bash
git clone https://github.com/seaweedfs/seaweedfs.git
cd seaweedfs
(cd seaweed-vector && cargo build --release -p weed-vector-server)
```
If you already have a checkout, start at its root and skip the clone and `cd seaweedfs` steps.
For Windows source builds, set `PROTOC` to a native `protoc.exe` before running Cargo; the [desktop build workflow](.github/workflows/rust-vector-platforms.yml) shows how to select the vendored executable.
Run the installed `weed-vector` binary alongside the local cluster started with `weed mini` above (or use `seaweed-vector/target/release/weed-vector` after building from source):
```bash
weed-vector --masters=localhost:9333
```
It registers with the master and the S3 gateway discovers it automatically. An AWS S3 Vectors client uses the same S3 endpoint at http://localhost:8333. The vector engine stores its data through the cluster's filers and volume servers, so embeddings share the storage layer's replication and erasure coding. See the [AWS SDK examples](test/s3vectors/s3vectors_test.py) for bucket, index, and query operations.
## A fast cache for cloud storage ##
[Cloud Drive][CloudDrive] mounts a bucket from S3, Google Cloud Storage, Azure, Backblaze B2, Wasabi, Storj, or any S3-compatible store into SeaweedFS and serves it at local speed:
-4
View File
@@ -271,10 +271,6 @@ curl "http://localhost:9333/vol/vacuum?garbageThreshold=0.4"
Vacuuming makes a volume read-only, copies live needles to a new volume, and
swaps it in.
The master runs one vacuum at a time. A request that arrives while the
automatic vacuum or another request is running does nothing and gets
`409 Conflict` with `{"error":"another vacuum is running, try again later"}`.
### Delete a collection
```bash
+10 -8
View File
@@ -3,15 +3,17 @@
# unreachable. See docker/Dockerfile.e2e.
set -e
# Every rewrite starts from the pristine list, so a mirror that just failed does
# not become the pattern the next rewrite has to match.
[ -f /etc/apt/sources.list.orig ] || cp /etc/apt/sources.list /etc/apt/sources.list.orig
for mirror in azure.archive.ubuntu.com archive.ubuntu.com; do
for apt_source in /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do
[ -f "$apt_source" ] || continue
[ -f "$apt_source.orig" ] || cp "$apt_source" "$apt_source.orig"
sed -E "s|(https?://)[a-z0-9.]*archive\.ubuntu\.com/ubuntu|\1$mirror/ubuntu|g; s|(https?://)security\.ubuntu\.com/ubuntu|\1$mirror/ubuntu|g" \
"$apt_source.orig" > "$apt_source"
done
if timeout --kill-after=5s 120s apt-get -o Acquire::Retries=1 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 -o APT::Update::Error-Mode=any update && \
DEBIAN_FRONTEND=noninteractive timeout --kill-after=5s 180s apt-get -o Acquire::Retries=1 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 install -y \
# Any archive host, so this works whether the pristine list came from the
# base image (archive.ubuntu.com) or a CI runner (azure.archive.ubuntu.com).
sed "s|http://[a-z0-9.]*archive\.ubuntu\.com/ubuntu|http://$mirror/ubuntu|g; s|http://security\.ubuntu\.com/ubuntu|http://$mirror/ubuntu|g" \
/etc/apt/sources.list.orig > /etc/apt/sources.list
if apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 update && \
DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 install -y \
--no-install-recommends --no-install-suggests "$@"; then
apt-get clean
rm -rf /var/lib/apt/lists/*
+8 -8
View File
@@ -64,7 +64,7 @@ case "$1" in
'master')
ARGS="-mdir=/data -volumeSizeLimitMB=1024"
shift
exec /usr/bin/weed -logtostderr=true master $ARGS "$@"
exec /usr/bin/weed -logtostderr=true master $ARGS $@
;;
'volume')
@@ -73,7 +73,7 @@ case "$1" in
ARGS="-dir=/data"
fi
shift
exec /usr/bin/weed -logtostderr=true volume $ARGS "$@"
exec /usr/bin/weed -logtostderr=true volume $ARGS $@
;;
'volume-rust')
@@ -87,7 +87,7 @@ case "$1" in
echo "Use 'volume' for the Go volume server instead." >&2
exit 1
fi
exec /usr/bin/weed-volume $ARGS "$@"
exec /usr/bin/weed-volume $ARGS $@
;;
'worker-rust')
@@ -119,7 +119,7 @@ case "$1" in
ARGS="-dir=/data -master.volumeSizeLimitMB=1024"
fi
shift
exec /usr/bin/weed -logtostderr=true server $ARGS "$@"
exec /usr/bin/weed -logtostderr=true server $ARGS $@
;;
'mini')
@@ -128,19 +128,19 @@ case "$1" in
ARGS=""
fi
shift
exec /usr/bin/weed -logtostderr=true mini $ARGS "$@"
exec /usr/bin/weed -logtostderr=true mini $ARGS $@
;;
'filer')
ARGS=""
shift
exec /usr/bin/weed -logtostderr=true filer $ARGS "$@"
exec /usr/bin/weed -logtostderr=true filer $ARGS $@
;;
's3')
ARGS="-domainName=$S3_DOMAIN_NAME -key.file=$S3_KEY_FILE -cert.file=$S3_CERT_FILE"
shift
exec /usr/bin/weed -logtostderr=true s3 $ARGS "$@"
exec /usr/bin/weed -logtostderr=true s3 $ARGS $@
;;
'shell')
@@ -150,6 +150,6 @@ case "$1" in
;;
*)
exec /usr/bin/weed "$@"
exec /usr/bin/weed $@
;;
esac
-39
View File
@@ -1,39 +0,0 @@
# Vector buckets locally
Run on Linux containers (amd64 or arm64):
```sh
docker compose up -d
export AWS_ACCESS_KEY_ID=vector-demo
export AWS_SECRET_ACCESS_KEY=vector-demo-secret
export AWS_DEFAULT_REGION=us-east-1
aws --endpoint-url http://localhost:8333 s3vectors create-index \
--vector-bucket-name embeddings --index-name images \
--data-type float32 --dimension 3 --distance-metric cosine
aws --endpoint-url http://localhost:8333 s3vectors put-vectors \
--vector-bucket-name embeddings --index-name images \
--vectors '[{"key":"first","data":{"float32":[1,0,0]}}]'
aws --endpoint-url http://localhost:8333 s3vectors query-vectors \
--vector-bucket-name embeddings --index-name images \
--query-vector '{"float32":[1,0,0]}' --top-k 1
```
The engine registers with the master. Wait for that registration before creating
an index. The Lance worker builds and refreshes ANN indexes as data grows;
queries can scan data before an ANN index is built. The demo's admin UI is at
http://localhost:12535 (user `admin`, password `vector-demo`). Demo credentials
and plaintext cluster connections are for this local example. Production
settings are in the Helm/operator TLS and authentication documentation.
`docker compose down` preserves the named data volume. Add `-v` to discard it.
Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
`vector:9329/metrics` inside the Compose network.
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
compatible engine. The child inherits the cluster's configuration directory and
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
provides `s3vectors -operation <Operation> -file request.json` for the same API
operations using trusted cluster credentials.
-34
View File
@@ -1,34 +0,0 @@
services:
seaweedfs:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
environment: &environment
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
AWS_ACCESS_KEY_ID: vector-demo
AWS_SECRET_ACCESS_KEY: vector-demo-secret
ports:
- "127.0.0.1:8333:8333"
- "127.0.0.1:12535:12535"
volumes:
- data:/data
healthcheck:
test: [CMD-SHELL, "wget -q -O /dev/null http://127.0.0.1:9333/cluster/status"]
interval: 5s
timeout: 3s
retries: 30
vector:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: vector --listen=vector:8090 --masters=seaweedfs:9333
environment: *environment
depends_on:
seaweedfs:
condition: service_healthy
worker:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: worker-rust --admin=seaweedfs:12535 --masters=seaweedfs:9333 --namespace=http://seaweedfs:9101
environment: *environment
depends_on:
seaweedfs:
condition: service_healthy
volumes:
data:
-110
View File
@@ -1,110 +0,0 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
class AptInstallTests(unittest.TestCase):
def run_helper(self, sources, fail_action="update", timeout_azure=False):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
apt = root / "apt"
(apt / "sources.list.d").mkdir(parents=True)
(apt / "sources.list").write_text("")
for name, content in sources.items():
(apt / name).write_text(content)
helper = root / "apt-install"
helper.write_text(Path(__file__).with_name("apt-install").read_text()
.replace("/etc/apt", str(apt))
.replace("/var/lib/apt", str(root / "state")))
commands = root / "bin"
commands.mkdir()
fake_apt = commands / "apt-get"
fake_apt.write_text(r"""#!/usr/bin/env python3
import json, os, pathlib, sys
root = pathlib.Path(os.environ["VECTOR_APT_TEST_ROOT"])
apt = root / "apt"
sources = [apt / "sources.list", *apt.glob("sources.list.d/*.list"), *apt.glob("sources.list.d/*.sources")]
content = "".join(p.read_text() for p in sources)
action = next(a for a in sys.argv[1:] if a in ("update", "install", "clean"))
with (root / "calls").open("a") as output:
output.write(json.dumps({"action": action, "sources": content, "args": sys.argv[1:]}) + "\n")
if "azure.archive.ubuntu.com" in content and action == "update" and os.environ["VECTOR_APT_FAIL_ACTION"] == "partial":
sys.exit(100 if "APT::Update::Error-Mode=any" in sys.argv else 0)
if "azure.archive.ubuntu.com" in content and action == os.environ["VECTOR_APT_FAIL_ACTION"]:
sys.exit(100)
""")
fake_apt.chmod(0o755)
fake_timeout = commands / "timeout"
fake_timeout.write_text(r"""#!/usr/bin/env python3
import json, os, pathlib, sys
root = pathlib.Path(os.environ["VECTOR_APT_TEST_ROOT"])
apt = root / "apt"
sources = [apt / "sources.list", *apt.glob("sources.list.d/*.list"), *apt.glob("sources.list.d/*.sources")]
content = "".join(p.read_text() for p in sources)
with (root / "calls").open("a") as output:
output.write(json.dumps({"action": "timeout", "args": sys.argv[1:]}) + "\n")
if os.environ["VECTOR_APT_TIMEOUT_AZURE"] and "azure.archive.ubuntu.com" in content:
sys.exit(124)
os.execvp(sys.argv[3], sys.argv[3:])
""")
fake_timeout.chmod(0o755)
result = subprocess.run(["/bin/sh", str(helper), "fuse"],
env={**os.environ, "PATH": str(commands) + os.pathsep + os.environ["PATH"],
"VECTOR_APT_TEST_ROOT": str(root), "VECTOR_APT_FAIL_ACTION": fail_action,
"VECTOR_APT_TIMEOUT_AZURE": "1" if timeout_azure else ""},
text=True, capture_output=True, timeout=5)
calls = [json.loads(line) for line in (root / "calls").read_text().splitlines()] if (root / "calls").exists() else []
return result, calls
def test_fallback_rewrites_all_source_formats(self):
for protocol in ("http", "https"):
for layout in ("legacy", "deb822", "mixed"):
with self.subTest(protocol=protocol, layout=layout):
sources = {}
if layout in ("legacy", "mixed"):
sources["sources.list"] = f"deb {protocol}://azure.archive.ubuntu.com/ubuntu noble main\n"
if layout in ("deb822", "mixed"):
sources["sources.list.d/ubuntu.sources"] = f"Types: deb\nURIs: {protocol}://azure.archive.ubuntu.com/ubuntu\nSuites: noble\nComponents: main\n"
result, calls = self.run_helper(sources)
self.assertEqual(result.returncode, 0, result.stderr)
installs = [call for call in calls if call["action"] == "install"]
self.assertEqual(len(installs), 1)
self.assertNotIn("azure.archive.ubuntu.com", installs[0]["sources"])
self.assertIn(protocol + "://archive.ubuntu.com", installs[0]["sources"])
def test_install_failure_also_tries_the_next_mirror(self):
result, calls = self.run_helper({"sources.list.d/ubuntu.sources":
"Types: deb\nURIs: http://security.ubuntu.com/ubuntu\nSuites: noble-security\nComponents: main\n"},
fail_action="install")
self.assertEqual(result.returncode, 0, result.stderr)
installs = [call for call in calls if call["action"] == "install"]
self.assertEqual(len(installs), 2)
self.assertIn("azure.archive.ubuntu.com", installs[0]["sources"])
self.assertNotIn("azure.archive.ubuntu.com", installs[1]["sources"])
def test_partial_update_does_not_install_stale_indexes(self):
result, calls = self.run_helper({"sources.list": "deb http://azure.archive.ubuntu.com/ubuntu noble main\n"},
fail_action="partial")
self.assertEqual(result.returncode, 0, result.stderr)
installs = [call for call in calls if call["action"] == "install"]
self.assertEqual(len(installs), 1)
self.assertNotIn("azure.archive.ubuntu.com", installs[0]["sources"])
def test_timeout_advances_to_the_next_mirror(self):
result, calls = self.run_helper({"sources.list": "deb http://azure.archive.ubuntu.com/ubuntu noble main\n"},
fail_action="none", timeout_azure=True)
self.assertEqual(result.returncode, 0, result.stderr)
timeouts = [call for call in calls if call["action"] == "timeout"]
self.assertEqual(len(timeouts), 3)
for call in timeouts:
self.assertEqual(call["args"][0], "--kill-after=5s")
self.assertLessEqual(int(call["args"][1].removesuffix("s")), 180)
installs = [call for call in calls if call["action"] == "install"]
self.assertNotIn("azure.archive.ubuntu.com", installs[0]["sources"])
if __name__ == "__main__":
unittest.main()
+21 -20
View File
@@ -61,11 +61,11 @@ require (
github.com/prometheus/client_golang v1.24.1
github.com/prometheus/client_model v0.6.3
github.com/prometheus/common v0.71.0 // indirect
github.com/prometheus/procfs v0.23.0
github.com/prometheus/procfs v0.22.0
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/seaweedfs/goexif v1.0.3
github.com/seaweedfs/raft v1.2.4
github.com/seaweedfs/raft v1.2.3
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
@@ -84,7 +84,6 @@ require (
github.com/xdg-go/scram v1.2.0
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.etcd.io/etcd/api/v3 v3.7.1
go.etcd.io/etcd/client/v3 v3.7.1
go.mongodb.org/mongo-driver v1.17.9
go.opencensus.io v0.24.0 // indirect
@@ -94,7 +93,7 @@ require (
golang.org/x/crypto v0.58.0
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297
golang.org/x/image v0.46.0
golang.org/x/net v0.62.0
golang.org/x/net v0.61.0
golang.org/x/oauth2 v0.37.0
golang.org/x/sys v0.49.0
golang.org/x/text v0.43.0 // indirect
@@ -123,7 +122,8 @@ require (
github.com/apache/iceberg-go v0.7.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go-v2 v1.47.7
github.com/armon/go-metrics v0.4.1
github.com/aws/aws-sdk-go-v2 v1.47.5
github.com/aws/aws-sdk-go-v2/config v1.33.6
github.com/aws/aws-sdk-go-v2/credentials v1.20.6
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.1
@@ -134,7 +134,6 @@ require (
github.com/go-ldap/ldap/v3 v3.4.14
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
github.com/hashicorp/go-metrics v0.7.0
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/hashicorp/raft v1.8.0
github.com/hashicorp/raft-boltdb/v2 v2.4.2
@@ -151,10 +150,10 @@ require (
github.com/redis/go-redis/v9 v9.23.0
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/go-fuse/v2 v2.9.4
github.com/shirou/gopsutil/v4 v4.26.10
github.com/shirou/gopsutil/v4 v4.26.7
github.com/tarantool/go-option v1.1.0
github.com/tarantool/go-tarantool/v3 v3.0.2
github.com/testcontainers/testcontainers-go v0.45.0
github.com/testcontainers/testcontainers-go v0.44.0
github.com/tikv/client-go/v2 v2.0.7
github.com/twmb/avro v1.9.0
github.com/xeipuuv/gojsonschema v1.2.0
@@ -175,7 +174,7 @@ require (
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/FilenCloudDienste/filen-sdk-go v0.0.39 // indirect
github.com/ProtonMail/gopenpgp/v3 v3.4.1 // indirect
github.com/RoaringBitmap/roaring/v2 v2.26.0 // indirect
@@ -207,7 +206,7 @@ require (
github.com/dave/dst v0.27.2 // indirect
github.com/diskfs/go-diskfs v1.9.4 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.8.2 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dromara/dongle v1.0.1 // indirect
github.com/geoarrow/geoarrow-go v0.0.0-20260403143023-f54751c3e3a1 // indirect
@@ -236,11 +235,11 @@ require (
github.com/lib/pq v1.12.3 // indirect
github.com/lithammer/shortuuid/v3 v3.0.7 // indirect
github.com/lpar/calendar v0.2.0 // indirect
github.com/magiconair/properties v1.18.12 // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.3.3 // indirect
github.com/moby/moby/api v1.56.1 // indirect
github.com/moby/moby/client v0.6.2 // indirect
github.com/moby/go-archive v0.3.0 // indirect
github.com/moby/moby/api v1.55.0 // indirect
github.com/moby/moby/client v0.5.0 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.1 // indirect
@@ -283,7 +282,7 @@ require (
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/mock v0.5.2 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/mod v0.42.0 // indirect
gonum.org/v1/gonum v0.17.0 // indirect
)
@@ -296,7 +295,7 @@ require (
cloud.google.com/go/iam v1.14.0 // indirect
cloud.google.com/go/monitoring v1.30.0 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.2
@@ -335,7 +334,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.8
github.com/aws/smithy-go v1.28.7
github.com/boltdb/bolt v1.3.1 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
github.com/buengese/sgzip v0.1.1 // indirect
@@ -353,7 +352,7 @@ require (
github.com/d4l3k/messagediff v1.2.1 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.4.0 // indirect
github.com/ebitengine/purego v0.11.2 // indirect
github.com/ebitengine/purego v0.10.2 // indirect
github.com/elastic/gosigar v0.14.3 // indirect
github.com/emersion/go-message v0.18.2 // indirect
github.com/emersion/go-vcard v0.0.0-20260618161152-d854b7e0e2d3 // indirect
@@ -391,6 +390,7 @@ require (
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-metrics v0.7.0 // indirect
github.com/hashicorp/go-msgpack/v2 v2.1.5 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
@@ -442,7 +442,7 @@ require (
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
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect
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
github.com/rfjakob/eme v1.2.0 // indirect
@@ -480,6 +480,7 @@ require (
github.com/zeebo/blake3 v0.2.4 // indirect
github.com/zeebo/errs v1.4.0 // indirect
go.etcd.io/bbolt v1.5.0 // indirect
go.etcd.io/etcd/api/v3 v3.7.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.46.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect
@@ -494,7 +495,7 @@ require (
golang.org/x/term v0.47.0
golang.org/x/time v0.16.0
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b // 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
+36 -36
View File
@@ -34,8 +34,8 @@ filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
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.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3 h1:qgnWTiWs1G7AqcKZegFvkJD1bmXJcaDU3uC0ELSgZ5U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3/go.mod h1:XtxD48QPInqoj+GMlcRlXHEYsoOxFnP6w2JgIZ9rDS4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
@@ -54,8 +54,8 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 h1:cuiKf1UVyWHu+XSQg
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0/go.mod h1:9JSyvgXLPAOC4jfhgZg58XeU2FJHsGmxuYSclCFQ4ZY=
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 h1:X/bTwe0qpvmvPPutc+LWo7T4cKMqDP9JHP4k+Co9ZB4=
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0/go.mod h1:+kX7ahyFelQ42F3RScM2CFgHJljp0phc/FieKLYVpFI=
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 h1:m2xcjRABtG288vnlV3U/PKh/HnPURxZp50RKNUwBxM8=
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4/go.mod h1:MTUE7ZuZO89FAtAwozGg6AWD83pcdefnEq5gF82MB8s=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
@@ -173,8 +173,8 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
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.47.7 h1:jBmtzRtGWVAzbfc4RBWo1dTte0ZZH8p9U42YJIw2+Bw=
github.com/aws/aws-sdk-go-v2 v1.47.7/go.mod h1:I8lFSH4MGrZiw2m7miCrRYHsgpC1+HW8uiVGOiPYPcw=
github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4=
github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8=
github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug=
@@ -215,8 +215,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/S
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
github.com/aws/smithy-go v1.28.8 h1:aEmdAq7gVCoGCnvf1NnELlu3I6D/nhqrC321FyFiQkQ=
github.com/aws/smithy-go v1.28.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE=
github.com/aws/smithy-go v1.28.7/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=
@@ -389,8 +389,8 @@ github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaft
github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker-credential-helpers v0.9.8 h1:bIREROb7So6PRlq6KTtdS9MPEjC29OQRkFNlvK2OX8Q=
github.com/docker/docker-credential-helpers v0.9.8/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c=
github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc=
github.com/docker/go-connections v0.8.2/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dromara/dongle v1.0.1 h1:si/7UP/EXxnFVZok1cNos70GiMGxInAYMilHQFP5dJs=
@@ -407,8 +407,8 @@ github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4A
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3/go.mod h1:YvSRo5mw33fLEx1+DlK6L2VV43tJt5Eyel9n9XBcR+0=
github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc=
github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJtLmY22n99HaZTz+r2Z51xUPi01m3wg=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg=
github.com/elastic/gosigar v0.14.3 h1:xwkKwPia+hSfg9GqrCUKYdId102m9qTJIIr7egmK/uo=
@@ -827,8 +827,8 @@ github.com/lpar/calendar v0.2.0 h1:A1kxv6sbvBHFUkd2XotanIRqEXQGreQOeuGhkJqIaRA=
github.com/lpar/calendar v0.2.0/go.mod h1:fsVJa4o2NvXYzaCE5RXMadqbZzWEhNCGOUPVHTIZdjc=
github.com/lufia/plan9stats v0.0.0-20260627054121-477a66015f15 h1:YkjVPl/YH5XlJ+/NiwzJtPYXXKRcyjmEUhsDci6YK3c=
github.com/lufia/plan9stats v0.0.0-20260627054121-477a66015f15/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.18.12 h1:sT9zQpvTB3B4gzrX0tmZNTEaGyg8Zw55MFYRE32Mr9I=
github.com/magiconair/properties v1.18.12/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
@@ -865,22 +865,20 @@ github.com/moby/buildkit v0.31.1 h1:j3p55abBl4kiXXPZgYX+6zWgB2aefqHXoPown12fIzU=
github.com/moby/buildkit v0.31.1/go.mod h1:YM5iNEbNCc6L1Zt3YWFB/aXNLufvf4Rcu0DPlc9HwQg=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.3.3 h1:OxxR9paxsluYi+zDUEXTTaIxtkK3viymW+Ka7vRhhME=
github.com/moby/go-archive v0.3.3/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c=
github.com/moby/go-archive v0.3.0/go.mod h1:Npdv43fFqlhZW7Xo8fbm3ZMYFvAGNviUPqX21VERbcE=
github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg=
github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc=
github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c=
github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4=
github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc=
github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=
github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=
github.com/moby/sys/capability v0.4.0 h1:4D4mI6KlNtWMCM1Z/K0i7RV1FkX+DBDHKVJpCndZoHk=
github.com/moby/sys/capability v0.4.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I=
github.com/moby/sys/mount v0.3.5 h1:eS3fsZTjHaBihwjp4/+5Z3jxqLXYsbwxqpVSfFv3M00=
github.com/moby/sys/mount v0.3.5/go.mod h1:WUQDO+/uCiCIkIztx8SrwIDVn2dtMFRBebRhpDFT71M=
github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg=
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
@@ -963,6 +961,7 @@ github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZd
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
@@ -1016,8 +1015,8 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo=
github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s=
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 h1:jL3a8soXdzuTCcRnKhOmtcsVOObdDTFf4O2B403HPRU=
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/pquerna/cachecontrol v0.2.0 h1:vBXSNuE5MYP9IJ5kjsdo8uq+w41jSPgvba2DEnkRx9k=
github.com/pquerna/cachecontrol v0.2.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI=
github.com/pquerna/ffjson v0.0.0-20190930134022-aa0246cd15f7/go.mod h1:YARuvh7BUWHNhzDq2OM5tzR2RiCcN2D7sapiKyCel/M=
@@ -1041,8 +1040,8 @@ github.com/prometheus/common v0.71.0/go.mod h1:CLJ5H8TEsGX8bl31BdMkfhIZ+QmZ9tBPP
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 h1:Y258uzXU/potCYnQd1r6wlAnoMB68BiCkCcCnKx1SH8=
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8/go.mod h1:bSJjRokAHHOhA+XFxplld8w2R/dXLH7Z3BZ532vhFwU=
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
@@ -1106,8 +1105,8 @@ github.com/seaweedfs/go-fuse/v2 v2.9.4 h1:ACyloiuopdhRSjdLLeSWbsVaemMPskORaRF01T
github.com/seaweedfs/go-fuse/v2 v2.9.4/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/raft v1.2.4 h1:lEBQ9seDSGrJNs2WitMgfYpaDxLgh9qukm1IJTEV1hk=
github.com/seaweedfs/raft v1.2.4/go.mod h1:fgs/rAVEzjQ7e04XMzG3eJhwZZRmBW+2uRtjakeCGeU=
github.com/seaweedfs/raft v1.2.3 h1:/NMrdhztjx8ojeu+aAPa2GmuVShQXp8YwmNmsMPU63E=
github.com/seaweedfs/raft v1.2.3/go.mod h1:fgs/rAVEzjQ7e04XMzG3eJhwZZRmBW+2uRtjakeCGeU=
github.com/secure-systems-lab/go-securesystemslib v0.11.0 h1:iuCR9kcMFD4QurdKrGvPLoKZLv9YvwPYVr0473BdtFs=
github.com/secure-systems-lab/go-securesystemslib v0.11.0/go.mod h1:+PMOTjUGwHj2vcZ+TFKlb1tXRbrdWE1LYDT5i9JC80Q=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
@@ -1116,8 +1115,8 @@ github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shibumi/go-pathspec v1.3.0 h1:QUyMZhFo0Md5B8zV8x2tesohbb5kfbpTi9rBnKh5dkI=
github.com/shibumi/go-pathspec v1.3.0/go.mod h1:Xutfslp817l2I1cZvgcfeMQJG5QnU2lh5tVaaMCl3jE=
github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg=
github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk=
github.com/shirou/gopsutil/v4 v4.26.7 h1:IXzpHz/dkMRYAhKkOXr1HB6SuzWU3eoyyeWe7g3bNZc=
github.com/shirou/gopsutil/v4 v4.26.7/go.mod h1:5O9FjBiXoTDFatIWjZZosqj4pV0DRtLx598xGbBehzM=
github.com/sigstore/sigstore v1.10.8 h1:1Mgkxvkw4AXMfIP1DOjc6kw0GkUgA8pGVpveN/EfOq4=
github.com/sigstore/sigstore v1.10.8/go.mod h1:f9+B/4iaYimvUkySyb2mvc73n3RLqNn24grHZM/ET8M=
github.com/sigstore/sigstore-go v1.2.1 h1:YWP/rDbBaEBvtbkj6xtwsSj38ZCFEhTVVadNOXjVe3A=
@@ -1200,8 +1199,8 @@ github.com/tarantool/go-option v1.1.0 h1:ShoOhNsdL41sRpm4hXCRDjV8H0WzPkd4UnKhLKb
github.com/tarantool/go-option v1.1.0/go.mod h1:hMr9z2JXOWlgdCBpCPSL2nwp8718GKYvNBJ+ZuzJbCo=
github.com/tarantool/go-tarantool/v3 v3.0.2 h1:9ZtHllun80QX7KS9tqd3dXa+QAu2BfqFtX1ZWcNnaW8=
github.com/tarantool/go-tarantool/v3 v3.0.2/go.mod h1:TXxLWhUCgdxXFfelnTSkq+goKRTRj660zxq4/WXPe8k=
github.com/testcontainers/testcontainers-go v0.45.0 h1:ss9Stm9KDX6JLgGL4jr2fC5dwpabTbCBsRcGadBPR9k=
github.com/testcontainers/testcontainers-go v0.45.0/go.mod h1:VMJZ7M+qhgfEHWNbtjm596OyEOraULSTDaus/h0hmJI=
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
github.com/testcontainers/testcontainers-go/modules/compose v0.44.0 h1:8YcW51jhgpkkiRVe10Wj9TCBthJmoNpU2fK5WSf7TQ8=
github.com/testcontainers/testcontainers-go/modules/compose v0.44.0/go.mod h1:0du5YaH5n8Of4bDM/RwIt421Q14kvqrXZ0mB8EjuMoo=
github.com/the42/cartconvert v0.0.0-20131203171324-aae784c392b8 h1:I4DY8wLxJXCrMYzDM6lKCGc3IQwJX0PlTLsd3nQqI3c=
@@ -1423,8 +1422,8 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
gocloud.dev v0.47.0 h1:qN4/0vtutn97f1X5ziisf3WXuaFL9AR0FIRnyJRYzgA=
@@ -1499,8 +1498,8 @@ golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
@@ -1542,6 +1541,7 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+18 -14
View File
@@ -157,20 +157,12 @@ worker_asset_name() {
echo "weed-worker_${os}_${arch}.tar.gz"
}
# The vector engine behind the S3 Vectors API, published for linux only like
# the worker.
# The vector engine behind the S3 Vectors API, built like the worker.
vector_asset_name() {
local os="$1" arch="$2"
echo "weed-vector_${os}_${arch}.tar.gz"
}
vector_platform_supported() {
case "$1/$2" in
linux/amd64|linux/arm64) return 0 ;;
*) return 1 ;;
esac
}
# Install a single component
install_component() {
local component="$1" os="$2" arch="$3"
@@ -280,7 +272,15 @@ install_component() {
;;
vector)
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}. Supported: linux/amd64, linux/arm64"
# Published for linux amd64/arm64 only, like the worker.
case "$os" in
linux) ;;
*) error "The vector engine is not available for ${os}. Supported: linux" ;;
esac
case "$arch" in
amd64|arm64) ;;
*) error "The vector engine is not available for ${arch}. Supported: amd64, arm64" ;;
esac
asset_name="$(vector_asset_name "$os" "$arch")"
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
@@ -288,11 +288,15 @@ install_component() {
info "Extracting ${asset_name}..."
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
local vector_bin
vector_bin="$(find "$tmpdir" -name weed-vector -type f | head -1)"
[ -n "$vector_bin" ] || error "Could not find weed-vector binary in archive"
vector_bin="$(find "$tmpdir" -name 'weed-vector' -type f | head -1)"
if [ -z "$vector_bin" ]; then
error "Could not find weed-vector binary in archive"
fi
chmod +x "$vector_bin"
install_binary "$vector_bin" weed-vector
install_binary "$vector_bin" "weed-vector"
VECTOR_INSTALLED=true
ok "Installed weed-vector to ${INSTALL_DIR}/weed-vector"
;;
@@ -360,7 +364,7 @@ main() {
else
install_component "worker-rust" "$os" "$arch"
fi
if ! vector_platform_supported "$os" "$arch"; then
if [ "$os" != "linux" ] || { [ "$arch" != "amd64" ] && [ "$arch" != "arm64" ]; }; then
warn "Skipping the vector engine: no build for ${os}/${arch}"
elif ! asset_exists "https://github.com/${REPO}/releases/download/${VERSION}/$(vector_asset_name "$os" "$arch")"; then
warn "Skipping the vector engine: ${VERSION} does not carry one"
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.53"
appVersion: "4.52"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.53.1
version: 4.52.0
-44
View File
@@ -687,47 +687,3 @@ generates a new UUID and the license stops matching. See
[Master data](#master-data-hostpath-vs-a-claim). Check the binding with
`kubectl exec <master-pod> -- curl -s localhost:9333/license/status`
(`cluster_uuid` must equal `license_uuid`).
## Vector buckets
The S3 gateway serves the S3 Vectors API on its existing endpoint. Enable a vector engine and Lance maintenance worker alongside the cluster:
```yaml
s3:
enabled: true
vector:
enabled: true
replicas: 1
worker:
enabled: true
admin:
enabled: true
secret:
adminPassword: change-me
global:
seaweedfs:
securityConfig:
jwtSigning:
filerWrite: true
```
The engine registers its pod address with the masters and stores indexes through the filers and volume servers. Both Go and Rust volume servers use the same setup. The maintenance worker builds and updates ANN indexes; queries can scan data before indexing completes. Enabling filer write signing also requires clients writing directly to the filer HTTP API to supply a signed JWT.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The cache defaults to 512 MiB and is configured with `vector.readCacheMB`.
`global.seaweedfs.enableSecurity` provisions and mounts the vector certificate and shared security configuration. With external certificates, provide the `<fullname>-vector-cert` secret (`my-seaweedfs-vector-cert` for release `my`). `fullname` follows `seaweedfs.fullname`, including `fullnameOverride`, `nameOverride`, and DNS-name truncation. Provide this secret alongside the existing CA and client secrets.
The default `vector.metricsPort: 0` and TCP probes support existing engine images. The default 4.53 image does not accept metrics flags; enabling metrics with it is rejected at render time. For engine builds with `/metrics`, `/health`, and `/ready`, set `vector.imageOverride` to that compatible image and `vector.metricsPort: 9329`; readiness then checks master registration. Enabling `global.seaweedfs.monitoring.enabled` also creates the vector ServiceMonitor. NetworkPolicy includes the configured gRPC and metrics ports.
To provision vector buckets during installation and upgrades, set:
```yaml
vector:
enabled: true
createBuckets:
- embeddings
```
The hook uses the AWS CLI's S3 Vectors API and works with existing SeaweedFS vector releases. It creates missing buckets, preserves existing vector buckets, and fails if the name belongs to an Iceberg bucket. It uses the chart's generated S3 admin credentials, including `s3.credentials.admin.existingSecret`. With a custom `s3.existingConfigSecret` or an external endpoint, set `vector.bucketHook.credentialsSecret` to a Secret containing `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (and optionally `AWS_SESSION_TOKEN`). Key names are configurable. `vector.bucketHook.endpoint` overrides the internal S3 service URL; `caBundleSecret` and `caBundleKey` configure a private HTTPS CA. The hook image and resource limits are configurable under `vector.bucketHook`. For restricted Pod Security, select a non-root-compatible image and configure `vector.bucketHook.podSecurityContext` and `containerSecurityContext`, including `runAsNonRoot` and the image user ID.
@@ -3951,970 +3951,6 @@
],
"title": "Filer Object Size Distribution",
"type": "bargauge"
},
{
"type": "row",
"title": "S3 Vectors",
"collapsed": true,
"id": 95,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 139
},
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "reqps",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 140
},
"id": 96,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (type, bucket) (rate(SeaweedFS_s3_request_total{namespace=~\"$NAMESPACE\",type=~\"s3vectors\\\\..*\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{type}} {{bucket}}"
}
],
"title": "Vector API requests by bucket",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "s",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 140
},
"id": 97,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.95, sum by (le, bucket) (rate(SeaweedFS_s3_request_seconds_bucket{namespace=~\"$NAMESPACE\",type=\"s3vectors.QueryVectors\"}[$__rate_interval])))",
"range": true,
"refId": "A",
"legendFormat": "{{bucket}}"
}
],
"title": "Vector query p95 latency",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "reqps",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 148
},
"id": 98,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (type, code) (rate(SeaweedFS_s3_request_total{namespace=~\"$NAMESPACE\",type=~\"s3vectors\\\\..*\",code=~\"[45]..\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{type}} {{code}}"
}
],
"title": "Vector API errors",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "short",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 148
},
"id": 99,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "last_over_time(SeaweedFS_vector_connected{namespace=~\"$NAMESPACE\"}[5m]) * on (cluster, namespace, instance, job) up{namespace=~\"$NAMESPACE\"}",
"range": true,
"refId": "A",
"legendFormat": "{{instance}}"
}
],
"title": "Registered vector engines",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "reqps",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 156
},
"id": 100,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (type, code) (rate(SeaweedFS_vector_request_total{namespace=~\"$NAMESPACE\",code!=\"OK\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{type}} {{code}}"
}
],
"title": "Vector engine request failures",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "short",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 156
},
"id": 101,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (type) (SeaweedFS_vector_in_flight_requests{namespace=~\"$NAMESPACE\"})",
"range": true,
"refId": "A",
"legendFormat": "{{type}}"
}
],
"title": "Vector engine requests in flight",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "percentunit",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 164
},
"id": 102,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "(sum by (cluster, namespace, job, instance) (rate(SeaweedFS_vector_cache_requests_total{namespace=~\"$NAMESPACE\",result=\"hit\"}[$__rate_interval])) or on (cluster, namespace, job, instance) (0 * sum by (cluster, namespace, job, instance) (rate(SeaweedFS_vector_cache_requests_total{namespace=~\"$NAMESPACE\"}[$__rate_interval])))) / sum by (cluster, namespace, job, instance) (rate(SeaweedFS_vector_cache_requests_total{namespace=~\"$NAMESPACE\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{cluster}} {{namespace}} {{instance}}"
}
],
"title": "Vector cache hit ratio",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "bytes",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 164
},
"id": 103,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "SeaweedFS_vector_cache_bytes{namespace=~\"$NAMESPACE\"}",
"range": true,
"refId": "A",
"legendFormat": "{{instance}}"
}
],
"title": "Vector cache memory",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "Bps",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 172
},
"id": 104,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "rate(SeaweedFS_vector_storage_read_bytes_total{namespace=~\"$NAMESPACE\"}[$__rate_interval])",
"range": true,
"refId": "A",
"legendFormat": "{{instance}}"
}
],
"title": "Vector storage read bandwidth",
"type": "timeseries"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"description": "Vector engine metrics require HTTP metrics to be enabled. Gateway bucket labels require vector bucket attribution.",
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
},
"unit": "ops",
"unitScale": true
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 172
},
"id": 105,
"links": [],
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "single",
"sort": "none"
}
},
"pluginVersion": "8.1.2",
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance) (rate(SeaweedFS_worker_lance_vector_indexes_built_total{namespace=~\"$NAMESPACE\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{instance}}"
}
],
"title": "Vector index maintenance builds",
"type": "timeseries"
}
]
}
],
"refresh": "",
@@ -5003,6 +4039,6 @@
"timezone": "browser",
"title": "SeaweedFS",
"uid": "a24009d7-cbda-4443-a132-1cc1c4677304",
"version": 2,
"version": 1,
"weekStart": ""
}
@@ -1,50 +0,0 @@
{{- include "seaweedfs.compat" . -}}
{{- if and .Values.vector.enabled .Values.global.seaweedfs.enableSecurity (not .Values.certificates.externalCertificates.enabled)}}
apiVersion: cert-manager.io/v1{{ if .Values.global.seaweedfs.certificates.alphacrds }}alpha1{{ end }}
kind: Certificate
metadata:
name: {{ include "seaweedfs.fullname" . }}-vector-cert
namespace: {{ include "seaweedfs.namespace" . | quote }}
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 | quote }}
app.kubernetes.io/component: vector
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
{{- if .Values.vector.annotations }}
annotations:
{{- toYaml .Values.vector.annotations | nindent 4 }}
{{- end }}
spec:
secretName: {{ include "seaweedfs.fullname" . }}-vector-cert
issuerRef:
name: {{ include "seaweedfs.fullname" . }}-ca-issuer
kind: Issuer
commonName: {{ .Values.certificates.commonName }}
subject:
organizations:
- "SeaweedFS CA"
dnsNames:
- '*.{{ include "seaweedfs.fullname" . }}-vector'
- '*.{{ include "seaweedfs.fullname" . }}-vector.{{ include "seaweedfs.namespace" . }}'
- '*.{{ include "seaweedfs.fullname" . }}-vector.{{ include "seaweedfs.namespace" . }}.svc'
- '*.{{ include "seaweedfs.fullname" . }}-vector.{{ include "seaweedfs.namespace" . }}.svc.cluster.local'
{{- if .Values.certificates.dnsNames }}
{{- range .Values.certificates.dnsNames }}
- {{ . | quote }}
{{- end }}
{{- end }}
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
- {{ . }}
{{- end }}
{{- end }}
privateKey:
algorithm: {{ .Values.certificates.keyAlgorithm }}
size: {{ .Values.certificates.keySize }}
duration: {{ .Values.certificates.duration }}
renewBefore: {{ .Values.certificates.renewBefore }}
{{- end }}
@@ -770,15 +770,3 @@ on install.
{{- $context := merge (dict "Values" (omit .Values "commonLabels")) (omit . "Values") -}}
{{- include (print .Template.BasePath "/master/master-configmap.yaml") $context | sha256sum -}}
{{- end -}}
{{- define "seaweedfs.vector.selectorLabels" -}}
app.kubernetes.io/name: {{ include "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name | quote }}
app.kubernetes.io/component: vector
{{- end -}}
{{- define "seaweedfs.vector.labels" -}}
{{ include "seaweedfs.vector.selectorLabels" . }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
{{- with include "seaweedfs.commonLabels" . }}{{ . | nindent 0 }}{{ end }}
{{- end -}}
@@ -110,18 +110,6 @@
{{- $targets = append $targets (dict "component" "worker" "ports" $ports) }}
{{- end }}
{{- if .Values.vector.enabled }}
{{- $ports := list .Values.vector.port }}
{{- if .Values.vector.metricsPort }}
{{- $ports = append $ports .Values.vector.metricsPort }}
{{- end }}
{{- $targets = append $targets (dict "component" "vector" "ports" $ports) }}
{{- end }}
{{- if and .Values.vector.enabled .Values.vector.createBuckets }}
{{- $targets = append $targets (dict "component" "vector-bucket-hook" "ports" (list)) }}
{{- end }}
{{- if .Values.cosi.enabled }}
{{- /* The provisioner sidecar watches the COSI CRs, so it needs the API
server; nothing needs to reach the driver itself. */}}
@@ -155,7 +143,7 @@
every component the chart can produce rather than the ones enabled here,
so one values file can still carry overrides for a component this release
leaves off. */}}
{{- $known := list "vector" "vector-bucket-hook" "master" "filer" "s3" "sftp" "admin" "worker" "volume" "bucket-hook" "volume-resize-hook" "objectstorage-provisioner" "seaweedfs-all-in-one" }}
{{- $known := list "master" "filer" "s3" "sftp" "admin" "worker" "volume" "bucket-hook" "volume-resize-hook" "objectstorage-provisioner" "seaweedfs-all-in-one" }}
{{- range $vname, $_ := (.Values.volumes | default dict) }}
{{- $known = append $known (trimSuffix "-" (printf "volume-%s" $vname)) }}
{{- end }}
@@ -215,11 +215,8 @@ spec:
{{- end }}
{{- end }}
{{- range $createBuckets }}
{{- if not (or (kindIs "invalid" .replication) (and (kindIs "string" .replication) (or (eq .replication "") (regexMatch "^([01][0-9]{2}|2[0-4][0-9]|25[0-5])$" .replication)))) }}
{{- fail (printf "createBuckets %s: replication must be a quoted three-digit string from 000 to 255 such as \"001\" (use --set-string)" .name) }}
{{- end }}
{{- if or .ttl .replication .disk }}
/bin/echo 'fs.configure -locationPrefix={{ $bucketsFolder }}/{{ .name }}/{{- with .ttl }} -ttl={{ . }}{{- end }}{{- with .replication }} -replication={{ . }}{{- end }}{{- with .disk }} -disk={{ . }}{{- end }} -apply' | /usr/bin/weed shell
{{- if .ttl }}
/bin/echo 'fs.configure -locationPrefix={{ $bucketsFolder }}/{{ .name }}/ -ttl={{ .ttl }} -apply' | /usr/bin/weed shell
{{- end }}
{{- end }}
{{- range $createBuckets }}
@@ -94,10 +94,6 @@ data:
cert = "/usr/local/share/ca-certificates/admin/tls.crt"
key = "/usr/local/share/ca-certificates/admin/tls.key"
[grpc.vector]
cert = "/usr/local/share/ca-certificates/vector/tls.crt"
key = "/usr/local/share/ca-certificates/vector/tls.key"
[grpc.worker]
cert = "/usr/local/share/ca-certificates/worker/tls.crt"
key = "/usr/local/share/ca-certificates/worker/tls.key"
@@ -1,167 +0,0 @@
{{- include "seaweedfs.compat" . -}}
{{- if and .Values.vector.enabled .Values.vector.createBuckets }}
{{- $hook := .Values.vector.bucketHook }}
{{- $component := "s3" }}
{{- $port := .Values.s3.port }}
{{- $enabled := .Values.s3.enabled }}
{{- $auth := .Values.s3.enableAuth }}
{{- $configSecret := .Values.s3.existingConfigSecret }}
{{- if and .Values.allInOne.enabled .Values.allInOne.s3.enabled }}
{{- $component = "all-in-one" }}
{{- $port = .Values.allInOne.s3.port | default .Values.s3.port }}
{{- $enabled = true }}
{{- $auth = or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth }}
{{- $configSecret = or .Values.allInOne.s3.existingConfigSecret .Values.s3.existingConfigSecret .Values.filer.s3.existingConfigSecret }}
{{- else if and (not $enabled) .Values.filer.s3.enabled }}
{{- $component = "filer" }}
{{- $port = .Values.filer.s3.port }}
{{- $enabled = true }}
{{- $auth = .Values.filer.s3.enableAuth }}
{{- $configSecret = .Values.filer.s3.existingConfigSecret }}
{{- end }}
{{- if and (not $enabled) (not $hook.endpoint) }}
{{- fail "vector.createBuckets requires an enabled S3 gateway or vector.bucketHook.endpoint" }}
{{- end }}
{{- range .Values.vector.createBuckets }}
{{- if not (kindIs "string" .) }}{{ fail "vector.createBuckets entries must be bucket names" }}{{ end }}
{{- if not (and (ge (len .) 3) (le (len .) 63) (regexMatch "^[a-z0-9][a-z0-9-]*[a-z0-9]$" .)) }}
{{- fail "vector.createBuckets names must be 3-63 lowercase letters, digits or hyphens" }}
{{- end }}
{{- end }}
{{- $credentials := .Values.s3.credentials | default dict }}
{{- $admin := $credentials.admin | default dict }}
{{- $secret := $hook.credentialsSecret }}
{{- $accessKey := $hook.accessKeyKey }}
{{- $secretKey := $hook.secretKeyKey }}
{{- if and $auth (not $secret) }}
{{- if $configSecret }}{{ fail "vector.bucketHook.credentialsSecret is required with s3.existingConfigSecret" }}{{ end }}
{{- $secret = $admin.existingSecret | default (printf "%s-s3-secret" (include "seaweedfs.fullname" .)) }}
{{- $accessKey = $admin.accessKeyKey | default "admin_access_key_id" }}
{{- $secretKey = $admin.secretKeyKey | default "admin_secret_access_key" }}
{{- end }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "seaweedfs.fullname" . }}-vector-bucket-hook
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
app.kubernetes.io/name: {{ include "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name | quote }}
app.kubernetes.io/component: vector-bucket-hook
{{- with include "seaweedfs.commonLabels" . }}{{ . | nindent 4 }}{{ end }}
annotations:
helm.sh/hook: post-install,post-upgrade
helm.sh/hook-weight: "-5"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
backoffLimit: 2
activeDeadlineSeconds: 360
template:
metadata:
labels:
app.kubernetes.io/name: {{ include "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name | quote }}
app.kubernetes.io/component: vector-bucket-hook
spec:
restartPolicy: Never
automountServiceAccountToken: false
{{- with $hook.podSecurityContext }}
securityContext:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.vector.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.vector.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
containers:
- name: create-vector-buckets
image: {{ $hook.image | quote }}
command: ["/bin/sh", "-ec"]
args:
- |
for bucket in {{ range .Values.vector.createBuckets }}{{ . | quote }} {{ end }}; do
attempt=0
while ! aws --endpoint-url "$S3_ENDPOINT" s3vectors get-vector-bucket --vector-bucket-name "$bucket" >/dev/null 2>/tmp/bucket-error; do
if grep -q NotFound /tmp/bucket-error; then
aws --endpoint-url "$S3_ENDPOINT" s3vectors create-vector-bucket --vector-bucket-name "$bucket" ||
aws --endpoint-url "$S3_ENDPOINT" s3vectors get-vector-bucket --vector-bucket-name "$bucket"
break
fi
if grep -q AccessDenied /tmp/bucket-error; then cat /tmp/bucket-error >&2; exit 1; fi
attempt=$((attempt + 1))
if [ "$attempt" -ge 60 ]; then cat /tmp/bucket-error >&2; exit 1; fi
sleep 5
done
done
env:
- name: S3_ENDPOINT
value: {{ $hook.endpoint | default (printf "http://%s.%s:%d" (include "seaweedfs.componentName" (list . $component)) (include "seaweedfs.namespace" .) (int $port)) | quote }}
- name: AWS_DEFAULT_REGION
value: {{ $hook.region | quote }}
- name: AWS_EC2_METADATA_DISABLED
value: "true"
- name: AWS_PAGER
value: ""
- name: AWS_MAX_ATTEMPTS
value: "2"
- name: AWS_ACCESS_KEY_ID
{{- if $secret }}
valueFrom:
secretKeyRef:
name: {{ $secret | quote }}
key: {{ $accessKey | quote }}
{{- else }}
value: seaweedfs
{{- end }}
- name: AWS_SECRET_ACCESS_KEY
{{- if $secret }}
valueFrom:
secretKeyRef:
name: {{ $secret | quote }}
key: {{ $secretKey | quote }}
{{- else }}
value: seaweedfs
{{- end }}
{{- if $hook.credentialsSecret }}
- name: AWS_SESSION_TOKEN
valueFrom:
secretKeyRef:
name: {{ $secret | quote }}
key: {{ $hook.sessionTokenKey | quote }}
optional: true
{{- end }}
{{- if $hook.caBundleSecret }}
- name: AWS_CA_BUNDLE
value: /etc/ssl/vector/ca.crt
{{- end }}
securityContext:
{{- toYaml $hook.containerSecurityContext | nindent 12 }}
{{- with $hook.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
volumeMounts:
- name: tmp
mountPath: /tmp
{{- if $hook.caBundleSecret }}
- name: ca
mountPath: /etc/ssl/vector
readOnly: true
{{- end }}
volumes:
- name: tmp
emptyDir: {}
{{- if $hook.caBundleSecret }}
- name: ca
secret:
secretName: {{ $hook.caBundleSecret | quote }}
items:
- key: {{ $hook.caBundleKey | quote }}
path: ca.crt
{{- end }}
{{- end }}
@@ -1,166 +0,0 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.vector.enabled }}
{{- if and .Values.vector.metricsPort (not .Values.vector.imageOverride) (eq (toString (.Values.image.tag | default .Chart.AppVersion)) "4.53") }}
{{- fail "vector.metricsPort requires vector.imageOverride selecting an engine with metrics support; the default 4.53 image does not support metrics" }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "seaweedfs.componentName" (list . "vector") }}
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
{{- include "seaweedfs.vector.labels" . | nindent 4 }}
{{- with .Values.vector.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
replicas: {{ .Values.vector.replicas }}
selector:
matchLabels:
{{- include "seaweedfs.vector.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "seaweedfs.vector.selectorLabels" . | nindent 8 }}
{{- with .Values.podLabels }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with .Values.vector.podLabels }}{{ toYaml . | nindent 8 }}{{ end }}
annotations:
{{- with .Values.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with .Values.vector.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
spec:
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
automountServiceAccountToken: {{ .Values.global.seaweedfs.automountServiceAccountToken }}
{{- with .Values.vector.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.vector.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.vector.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if and .Values.vector.podSecurityContext (or (not (hasKey .Values.vector.podSecurityContext "enabled")) .Values.vector.podSecurityContext.enabled) }}
securityContext:
{{- omit .Values.vector.podSecurityContext "enabled" | toYaml | nindent 8 }}
{{- end }}
containers:
- name: vector
image: {{ .Values.vector.imageOverride | default (include "seaweedfs.image" .) | quote }}
imagePullPolicy: {{ .Values.global.seaweedfs.imagePullPolicy }}
{{- $masters := include "seaweedfs.masterServerArg" . }}
{{- if .Values.allInOne.enabled }}{{ $masters = include "seaweedfs.cluster.masterAddress" . }}{{ end }}
command: ["/bin/sh", "-ec"]
args:
- 'case "$POD_IP" in *:*) POD_IP="[$POD_IP]";; esac; exec /usr/bin/weed-vector --listen="$POD_IP:{{ .Values.vector.port }}" "$@"'
- vector
- {{ printf "--masters=%s" (.Values.vector.masters | default $masters) | quote }}
- {{ printf "--read-cache-mb=%d" (int .Values.vector.readCacheMB) | quote }}
{{- if .Values.filer.filerGroup }}
- {{ printf "--filer-group=%s" .Values.filer.filerGroup | quote }}
{{- end }}
{{- if .Values.vector.nprobes }}
- {{ printf "--nprobes=%d" (int .Values.vector.nprobes) | quote }}
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- --security-toml=/etc/seaweedfs/security.toml
{{- end }}
{{- if .Values.vector.metricsPort }}
- {{ printf "--metrics-port=%d" (int .Values.vector.metricsPort) | quote }}
- --metrics-ip=$(POD_IP)
{{- end }}
{{- range .Values.vector.extraArgs }}
- {{ . | quote }}
{{- end }}
env:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
{{- $env := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.vector "target" $env) }}
{{- range $key := keys $env | sortAlpha }}
- name: {{ $key }}
{{- $value := index $env $key }}
{{- if kindIs "map" $value }}
valueFrom:
{{- toYaml $value | nindent 16 }}
{{- else }}
value: {{ tpl (toString $value) $ | quote }}
{{- end }}
{{- end }}
ports:
- name: grpc
containerPort: {{ .Values.vector.port }}
{{- if .Values.vector.metricsPort }}
- name: metrics
containerPort: {{ .Values.vector.metricsPort }}
{{- end }}
startupProbe:
tcpSocket:
port: grpc
periodSeconds: 5
failureThreshold: 60
readinessProbe:
{{- if .Values.vector.metricsPort }}
httpGet:
path: /ready
port: metrics
{{- else }}
tcpSocket:
port: grpc
{{- end }}
periodSeconds: 5
livenessProbe:
{{- if .Values.vector.metricsPort }}
httpGet:
path: /health
port: metrics
{{- else }}
tcpSocket:
port: grpc
{{- end }}
initialDelaySeconds: 10
periodSeconds: 10
{{- if or (not (hasKey .Values.vector.containerSecurityContext "enabled")) .Values.vector.containerSecurityContext.enabled }}
securityContext:
{{- omit .Values.vector.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- with .Values.vector.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
volumeMounts:
- name: tmp
mountPath: /tmp
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
mountPath: /etc/seaweedfs
readOnly: true
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
{{- range list "ca" "client" "vector" }}
- name: {{ . }}-cert
mountPath: /usr/local/share/ca-certificates/{{ . }}
readOnly: true
{{- end }}
{{- end }}
volumes:
- name: tmp
emptyDir: {}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
{{- range list "ca" "client" "vector" }}
- name: {{ . }}-cert
secret:
secretName: {{ include "seaweedfs.fullname" $ }}-{{ . }}-cert
{{- end }}
{{- end }}
{{- end }}
@@ -1,22 +0,0 @@
{{- if .Values.vector.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ include "seaweedfs.componentName" (list . "vector") }}
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
{{- include "seaweedfs.vector.labels" . | nindent 4 }}
spec:
clusterIP: None
selector:
{{- include "seaweedfs.vector.selectorLabels" . | nindent 4 }}
ports:
- name: grpc
port: {{ .Values.vector.port }}
targetPort: grpc
{{- if .Values.vector.metricsPort }}
- name: metrics
port: {{ .Values.vector.metricsPort }}
targetPort: metrics
{{- end }}
{{- end }}
@@ -1,25 +0,0 @@
{{- if and .Values.vector.enabled .Values.vector.metricsPort .Values.global.seaweedfs.monitoring.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ include "seaweedfs.componentName" (list . "vector") }}
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
{{- include "seaweedfs.vector.selectorLabels" . | nindent 4 }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
{{- with include "seaweedfs.commonLabels" (dict "context" $ "exclude" $.Values.global.seaweedfs.monitoring.additionalLabels) }}{{ . | nindent 4 }}{{ end }}
{{- with .Values.global.seaweedfs.monitoring.additionalLabels }}{{ toYaml . | nindent 4 }}{{ end }}
{{- with .Values.vector.serviceMonitor.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
endpoints:
- port: metrics
interval: 30s
scrapeTimeout: 5s
selector:
matchLabels:
{{- include "seaweedfs.vector.selectorLabels" . | nindent 6 }}
{{- end }}
@@ -239,22 +239,6 @@ spec:
{{- /* the URL crosses a shell line; metacharacters must arrive as data, not syntax */}}
- name: LANCE_NAMESPACE_URL
value: {{ include "seaweedfs.worker.lanceNamespaceUrl" . | quote }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.worker "target" $mergedExtraEnvironmentVars) }}
{{- /* a duplicate would win over the chart's value and change --id or --namespace */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "LANCE_NAMESPACE_URL" }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
- name: {{ $key }}
{{- if kindIs "string" $value }}
value: {{ tpl $value $ | quote }}
{{- else if kindIs "map" $value }}
valueFrom:
{{ toYaml $value | nindent 16 | trim }}
{{- else if not (kindIs "invalid" $value) }}
value: {{ toJson $value | quote }}
{{- end -}}
{{- end }}
command:
- "/bin/sh"
- "-ec"
@@ -272,10 +256,6 @@ spec:
--admin={{ template "seaweedfs.fullname" . }}-admin.{{ include "seaweedfs.namespace" . }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
{{- end }}
--namespace="$LANCE_NAMESPACE_URL" \
--masters={{ include "seaweedfs.masterServerArg" . }} \
{{- if .Values.filer.filerGroup }}
--filer-group={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
--tls-ca=/usr/local/share/ca-certificates/ca/tls.crt \
--tls-cert=/usr/local/share/ca-certificates/worker/tls.crt \
@@ -288,20 +268,10 @@ spec:
--max-concurrency={{ .Values.worker.maxExecute }}
volumeMounts:
{{- include "seaweedfs.tmpDirVolumeMount" (list . .Values.worker.containerSecurityContext "" "") | nindent 12 }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
readOnly: true
mountPath: /etc/seaweedfs/security.toml
subPath: security.toml
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/ca/
{{- /* grpc.client, which the worker dials the masters and filers with */}}
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
- name: worker-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/worker/
@@ -1,113 +0,0 @@
package tests
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestVectorBucketHook(t *testing.T) {
for _, auth := range []bool{false, true} {
t.Run(fmt.Sprint(auth), func(t *testing.T) {
output, documents := render(t, "s3.enabled=true", "vector.enabled=true", "vector.createBuckets[0]=embeddings", "s3.enableAuth="+fmt.Sprint(auth), "networkPolicy.enabled=true")
var found bool
for _, document := range documents {
metadata := document["metadata"].(map[string]interface{})
if document["kind"] == "Job" && strings.HasSuffix(metadata["name"].(string), "-vector-bucket-hook") {
found = true
if metadata["annotations"].(map[string]interface{})["helm.sh/hook"] != "post-install,post-upgrade" {
t.Fatal("missing upgrade hook")
}
}
}
if !found || !strings.Contains(output, "s3vectors get-vector-bucket") || !strings.Contains(output, "s3vectors create-vector-bucket") {
t.Fatal("missing vector bucket provisioning")
}
if auth && !strings.Contains(output, "key: \"admin_access_key_id\"") {
t.Fatal("missing generated admin credential reference")
}
})
}
}
func TestVectorBucketHookRetriesRacesAndRefusesConflicts(t *testing.T) {
_, documents := render(t, "s3.enabled=true", "vector.enabled=true", "vector.createBuckets[0]=embeddings")
var script string
for _, document := range documents {
if document["kind"] != "Job" {
continue
}
metadata := document["metadata"].(map[string]interface{})
if strings.HasSuffix(metadata["name"].(string), "-vector-bucket-hook") {
pod := document["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})
container := pod["containers"].([]interface{})[0].(map[string]interface{})
script = container["args"].([]interface{})[0].(string)
}
}
if script == "" {
t.Fatal("missing hook script")
}
for _, mode := range []string{"missing", "existing", "race", "iceberg", "denied"} {
t.Run(mode, func(t *testing.T) {
dir := t.TempDir()
stub := `#!/bin/sh
shift 2
operation=$2
case "$operation" in
get-vector-bucket)
if [ "$BUCKET_MODE" = denied ]; then echo AccessDenied >&2; exit 1; fi
if [ "$BUCKET_MODE" = existing ] || { [ -f "$BUCKET_STATE" ] && [ "$BUCKET_MODE" != iceberg ]; }; then exit 0; fi
echo NotFoundException >&2; exit 1;;
create-vector-bucket)
touch "$BUCKET_STATE"
if [ "$BUCKET_MODE" = race ] || [ "$BUCKET_MODE" = iceberg ]; then exit 1; fi;;
esac
`
if err := os.WriteFile(filepath.Join(dir, "aws"), []byte(stub), 0755); err != nil {
t.Fatal(err)
}
command := exec.Command("sh", "-ec", script)
command.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "S3_ENDPOINT=http://unused", "BUCKET_MODE="+mode, "BUCKET_STATE="+filepath.Join(dir, "state"))
output, err := command.CombinedOutput()
wantFailure := mode == "iceberg" || mode == "denied"
if (err != nil) != wantFailure {
t.Fatalf("mode %s: %v %s", mode, err, output)
}
})
}
}
func TestVectorBucketHookRejectsShellNames(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
command := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "vector.enabled=true", "--set", "vector.createBuckets[0]=bucket;touch /tmp/invalid")
output, err := command.CombinedOutput()
if err == nil || !strings.Contains(string(output), "vector.createBuckets names") {
t.Fatalf("invalid bucket accepted: %v %s", err, output)
}
}
func TestVectorBucketHookGatewayModes(t *testing.T) {
for _, mode := range []string{"s3", "filer", "allInOne"} {
settings := []string{"vector.enabled=true", "vector.createBuckets[0]=embeddings"}
component := "s3"
switch mode {
case "s3":
settings = append(settings, "s3.enabled=true", "s3.enableAuth=true")
case "filer":
settings = append(settings, "s3.enabled=false", "filer.s3.enabled=true", "filer.s3.enableAuth=true")
component = "filer"
case "allInOne":
settings = append(settings, "s3.enabled=false", "allInOne.enabled=true", "allInOne.s3.enabled=true", "allInOne.s3.enableAuth=true")
component = "all-in-one"
}
output, _ := render(t, settings...)
if !strings.Contains(output, "http://vector-test-seaweedfs-"+component+".default:8333") || !strings.Contains(output, "key: \"admin_access_key_id\"") {
t.Fatalf("missing endpoint or auth for %s", mode)
}
}
}
-148
View File
@@ -1,148 +0,0 @@
package tests
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
"testing"
"go.yaml.in/yaml/v3"
)
func render(t *testing.T, settings ...string) (string, []map[string]interface{}) {
t.Helper()
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
args := []string{"template", "vector-test", ".."}
for _, setting := range settings {
args = append(args, "--set", setting)
}
output, err := exec.Command("helm", args...).CombinedOutput()
if err != nil {
t.Fatalf("helm: %v\n%s", err, output)
}
decoder := yaml.NewDecoder(strings.NewReader(string(output)))
var documents []map[string]interface{}
for {
var document map[string]interface{}
if err := decoder.Decode(&document); err == io.EOF {
break
} else if err != nil {
t.Fatal(err)
}
if document != nil {
documents = append(documents, document)
}
}
return string(output), documents
}
func TestVectorDeployment(t *testing.T) {
_, defaults := render(t)
for _, document := range defaults {
if strings.HasSuffix(fmt.Sprint(document["metadata"].(map[string]interface{})["name"]), "-vector") {
t.Fatal("vector resource enabled by default")
}
}
for _, secure := range []bool{false, true} {
t.Run(fmt.Sprintf("security-%v", secure), func(t *testing.T) {
output, documents := render(t, "vector.enabled=true", "vector.metricsPort=9329", "vector.imageOverride=example/metrics-engine:test", "vector.port=8098", "global.seaweedfs.enableSecurity="+fmt.Sprint(secure), "global.seaweedfs.monitoring.enabled=true", "networkPolicy.enabled=true")
for _, want := range []string{"--listen=\"$POD_IP:8098\"", "--metrics-port=9329", "path: /ready", "path: /health", "kind: ServiceMonitor"} {
if !strings.Contains(output, want) {
t.Fatalf("missing %s", want)
}
}
found := false
for _, document := range documents {
metadata := document["metadata"].(map[string]interface{})
if document["kind"] == "Deployment" && strings.HasSuffix(metadata["name"].(string), "-vector") {
found = true
spec := document["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})
if spec["nodeSelector"].(map[string]interface{})["kubernetes.io/os"] != "linux" {
t.Fatal("vector engine must use Linux image platforms")
}
}
}
if !found {
t.Fatal("no vector deployment")
}
if secure && (!strings.Contains(output, "[grpc.vector]") || !strings.Contains(output, "vector-cert")) {
t.Fatal("missing vector TLS configuration")
}
})
}
}
func TestVectorExistingImagesAndExternalCertificates(t *testing.T) {
output, _ := render(t, "vector.enabled=true")
start := strings.Index(output, "# Source: seaweedfs/templates/vector/vector-deployment.yaml")
deployment := strings.Split(output[start:], "\n---")[0]
if strings.Contains(deployment, "--metrics-port") || !strings.Contains(deployment, "tcpSocket:") {
t.Fatal("default probes must support existing vector images")
}
output, _ = render(t, "vector.enabled=true", "global.seaweedfs.enableSecurity=true", "certificates.externalCertificates.enabled=true")
if strings.Contains(output, "kind: Certificate") || !strings.Contains(output, "mountPath: /usr/local/share/ca-certificates/vector") {
t.Fatal("external vector certificates are not mounted")
}
}
func TestVectorIPv6Listen(t *testing.T) {
_, docs := render(t, "vector.enabled=true")
var args []interface{}
for _, doc := range docs {
if doc["kind"] != "Deployment" {
continue
}
pod := doc["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})
c := pod["containers"].([]interface{})[0].(map[string]interface{})
if c["name"] == "vector" {
args = c["args"].([]interface{})
}
}
for _, ip := range []string{"10.0.0.20", "fd00::20"} {
dir := t.TempDir()
script := strings.ReplaceAll(args[0].(string), "/usr/bin/weed-vector", "printf '%s\\n'")
cmd := exec.Command("sh", "-ec", script, "vector", "--masters=master")
cmd.Dir = dir
cmd.Env = append(os.Environ(), "POD_IP="+ip)
out, err := cmd.CombinedOutput()
address := ip
if strings.Contains(ip, ":") {
address = "[" + ip + "]"
}
if err != nil || !strings.Contains(string(out), "--listen="+address+":8090") || !strings.Contains(string(out), "--masters=master") {
t.Fatalf("%s: %s %v", ip, out, err)
}
}
}
func TestVectorAllInOneMasters(t *testing.T) {
output, _ := render(t, "vector.enabled=true", "allInOne.enabled=true", "master.enabled=false")
if !strings.Contains(output, "--masters=vector-test-seaweedfs-all-in-one.default:9333") {
t.Fatal("vector cannot discover all-in-one master")
}
output, _ = render(t, "vector.enabled=true", "allInOne.enabled=true", "master.enabled=false", "vector.masters=external:9333")
if !strings.Contains(output, "--masters=external:9333") {
t.Fatal("explicit master override lost")
}
}
func TestVectorNetworkPolicyOverrides(t *testing.T) {
output, _ := render(t, "vector.enabled=true", "s3.enabled=true", "vector.createBuckets[0]=embeddings", "networkPolicy.enabled=true", "networkPolicy.components.vector.extraIngress[0].ports[0].port=9329", "networkPolicy.egress.enabled=true", "networkPolicy.components.vector-bucket-hook.extraEgress[0].ports[0].port=443")
if !strings.Contains(output, "port: 9329") || !strings.Contains(output, "port: 443") {
t.Fatal("vector network overrides missing")
}
}
func TestVectorMetricsImageCompatibility(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
out, err := exec.Command("helm", "template", "vector-test", "..", "--set", "vector.enabled=true", "--set", "vector.metricsPort=9329").CombinedOutput()
if err == nil || !strings.Contains(string(out), "default 4.53 image does not support metrics") {
t.Fatalf("incompatible image accepted: %v %s", err, out)
}
render(t, "vector.enabled=true", "vector.metricsPort=9329", "vector.imageOverride=example/metrics-engine:test")
}
-74
View File
@@ -1083,16 +1083,12 @@ filer:
# You may specify buckets to be created during the install or upgrade process.
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# replication (e.g., 001) and disk (e.g., ssd) apply to writes into the bucket
# removing ttl, replication or disk later keeps the stored rule; set a new value instead
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
# ttl: 7d
# replication: "001"
# disk: ssd
# objectLock: true
# versioning: Enabled
# - name: bucket-b
@@ -1169,16 +1165,12 @@ s3:
# You may specify buckets to be created during the install or upgrade process.
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# replication (e.g., 001) and disk (e.g., ssd) apply to writes into the bucket
# removing ttl, replication or disk later keeps the stored rule; set a new value instead
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
# ttl: 7d
# replication: "001"
# disk: ssd
# objectLock: true
# versioning: Enabled
# - name: bucket-b
@@ -1741,60 +1733,6 @@ admin:
serviceMonitor:
annotations: {}
vector:
enabled: false
imageOverride: null
replicas: 1
port: 8090
metricsPort: 0
masters: ""
readCacheMB: 512
nprobes: null
extraArgs: []
extraEnvironmentVars: {}
podLabels: {}
podAnnotations: {}
annotations: {}
nodeSelector:
kubernetes.io/os: linux
tolerations: []
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/arch
operator: In
values: [amd64, arm64]
resources: {}
podSecurityContext: {}
containerSecurityContext:
allowPrivilegeEscalation: false
capabilities:
drop: [ALL]
serviceMonitor:
annotations: {}
createBuckets: []
bucketHook:
podSecurityContext:
seccompProfile:
type: RuntimeDefault
containerSecurityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: [ALL]
image: amazon/aws-cli:2.39.6
endpoint: ""
region: us-east-1
credentialsSecret: ""
accessKeyKey: AWS_ACCESS_KEY_ID
secretKeyKey: AWS_SECRET_ACCESS_KEY
sessionTokenKey: AWS_SESSION_TOKEN
caBundleSecret: ""
caBundleKey: tls.crt
resources: {}
worker:
enabled: false
imageOverride: null
@@ -1806,14 +1744,6 @@ worker:
# The lance_* jobs run in their own container, /usr/bin/weed-worker.
# amd64/arm64 only; pin mixed clusters with worker.affinity/nodeSelector.
# It keeps tables through the filers the masters list and reads
# security.toml. The Lance namespace knows it by a token derived from
# jwt.filer_signing.key, which the chart renders only with
# global.seaweedfs.securityConfig.jwtSigning.filerWrite: true. When S3 has
# identities, set it, or the namespace lists the worker no tables and the
# lance_* jobs find nothing to do. It also makes the filer accept only signed
# HTTP writes, so clients writing to the filer's HTTP API directly need a JWT
# signed with that key.
# Lance namespace URL override; empty derives it from s3.lancePort.
namespaceUrl: ""
@@ -2015,16 +1945,12 @@ allInOne:
# You may specify buckets to be created during the install process.
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
# ttl format: [1-255][m|h|d|w|M|y] (e.g., 7d)
# replication (e.g., 001) and disk (e.g., ssd) apply to writes into the bucket
# removing ttl, replication or disk later keeps the stored rule; set a new value instead
# objectLock enables S3 Object Lock (irreversible, forces versioning)
# versioning: Enabled or Suspended (or bool true/false)
# createBuckets:
# - name: bucket-a
# anonymousRead: true
# ttl: 7d
# replication: "001"
# disk: ssd
# objectLock: true
# versioning: Enabled
# - name: bucket-b
-83
View File
@@ -1,83 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="650" viewBox="0 0 1080 650" role="img" aria-labelledby="title description">
<title id="title">SeaweedFS: one cluster for objects, files, tables, and vectors</title>
<desc id="description">S3 object storage, a POSIX file system, table buckets with a built-in Iceberg REST Catalog and Lance namespace, and S3 Vector Buckets share one SeaweedFS storage cluster. Masters coordinate the cluster, filers manage namespaces and metadata, and volume servers store replicated or erasure-coded blobs. Cloud caching, cloud tiering, and cross-cluster replication extend the cluster.</desc>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#75928e"/>
</marker>
</defs>
<rect width="1080" height="650" rx="20" fill="#f5f9f8"/>
<g font-family="Arial, Helvetica, sans-serif">
<text x="40" y="43" fill="#0f766e" font-size="15" font-weight="700" letter-spacing="2">SEAWEEDFS</text>
<text x="40" y="86" fill="#163832" font-size="32" font-weight="700">One cluster. Objects, files, tables, vectors.</text>
<!-- Four ways to use the same storage cluster. -->
<g>
<rect x="40" y="116" width="238" height="184" rx="14" fill="#fff" stroke="#cbded8"/>
<g transform="translate(62 136)" fill="none" stroke="#187b67" stroke-width="2.2" stroke-linejoin="round">
<path d="m0 10 18-9 18 9-18 9z M0 10v21l18 9 18-9V10 M18 19v21"/>
</g>
<text x="62" y="207" fill="#163832" font-size="22" font-weight="700">Object storage</text>
<text x="62" y="237" fill="#48635e" font-size="18">S3 API</text>
<text x="62" y="261" fill="#48635e" font-size="17">Apps, backups, media</text>
</g>
<g>
<rect x="294" y="116" width="238" height="184" rx="14" fill="#fff" stroke="#cbded8"/>
<g transform="translate(316 140)" fill="none" stroke="#2676a3" stroke-width="2.2" stroke-linejoin="round">
<path d="M0 7V2h15l6 6h17v27H0V7z M0 12h38"/>
</g>
<text x="316" y="207" fill="#163832" font-size="22" font-weight="700">File system</text>
<text x="316" y="237" fill="#48635e" font-size="18">POSIX / FUSE</text>
<text x="316" y="261" fill="#48635e" font-size="17">WebDAV, SFTP, HDFS</text>
</g>
<g>
<rect x="548" y="116" width="238" height="184" rx="14" fill="#fff" stroke="#cbded8"/>
<g transform="translate(570 138)" fill="none" stroke="#7a62ab" stroke-width="2.2" stroke-linejoin="round">
<rect x="0" y="0" width="38" height="36" rx="3"/>
<path d="M0 12h38 M0 24h38 M13 12v24 M26 12v24"/>
</g>
<text x="570" y="207" fill="#163832" font-size="22" font-weight="700">Table buckets</text>
<text x="570" y="237" fill="#48635e" font-size="18">S3 Tables</text>
<text x="570" y="261" fill="#48635e" font-size="17">Iceberg REST Catalog</text>
<text x="570" y="285" fill="#48635e" font-size="17">Lance namespace</text>
</g>
<g>
<rect x="802" y="116" width="238" height="184" rx="14" fill="#e4f5ee" stroke="#187b67" stroke-width="1.5"/>
<g transform="translate(824 138)" fill="none" stroke="#187b67" stroke-width="2.2">
<path d="m5 29 13-22 18 22H5z M18 7v30 M5 29l13 8 18-8"/>
<g fill="#e4f5ee">
<circle cx="5" cy="29" r="4"/>
<circle cx="18" cy="7" r="4"/>
<circle cx="36" cy="29" r="4"/>
<circle cx="18" cy="37" r="4"/>
</g>
</g>
<text x="824" y="207" fill="#163832" font-size="22" font-weight="700">Vector buckets</text>
<text x="824" y="237" fill="#266354" font-size="18">S3 Vectors</text>
<text x="824" y="261" fill="#266354" font-size="17">Search, RAG, embeddings</text>
</g>
<!-- A shared connection expresses capabilities, not request routing. -->
<path d="M159 300v28h762v-28 M413 300v28 M667 300v28 M540 328v30" fill="none" stroke="#75928e" stroke-width="2" marker-end="url(#arrow)"/>
<rect x="40" y="362" width="1000" height="174" rx="16" fill="#163e35"/>
<text x="540" y="400" text-anchor="middle" fill="#fff" font-size="25" font-weight="700">One shared storage cluster</text>
<g fill="#fff" font-size="20" font-weight="700" text-anchor="middle">
<text x="213" y="445">Masters</text>
<text x="540" y="445">Filers</text>
<text x="867" y="445">Volume servers</text>
</g>
<path d="M376 425v51 M704 425v51" stroke="#497266"/>
<g fill="#cfe4dc" font-size="17" text-anchor="middle">
<text x="213" y="473">Coordination &amp; placement</text>
<text x="540" y="473">Namespaces &amp; metadata</text>
<text x="867" y="473">Replicated or erasure-coded blobs</text>
</g>
<text x="540" y="511" text-anchor="middle" fill="#cfe4dc" font-size="17">Add volume servers to grow capacity</text>
<path d="M284 536v23 M796 536v23" stroke="#75928e" stroke-width="2" stroke-dasharray="5 5"/>
<rect x="40" y="560" width="488" height="58" rx="12" fill="#fff" stroke="#cbded8"/>
<rect x="552" y="560" width="488" height="58" rx="12" fill="#fff" stroke="#cbded8"/>
<text x="284" y="596" text-anchor="middle" fill="#305c50" font-size="19">Cloud caching &amp; tiering</text>
<text x="796" y="596" text-anchor="middle" fill="#305c50" font-size="19">Cross-cluster replication</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.3 KiB

+1011 -1084
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 53 KiB

@@ -286,7 +286,6 @@ message WriteCondition {
IF_EXTENDED_TIME_ELAPSED = 8; // fail if present and extended[ext_key] (unix seconds) is in the future
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
IF_ENTRY_EQUAL = 10; // fail unless the stored entry equals expected_entry
IF_OBJECT_EXISTS = 11; // fail if absent or a plain directory, one holding no object of its own (If-Match: * on a null version)
}
// Clause is one primitive comparison. IF_ETAG_MATCH holds when the current
// entry's ETag equals any value in etags; IF_ETAG_NOT_MATCH holds when it
File diff suppressed because it is too large. Load diff
-3
View File
@@ -6,9 +6,6 @@
//! second copy is a correctness risk rather than a typing cost: the HTTP↔gRPC
//! address rule, which two copies had already drifted on, and the process-wide
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
pub mod address;
pub mod security_config;
pub mod tls;
-79
View File
@@ -1,79 +0,0 @@
//! Where a SeaweedFS process finds security.toml, the way `weed` does.
//!
//! Mirrors the search list in `weed/util/config.go`: the working directory,
//! `$HOME/.seaweedfs`, `/usr/local/etc/seaweedfs` and `/etc/seaweedfs`, first
//! existing file wins. The volume server and the workers each read the file
//! for different sections, but an operator mounts it in one place and expects
//! every binary to pick it up from there.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
pub const SECURITY_CONFIG_FILE_NAME: &str = "security.toml";
/// The locations searched for security.toml, in order.
pub fn candidates(current_dir: Option<&Path>, home_dir: Option<&Path>) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Some(dir) = current_dir {
candidates.push(dir.join(SECURITY_CONFIG_FILE_NAME));
}
if let Some(home) = home_dir {
candidates.push(home.join(".seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
}
candidates.push(PathBuf::from("/usr/local/etc/seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
candidates.push(PathBuf::from("/etc/seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
candidates
}
/// The first candidate that is a file.
pub fn find(current_dir: Option<&Path>, home_dir: Option<&Path>) -> Option<PathBuf> {
candidates(current_dir, home_dir)
.into_iter()
.find(|candidate| candidate.is_file())
}
/// `$HOME`, or `%USERPROFILE%` where that is what the platform sets, read
/// through an injected lookup so tests need not touch the process environment.
pub fn home_dir(env: &dyn Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
env("HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| {
env("USERPROFILE")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_order_matches_go() {
let found = candidates(Some(Path::new("/work")), Some(Path::new("/home/u")));
assert_eq!(
found,
vec![
PathBuf::from("/work/security.toml"),
PathBuf::from("/home/u/.seaweedfs/security.toml"),
PathBuf::from("/usr/local/etc/seaweedfs/security.toml"),
PathBuf::from("/etc/seaweedfs/security.toml"),
]
);
}
#[test]
fn home_falls_back_to_userprofile() {
let env = |key: &str| match key {
"USERPROFILE" => Some(OsString::from("/users/u")),
_ => None,
};
assert_eq!(home_dir(&env), Some(PathBuf::from("/users/u")));
let empty_home = |key: &str| match key {
"HOME" => Some(OsString::new()),
_ => None,
};
assert_eq!(home_dir(&empty_home), None);
}
}
+10 -798
View File
File diff suppressed because it is too large. Load diff
-339
View File
@@ -1,339 +0,0 @@
# S3 Vectors ANN — Dev Plan
## Goal
Approximate nearest-neighbour search for S3 Vectors indexes, built on Lance
vector indexes, so that query latency stops growing linearly with the index.
Target: 90%+ recall@10 (what AWS states for S3 Vectors), exact results below
a size threshold and for rows written since the last index build, and one
code path that serves both the open-source single engine and the Enterprise
distributed query layer. Writes stay unchanged.
## Status (2026-11-04)
| Phase | Branch | State |
|---|---|---|
| 0 Build and measure | `vector-ann-phase0` | open: `vector_index` builder, `weed-vector-cli index`, `PERF_INDEX`, `PERF_CLUSTERS` |
| 1 Probe policy | `vector-ann-phase1` | open: policy in `query::scanner`, `--nprobes`, one Lance session per engine |
| 2 Build job | `vector-ann-phase2` | open: `lance_vector_index` in `weed-worker`, admin-driven end-to-end test, worker CI legs |
| 3 Keep it covering | `vector-ann-phase3` | open: relative budget, retrain rule, end-to-end steps |
| 4 Docs and gates | — | after the above merge |
| 5 Enterprise sharded builds | — | the Enterprise repository |
What the measurements changed:
- **IVF needs structure in the data.** On independent Gaussian vectors, the
perf suite's default, recall through an IVF index tracks the fraction of
partitions probed: at 50k × 384 with 224 partitions, 8 probes gave 0.13 and
64 probes 0.56, and latency did not fall with fewer probes. On vectors drawn
around 100 shared centres, 8 probes gave recall 1.0; with eight clients
the index served 145 queries/s against 52 exact at 50k and 70 against 11
at 200k, and the 10% filtered query at 200k fell from 445 to 265 ms,
while one client's latency stayed at the request path's floor on the
shared host. Embeddings cluster; the perf suite grows `PERF_CLUSTERS`
and the end-to-end test draws its rows around centres. The probe rule
stands as written.
- **The engine opened every table in a fresh Lance session**, so the index
cache died with each request. Phase 1 gives the engine one session, sized
by `--index-cache-mb`.
- **Compaction keeps the index covering** (Lance 10 remaps it), so the
compaction risk below did not materialise.
## Where things stand (2026-11-04)
What already exists, with the files that hold it:
- **The engine is index-aware; nothing builds an index.** `QueryVectors` in
`crates/server/src/service.rs` always calls `weed_vector_core::query::ann`,
which runs a Lance scan with `use_index(true)`: ANN on fragments an index
covers, a flat pass on the rest, decided per fragment by Lance
(`crates/core/src/query.rs`). `nprobes` is `None`. `CreateIndex` writes an
empty Lance dataset and no vector index, so today every fragment is "tail"
and every query is an exact scan.
- **The maintenance worker only extends indexes that exist.** The
`lance_optimize_indices` job in `seaweed-worker/crates/lance/src/jobs/indices.rs`
skips a table whose `load_indices()` is empty and otherwise calls
`optimize_indices(&OptimizeOptions::default())` once `num_unindexed_rows`
exceeds its `max_unindexed_rows` budget (default 100,000).
- **Coverage and segments are modelled.** `crates/core/src/coverage.rs` reports,
per index name, the fragments covered and the uncovered rows; it requires the
fragment bitmap each Lance `IndexMetadata` delta carries.
`crates/core/src/segments.rs` lists physical segments (one per delta) with
their names and bitmaps, and partitions them across workers. `weed-vector-cli
coverage` and `weed-vector-cli query --flat` expose both.
- **Filters are applied before ranking.** `query.rs` sets `prefilter(true)`
unless the request asks for post-filtering, which S3 Vectors never does.
Lance's IVF search honours the prefilter, so this is already the behaviour
AWS calls an `ENHANCED` index.
- **Enterprise consumes exactly this model.** In the Enterprise repository,
`enterprise/weed/pb/vector_coord.proto` defines `SegmentInfo{id,
resident_bytes, rows, fragment_ids}` and `SegmentList{tail_fragment_ids,
tail_bytes}`; `VectorQuery` already carries `nprobes`; a `Task` is a set of
segment ids plus fragment ids. `sw-vector-distributed/src/plan.rs` assigns
a fragment covered by several segments to the lowest segment and never mixes
index names in one scan; `resident_bytes` is the index files' size.
`datasets.rs` warms a slot with `prewarm_index_segments` per index name and
warms the tail by scanning it. `sw-vector-distributed/src/index.rs` holds
`plan_index` (shard the uncovered fragments across workers),
`build_index_task` (one delta per shard, named
`<column>-w<worker>-v<version>`, built with `create_index_builder(..)
.fragments(..)`) and `optimize_policy` (append deltas until `MAX_DELTAS = 8`,
then Lance's default options, which promise no merge; see phase 3).
Nothing calls these three yet; `tests/index.rs`,
`tests/plan_search.rs` and `tests/engine_query.rs` exercise them with
`ivf_flat(4)` indexes.
- **Lance 10.0.0 offers** `VectorIndexParams::ivf_flat`, `ivf_pq`,
`with_ivf_sq_params`, `with_ivf_rq_params`, `ivf_hnsw` and HNSW variants;
scanner knobs `nprobes`, `minimum_nprobes`, `maximum_nprobes`, `ef`,
`refine`; `OptimizeOptions{num_indices_to_merge, index_names, retrain}`.
- **Measured today** (384-d, cosine, top-10, one 16-core host, exact scans):
one engine answers in 42 ms at 50k vectors and 82 ms at 200k; filtered
queries take 81 and 259–336 ms. Four Enterprise engines split four ways
bring 200k to 58 ms and the filtered query to 73 ms. Recall is 1.000.
- **Tests assume exactness only on tiny tables.** `test/s3vectors/s3vectors_test.py`
asserts exact result order on indexes of a handful of vectors; the perf
suite asserts recall@10 ≥ 0.9 against a client-side exact search.
- **AWS**: "90%+ average recall for most datasets"; `CLASSIC` and `ENHANCED`
index modes, the latter pre-filtering; no algorithm named.
## Design
### The contract every consumer relies on
An S3 Vectors index gains a Lance vector index on its `vector` column, and
everything downstream keeps working because it only ever sees:
1. **Segments**: Lance index deltas with fragment bitmaps. Every build and
every merge must leave `coverage_known == true`; a delta without a bitmap
turns the whole index into "rebuild" for the Enterprise planner.
2. **Names**: one logical index name per shard, never two shards under one
name within a build. Scans and warm-ups group by name.
3. **Tail**: fragments no segment covers, searched exactly. Rows written
after a build land here, so recall never drops to zero between builds.
4. **Bytes**: `resident_bytes` of a segment is its index files' size. The
controller's W sizing (`W_mem`, `W_scan`) and the engine's
`--capacity-bytes` budget use it unchanged.
5. **Versions**: a build or merge commits a new dataset version. Routers cache
segment lists per version, plans pin versions with the lease tags in
`crates/core/src/maintenance.rs`, and cleanup respects those leases. No
new mechanism is needed, but the build job must go through the same
commit path as any Lance write.
### Index type and parameters
- **IVF_FLAT first.** Distances inside probed partitions are exact, so recall
is governed by `nprobes` alone; the only training is k-means over the
centroids; resident bytes stay close to the raw vectors, which keeps the
Enterprise W sizing in the same range as today. `IVF_PQ` becomes an
operator option later for indexes whose raw size is the constraint. HNSW
variants are out of scope: their build cost and memory do not fit the
maintenance-worker model.
- **Metric from the table.** The vector field's `distance_metric` metadata
(`COSINE`, `DOT_PRODUCT`, else L2) is the metric the index is built with,
exactly as `service.rs` resolves it for queries.
- **Partitions**: start at `clamp(round(sqrt(rows)), 1, 4096)` for the whole
table, and for a shard, `sqrt` of the shard's rows. Phase 0 measures
recall and latency against this and adjusts before it becomes a default.
- **Probes**: one count per query, `max(8, ceil(partitions / 10))` clamped to
the partition count, taken from the largest delta of the index. A delta
with no more partitions than that count is searched in full; a larger one
at that count. Lance searches at least that many partitions. Under a
filter it may widen to four times the count until it has k rows, which a
selective filter needs; an open upper bound made Lance prepare every
partition for that and cost as much as the exact scan (201 ms against
104 ms for the 10% filter at 50k × 384). Without a filter it stops at the
count.
### Who builds, and when
The Lance maintenance worker (`weed-worker`) gets a new job type,
`lance_vector_index`, beside `lance_optimize_indices`:
- **Detection**: tables in a vector bucket's `vector` namespace (ids of the
form `<bucket>$vector$<index>`) whose vector column has no index and at
least `min_rows` live rows (default 50,000). Below the threshold the index
stays exact, which also keeps the existing small-table tests exact.
- **Execution**: one `create_index` call with IVF_FLAT, the table's metric,
the partition rule above, and a fixed name (`vector_idx`). Progress and
counters follow the pattern of `indices.rs`; a new `indexes_built_total`
metric and an admin observation of index coverage sit beside the row and
fragment counts the worker already reports.
- **Why the worker and not the engine or the gateway.** `CreateIndex` has no
rows to index. The engine serves queries and should not run minute-long
k-means builds. The worker already has the catalog client, credentials,
the admin UI settings form, metrics, retries and dedupe, and plugin jobs
start disabled until an operator turns them on, which is the rollout
switch we want.
- **Enterprise sharded builds** (phase 5): the same job, when Enterprise
engines are registered, splits the uncovered fragments with `plan_index`
and has each engine run `build_index_task` for its shard, producing one
named delta per shard. This is what `index.rs` was written for; the worker
drives it, the engines build, and the shared `optimize_policy` keeps each
name's delta count under eight.
### Keeping it covering
`lance_optimize_indices` already does the work once an index exists. Two
changes:
- The budget becomes relative for vector tables: reindex when uncovered rows
exceed `min(absolute budget, 10% of indexed rows)`, so a 60k-row index
reindexes after 6k new rows instead of waiting for 100k.
- A retrain once the table has grown to about 4× the rows the centroids were
trained on, so partitions do not go stale. No row count is recorded: the
retrain is due when the partition rule for the current rows gives twice
the partitions the index has, and it rebuilds a single IVF_FLAT name
through the builder at that count. Past 2,048 partitions (about 4.2M
rows) the rule cannot double under the 4,096 cap, so those centroids are
not retrained again: that would need the trained row count recorded and a
full rebuild of a table that size, which is left for later.
### Deletes and upserts
A delete marks rows in Lance deletion files; an upsert is a delete plus an
append. Deleted rows are excluded through the prefilter on indexed and
unindexed fragments alike, and appended rows are tail until the next
optimize. Phase 1 adds a test that proves both, since this is where ANN
systems silently return stale hits.
### API surface
No new S3 Vectors API parameter is needed to reach AWS parity. Two optional
items for later: accept and echo AWS's `indexMode`/`queryMode` (both behave
as `ENHANCED` here, because filters are always applied first), and a
non-AWS per-request `nprobes` for the perf suite and the CLI, carried in the
engine's `QueryVectorsRequest` (the Enterprise `VectorQuery` already has the
field).
### Enterprise compatibility requirements
These hold for every phase, and the mono s3vectors legs (go/rust ×
single/distributed) are the gate:
- Builds produce deltas with fragment bitmaps; merges keep them. A test in
`tests/index.rs` asserts `coverage_known` after build, append and merge.
- Index names never mix within a shard set; the router and `plan.rs` group by
name, and `with_index_segments` rejects mixed names.
- Segment count per index name stays under `MAX_DELTAS`: at the limit
`optimize_policy(deltas)` passes `OptimizeOptions::merge(deltas)`, where
`deltas` is the name's delta count, so every delta of that name folds
into one with the new rows; Lance's default options may append another
delta instead of merging. A test runs repeated append-and-optimize cycles
and checks the actual segment counts.
- Coverage is measured as the union over an index's names. After a sharded
build each name misses the other shards' fragments, so a per-name count
would extend every shard over the whole table and duplicate the index.
An optimize extends one name only, the one with the fewest deltas; a test
checks that two disjoint shards stay disjoint through it.
- `resident_bytes` is the index files' size and `tail_bytes` the uncovered
fragments' size; the controller's `max_scan_mb` and memory sizing need no
change for IVF_FLAT, and PQ only makes slots smaller.
- A merge replaces segment UUIDs, which is a new placement epoch. The
existing make-before-break (target groups warm with
`prewarm_index_segments` while serving groups keep answering) covers it;
phase 5 measures how long a merged segment takes to warm and sets
expectations for `warmup_timeout`.
- Workers read index files the way they read data files, directly from the
filers and volume servers, and the files are write-once,
so the read cache and the warm path apply unchanged.
- Query semantics are identical in both modes: each engine applies the same
probe policy to the segments it owns, or the count the router passes in
`VectorQuery.nprobes`, plus a flat pass over its tail fragments; the
gateway merges the partial top-k lists. Each delta is probed on its own
centroids, so the merged answer is never worse than one engine's.
- The open-source `weed-vector` stays the writer and the fallback engine, and
it serves ANN through the same `query::ann` the workers call.
## Phases
### Phase 0 — Measure before deciding (small)
- `weed-vector-cli index build --partitions N --name ..` on a local table,
reusing the code paths the tests already use, so builds can be tried
without the worker.
- Perf suite: `PERF_INDEX=1` builds the index after ingest and reports exact
versus ANN latency and recall@10 at 50k, 200k and 1M × 384, unfiltered and
with the 10% filter, for a grid of partitions and `nprobes`.
- Verify Lance behaviour we depend on: deletions excluded under ANN;
compaction (`lance_compact`) keeps bitmaps and coverage; `optimize_indices`
with `append` versus merge versus `retrain`.
- Exit: chosen defaults for `min_rows`, partitions and probes with numbers
behind them, and a written answer to each verification item.
### Phase 1 — Engine query path (small)
- Probe policy when an index exists: `minimum_nprobes` is the per-query
count from the Probes rule above, taken from the largest delta;
`maximum_nprobes` is four times it, which Lance uses only under a
prefilter.
- `nprobes` in `QueryVectorsRequest` for tests and the CLI; zero means the
policy.
- Per-query log line and counters: segments searched, tail rows scanned,
index hit or not. Without these, recall regressions are invisible.
- Tests in `crates/core`: ANN versus flat recall on a 50k synthetic table;
delete and upsert correctness under ANN; filtered query with a selective
filter still returns k results.
### Phase 2 — Build job in the maintenance worker (medium)
- `lance_vector_index` job: detection, execution, settings form (`min_rows`,
index type, partition rule), metrics, admin observation of coverage.
- Unit tests after the pattern of the other jobs; an integration test in
`test/s3vectors` that ingests above the threshold, runs the worker, and
asserts coverage through the CLI and recall ≥ 0.9 through the API.
- Exit: a fresh cluster with the job enabled indexes a 100k-vector table on
its own, and the small-table tests stay exact.
### Phase 3 — Keep it covering (small)
- Relative budget and `retrain` policy in `lance_optimize_indices` for vector
tables. The retrain rebuilds through the builder with partitions for the
current row count; Lance's `OptimizeOptions::retrain()` does not size them.
- Union-based coverage over an index's names, extension scoped to one name,
and `optimize_policy` with an explicit merge of all deltas at
`MAX_DELTAS`, shared with the Enterprise builds in the worker crate.
- Tests: append and optimize nine times and check the delta counts climb to
the limit and fold; two names on disjoint fragments stay disjoint through
an optimize; the end-to-end test runs the job after a tenth of the index
is appended and again after the table has grown fivefold.
### Phase 4 — Gateway, docs and gates (small)
- Optional `indexMode`/`queryMode` acceptance; `GetIndex` echoes the mode.
- Wiki and site docs: "Queries are exact" becomes "exact below the threshold,
ANN above it, with the tail exact", with the recall and latency measured
in phase 0. The performance page gets an ANN column.
- CI: a `test/s3vectors` leg with the worker and a low threshold, gated on
recall.
### Phase 5 — Enterprise distributed builds and placement (medium)
- Drive `plan_index` / `build_index_task` from the worker job when engines
are registered; replace the Enterprise copy of `optimize_policy` with the
shared one, which merges at the limit.
- Measure four engines on 1M × 384 with ANN: latency, warm time of a merged
segment, placement epochs per merge.
- mono s3vectors legs with the index enabled, go and rust volume servers,
single and distributed, plus the hardened TLS legs.
## Risks
- **Filtered recall.** AWS's weak spot is selective filters. Pre-filtering
keeps recall but costs probes; `minimum_nprobes`/`maximum_nprobes` is the
lever, and phase 0 has to show the latency is acceptable at 1M rows.
- **Memory.** IVF_FLAT resident bytes are about the raw vectors: 1M × 384 ×
4 bytes is 1.5 GB per copy. Enterprise spreads it by `capacity_bytes`; the
single open-source engine needs that much RAM or PQ.
- **Compaction and coverage.** Settled in phase 0: Lance 10 keeps the
bitmaps through `compact_files`, and coverage stays complete.
- **Build cost on the worker.** k-means over 1M × 384 is CPU-bound; execution
concurrency stays at one and the job reports progress so the admin UI shows
it working rather than hung.
- **Placement churn after merges.** Every merge is a new epoch; too frequent
merging makes engines re-warm constantly. `MAX_DELTAS = 8` bounds it; the
phase 5 measurement decides whether to raise it.
## Out of scope
HNSW indexes, GPU builds, per-request recall parameters in the AWS API
surface, and building an index at `CreateIndex` time.
-40
View File
@@ -1,40 +0,0 @@
# SeaweedFS vector engine
`weed-vector` serves the S3 Vectors data plane through the S3 gateway. Indexes use Lance tables on the cluster's filers and volume servers. Go and Rust volume servers use the same engine and API.
With a local `weed mini` cluster running:
```sh
weed-vector --masters=localhost:9333 --metrics-port=9329
```
Point an AWS S3 Vectors client at the S3 endpoint, normally `http://localhost:8333`. The engine registers with the masters automatically. `--listen` defaults to `127.0.0.1:8090`; use an address reachable from the gateway when running on another host or in a container.
| Setting | Default | Purpose |
| --- | --- | --- |
| `--masters` | Required | Comma-separated master addresses |
| `--listen` | `127.0.0.1:8090` | gRPC listener and registered address |
| `--filer-group` | Empty | Filer group used for table storage |
| `--read-cache-mb` | `512` | Immutable data/index read cache; zero disables it |
| `--nprobes` | Automatic | ANN partitions searched per query |
| `--metrics-port` | `0` | HTTP metrics and health listener; zero disables it |
| `--metrics-ip` | `127.0.0.1` | HTTP listener address |
| `--security-toml` | Discovered | Cluster certificates, signing keys and encryption keys |
The HTTP listener provides `/health`, `/ready`, and `/metrics`. Readiness requires an active registration with the master. The gRPC listener also implements the standard health service for `vector_pb.VectorService` and the whole server. These health statuses follow master registration.
Metrics use the `SeaweedFS_vector_` prefix:
- `connected`: active master registration.
- `request_total{type,code}`, `request_seconds{type}`, and `in_flight_requests{type}`: engine requests and their gRPC outcomes.
- `query_results_total`: vectors returned by queries.
- `cache_requests_total{result}`, `cache_bytes`, and `cache_entries`: immutable read cache activity and occupancy.
- `storage_read_bytes_total` and `storage_read_seconds`: storage fetches for cacheable immutable reads.
The S3 gateway separately publishes `SeaweedFS_s3_` request metrics with `type="s3vectors.<Operation>"`. Scrape both processes to distinguish gateway latency from engine work. Metrics and HTTP probes are unauthenticated; bind them to an internal address or restrict their network access.
For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `[grpc.client]` for its master/filer connections, and the cluster CA. HTTPS volume reads also use `[https.client]`. The engine follows the same signing and encryption configuration as the other cluster clients.
Run the Lance maintenance worker against the same masters and Lance namespace to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data.
@@ -13,8 +13,6 @@ pub struct IndexCoverage {
pub index_name: String,
/// Physical index segments: the IndexMetadata deltas sharing the name.
pub segments: usize,
/// IVF partitions of the largest segment.
pub partitions: usize,
/// False when any delta of this index lacks a fragment bitmap: the index
/// exists but which fragments it covers is unknown.
pub coverage_known: bool,
@@ -30,7 +28,6 @@ pub async fn coverage(dataset: &Dataset, vector_column: &str) -> Result<Vec<Inde
.field(vector_column)
.with_context(|| format!("no such column {vector_column}"))?;
let mut by_name: BTreeMap<String, Vec<Option<RoaringBitmap>>> = BTreeMap::new();
let mut partitions: BTreeMap<String, usize> = BTreeMap::new();
for index in dataset.load_indices().await?.iter() {
if index.fields != [field.id] {
continue;
@@ -39,9 +36,6 @@ pub async fn coverage(dataset: &Dataset, vector_column: &str) -> Result<Vec<Inde
.entry(index.name.clone())
.or_default()
.push(index.fragment_bitmap.clone());
let count = crate::index::segment_partitions(dataset, vector_column, &index.uuid).await?;
let most = partitions.entry(index.name.clone()).or_default();
*most = count.max(*most);
}
let all: RoaringBitmap = dataset.fragments().iter().map(|f| f.id as u32).collect();
let mut out = Vec::new();
@@ -64,7 +58,6 @@ pub async fn coverage(dataset: &Dataset, vector_column: &str) -> Result<Vec<Inde
}
}
out.push(IndexCoverage {
partitions: partitions.get(&name).copied().unwrap_or(0),
index_name: name,
segments: bitmaps.len(),
coverage_known,
-565
View File
@@ -1,565 +0,0 @@
//! Sizing the vector index an S3 Vectors table searches through, and the
//! probes a query spends on it. Building lives in the worker crate.
use anyhow::Result;
use lance::Dataset;
use lance::index::{DatasetIndexExt, DatasetIndexInternalExt};
pub use weed_lance_worker::vector_index::{
INDEX_NAME, MAX_PARTITIONS, build, distance_metric, index_names, optimize, partitions_for,
};
pub const MIN_PROBES: usize = 8;
/// How many partitions a query searches: `min` always, and under a prefilter
/// up to `max` until it has k rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Probes {
pub min: usize,
pub max: usize,
}
/// Probes for an index of `partitions`: a tenth of them, at least
/// [`MIN_PROBES`], never more than exist; a filtered query may widen to four
/// times that.
pub fn probes_for(partitions: usize) -> Probes {
let partitions = partitions.max(1);
let min = MIN_PROBES.max(partitions.div_ceil(10)).min(partitions);
Probes {
min,
max: (min * 4).min(partitions),
}
}
/// Partitions of one index segment, read from the opened index. Lance's index
/// statistics cost several milliseconds and may rewrite an old manifest.
pub async fn segment_partitions(
dataset: &Dataset,
vector_column: &str,
segment: &uuid::Uuid,
) -> Result<usize> {
let opened = dataset
.open_vector_index(
vector_column,
segment,
&lance_index::metrics::NoOpMetricsCollector,
)
.await?;
Ok(opened.total_partitions())
}
/// The probes a query of `vector_column` uses when it names none, or `None`
/// without an index. The count comes from the most partitions any index on
/// the column has, whichever of them the scan ends up searching; the scan
/// then finds the index it was read from already open.
pub async fn default_probes(dataset: &Dataset, vector_column: &str) -> Result<Option<Probes>> {
let Some(field) = dataset.schema().field(vector_column) else {
return Ok(None);
};
let mut partitions = None;
for index in dataset.load_indices().await?.iter() {
if index.fields != [field.id] {
continue;
}
let count = segment_partitions(dataset, vector_column, &index.uuid).await?;
partitions = Some(count.max(partitions.unwrap_or(0)));
}
Ok(partitions.map(probes_for))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::coverage::coverage;
use crate::query::{self, Query};
use crate::table::VectorTable;
use crate::testing::{self, DIM};
use lance::Dataset;
use lance::dataset::optimize::{CompactionOptions, compact_files};
use lance_linalg::distance::DistanceType;
use tempfile::TempDir;
#[test]
fn probes_are_a_tenth_with_a_floor() {
assert_eq!(probes_for(1), Probes { min: 1, max: 1 });
assert_eq!(probes_for(8), Probes { min: 8, max: 8 });
assert_eq!(probes_for(64), Probes { min: 8, max: 32 });
assert_eq!(probes_for(224), Probes { min: 23, max: 92 });
assert_eq!(
probes_for(4096),
Probes {
min: 410,
max: 1640
}
);
}
fn exact(vector: &[f32], k: usize) -> Query {
Query {
vector: vector.to_vec(),
k,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: None,
}
}
/// The test vectors repeat, so ties are common: compare distances, not rows.
async fn assert_same_top_k(dataset: &Dataset, vector: &[f32], k: usize) {
let table = VectorTable::resolve(dataset, None, None).unwrap();
let q = exact(vector, k);
let flat = query::flat(dataset, &table, &q).await.unwrap();
let ann = query::ann(
dataset,
&table,
&Query {
nprobes: Some(MAX_PARTITIONS),
..q
},
)
.await
.unwrap();
assert_eq!(flat.len(), ann.len());
for (f, a) in flat.iter().zip(ann.iter()) {
assert!(
(f.distance - a.distance).abs() < 1e-6,
"{flat:?} vs {ann:?}"
);
}
}
/// Pseudo-random rows, so partitions are not degenerate; a different seed
/// gives vectors the table does not hold.
fn scattered(rows: usize, dim: usize, seed: u64) -> Vec<Vec<f32>> {
let mut state: u64 = seed;
(0..rows)
.map(|_| {
(0..dim)
.map(|_| {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((state >> 40) as f32) / (1u64 << 24) as f32
})
.collect()
})
.collect()
}
#[tokio::test]
async fn default_probes_follow_the_index_and_find_the_neighbours() {
let dir = TempDir::new().unwrap();
let rows = scattered(4000, 8, 0x9E3779B97F4A7C15);
let tags: Vec<&str> = (0..4000)
.map(|i| if i % 100 == 0 { "rare" } else { "common" })
.collect();
let mut dataset = testing::write_dataset(&dir, &rows, &tags).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
assert_eq!(default_probes(&dataset, "vector").await.unwrap(), None);
build(&mut dataset, &table.vector_column, INDEX_NAME, 64, false)
.await
.unwrap();
assert_eq!(
default_probes(&dataset, "vector").await.unwrap(),
Some(probes_for(64))
);
let mut found = 0;
let total = 20 * 10;
for vector in &scattered(20, 8, 0xD1B54A32D192ED03) {
let q = exact(vector, 10);
let flat: std::collections::HashSet<u64> = query::flat(&dataset, &table, &q)
.await
.unwrap()
.iter()
.map(|h| h.row_id)
.collect();
let ann = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(ann.len(), 10);
found += ann.iter().filter(|h| flat.contains(&h.row_id)).count();
}
assert!(found * 10 >= total * 9, "recall {found}/{total}");
// Eight probes do not hold ten of the 1% rare rows; a filtered query
// widens past the minimum until it has them.
let filtered = query::ann(
&dataset,
&table,
&Query {
filter: Some("tag = 'rare'".to_string()),
..exact(&rows[0], 10)
},
)
.await
.unwrap();
assert_eq!(filtered.len(), 10);
}
#[tokio::test]
async fn default_probes_take_the_largest_index() {
use lance::index::DatasetIndexExt;
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &scattered(1000, 8, 0x9E3779B97F4A7C15), &["a"; 1000])
.await;
testing::append_dataset(
&mut dataset,
&scattered(1000, 8, 0xD1B54A32D192ED03),
&["b"; 1000],
)
.await;
for (name, fragment, partitions) in [("a-small", 0u32, 2), ("z-large", 1u32, 100)] {
dataset
.create_index_builder(
&["vector"],
IndexType::Vector,
&VectorIndexParams::ivf_flat(partitions, DistanceType::L2),
)
.name(name.to_string())
.fragments(vec![fragment])
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
}
assert_eq!(
default_probes(&dataset, "vector").await.unwrap(),
Some(probes_for(100))
);
}
#[tokio::test]
async fn build_covers_every_fragment() {
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(200, DIM), &["a"; 200]).await;
testing::append_dataset(&mut dataset, &testing::vectors(50, DIM), &["b"; 50]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(
&mut dataset,
&table.vector_column,
INDEX_NAME,
partitions_for(250),
false,
)
.await
.unwrap();
let cov = coverage(&dataset, "vector").await.unwrap();
assert_eq!(cov.len(), 1);
assert_eq!(cov[0].index_name, INDEX_NAME);
assert_eq!(cov[0].segments, 1);
assert!(cov[0].coverage_known);
assert!(cov[0].unindexed_fragments.is_empty());
for vector in testing::vectors(4, DIM) {
assert_same_top_k(&dataset, &vector, 10).await;
}
}
#[tokio::test]
async fn build_uses_the_tables_metric() {
for (metric, distance) in [
("COSINE", DistanceType::Cosine),
("DOT_PRODUCT", DistanceType::Dot),
("L2", DistanceType::L2),
] {
let dir = TempDir::new().unwrap();
let rows = testing::vectors(300, DIM);
let mut dataset =
testing::write_dataset_with_metric(&dir, &rows, &["a"; 300], metric).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
assert_eq!(distance_metric(&dataset, "vector"), distance);
build(&mut dataset, &table.vector_column, INDEX_NAME, 4, false)
.await
.unwrap();
for vector in testing::vectors(3, DIM) {
let q = Query {
distance,
..exact(&vector, 10)
};
let flat = query::flat(&dataset, &table, &q).await.unwrap();
let ann = query::ann(
&dataset,
&table,
&Query {
nprobes: Some(4),
..q
},
)
.await
.unwrap();
assert_eq!(flat.len(), ann.len(), "{metric}");
for (f, a) in flat.iter().zip(ann.iter()) {
assert!(
(f.distance - a.distance).abs() < 1e-5,
"{metric}: {flat:?} vs {ann:?}"
);
}
}
}
}
/// An index built as cosine on a table without metric metadata keeps
/// cosine through a retrain, and gets partitions for the new row count.
#[tokio::test]
async fn retrain_keeps_the_indexs_own_metric() {
use lance::index::DatasetIndexExt;
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
use weed_lance_worker::vector_index::index_settings;
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(100, DIM), &["a"; 100]).await;
let params = VectorIndexParams::ivf_flat(2, DistanceType::Cosine);
dataset
.create_index(
&["vector"],
IndexType::Vector,
Some("idx".to_string()),
&params,
false,
)
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
testing::append_dataset(&mut dataset, &testing::vectors(800, DIM), &["b"; 800]).await;
optimize(&mut dataset, "vector", true).await.unwrap();
let settings = index_settings(&dataset, "idx").await.unwrap();
assert_eq!(settings.metric, Some(DistanceType::Cosine));
assert_eq!(settings.index_type, "IVF_FLAT");
assert_eq!(settings.partitions, partitions_for(900));
}
#[tokio::test]
async fn optimize_appends_then_retrain_folds_segments() {
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(100, DIM), &["a"; 100]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(&mut dataset, &table.vector_column, INDEX_NAME, 4, false)
.await
.unwrap();
let mut appended = testing::vectors(40, DIM);
appended.push(vec![9.0; DIM]);
testing::append_dataset(&mut dataset, &appended, &["b"; 41]).await;
optimize(&mut dataset, &table.vector_column, false)
.await
.unwrap();
let cov = &coverage(&dataset, "vector").await.unwrap()[0];
assert_eq!(cov.segments, 2);
assert!(cov.unindexed_fragments.is_empty());
let hits = query::ann(
&dataset,
&table,
&Query {
nprobes: Some(4),
..exact(&[9.0; DIM], 1)
},
)
.await
.unwrap();
assert_eq!(hits[0].key, "k140", "{hits:?}");
testing::append_dataset(&mut dataset, &testing::vectors(40, DIM), &["c"; 40]).await;
optimize(&mut dataset, &table.vector_column, true)
.await
.unwrap();
let cov = &coverage(&dataset, "vector").await.unwrap()[0];
assert_eq!(cov.segments, 1);
assert!(cov.coverage_known);
assert!(cov.unindexed_fragments.is_empty());
for vector in testing::vectors(4, DIM) {
assert_same_top_k(&dataset, &vector, 10).await;
}
}
/// Append and optimize nine times: the deltas climb to the limit and then
/// fold into one, and nothing is ever uncovered after an optimize.
#[tokio::test]
async fn deltas_stay_under_the_limit_across_cycles() {
use weed_lance_worker::vector_index::{MAX_DELTAS, coverage as covered};
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(100, DIM), &["a"; 100]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(&mut dataset, &table.vector_column, INDEX_NAME, 4, false)
.await
.unwrap();
let mut seen = Vec::new();
for round in 0..9 {
testing::append_dataset(&mut dataset, &testing::vectors(20, DIM), &["b"; 20]).await;
optimize(&mut dataset, &table.vector_column, false)
.await
.unwrap();
let cover = covered(&dataset, "vector").await.unwrap().unwrap();
assert_eq!(cover.unindexed_rows, 0, "round {round}");
seen.push(cover.deltas[INDEX_NAME]);
}
assert_eq!(seen, vec![2, 3, 4, 5, 6, 7, 8, 1, 2]);
assert!(seen.iter().all(|&d| d <= MAX_DELTAS));
}
/// Two names covering disjoint fragments, as a sharded build leaves them:
/// coverage is their union, and an optimize extends one name only.
#[tokio::test]
async fn shards_stay_disjoint_through_an_optimize() {
use lance::index::DatasetIndexExt;
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
use weed_lance_worker::vector_index::coverage as covered;
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(60, DIM), &["a"; 60]).await;
testing::append_dataset(&mut dataset, &testing::vectors(60, DIM), &["b"; 60]).await;
let params = VectorIndexParams::ivf_flat(2, DistanceType::L2);
for (name, fragment) in [("shard-0", 0u32), ("shard-1", 1u32)] {
dataset
.create_index_builder(&["vector"], IndexType::Vector, &params)
.name(name.to_string())
.fragments(vec![fragment])
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
}
let cover = covered(&dataset, "vector").await.unwrap().unwrap();
assert_eq!((cover.indexed_rows, cover.unindexed_rows), (120, 0));
assert_eq!(cover.deltas.len(), 2);
testing::append_dataset(&mut dataset, &testing::vectors(30, DIM), &["c"; 30]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
optimize(&mut dataset, &table.vector_column, false)
.await
.unwrap();
let cover = covered(&dataset, "vector").await.unwrap().unwrap();
assert_eq!(cover.unindexed_rows, 0);
assert_eq!(
cover.deltas.values().sum::<usize>(),
3,
"{:?}",
cover.deltas
);
let per_name = coverage(&dataset, "vector").await.unwrap();
let untouched = per_name
.iter()
.filter(|c| c.segments == 1 && c.indexed_fragments.len() == 1)
.count();
assert_eq!(untouched, 1, "{per_name:?}");
for vector in testing::vectors(3, DIM) {
assert_same_top_k(&dataset, &vector, 10).await;
}
}
/// A retrain is due for one IVF_FLAT name the table outgrew, never for
/// shards sized each for their own fragments or for another index type,
/// and an explicit retrain of shards leaves them as they are.
#[tokio::test]
async fn retrain_is_due_for_one_ivf_flat_name_only() {
use lance::index::DatasetIndexExt;
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
use weed_lance_worker::vector_index::{coverage as covered, retrain_due};
let grown = |dir: &TempDir| {
let path = dir.path().to_str().unwrap().to_string();
async move {
let mut dataset =
testing::write_dataset_at(&path, &testing::vectors(300, DIM), &["a"; 300])
.await;
testing::append_dataset(&mut dataset, &testing::vectors(300, DIM), &["b"; 300])
.await;
dataset
}
};
let dir = TempDir::new().unwrap();
let mut dataset = grown(&dir).await;
build(&mut dataset, "vector", INDEX_NAME, 2, false)
.await
.unwrap();
assert!(retrain_due(&dataset, "vector").await.unwrap());
let dir = TempDir::new().unwrap();
let mut dataset = grown(&dir).await;
let params = VectorIndexParams::ivf_pq(2, 8, 2, DistanceType::L2, 10);
dataset
.create_index(&["vector"], IndexType::Vector, None, &params, false)
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
assert!(!retrain_due(&dataset, "vector").await.unwrap());
let dir = TempDir::new().unwrap();
let mut dataset = grown(&dir).await;
let params = VectorIndexParams::ivf_flat(2, DistanceType::L2);
for (name, fragment) in [("shard-0", 0u32), ("shard-1", 1u32)] {
dataset
.create_index_builder(&["vector"], IndexType::Vector, &params)
.name(name.to_string())
.fragments(vec![fragment])
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
}
assert!(!retrain_due(&dataset, "vector").await.unwrap());
let before = covered(&dataset, "vector").await.unwrap();
assert!(optimize(&mut dataset, "vector", true).await.is_err());
assert_eq!(covered(&dataset, "vector").await.unwrap(), before);
let per_name = coverage(&dataset, "vector").await.unwrap();
assert!(
per_name.iter().all(|c| c.indexed_fragments.len() == 1),
"{per_name:?}"
);
}
#[tokio::test]
async fn compaction_keeps_the_index_covering() {
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(60, DIM), &["a"; 60]).await;
for tag in ["b", "c", "d"] {
testing::append_dataset(&mut dataset, &testing::vectors(60, DIM), &[tag; 60]).await;
}
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(&mut dataset, &table.vector_column, INDEX_NAME, 4, false)
.await
.unwrap();
dataset.delete("key = 'k0'").await.unwrap();
assert_eq!(dataset.get_fragments().len(), 4);
let options = CompactionOptions {
target_rows_per_fragment: 1000,
materialize_deletions: true,
materialize_deletions_threshold: 0.0,
..Default::default()
};
compact_files(&mut dataset, options, None).await.unwrap();
dataset.checkout_latest().await.unwrap();
assert_eq!(dataset.get_fragments().len(), 1);
let cov = &coverage(&dataset, "vector").await.unwrap()[0];
assert!(cov.coverage_known);
assert!(cov.unindexed_fragments.is_empty(), "{cov:?}");
let hits = query::ann(
&dataset,
&table,
&Query {
nprobes: Some(MAX_PARTITIONS),
..exact(&testing::vectors(1, DIM)[0], 10)
},
)
.await
.unwrap();
let mut tied: Vec<&str> = hits
.iter()
.filter(|h| h.distance < 1e-6)
.map(|h| h.key.as_str())
.collect();
tied.sort();
assert_eq!(tied, ["k120", "k180", "k60"], "{hits:?}");
for vector in testing::vectors(4, DIM) {
assert_same_top_k(&dataset, &vector, 10).await;
}
}
}
-1
View File
@@ -7,7 +7,6 @@
pub mod coverage;
mod filter;
pub mod index;
pub mod maintenance;
pub mod query;
pub mod segments;
+31 -200
View File
@@ -1,21 +1,17 @@
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id};
use weed_lance_worker::dataset::{self, Storage};
use weed_lance_worker::catalog::{NamespaceClient, parse_id};
use weed_lance_worker::dataset::{self, FallbackOptions};
use weed_vector_core::coverage;
use weed_vector_core::index;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
/// Mirrors `weed-worker`'s flags where the two touch the same thing: the
/// namespace that says where a table is, and the masters whose filers hold
/// it.
/// namespace is WEED_LANCE_NAMESPACE and the fallback storage credentials are
/// the same env vars.
#[derive(Parser, Debug)]
#[command(
name = "weed-vector",
about = "Describe, query and index S3 Vectors tables"
)]
#[command(name = "weed-vector", about = "SeaweedFS vector query spike")]
struct Args {
/// Lance namespace the tables live in.
#[arg(
@@ -25,29 +21,12 @@ struct Args {
)]
namespace: String,
/// Comma-separated master addresses, whose filers the tables are kept
/// through. A table named by a local URI needs none.
#[arg(long, alias = "master", env = "WEED_MASTERS")]
masters: Option<String>,
/// Storage credentials to use where the namespace vends none.
#[arg(long, env = "WEED_S3_ACCESS_KEY")]
access_key: Option<String>,
/// The filer group whose filers hold the tables.
#[arg(
long,
alias = "filer.group",
env = "WEED_FILER_GROUP",
default_value = ""
)]
filer_group: String,
/// The `jwt.filer_signing.key` of the cluster, which the namespace
/// authenticates cluster processes with; security.toml's by default.
#[arg(long, env = "WEED_FILER_SIGNING_KEY")]
filer_signing_key: Option<String>,
/// The cluster's security.toml; by default the file weed processes find
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<std::path::PathBuf>,
#[arg(long, env = "WEED_S3_SECRET_KEY")]
secret_key: Option<String>,
#[command(subcommand)]
command: Command,
@@ -112,67 +91,24 @@ enum Command {
#[arg(long)]
key_column: Option<String>,
},
/// Build or extend the vector index, then print its coverage.
Index {
#[command(subcommand)]
action: IndexAction,
},
}
#[derive(Subcommand, Debug)]
enum IndexAction {
/// An IVF_FLAT index in the table's metric; partitions default to the
/// square root of the row count.
Build {
id: String,
#[arg(long)]
partitions: Option<usize>,
#[arg(long, default_value = index::INDEX_NAME)]
name: String,
/// Rebuild an index of that name instead of failing.
#[arg(long)]
replace: bool,
#[arg(long)]
vector_column: Option<String>,
},
/// Cover the rows written since the index was built.
Optimize {
id: String,
/// Train the index again on every row instead of adding a segment.
#[arg(long)]
retrain: bool,
#[arg(long)]
vector_column: Option<String>,
},
}
/// `id` is a delimiter-joined table id; when it looks like a URI the dataset
/// is opened directly, skipping the namespace: an `s3://` URI on the
/// cluster's storage, a local path (`/path/...`, `file://...`) as it is.
/// `id` is a delimiter-joined table id; when it looks like a URI (`s3://...`,
/// `/path/...`, `file://...`) the dataset is opened directly, skipping the
/// namespace — useful for a spike run against a local dataset.
async fn open_dataset(
client: &NamespaceClient,
id: &str,
storage: &Storage,
fallback: &FallbackOptions,
) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
if id.contains("://") || id.starts_with('/') {
let mut builder = lance::dataset::builder::DatasetBuilder::from_uri(id);
if !fallback.is_empty() {
builder = builder.with_storage_options(fallback.clone());
}
return builder.load().await.with_context(|| format!("open {id}"));
}
if storage.0.is_none() {
bail!("{id} is kept on the cluster and needs --masters");
}
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
};
return dataset::open_at(&description, storage.wrapper(id).await?, None).await;
}
let table = dataset::open(client, &parse_id(id), storage).await?;
let table = dataset::open(client, &parse_id(id), fallback).await?;
Ok(table.dataset)
}
@@ -180,7 +116,6 @@ async fn open_dataset(
async fn main() -> Result<()> {
weed_lance_worker::tls::install_default_crypto_provider();
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
@@ -188,21 +123,12 @@ async fn main() -> Result<()> {
.init();
let args = Args::parse();
let security =
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
);
let client = NamespaceClient::new(args.namespace).with_signing_key(signing_key.as_ref());
let storage = match &args.masters {
Some(masters) => {
let cluster =
weed_lance_worker::cluster::Cluster::new(masters, &args.filer_group, &security)?;
Storage(Some(cluster.storage(&security).await?))
}
None => Storage::default(),
};
let mut fallback = FallbackOptions::new();
if let (Some(access), Some(secret)) = (args.access_key, args.secret_key) {
fallback.insert("aws_access_key_id".to_string(), access);
fallback.insert("aws_secret_access_key".to_string(), secret);
}
let client = NamespaceClient::new(args.namespace).with_fallback(&fallback);
match args.command {
Command::Describe {
@@ -210,7 +136,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = open_dataset(&client, &id, &fallback).await?;
let schema: arrow_schema::Schema = dataset.schema().into();
let resolved =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
@@ -250,7 +176,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = open_dataset(&client, &id, &fallback).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
@@ -262,7 +188,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = open_dataset(&client, &id, &fallback).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
for batch in query::get(&dataset, &vector, &keys, None).await? {
@@ -282,7 +208,7 @@ async fn main() -> Result<()> {
key_column,
nprobes,
} => {
let opened = open_dataset(&client, &id, &storage).await?;
let opened = open_dataset(&client, &id, &fallback).await?;
let dataset = match version {
Some(v) => opened.checkout_version(v).await?,
None => opened,
@@ -317,49 +243,6 @@ async fn main() -> Result<()> {
};
println!("{}", serde_json::to_string_pretty(&hits)?);
}
Command::Index { action } => {
let (id, vector_column) = match &action {
IndexAction::Build {
id, vector_column, ..
}
| IndexAction::Optimize {
id, vector_column, ..
} => (id.clone(), vector_column.clone()),
};
let mut dataset = open_dataset(&client, &id, &storage).await?;
let table = VectorTable::resolve(&dataset, vector_column.as_deref(), None)?;
let started = std::time::Instant::now();
match action {
IndexAction::Build {
partitions,
name,
replace,
..
} => {
let rows = dataset.count_rows(None).await?;
let partitions = partitions.unwrap_or_else(|| index::partitions_for(rows));
index::build(
&mut dataset,
&table.vector_column,
&name,
partitions,
replace,
)
.await?;
}
IndexAction::Optimize { retrain, .. } => {
index::optimize(&mut dataset, &table.vector_column, retrain).await?;
}
}
println!(
"{}",
serde_json::json!({
"version": dataset.version().version,
"seconds": started.elapsed().as_secs_f64(),
"coverage": coverage::coverage(&dataset, &table.vector_column).await?,
})
);
}
}
Ok(())
}
@@ -389,58 +272,6 @@ mod tests {
}
}
#[test]
fn cluster_flags_mirror_the_engine_and_the_worker() {
let args = Args::try_parse_from([
"weed-vector",
"--masters",
"m:9333",
"--filer-group",
"eu",
"describe",
"t",
])
.unwrap();
assert_eq!(args.masters.as_deref(), Some("m:9333"));
assert_eq!(args.filer_group, "eu");
assert!(
Args::try_parse_from(["weed-vector", "--encryptVolumeData", "describe", "t"]).is_err(),
"volume encryption follows the filer"
);
}
#[test]
fn index_build_takes_partitions_and_a_name() {
let args = Args::try_parse_from([
"weed-vector",
"index",
"build",
"b$vector$i",
"--partitions",
"32",
"--replace",
])
.unwrap();
match args.command {
Command::Index {
action:
IndexAction::Build {
id,
partitions,
name,
replace,
..
},
} => {
assert_eq!(id, "b$vector$i");
assert_eq!(partitions, Some(32));
assert_eq!(name, index::INDEX_NAME);
assert!(replace);
}
_ => panic!("expected index build"),
}
}
#[test]
fn column_flags_on_get_describe_coverage() {
for argv in [
+5 -237
View File
@@ -2,8 +2,8 @@
//! and version tags act as the lease maintenance must respect.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex, Weak};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::Result;
use lance::Dataset;
@@ -21,11 +21,6 @@ const FOREIGN_TTL: Duration = Duration::from_secs(24 * 3600);
/// Expired-lease scans run at most once per interval per dataset, not per
/// request.
const REAP_INTERVAL: Duration = Duration::from_secs(60);
/// How long a shared lease stays after the last read that took it.
const SHARED_LINGER: Duration = Duration::from_secs(10);
/// A shared lease is handed out for this long after it was taken, then
/// replaced, so a busy version's tag never ages into a reaper's TTL.
const SHARED_FOR: Duration = Duration::from_secs(300);
/// A process-unique owner id embedded in lease tags so a reaper only applies
/// the short TTL to its own leases.
static INSTANCE: LazyLock<String> = LazyLock::new(|| Uuid::new_v4().simple().to_string());
@@ -143,106 +138,6 @@ fn untrack(tag: &str) {
}
}
/// Leases that reads of one version share: the first read tags the version,
/// reads that follow reuse the tag, and the tag goes once no read has taken it
/// for [`SHARED_LINGER`]. Spares a tag write and delete per read.
pub struct SharedLeases {
/// By location, version, manifest ETag and commit time: a table dropped
/// and created again at its location reuses version numbers, not
/// manifests. A rename commit leaves no ETag.
held: Mutex<Held>,
linger: Duration,
share_for: Duration,
}
type LeaseKey = (String, u64, Option<String>, u128);
#[derive(Default)]
struct Held {
slots: HashMap<LeaseKey, Slot>,
/// Slots are pruned once they reach this many, so a lookup does not
/// scan them all.
prune_at: usize,
}
/// Reads of a version that find no lease wait here for the first to take it.
type Slot = Arc<tokio::sync::Mutex<Weak<SharedLease>>>;
impl Default for SharedLeases {
fn default() -> Self {
Self {
held: Mutex::default(),
linger: SHARED_LINGER,
share_for: SHARED_FOR,
}
}
}
/// A lease held for as long as any read, or the linger after the last one,
/// keeps it.
pub struct SharedLease {
_lease: Lease,
taken: Instant,
}
impl SharedLeases {
/// [`try_pin`], reusing a lease another read of this version holds.
pub async fn try_pin(&self, dataset: &Dataset) -> Result<Option<Arc<SharedLease>>> {
let key = (
dataset.uri().to_string(),
dataset.version().version,
dataset.manifest_location().e_tag.clone(),
dataset.manifest().timestamp_nanos,
);
let slot = match self.held.lock() {
Ok(mut held) => {
if held.slots.len() >= held.prune_at {
// A slot another read has taken but not yet locked stays.
held.slots.retain(|_, slot| {
Arc::strong_count(slot) > 1
|| slot
.try_lock()
.map_or(true, |lease| lease.strong_count() > 0)
});
held.prune_at = (2 * held.slots.len()).max(64);
// A burst's allocation would otherwise make every later
// prune scan it.
let capacity = held.prune_at;
held.slots.shrink_to(capacity);
}
held.slots.entry(key).or_default().clone()
}
Err(_) => Slot::default(),
};
let mut slot = slot.lock().await;
let lease = match slot
.upgrade()
.filter(|lease| lease.taken.elapsed() < self.share_for)
{
Some(lease) => lease,
None => {
let Some(lease) = try_pin(dataset).await? else {
return Ok(None);
};
let lease = Arc::new(SharedLease {
_lease: lease,
taken: Instant::now(),
});
*slot = Arc::downgrade(&lease);
lease
}
};
drop(slot);
if let Ok(handle) = tokio::runtime::Handle::try_current() {
let (lingering, linger) = (lease.clone(), self.linger);
handle.spawn(async move {
tokio::time::sleep(linger).await;
drop(lingering);
});
}
Ok(Some(lease))
}
}
/// Drop lease tags whose owner never released them, so an abandoned lease
/// cannot keep a version out of cleanup forever.
async fn reap_expired(dataset: &Dataset, now: u128) {
@@ -283,7 +178,8 @@ async fn reap_expired(dataset: &Dataset, now: u128) {
}
})
.is_some_and(|(own, stamp)| {
now.saturating_sub(stamp) > if own { LEASE_TTL } else { FOREIGN_TTL }.as_nanos()
now.saturating_sub(stamp)
> if own { LEASE_TTL } else { FOREIGN_TTL }.as_nanos()
});
if expired && !held {
let _ = dataset.tags().delete(name).await;
@@ -429,131 +325,6 @@ mod tests {
b.release().await.unwrap();
}
/// Reads of one version share a tag, another version gets its own, and
/// the tags go once the linger after the last read has passed.
#[tokio::test]
async fn reads_of_a_version_share_one_lease() {
let dir = TempDir::new().unwrap();
let mut dataset =
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
let leases = SharedLeases {
linger: Duration::from_millis(50),
..Default::default()
};
let a = leases.try_pin(&dataset).await.unwrap().unwrap();
let b = leases.try_pin(&dataset).await.unwrap().unwrap();
assert!(Arc::ptr_eq(&a, &b));
assert_eq!(dataset.tags().list().await.unwrap().len(), 1);
testing::append_dataset(&mut dataset, &testing::vectors(1, 4), &["e"]).await;
let c = leases.try_pin(&dataset).await.unwrap().unwrap();
assert!(!Arc::ptr_eq(&a, &c));
assert_eq!(dataset.tags().list().await.unwrap().len(), 2);
drop((a, b, c));
tokio::time::sleep(leases.linger).await;
let mut left = usize::MAX;
for _ in 0..1000 {
// A listing that meets a tag as it is deleted fails; try again.
if let Ok(tags) = dataset.tags().list().await {
left = tags.len();
}
if left == 0 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(left, 0);
}
/// Reads that arrive together, before any lease exists, share the one the
/// first takes.
#[tokio::test]
async fn concurrent_reads_take_one_lease() {
let dir = TempDir::new().unwrap();
let dataset =
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
let leases = SharedLeases::default();
let pins: Vec<_> = futures::future::join_all((0..8).map(|_| leases.try_pin(&dataset)))
.await
.into_iter()
.map(|lease| lease.unwrap().unwrap())
.collect();
assert!(pins.iter().all(|lease| Arc::ptr_eq(lease, &pins[0])));
assert_eq!(dataset.tags().list().await.unwrap().len(), 1);
}
/// A table dropped and written again at its location gets its own lease
/// for a version number the old table had.
#[tokio::test]
async fn a_recreated_table_takes_its_own_lease() {
let dir = TempDir::new().unwrap();
let rows = testing::vectors(4, 4);
let old = testing::write_dataset(&dir, &rows, &["a", "b", "c", "d"]).await;
let leases = SharedLeases::default();
let first = leases.try_pin(&old).await.unwrap().unwrap();
std::fs::remove_dir_all(dir.path()).unwrap();
let new = testing::write_dataset(&dir, &rows, &["e", "f", "g", "h"]).await;
assert_eq!(new.version().version, old.version().version);
let second = leases.try_pin(&new).await.unwrap().unwrap();
assert!(!Arc::ptr_eq(&first, &second));
assert_eq!(new.tags().list().await.unwrap().len(), 1);
}
/// Slots of released leases are pruned as new versions come in.
#[tokio::test]
async fn released_lease_slots_are_pruned() {
let dir = TempDir::new().unwrap();
let mut dataset = testing::write_dataset(&dir, &testing::vectors(1, 4), &["a"]).await;
let leases = SharedLeases {
linger: Duration::ZERO,
..Default::default()
};
for _ in 0..200 {
drop(leases.try_pin(&dataset).await.unwrap());
tokio::task::yield_now().await;
testing::append_dataset(&mut dataset, &testing::vectors(1, 4), &["b"]).await;
}
assert!(leases.held.lock().unwrap().slots.len() <= 128);
}
/// A slot a read has taken but not yet locked survives a prune, so that
/// read and the next share the lease.
#[tokio::test]
async fn a_taken_slot_survives_a_prune() {
let dir = TempDir::new().unwrap();
let dataset = testing::write_dataset(&dir, &testing::vectors(1, 4), &["a"]).await;
let leases = SharedLeases::default();
let key: LeaseKey = ("elsewhere".into(), 1, None, 0);
let taken = {
let mut held = leases.held.lock().unwrap();
held.prune_at = 0;
held.slots.entry(key.clone()).or_default().clone()
};
leases.try_pin(&dataset).await.unwrap().unwrap();
assert!(Arc::ptr_eq(
&leases.held.lock().unwrap().slots[&key],
&taken
));
}
/// A shared lease is not handed out past SHARED_FOR, so a busy version
/// moves to a fresh tag.
#[tokio::test]
async fn a_shared_lease_is_replaced_when_old() {
let dir = TempDir::new().unwrap();
let dataset =
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
let leases = SharedLeases {
share_for: Duration::from_millis(50),
..Default::default()
};
let a = leases.try_pin(&dataset).await.unwrap().unwrap();
tokio::time::sleep(leases.share_for).await;
let b = leases.try_pin(&dataset).await.unwrap().unwrap();
assert!(!Arc::ptr_eq(&a, &b));
}
/// A stale lease tag left behind is reaped by the next pin; a stale-named
/// tag this process still holds is not.
#[tokio::test]
@@ -608,10 +379,7 @@ mod tests {
let foreign = format!("{QUERY_TAG_PREFIX}other-{stale}-foreign");
dataset
.tags()
.create(
&foreign,
Ref::Version(None, Some(dataset.version().version)),
)
.create(&foreign, Ref::Version(None, Some(dataset.version().version)))
.await
.unwrap();
let lease = pin(&dataset).await.unwrap();
+2 -22
View File
@@ -120,28 +120,8 @@ async fn scanner(
crate::filter::apply(&mut scanner, filter)?;
scanner.prefilter(!query.postfilter);
}
// An explicitly empty segment list searches no index, so there is
// nothing to size probes for.
let no_segments = query.index_segments.as_ref().is_some_and(|s| s.is_empty());
if use_index && !no_segments {
let probes = match query.nprobes {
Some(n) => Some(crate::index::Probes { min: n, max: n }),
None => crate::index::default_probes(dataset, &table.vector_column).await?,
};
if let Some(probes) = probes {
// Lance searches `min` partitions, and under a prefilter keeps
// going up to `max` until it has k rows. An open bound would
// make it prepare every partition for that, which costs as much
// as the exact scan it is meant to avoid.
scanner.minimum_nprobes(probes.min);
scanner.maximum_nprobes(probes.max);
tracing::debug!(
min = probes.min,
max = probes.max,
filtered = query.filter.is_some(),
"ann scan"
);
}
if let Some(nprobes) = query.nprobes {
scanner.nprobes(nprobes);
}
let segments = query.index_segments.as_deref().unwrap_or(&[]);
if use_index && !segments.is_empty() {
-34
View File
@@ -66,40 +66,6 @@ pub async fn write_dataset_at(uri: &str, vectors: &[Vec<f32>], tags: &[&str]) ->
Dataset::write(reader, uri, None).await.unwrap()
}
/// Like [`write_dataset`], with the vector field carrying the `distance_metric`
/// metadata `CreateIndex` writes (`L2`, `COSINE`, `DOT_PRODUCT`).
pub async fn write_dataset_with_metric(
dir: &TempDir,
vectors: &[Vec<f32>],
tags: &[&str],
metric: &str,
) -> Dataset {
let dim = vectors[0].len();
let plain = schema(dim);
let fields: Vec<Arc<Field>> =
plain
.fields()
.iter()
.map(|f| {
if f.name() == "vector" {
Arc::new(f.as_ref().clone().with_metadata(
[("distance_metric".to_string(), metric.to_string())].into(),
))
} else {
f.clone()
}
})
.collect();
let schema = Arc::new(Schema::new(fields));
let batch = batch(0, vectors, tags, dim)
.with_schema(schema.clone())
.unwrap();
let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema);
Dataset::write(reader, dir.path().to_str().unwrap(), None)
.await
.unwrap()
}
/// Deterministic non-trivial vectors for index coverage tests.
pub fn vectors(rows: usize, dim: usize) -> Vec<Vec<f32>> {
(0..rows)
+1 -6
View File
@@ -13,12 +13,8 @@ name = "weed-vector"
path = "src/main.rs"
[dependencies]
axum = "0.8"
prometheus = { version = "0.13", default-features = false }
tonic-health = "0.14"
weed-vector-core = { path = "../core" }
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
sw-client = { path = "../../../seaweed-worker/crates/sw-client" }
lance = { version = "10", default-features = false, features = ["aws"] }
lance-arrow = "10"
lance-linalg = "10"
@@ -36,8 +32,7 @@ bytes = "1"
clap = { version = "4", features = ["derive", "env"] }
futures = "0.3"
moka = { version = "0.12", features = ["sync"] }
uuid = { version = "1", features = ["v4"] }
object_store = { version = "0.13", features = ["aws"] }
object_store = "0.13"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio.workspace = true
-8
View File
@@ -1,7 +1,5 @@
//! The VectorService gRPC server the S3 gateway talks to.
pub mod metrics;
pub mod observed;
pub mod read_cache;
pub mod service;
@@ -15,12 +13,6 @@ pub mod master_pb {
tonic::include_proto!("master_pb");
}
pub mod master_client;
pub mod security {
pub use weed_lance_worker::security::*;
}
pub mod tls {
pub use weed_lance_worker::grpc_tls::*;
}
pub mod pb {
pub mod vector {
+55 -199
View File
@@ -1,83 +1,47 @@
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::Parser;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::Server;
use weed_lance_worker::cluster::Cluster;
use tonic::transport::server::TcpIncoming;
use weed_lance_worker::catalog::{NamespaceClient, SigningKey};
use weed_lance_worker::dataset::FallbackOptions;
use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer;
use weed_vector_server::read_cache::ReadCache;
use weed_vector_server::security::Security;
use weed_vector_server::service::VectorServer;
use weed_vector_server::tls::{self, ServerTls};
use weed_vector_server::{
master_client,
metrics::{self, Metrics},
observed::ObservedService,
};
/// The VectorService the S3 gateway fans vector calls out to.
#[derive(Parser)]
struct Args {
/// Lance Namespace base URL: the S3 gateway's Lance port (-s3.port.lance).
#[arg(
long,
env = "WEED_VECTOR_NAMESPACE",
default_value = "http://localhost:9101"
)]
namespace: String,
/// gRPC listen address.
#[arg(long, env = "WEED_VECTOR_LISTEN", default_value = "127.0.0.1:8090")]
listen: String,
/// Address to register when it differs from the listen address.
#[arg(long, env = "WEED_VECTOR_ADVERTISE")]
advertise: Option<String>,
/// Comma-separated master addresses. The engine registers with them, so
/// the gateway finds it, and asks them for the filers it keeps tables
/// through.
/// object_store option fallback for deployments that vend no credentials:
/// key=value, repeatable.
#[arg(long = "storage-option", alias = "storage.option", value_parser = parse_option)]
storage_options: Vec<(String, String)>,
/// Comma-separated master addresses to register this server with; the
/// gateway discovers it via ListClusterNodes(client_type=vector).
#[arg(long, alias = "master", env = "WEED_VECTOR_MASTERS")]
masters: String,
/// The filer group whose filers the engine keeps tables through.
#[arg(
long,
alias = "filer.group",
env = "WEED_VECTOR_FILER_GROUP",
default_value = ""
)]
filer_group: String,
masters: Option<String>,
/// Memory for caching reads of write-once table files, in MiB; 0 disables.
#[arg(long, env = "WEED_VECTOR_READ_CACHE_MB", default_value_t = 512)]
read_cache_mb: u64,
/// Memory for indexes loaded by queries, kept for the next query, in MiB.
#[arg(long, env = "WEED_VECTOR_INDEX_CACHE_MB", default_value_t = 1024)]
index_cache_mb: usize,
/// Memory for table metadata (manifests, file footers) kept across
/// queries, in MiB.
#[arg(long, env = "WEED_VECTOR_METADATA_CACHE_MB", default_value_t = 256)]
metadata_cache_mb: usize,
/// Partitions each query probes in a table's vector index. Default: a
/// tenth of the index's partitions, at least 8; more under a filter.
#[arg(long, env = "WEED_VECTOR_NPROBES")]
nprobes: Option<std::num::NonZeroUsize>,
/// The cluster's security.toml: [grpc.vector] for this server,
/// [grpc.client] for the masters and filers, https.client for volume
/// servers under HTTPS, jwt.signing.read.key for signed volume reads,
/// s3.sse.kek or s3.sse.key for SSE-S3 buckets. By default the file weed
/// processes find in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<PathBuf>,
#[arg(
long,
alias = "metricsPort",
env = "WEED_VECTOR_METRICS_PORT",
default_value_t = 0
)]
metrics_port: u16,
#[arg(
long,
alias = "metricsIp",
env = "WEED_VECTOR_METRICS_IP",
default_value = "127.0.0.1"
)]
metrics_ip: String,
/// The `jwt.filer_signing.key` of the cluster. The Lance namespace vends
/// credentials that write index data only to a caller holding it.
#[arg(long, env = "WEED_FILER_SIGNING_KEY")]
filer_signing_key: Option<String>,
}
/// The directory weed's -config_dir names, searched for security.toml
/// first.
#[arg(long, alias = "config_dir", env = "WEED_VECTOR_CONFIG_DIR")]
config_dir: Option<PathBuf>,
fn parse_option(s: &str) -> Result<(String, String), String> {
s.split_once('=')
.map(|(k, v)| (k.to_string(), v.to_string()))
.ok_or_else(|| "expected key=value".to_string())
}
// weed tools take Go-style single-dash long flags; normalize_args converts
@@ -107,13 +71,7 @@ fn normalize_args(args: Vec<String>) -> Vec<String> {
/// A wildcard listen address is not reachable for peers; derive the outbound
/// IP toward the first master instead — the address the master sees anyway.
fn advertised_addr(listen: &str, masters: &[String], advertise: Option<&str>) -> String {
if let Some(address) = advertise
.map(str::trim)
.filter(|address| !address.is_empty())
{
return address.to_string();
}
fn advertised_addr(listen: &str, masters: &[String]) -> String {
let Some((host, _)) = listen.rsplit_once(':') else {
return listen.to_string();
};
@@ -147,142 +105,40 @@ fn advertised_addr(listen: &str, masters: &[String], advertise: Option<&str>) ->
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse_from(normalize_args(std::env::args().collect()));
weed_lance_worker::tls::install_default_crypto_provider();
let security = Security::load(args.security_toml.as_deref(), args.config_dir.as_deref())?;
if let Some(path) = security.path() {
tracing::info!("security settings from {}", path.display());
}
let server_tls = security
.grpc_server_tls("grpc.vector")?
.map(ServerTls::load)
.transpose()?;
// Bind before registering, so the master never lists an engine that is
// about to exit because its port is taken.
let listener = tokio::net::TcpListener::bind(&args.listen)
.await
.with_context(|| format!("listen on {}", args.listen))?;
let cluster = Cluster::new(&args.masters, &args.filer_group, &security)?;
let reads = cluster.storage(&security).await?;
let (health, health_service) = tonic_health::server::health_reporter();
let metrics = Metrics::new()?.with_health(health);
metrics.set_connected(false).await;
let cache = (args.read_cache_mb > 0)
.then(|| ReadCache::new(args.read_cache_mb << 20).with_metrics(metrics.clone()));
let mut service = VectorServer::new()
.with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get))
.with_lance_caches(args.index_cache_mb << 20, args.metadata_cache_mb << 20)
.with_storage(reads);
if let Some(cache) = &cache {
service = service.with_read_cache(cache.clone());
let incoming = TcpIncoming::bind(args.listen.parse()?)
.with_context(|| format!("listen on {}", args.listen))?
.with_nodelay(Some(true));
if let Some(masters) = &args.masters {
let masters: Vec<String> = masters.split(',').map(|s| s.trim().to_string()).collect();
for master in &masters {
weed_vector_server::master_client::grpc_addr(master)?;
}
let advertise = advertised_addr(&args.listen, &masters);
tokio::spawn(weed_vector_server::master_client::keep_connected(
masters, advertise,
));
}
if args.metrics_port > 0 {
let ip = args
.metrics_ip
.trim_start_matches('[')
.trim_end_matches(']')
.parse::<std::net::IpAddr>()?;
let listener =
tokio::net::TcpListener::bind(std::net::SocketAddr::new(ip, args.metrics_port)).await?;
let metrics = metrics.clone();
tokio::spawn(async move {
if let Err(error) = metrics::serve_listener(metrics, listener, cache).await {
tracing::error!(%error, "vector metrics server stopped");
}
});
let fallback: FallbackOptions = args.storage_options.into_iter().collect();
let signing_key = SigningKey::new(args.filer_signing_key);
let client = NamespaceClient::new(args.namespace.clone())
.with_fallback(&fallback)
.with_signing_key(signing_key.as_ref());
let mut service = VectorServer::new(client, fallback);
if args.read_cache_mb > 0 {
service = service.with_read_cache(ReadCache::new(args.read_cache_mb << 20));
}
tracing::info!(
listen = %args.listen,
"weed-vector; serving gRPC {}, dialing masters {}",
match &server_tls {
Some(tls) if tls.files().allowed_common_names.is_empty()
&& tls.files().allowed_wildcard_domain.is_empty() =>
"over TLS with client certificates required",
Some(_) => "over TLS with allowed client certificates required",
None => "in plaintext",
},
if cluster.master_tls.is_some() { "over TLS" } else { "in plaintext" },
);
// Registered only now, with storage connected and the listener bound,
// so the gateway never finds an engine that cannot serve yet.
let advertise = advertised_addr(&args.listen, &cluster.masters, args.advertise.as_deref());
tokio::spawn(master_client::keep_connected(
cluster.masters.clone(),
advertise,
args.filer_group.clone(),
args.metrics_port,
cluster.master_tls.clone(),
metrics.clone(),
));
let router = Server::builder()
.add_service(health_service)
tracing::info!(namespace = %args.namespace, listen = %args.listen, "weed-vector");
Server::builder()
// Match the gateway's 1 GiB cap — put batches over the tonic 4 MiB
// default otherwise get rejected before they reach the handler.
.add_service(
VectorServiceServer::new(ObservedService {
inner: service,
metrics,
})
.max_decoding_message_size(1 << 30)
.max_encoding_message_size(1 << 30),
);
match server_tls {
Some(tls) => {
tokio::spawn(tls.clone().refresh(tls::refresh_interval()));
router.serve_with_incoming(tls.incoming(listener)).await?;
}
None => {
router
.serve_with_incoming(TcpListenerStream::new(listener))
.await?
}
}
VectorServiceServer::new(service)
.max_decoding_message_size(1 << 30)
.max_encoding_message_size(1 << 30),
)
.serve_with_incoming(incoming)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_advertise_uses_the_listen_address() {
for value in [None, Some(""), Some(" ")] {
assert_eq!(
advertised_addr("127.0.0.1:8090", &[], value),
"127.0.0.1:8090"
);
}
assert_eq!(
advertised_addr("127.0.0.1:8090", &[], Some("vector.example:8090")),
"vector.example:8090"
);
}
#[test]
fn nprobes_must_be_positive() {
let parse = |nprobes: &str| {
Args::try_parse_from(["weed-vector", "--masters", "m:9333", "--nprobes", nprobes])
};
assert!(parse("0").is_err());
let args = parse("12").unwrap();
assert_eq!(args.nprobes.map(std::num::NonZeroUsize::get), Some(12));
}
#[test]
fn the_catalog_flags_are_gone() {
let parse = |extra: &[&str]| {
let mut argv = vec!["weed-vector", "-master", "m:9333"];
argv.extend_from_slice(extra);
Args::try_parse_from(normalize_args(argv.into_iter().map(String::from).collect()))
};
assert_eq!(parse(&[]).unwrap().masters, "m:9333");
// The gateway resolves every table it sends; the engine has no
// catalog to name or authenticate to.
assert!(parse(&["--namespace", "http://localhost:9101"]).is_err());
assert!(parse(&["-filer-signing-key", "k"]).is_err());
}
#[test]
fn the_masters_are_required() {
assert!(Args::try_parse_from(["weed-vector"]).is_err());
}
}
+53 -162
View File
@@ -7,26 +7,53 @@ use std::time::Duration;
use anyhow::{Context, Result};
use tokio::time::sleep;
use tonic::transport::Endpoint;
use crate::master_pb::{
KeepConnectedRequest, ListClusterNodesRequest, seaweed_client::SeaweedClient,
};
use crate::security::GrpcTls;
pub use weed_lance_worker::cluster::{CONNECT_TIMEOUT, connect, grpc_addr};
use crate::master_pb::{KeepConnectedRequest, seaweed_client::SeaweedClient};
fn registration(client_addr: &str, filer_group: &str, metrics_port: u16) -> KeepConnectedRequest {
fn registration(client_addr: &str) -> KeepConnectedRequest {
KeepConnectedRequest {
client_type: "vector".into(),
client_address: client_addr.into(),
version: env!("CARGO_PKG_VERSION").into(),
filer_group: filer_group.into(),
filer_group: String::new(),
data_center: String::new(),
rack: String::new(),
leave_lock_ring: false,
metrics_port: metrics_port.into(),
..Default::default()
}
}
/// Masters are configured by their HTTP address; gRPC lives +10000 like the
/// weed conventions (server_address.ToGrpcAddress).
// A master address may carry an explicit gRPC port as `host:http.grpc` —
// use it directly; otherwise the gRPC port is http + 10000.
pub fn grpc_addr(master: &str) -> Result<String> {
let (scheme, rest) = master.split_once("://").unwrap_or(("http", master));
if let Some((host, port)) = rest.rsplit_once(':') {
if let Some((_, grpc)) = port.split_once('.') {
if let Ok(grpc) = grpc.parse::<u64>() {
let grpc = u16::try_from(grpc)
.with_context(|| format!("master {master}: gRPC port {grpc} is past 65535"))?;
return Ok(format!("{scheme}://{host}:{grpc}"));
}
}
if let Ok(port) = port.parse::<u64>() {
let grpc = port
.checked_add(10000)
.and_then(|grpc| u16::try_from(grpc).ok())
.with_context(|| {
format!(
"master {master}: gRPC port {port}+10000 is past 65535; \
give it explicitly as {host}:{port}.<grpc port>"
)
})?;
return Ok(format!("{scheme}://{host}:{grpc}"));
}
}
Ok(format!("{scheme}://{rest}"))
}
// `host:http.grpc` normalizes to `host:http` so a leader hint naming the
// dialed master does not read as a redirect.
fn http_addr(master: &str) -> String {
@@ -41,22 +68,11 @@ fn http_addr(master: &str) -> String {
/// Retry forever: try each master until a stream opens, hold it until it
/// errors, then rediscover — same shape as wdclient.KeepConnectedToMaster.
pub async fn keep_connected(
masters: Vec<String>,
client_addr: String,
filer_group: String,
metrics_port: u16,
tls: Option<GrpcTls>,
metrics: crate::metrics::Metrics,
) {
let registration = &registration(&client_addr, &filer_group, metrics_port);
let tls = tls.as_ref();
let metrics = &metrics;
pub async fn keep_connected(masters: Vec<String>, client_addr: String) {
let client_addr = client_addr.as_str();
loop {
try_all_masters(&masters, |master| async move {
let result = stream_to(&master, registration, tls, Some(&metrics)).await;
metrics.set_connected(false).await;
result
stream_to(&master, client_addr).await
})
.await;
sleep(Duration::from_secs(3)).await;
@@ -92,18 +108,21 @@ where
}
}
async fn stream_to(
master: &str,
registration: &KeepConnectedRequest,
tls: Option<&GrpcTls>,
metrics: Option<&crate::metrics::Metrics>,
) -> Result<Option<String>> {
let channel = connect(master, tls).await?;
/// Bounds the TCP connect and then the master's first answer, the 5s wdclient
/// gives a master call; a black-holed or silent master otherwise holds up the
/// other masters.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
async fn stream_to(master: &str, client_addr: &str) -> Result<Option<String>> {
let channel = Endpoint::new(grpc_addr(master)?)?
.connect_timeout(CONNECT_TIMEOUT)
.connect()
.await?;
// A master answers at once, a follower with its leader hint.
let answer_by = tokio::time::Instant::now() + CONNECT_TIMEOUT;
let mut client = SeaweedClient::new(channel);
let (tx, rx) = tokio::sync::mpsc::channel(8);
tx.send(registration.clone()).await?;
tx.send(registration(client_addr)).await?;
let mut stream = tokio::time::timeout_at(
answer_by,
client.keep_connected(tokio_stream::wrappers::ReceiverStream::new(rx)),
@@ -112,8 +131,6 @@ async fn stream_to(
.context("master did not answer keep-connected")??
.into_inner();
let mut answered = false;
let interval = Duration::from_secs(5);
let mut heartbeat = tokio::time::interval_at(tokio::time::Instant::now() + interval, interval);
// The master keeps the node live while the stream is open; resend the
// registration periodically so a reconnect never leaves a stale entry.
loop {
@@ -132,72 +149,23 @@ async fn stream_to(
return Ok(Some(loc.leader));
}
}
if let Some(metrics) = metrics { metrics.set_connected(true).await; }
}
None => anyhow::bail!("master closed the keep-connected stream"),
},
_ = tokio::time::sleep_until(answer_by), if !answered => {
anyhow::bail!("master did not answer keep-connected");
}
_ = heartbeat.tick() => {
tokio::time::timeout(CONNECT_TIMEOUT, tx.send(registration.clone())).await
.context("registration send stalled")??;
probe_registration(&mut client).await?;
_ = sleep(Duration::from_secs(5)) => {
tx.send(registration(client_addr)).await?;
}
}
}
}
async fn probe_registration(client: &mut SeaweedClient<tonic::transport::Channel>) -> Result<()> {
tokio::time::timeout(
CONNECT_TIMEOUT,
client.list_cluster_nodes(ListClusterNodesRequest {
client_type: "vector".into(),
..Default::default()
}),
)
.await
.context("registration heartbeat stalled")??;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registration_preserves_filer_group() {
assert_eq!(
registration("vector:8090", "tenant-a", 0).filer_group,
"tenant-a"
);
}
#[test]
fn registration_advertises_metrics_port() {
assert_eq!(registration("vector:8090", "", 9327).metrics_port, 9327);
assert_eq!(registration("vector:8090", "", 0).metrics_port, 0);
}
#[tokio::test]
async fn stalled_registration_heartbeat_is_bounded() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let hold = tokio::spawn(async move {
let (_connection, _) = listener.accept().await.unwrap();
std::future::pending::<()>().await;
});
let channel = tonic::transport::Endpoint::from_shared(format!("http://{address}"))
.unwrap()
.connect_lazy();
let mut client = SeaweedClient::new(channel);
let result = tokio::time::timeout(CONNECT_TIMEOUT * 3, probe_registration(&mut client))
.await
.unwrap();
assert!(format!("{:#}", result.unwrap_err()).contains("registration heartbeat stalled"));
hold.abort();
}
/// Runs one pass against scripted masters and returns the dial order.
async fn pass(masters: &[&str], answer: fn(&str) -> Result<Option<String>>) -> Vec<String> {
let masters: Vec<String> = masters.iter().map(|m| m.to_string()).collect();
@@ -247,8 +215,7 @@ mod tests {
#[tokio::test]
async fn dial_to_a_black_holed_master_is_bounded() {
// TEST-NET-1 (RFC 5737) is reserved, so nothing answers the SYN.
let registration = registration("127.0.0.1:8080", "", 0);
let dial = stream_to("192.0.2.1:9333", &registration, None, None);
let dial = stream_to("192.0.2.1:9333", "127.0.0.1:8080");
let result = tokio::time::timeout(CONNECT_TIMEOUT * 3, dial).await;
assert!(matches!(result, Ok(Err(_))), "dial was not bounded");
}
@@ -262,89 +229,13 @@ mod tests {
let _ = tokio::io::copy(&mut conn, &mut tokio::io::sink()).await;
});
let master = format!("127.0.0.1:9333.{port}");
let registration = registration("127.0.0.1:8080", "", 0);
let open = stream_to(&master, &registration, None, None);
let open = stream_to(&master, "127.0.0.1:8080");
match tokio::time::timeout(CONNECT_TIMEOUT * 3, open).await {
Ok(Err(e)) => assert!(format!("{e:#}").contains("did not answer"), "{e:#}"),
other => panic!("open was not bounded: {other:?}"),
}
}
/// The worker crate's `tests/tls`: a CA and the `engine-a` leaf it signed.
fn credentials() -> GrpcTls {
let fixture = |name: &str| {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../../seaweed-worker/crates/lance/tests/tls")
.join(name)
.display()
.to_string()
};
GrpcTls {
ca_path: fixture("ca.pem"),
cert_path: fixture("a.pem"),
key_path: fixture("a.key"),
allowed_server_names: Vec::new(),
allowed_server_wildcard_domain: String::new(),
}
}
#[tokio::test]
async fn a_master_that_stalls_the_tls_handshake_is_bounded() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut conn, _) = listener.accept().await.unwrap();
let _ = tokio::io::copy(&mut conn, &mut tokio::io::sink()).await;
});
let master = format!("127.0.0.1:9333.{port}");
let tls = credentials();
let registration = registration("127.0.0.1:8080", "", 0);
let open = stream_to(&master, &registration, Some(&tls), None);
match tokio::time::timeout(CONNECT_TIMEOUT * 3, open).await {
Ok(Err(e)) => assert!(format!("{e:#}").contains("did not complete"), "{e:#}"),
other => panic!("handshake was not bounded: {other:?}"),
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_credential_read_that_stalls_is_bounded() {
let dir = tempfile::tempdir().unwrap();
let fifo = dir.path().join("ca.pem");
let made = std::process::Command::new("mkfifo").arg(&fifo).status();
assert!(made.unwrap().success());
// Every connection is dropped at once, so a dial that skipped the read
// fails its handshake instead of timing out.
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
while let Ok((conn, _)) = listener.accept().await {
drop(conn);
}
});
let mut tls = credentials();
tls.ca_path = fifo.display().to_string();
let master = format!("127.0.0.1:9333.{port}");
let registration = registration("127.0.0.1:8080", "", 0);
let open = stream_to(&master, &registration, Some(&tls), None);
let result = tokio::time::timeout(CONNECT_TIMEOUT * 3, open).await;
use std::io::Write;
let mut cleanup = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&fifo)
.unwrap();
let replacement = dir.path().join("ca.replacement");
std::fs::write(&replacement, b"invalid CA").unwrap();
std::fs::rename(&replacement, &fifo).unwrap();
cleanup.write_all(b"invalid CA").unwrap();
drop(cleanup);
match result {
Ok(Err(e)) => assert!(format!("{e:#}").contains("did not complete"), "{e:#}"),
other => panic!("credential read was not bounded: {other:?}"),
}
}
#[test]
fn grpc_addr_refuses_a_port_past_65535() {
assert_eq!(grpc_addr("m1:9333").unwrap(), "http://m1:19333");
-341
View File
@@ -1,341 +0,0 @@
use std::net::SocketAddr;
use anyhow::Result;
use axum::{Router, http::StatusCode, routing::get};
use prometheus::{
Encoder, Histogram, HistogramOpts, HistogramVec, IntCounter, IntCounterVec, IntGauge,
IntGaugeVec, Opts, Registry, TextEncoder,
};
use tonic_health::{ServingStatus, server::HealthReporter};
use crate::read_cache::ReadCache;
#[derive(Clone)]
pub struct Metrics {
pub registry: Registry,
pub connected: IntGauge,
pub requests: IntCounterVec,
pub request_seconds: HistogramVec,
pub in_flight: IntGaugeVec,
pub query_results: IntCounter,
pub cache_requests: IntCounterVec,
pub storage_bytes: IntCounter,
pub storage_read_seconds: Histogram,
cache_bytes: IntGauge,
cache_entries: IntGauge,
health: Option<HealthReporter>,
}
impl Metrics {
pub fn new() -> Result<Self> {
let registry = Registry::new();
let opts = |name: &str, help: &str| {
Opts::new(name, help)
.namespace("SeaweedFS")
.subsystem("vector")
};
let buckets = prometheus::exponential_buckets(0.0001, 2.0, 24)?;
let histogram =
|name: &str, help: &str| HistogramOpts::from(opts(name, help)).buckets(buckets.clone());
let connected = IntGauge::with_opts(opts(
"connected",
"Whether the engine is registered with the master.",
))?;
let requests = IntCounterVec::new(
opts(
"request_total",
"Vector engine requests by operation and gRPC status.",
),
&["type", "code"],
)?;
let request_seconds = HistogramVec::new(
histogram("request_seconds", "Vector engine request duration."),
&["type"],
)?;
let in_flight = IntGaugeVec::new(
opts("in_flight_requests", "Vector engine requests in progress."),
&["type"],
)?;
let query_results =
IntCounter::with_opts(opts("query_results_total", "Vectors returned by queries."))?;
let cache_requests = IntCounterVec::new(
opts("cache_requests_total", "Immutable reads by cache outcome."),
&["result"],
)?;
let storage_bytes = IntCounter::with_opts(opts(
"storage_read_bytes_total",
"Bytes fetched for immutable cache reads.",
))?;
let storage_read_seconds = Histogram::with_opts(histogram(
"storage_read_seconds",
"Immutable storage fetch duration.",
))?;
let cache_bytes =
IntGauge::with_opts(opts("cache_bytes", "Current cache weight in bytes."))?;
let cache_entries = IntGauge::with_opts(opts("cache_entries", "Current cache entries."))?;
for collector in [
Box::new(connected.clone()) as Box<dyn prometheus::core::Collector>,
Box::new(requests.clone()),
Box::new(request_seconds.clone()),
Box::new(in_flight.clone()),
Box::new(query_results.clone()),
Box::new(cache_requests.clone()),
Box::new(storage_bytes.clone()),
Box::new(storage_read_seconds.clone()),
Box::new(cache_bytes.clone()),
Box::new(cache_entries.clone()),
] {
registry.register(collector)?;
}
Ok(Self {
registry,
connected,
requests,
request_seconds,
in_flight,
query_results,
cache_requests,
storage_bytes,
storage_read_seconds,
cache_bytes,
cache_entries,
health: None,
})
}
pub fn with_health(mut self, health: HealthReporter) -> Self {
self.health = Some(health);
self
}
pub async fn set_connected(&self, connected: bool) {
self.connected.set(i64::from(connected));
if let Some(health) = self.health.clone() {
let status = if connected {
ServingStatus::Serving
} else {
ServingStatus::NotServing
};
health.set_service_status("", status).await;
health
.set_service_status("vector_pb.VectorService", status)
.await;
}
}
pub fn start(&self, operation: &str) -> InFlight {
let gauge = self.in_flight.with_label_values(&[operation]);
gauge.inc();
InFlight {
gauge,
requests: self.requests.clone(),
operation: operation.into(),
completed: false,
_timer: self
.request_seconds
.with_label_values(&[operation])
.start_timer(),
}
}
fn gather(&self, cache: Option<&ReadCache>) -> Result<String> {
if let Some(cache) = cache {
let (entries, bytes) = cache.size();
self.cache_entries.set(entries as i64);
self.cache_bytes.set(bytes as i64);
}
let mut buffer = Vec::new();
TextEncoder::new().encode(&self.registry.gather(), &mut buffer)?;
Ok(String::from_utf8(buffer)?)
}
}
pub struct InFlight {
gauge: IntGauge,
requests: IntCounterVec,
operation: String,
completed: bool,
_timer: prometheus::HistogramTimer,
}
impl InFlight {
pub fn complete(&mut self, error: Option<tonic::Code>) {
let code = error
.map(|c| format!("{c:?}"))
.unwrap_or_else(|| "OK".into());
self.requests
.with_label_values(&[&self.operation, &code])
.inc();
self.completed = true;
}
}
impl Drop for InFlight {
fn drop(&mut self) {
self.gauge.dec();
if !self.completed {
self.requests
.with_label_values(&[&self.operation, "Cancelled"])
.inc();
}
}
}
pub async fn serve(metrics: Metrics, address: SocketAddr, cache: Option<ReadCache>) -> Result<()> {
let listener = tokio::net::TcpListener::bind(address).await?;
serve_listener(metrics, listener, cache).await
}
pub async fn serve_listener(
metrics: Metrics,
listener: tokio::net::TcpListener,
cache: Option<ReadCache>,
) -> Result<()> {
let readiness = metrics.clone();
let app = Router::new()
.route("/health", get(|| async { StatusCode::OK }))
.route(
"/ready",
get(move || {
let metrics = readiness.clone();
async move {
if metrics.connected.get() == 1 {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
}
}
}),
)
.route(
"/metrics",
get(move || {
let metrics = metrics.clone();
let cache = cache.clone();
async move {
metrics
.gather(cache.as_ref())
.map(|body| ([("content-type", "text/plain; version=0.0.4")], body))
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
}),
);
axum::serve(listener, app).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn endpoints_follow_registration_and_publish_metrics() {
let metrics = Metrics::new().unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let task = tokio::spawn(serve_listener(metrics.clone(), listener, None));
let client = reqwest::Client::new();
assert_eq!(
client
.get(format!("{endpoint}/health"))
.send()
.await
.unwrap()
.status(),
200
);
assert_eq!(
client
.get(format!("{endpoint}/ready"))
.send()
.await
.unwrap()
.status(),
503
);
metrics.set_connected(true).await;
assert_eq!(
client
.get(format!("{endpoint}/ready"))
.send()
.await
.unwrap()
.status(),
200
);
let in_flight = metrics.start("QueryVectors");
let body = client
.get(format!("{endpoint}/metrics"))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert!(body.contains("SeaweedFS_vector_connected 1"));
assert!(body.contains("SeaweedFS_vector_in_flight_requests{type=\"QueryVectors\"} 1"));
drop(in_flight);
assert_eq!(
metrics.in_flight.with_label_values(&["QueryVectors"]).get(),
0
);
metrics.set_connected(false).await;
assert_eq!(
client
.get(format!("{endpoint}/ready"))
.send()
.await
.unwrap()
.status(),
503
);
task.abort();
}
#[tokio::test]
async fn grpc_health_follows_registration() {
use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
let (reporter, service) = tonic_health::server::health_reporter();
let metrics = Metrics::new().unwrap().with_health(reporter);
metrics.set_connected(false).await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let task = tokio::spawn(
tonic::transport::Server::builder()
.add_service(service)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),
);
let channel = tonic::transport::Endpoint::from_shared(endpoint)
.unwrap()
.connect()
.await
.unwrap();
let mut client = HealthClient::new(channel);
let request = || HealthCheckRequest {
service: "vector_pb.VectorService".into(),
};
assert_eq!(
client.check(request()).await.unwrap().into_inner().status,
2
);
metrics.set_connected(true).await;
assert_eq!(
client.check(request()).await.unwrap().into_inner().status,
1
);
metrics.set_connected(false).await;
assert_eq!(
client.check(request()).await.unwrap().into_inner().status,
2
);
task.abort();
}
}
impl std::fmt::Debug for Metrics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Metrics")
.field("connected", &self.connected.get())
.finish()
}
}
@@ -1,122 +0,0 @@
use crate::metrics::Metrics;
use crate::pb::vector::{self as pb, vector_service_server::VectorService};
use crate::service::VectorServer;
use tonic::{Request, Response, Status};
pub struct ObservedService {
pub inner: VectorServer,
pub metrics: Metrics,
}
#[tonic::async_trait]
impl VectorService for ObservedService {
async fn create_index(
&self,
request: Request<pb::CreateIndexRequest>,
) -> Result<Response<pb::CreateIndexResponse>, Status> {
let mut in_flight = self.metrics.start("CreateIndex");
let result = self.inner.create_index(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn drop_index(
&self,
request: Request<pb::DropIndexRequest>,
) -> Result<Response<pb::DropIndexResponse>, Status> {
let mut in_flight = self.metrics.start("DropIndex");
let result = self.inner.drop_index(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn put_vectors(
&self,
request: Request<pb::PutVectorsRequest>,
) -> Result<Response<pb::PutVectorsResponse>, Status> {
let mut in_flight = self.metrics.start("PutVectors");
let result = self.inner.put_vectors(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn get_vectors(
&self,
request: Request<pb::GetVectorsRequest>,
) -> Result<Response<pb::GetVectorsResponse>, Status> {
let mut in_flight = self.metrics.start("GetVectors");
let result = self.inner.get_vectors(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn delete_vectors(
&self,
request: Request<pb::DeleteVectorsRequest>,
) -> Result<Response<pb::DeleteVectorsResponse>, Status> {
let mut in_flight = self.metrics.start("DeleteVectors");
let result = self.inner.delete_vectors(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn list_vectors(
&self,
request: Request<pb::ListVectorsRequest>,
) -> Result<Response<pb::ListVectorsResponse>, Status> {
let mut in_flight = self.metrics.start("ListVectors");
let result = self.inner.list_vectors(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn query_vectors(
&self,
request: Request<pb::QueryVectorsRequest>,
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
let mut in_flight = self.metrics.start("QueryVectors");
let result = self.inner.query_vectors(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
if let Ok(response) = &result {
self.metrics
.query_results
.inc_by(response.get_ref().vectors.len() as u64);
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn failures_are_counted_and_release_in_flight_requests() {
let service = ObservedService {
inner: VectorServer::new(),
metrics: Metrics::new().unwrap(),
};
let response = service
.query_vectors(Request::new(pb::QueryVectorsRequest::default()))
.await;
let code = format!("{:?}", response.unwrap_err().code());
assert_eq!(
service
.metrics
.requests
.with_label_values(&["QueryVectors", &code])
.get(),
1
);
assert_eq!(
service
.metrics
.in_flight
.with_label_values(&["QueryVectors"])
.get(),
0
);
assert_eq!(
service
.metrics
.request_seconds
.with_label_values(&["QueryVectors"])
.get_sample_count(),
1
);
}
}
+49 -223
View File
@@ -9,7 +9,6 @@ use std::fmt;
use std::ops::Range;
use std::sync::Arc;
use crate::metrics::Metrics;
use bytes::Bytes;
use futures::StreamExt;
use futures::stream::BoxStream;
@@ -38,53 +37,26 @@ struct Entry {
/// Wraps each object store Lance opens; clones share one cache.
#[derive(Clone)]
pub struct ReadCache {
cache: moka::sync::Cache<Key, Entry>,
/// Keeps entries apart from those of another [`Self::scoped`] view, for
/// stores that share a prefix but not their bytes.
scope: Arc<str>,
metrics: Option<Metrics>,
}
pub struct ReadCache(moka::sync::Cache<Key, Entry>);
impl ReadCache {
pub fn new(capacity_bytes: u64) -> Self {
Self {
cache: moka::sync::Cache::builder()
Self(
moka::sync::Cache::builder()
.max_capacity(capacity_bytes)
.weigher(|key: &Key, entry: &Entry| {
u32::try_from(key.path.as_ref().len() + entry.bytes.len()).unwrap_or(u32::MAX)
})
.build(),
scope: "".into(),
metrics: None,
}
}
pub fn with_metrics(mut self, metrics: Metrics) -> Self {
self.metrics = Some(metrics);
self
}
pub fn size(&self) -> (u64, u64) {
self.cache.run_pending_tasks();
(self.cache.entry_count(), self.cache.weighted_size())
}
/// The same cache, keyed apart under `scope`.
pub fn scoped(&self, scope: &str) -> Self {
Self {
cache: self.cache.clone(),
scope: scope.into(),
metrics: self.metrics.clone(),
}
)
}
}
impl fmt::Debug for ReadCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReadCache")
.field("entries", &self.cache.entry_count())
.field("bytes", &self.cache.weighted_size())
.field("entries", &self.0.entry_count())
.field("bytes", &self.0.weighted_size())
.finish()
}
}
@@ -93,9 +65,8 @@ impl WrappingObjectStore for ReadCache {
fn wrap(&self, store_prefix: &str, original: Arc<dyn ObjectStore>) -> Arc<dyn ObjectStore> {
Arc::new(CachedStore {
inner: original,
store: format!("{}|{store_prefix}", self.scope).into(),
cache: self.cache.clone(),
metrics: self.metrics.clone(),
store: store_prefix.into(),
cache: self.0.clone(),
})
}
}
@@ -151,7 +122,6 @@ struct CachedStore {
inner: Arc<dyn ObjectStore>,
store: Arc<str>,
cache: moka::sync::Cache<Key, Entry>,
metrics: Option<Metrics>,
}
impl CachedStore {
@@ -200,47 +170,14 @@ impl ObjectStore for CachedStore {
object: Some(object),
}) = self.cache.get(&key)
{
if let Some(metrics) = &self.metrics {
metrics.cache_requests.with_label_values(&["hit"]).inc();
}
return Ok(whole(bytes, &object));
}
if let Some(metrics) = &self.metrics {
metrics.cache_requests.with_label_values(&["miss"]).inc();
}
let _timer = self
.metrics
.as_ref()
.map(|m| m.storage_read_seconds.start_timer());
let result = self.inner.get_opts(location, options).await?;
if result.meta.size > MAX_WHOLE_OBJECT {
let meta = result.meta.clone();
let range = result.range.clone();
let attributes = result.attributes.clone();
let metrics = self.metrics.clone();
let timer = _timer;
let stream = result
.into_stream()
.map(move |chunk| {
let _timer = &timer;
if let (Some(metrics), Ok(bytes)) = (&metrics, &chunk) {
metrics.storage_bytes.inc_by(bytes.len() as u64);
}
chunk
})
.boxed();
return Ok(GetResult {
payload: GetResultPayload::Stream(stream),
meta,
range,
attributes,
});
return Ok(result);
}
let object = Arc::new((result.meta.clone(), result.attributes.clone()));
let bytes = owned(result.bytes().await?);
if let Some(metrics) = &self.metrics {
metrics.storage_bytes.inc_by(bytes.len() as u64);
}
self.cache.insert(
key,
Entry {
@@ -269,21 +206,7 @@ impl ObjectStore for CachedStore {
.filter(|(_, hit)| hit.is_none())
.map(|(range, _)| range.clone())
.collect();
if let Some(metrics) = &self.metrics {
metrics
.cache_requests
.with_label_values(&["miss"])
.inc_by(missing.len() as u64);
metrics
.cache_requests
.with_label_values(&["hit"])
.inc_by((ranges.len() - missing.len()) as u64);
}
if !missing.is_empty() {
let _timer = self
.metrics
.as_ref()
.map(|m| m.storage_read_seconds.start_timer());
let mut fetched = self.inner.get_ranges(location, &missing).await?.into_iter();
for (range, slot) in ranges.iter().zip(out.iter_mut()) {
if slot.is_some() {
@@ -293,9 +216,6 @@ impl ObjectStore for CachedStore {
break;
};
let bytes = owned(bytes);
if let Some(metrics) = &self.metrics {
metrics.storage_bytes.inc_by(bytes.len() as u64);
}
self.cache.insert(
self.key(location, Some(range.clone())),
Entry {
@@ -353,10 +273,12 @@ mod tests {
use super::*;
use crate::pb::vector as pb;
use crate::pb::vector::vector_service_server::VectorService;
use crate::service::{VectorServer, schema_for, table_id};
use crate::service::VectorServer;
use object_store::ObjectStoreExt;
use object_store::memory::InMemory;
use tonic::Request;
use weed_lance_worker::catalog::NamespaceClient;
use weed_lance_worker::dataset::FallbackOptions;
fn cached(inner: Arc<InMemory>) -> Arc<dyn ObjectStore> {
ReadCache::new(1 << 20).wrap("memory", inner)
@@ -451,8 +373,8 @@ mod tests {
.unwrap();
read(&store, &path, 0..(8 << 10)).await;
}
cache.cache.run_pending_tasks();
assert!(cache.cache.weighted_size() <= 64 << 10, "{cache:?}");
cache.0.run_pending_tasks();
assert!(cache.0.weighted_size() <= 64 << 10, "{cache:?}");
}
#[tokio::test]
@@ -470,15 +392,40 @@ mod tests {
let backing = whole.as_ptr_range();
read(&store, &path, 10..20).await;
let key = Key {
store: "|memory".into(),
store: "memory".into(),
path,
range: Some(10..20),
};
let cached = cache.cache.get(&key).unwrap().bytes;
let cached = cache.0.get(&key).unwrap().bytes;
assert_eq!(cached.len(), 10);
assert!(!backing.contains(&cached.as_ptr()));
}
/// A catalog that answers every request with `location`.
async fn catalog_at(location: String) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let body = serde_json::json!({ "location": location }).to_string();
tokio::spawn(async move {
loop {
let (mut conn, _) = listener.accept().await.unwrap();
let body = body.clone();
tokio::spawn(async move {
let mut request = [0u8; 8192];
let _ = conn.read(&mut request).await;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
let _ = conn.write_all(response.as_bytes()).await;
let _ = conn.shutdown().await;
});
}
});
url
}
fn vector(key: &str, data: Vec<f32>) -> pb::Vector {
pb::Vector {
key: key.to_string(),
@@ -545,28 +492,18 @@ mod tests {
/// dropped and recreated at the same location answers with its new rows.
#[tokio::test]
async fn cached_reads_follow_writes_and_a_recreated_index() {
let bucket = format!("cache-{}", uuid_like());
let location = format!("shared-memory://{bucket}/vector/x");
let server = VectorServer::new()
.with_schemes(&["shared-memory"])
.with_read_cache(ReadCache::new(16 << 20));
let location = format!("shared-memory://cache-{}/vector/x", uuid_like(),);
let server = VectorServer::new(
NamespaceClient::new(catalog_at(location.clone()).await),
FallbackOptions::new(),
)
.with_read_cache(ReadCache::new(16 << 20));
let table = pb::Table {
id: vec![bucket, "vector".into(), "x".into()],
location: location.clone(),
..Default::default()
id: vec!["bkt".into(), "vector".into(), "x".into()],
version: 0,
};
create(&server, &table, 4).await;
create(&server, &table, 4).await;
let mismatch = server
.create_index(Request::new(pb::CreateIndexRequest {
table: Some(table.clone()),
dimension: 3,
..Default::default()
}))
.await
.unwrap_err();
assert_eq!(mismatch.code(), tonic::Code::AlreadyExists);
put(
&server,
&table,
@@ -616,117 +553,6 @@ mod tests {
assert_eq!(query(&server, &table, vec![1.0, 0.0]).await, ["z"]);
}
/// A query loads the index once; the next one finds it in the session
/// every read shares.
#[tokio::test]
async fn queries_reuse_the_loaded_index() {
let bucket = format!("session-{}", uuid_like());
let location = format!("shared-memory://{bucket}/vector/x");
let server = VectorServer::new().with_schemes(&["shared-memory"]);
let table = pb::Table {
id: vec![bucket, "vector".into(), "x".into()],
location: location.clone(),
..Default::default()
};
create(&server, &table, 2).await;
put(
&server,
&table,
(0..300)
.map(|i| vector(&format!("k{i}"), vec![i as f32, 1.0]))
.collect(),
)
.await;
let mut dataset = lance::Dataset::open(&location).await.unwrap();
weed_lance_worker::vector_index::build(&mut dataset, "vector", "idx", 2, false)
.await
.unwrap();
assert_eq!(query(&server, &table, vec![5.0, 1.0]).await[0], "k5");
let session = server.reads.lock().unwrap().session.clone();
let loaded = session.index_cache_stats().await;
assert!(session.approx_num_items() > 0);
assert_eq!(query(&server, &table, vec![7.0, 1.0]).await[0], "k7");
let again = session.index_cache_stats().await;
assert!(server.handles.contains_key(&(location, false)));
assert!(again.hits > loaded.hits, "{loaded:?} then {again:?}");
assert_eq!(again.misses, loaded.misses, "{loaded:?} then {again:?}");
}
/// An index dropped and created again at the same location reaches the
/// version numbers of the old one; the shared session must not answer
/// for them with the old index.
#[tokio::test]
async fn a_recreated_table_does_not_see_the_old_index() {
recreate_after(false).await;
recreate_after(true).await;
}
/// `unmarked`: the first table is written without a table id, as indexes
/// created before ids were are.
async fn recreate_after(unmarked: bool) {
let bucket = format!("recreate-{}", uuid_like());
let location = format!("shared-memory://{bucket}/vector/x");
let server = VectorServer::new().with_schemes(&["shared-memory"]);
let table = pb::Table {
id: vec![bucket, "vector".into(), "x".into()],
location: location.clone(),
..Default::default()
};
let rows = |offset: usize| {
(0..300)
.map(|i| vector(&format!("k{}", i + offset), vec![(i + offset) as f32, 1.0]))
.collect::<Vec<_>>()
};
if unmarked {
let schema = schema_for(2, pb::DistanceMetric::L2, &[]);
let empty = arrow_array::RecordBatch::new_empty(schema.clone());
let reader = arrow_array::RecordBatchIterator::new(vec![Ok(empty)], schema);
lance::Dataset::write(reader, &location, None)
.await
.unwrap();
} else {
create(&server, &table, 2).await;
}
put(&server, &table, rows(0)).await;
let mut dataset = lance::Dataset::open(&location).await.unwrap();
assert_eq!(table_id(&dataset).is_empty(), unmarked);
weed_lance_worker::vector_index::build(&mut dataset, "vector", "idx", 2, false)
.await
.unwrap();
let indexed = dataset.version().version;
assert_eq!(query(&server, &table, vec![5.0, 1.0]).await[0], "k5");
let other = pb::Table {
id: vec![table.id[0].clone(), "vector".into(), "y".into()],
location: location.replace("/vector/x", "/vector/y"),
..Default::default()
};
create(&server, &other, 2).await;
put(&server, &other, rows(0)).await;
assert_eq!(query(&server, &other, vec![5.0, 1.0]).await[0], "k5");
let (store, path) = lance::io::ObjectStore::from_uri(&location).await.unwrap();
store.remove_dir_all(path).await.unwrap();
create(&server, &table, 2).await;
let mut offset = 1000;
while lance::Dataset::open(&location)
.await
.unwrap()
.version()
.version
< indexed
{
put(&server, &table, rows(offset)).await;
offset += 1000;
}
assert_eq!(query(&server, &table, vec![1005.0, 1.0]).await[0], "k1005");
server.handles.run_pending_tasks();
let session = server.reads.lock().unwrap().session.clone();
for (_, (_, dataset)) in server.handles.iter() {
assert!(Arc::ptr_eq(&dataset.session(), &session));
}
}
fn uuid_like() -> String {
format!(
"{:x}",
+112 -471
View File
@@ -8,19 +8,17 @@ use lance::Dataset;
use lance::dataset::ProjectionRequest;
use lance::dataset::WriteParams;
use lance::dataset::{MergeInsertBuilder, WhenMatched, WhenNotMatched};
use lance::io::ObjectStoreParams;
use lance::io::StorageOptionsAccessor;
use lance::io::WrappingObjectStore;
use lance::session::Session;
use lance::table::format::Fragment;
use lance_linalg::distance::DistanceType;
use prost_types::{ListValue, Struct, Value, value::Kind};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use tonic::{Request, Response, Status};
use weed_lance_worker::catalog::TableDescription;
use weed_lance_worker::dataset;
use weed_lance_worker::direct_read::{DirectReads, Wrappers};
use weed_lance_worker::jobs::vector_index::is_vector_table;
use weed_vector_core::index;
use weed_vector_core::maintenance::SharedLeases;
use weed_lance_worker::catalog::NamespaceClient;
use weed_lance_worker::dataset::{self, FallbackOptions};
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
@@ -37,14 +35,17 @@ fn invalid(err: impl Into<anyhow::Error>) -> Status {
fn open_status(err: anyhow::Error) -> Status {
let missing = err.chain().any(|cause| {
cause.downcast_ref::<lance::Error>().is_some_and(|e| {
matches!(
e,
lance::Error::DatasetNotFound { .. }
| lance::Error::NotFound { .. }
| lance::Error::VersionNotFound { .. }
)
})
cause
.downcast_ref::<reqwest::Error>()
.is_some_and(|e| e.status() == Some(reqwest::StatusCode::NOT_FOUND))
|| cause.downcast_ref::<lance::Error>().is_some_and(|e| {
matches!(
e,
lance::Error::DatasetNotFound { .. }
| lance::Error::NotFound { .. }
| lance::Error::VersionNotFound { .. }
)
})
});
if missing {
Status::not_found(format!("{:#}", err))
@@ -57,9 +58,8 @@ const KEY_COLUMN: &str = "key";
const METADATA_COLUMN: &str = "metadata";
const VECTOR_COLUMN: &str = "vector";
const ROW_ID_COLUMN: &str = "_rowid";
const DEFAULT_INDEX_CACHE_BYTES: usize = 1 << 30;
const DEFAULT_METADATA_CACHE_BYTES: usize = 256 << 20;
pub(crate) fn schema_for(
fn schema_for(
dimension: usize,
metric: pb::DistanceMetric,
non_filterable: &[String],
@@ -99,44 +99,6 @@ pub(crate) fn schema_for(
]))
}
fn matches_index_schema(
dataset: &Dataset,
dimension: usize,
metric: pb::DistanceMetric,
non_filterable: &[String],
) -> bool {
let Ok(layout) = VectorTable::resolve(dataset, Some(VECTOR_COLUMN), Some(KEY_COLUMN)) else {
return false;
};
let schema = Schema::from(dataset.schema());
let Ok(vector) = schema.field_with_name(VECTOR_COLUMN) else {
return false;
};
let Ok(metadata) = schema.field_with_name(METADATA_COLUMN) else {
return false;
};
let stored_keys = metadata
.metadata()
.get("non_filterable_metadata_keys")
.map(|keys| serde_json::from_str::<Vec<String>>(keys))
.transpose();
let Ok(stored_keys) = stored_keys else {
return false;
};
let mut stored_keys = stored_keys.unwrap_or_default();
let mut requested_keys = non_filterable.to_vec();
stored_keys.sort();
requested_keys.sort();
layout.dimension == dimension
&& vector.metadata().get("distance_metric").map(String::as_str)
== Some(metric.as_str_name())
&& stored_keys == requested_keys
&& metadata
.metadata()
.get("ARROW:extension:name")
.is_some_and(|name| name == "lance.json")
}
fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Result<RecordBatch> {
let mut seen = std::collections::HashSet::new();
for vector in vectors {
@@ -408,294 +370,38 @@ fn rows_as_vectors(
out
}
/// Refuses a table of an SSE-S3 bucket when the engine's storage has no key
/// to read or write it with, rather than failing inside Lance.
fn sse_s3_ready(sse_s3: bool, key_configured: Option<bool>) -> Result<(), Status> {
if sse_s3 && key_configured == Some(false) {
return Err(Status::failed_precondition(
"the bucket encrypts with SSE-S3, which needs s3.sse.kek or s3.sse.key for the \
engine as for the S3 gateway",
));
}
Ok(())
}
/// The description a gateway sent with the table. Only a vector index at its
/// colocated path is taken, since the engine is that path's writer already;
/// any other location would point the engine at storage the catalog does not
/// know.
fn resolved(table: &pb::Table, schemes: &[&str]) -> Option<TableDescription> {
// Each id part is one path component; `..` would resolve the colocated
// path elsewhere on the filer.
if !table
.id
.iter()
.all(|part| !part.is_empty() && part != "." && part != ".." && !part.contains('/'))
{
return None;
}
let colocated = dataset::table_location(&table.id)?;
let path = colocated.strip_prefix("s3://")?;
let location = table.location.trim_end_matches('/');
let trusted = is_vector_table(&table.id)
&& schemes
.iter()
.any(|scheme| location == format!("{scheme}://{path}"));
trusted.then(|| TableDescription {
location: location.to_string(),
storage_options: dataset::unsigned_options(),
managed_versioning: false,
})
}
/// Marks the table an index was created as, in its schema metadata, which
/// every later version keeps.
const TABLE_ID_KEY: &str = "weed_vector_table_id";
/// The table a dataset was created as; empty for one created before tables
/// were marked.
pub(crate) fn table_id(dataset: &Dataset) -> &str {
dataset
.schema()
.metadata
.get(TABLE_ID_KEY)
.map_or("", String::as_str)
}
/// The session reads share, and the table each location held when this
/// session first read it. Lance keys some of its caches by location and
/// version alone, and an index dropped and created again at its location
/// numbers its versions from 1 again, so a session that sees a location hold
/// another table starts over.
pub(crate) struct Reads {
pub(crate) session: Arc<Session>,
generation: u64,
tables: HashMap<String, String>,
}
/// Opened tables kept for the next read of them.
const MAX_HANDLES: u64 = 1024;
fn handle_key(table: &pb::Table) -> (String, bool) {
(table.location.clone(), table.sse_s3)
}
/// Locations a session remembers before it starts over.
const MAX_READ_TABLES: usize = 100_000;
impl Reads {
fn new(index_bytes: usize, metadata_bytes: usize) -> Self {
Self {
session: Arc::new(Session::new(
index_bytes,
metadata_bytes,
Default::default(),
)),
generation: 0,
tables: HashMap::new(),
}
}
/// Whether a dataset of `table_id` at `location`, opened in this session,
/// may be read. Otherwise the session was replaced and the caller opens
/// the table again.
fn admit(&mut self, location: &str, table_id: &str, (index, metadata): (usize, usize)) -> bool {
match self.tables.get(location) {
Some(seen) if seen == table_id => return true,
None if self.tables.len() < MAX_READ_TABLES => {
self.tables
.insert(location.to_string(), table_id.to_string());
return true;
}
_ => {}
}
let generation = self.generation + 1;
*self = Self::new(index, metadata);
self.generation = generation;
false
}
}
pub struct VectorServer {
storage: Option<DirectReads>,
read_cache: Option<ReadCache>,
/// Lance's index and metadata caches, shared by every request that only
/// reads. Writes open in a session of their own.
pub(crate) reads: Mutex<Reads>,
/// A table opened by an earlier read, by location and encryption, with
/// the generation of the session it was opened in.
pub(crate) handles: moka::sync::Cache<(String, bool), (u64, Dataset)>,
lance_cache_bytes: (usize, usize),
leases: SharedLeases,
nprobes: Option<usize>,
/// URI schemes a table's location may have.
schemes: &'static [&'static str],
}
impl Default for VectorServer {
fn default() -> Self {
Self::new()
}
client: NamespaceClient,
fallback: FallbackOptions,
read_cache: Option<Arc<dyn WrappingObjectStore>>,
}
impl VectorServer {
pub fn new() -> Self {
pub fn new(client: NamespaceClient, fallback: FallbackOptions) -> Self {
Self {
storage: None,
client,
fallback,
read_cache: None,
reads: Mutex::new(Reads::new(
DEFAULT_INDEX_CACHE_BYTES,
DEFAULT_METADATA_CACHE_BYTES,
)),
lance_cache_bytes: (DEFAULT_INDEX_CACHE_BYTES, DEFAULT_METADATA_CACHE_BYTES),
handles: moka::sync::Cache::new(MAX_HANDLES),
leases: SharedLeases::default(),
nprobes: None,
schemes: &["s3"],
}
}
/// Tables on an in-process store, for tests.
#[cfg(test)]
pub(crate) fn with_schemes(mut self, schemes: &'static [&'static str]) -> Self {
self.schemes = schemes;
self
}
/// Partitions every query probes, instead of the index's own default.
pub fn with_nprobes(mut self, nprobes: Option<usize>) -> Self {
self.nprobes = nprobes;
self
}
/// Keep tables on the filers and volume servers, not through the gateway.
/// Unset only for tests on an in-process store.
pub fn with_storage(mut self, storage: DirectReads) -> Self {
self.storage = Some(storage);
self
}
/// Bytes of loaded indexes and of table metadata kept across reads.
pub fn with_lance_caches(mut self, index_bytes: usize, metadata_bytes: usize) -> Self {
self.reads = Mutex::new(Reads::new(index_bytes, metadata_bytes));
self.lance_cache_bytes = (index_bytes, metadata_bytes);
self
}
/// Serve repeated reads of write-once table files from `cache`.
pub fn with_read_cache(mut self, cache: ReadCache) -> Self {
self.read_cache = Some(cache);
self.read_cache = Some(Arc::new(cache));
self
}
/// The table as the gateway resolved it. A request that names no
/// location, another location than the index's own, or storage options
/// the engine's credentials must not be used with is refused.
fn describe(&self, table: &pb::Table) -> Result<TableDescription, Status> {
if table.location.is_empty() {
return Err(Status::invalid_argument("the table names no location"));
}
let description = resolved(table, self.schemes).ok_or_else(|| {
Status::permission_denied(format!(
"{} is not the location of index {}",
table.location,
table.id.join("/")
))
})?;
sse_s3_ready(
table.sse_s3,
self.storage.as_ref().map(|s| s.sse_s3_configured()),
)?;
Ok(description)
}
/// The store Lance opens a table with: direct storage innermost, the read
/// cache outside it so a hit never reaches storage.
fn wrapper(&self, table: &pb::Table) -> Option<Arc<dyn WrappingObjectStore>> {
let mut wrappers: Vec<Arc<dyn WrappingObjectStore>> = Vec::new();
if let Some(storage) = &self.storage {
wrappers.push(Arc::new(storage.encrypting(table.sse_s3)));
}
if let Some(cache) = &self.read_cache {
wrappers.push(Arc::new(cache.clone()));
}
(!wrappers.is_empty()).then(|| Arc::new(Wrappers(wrappers)) as Arc<dyn WrappingObjectStore>)
}
async fn open(&self, table: &pb::Table) -> Result<Dataset, Status> {
self.open_in(table, None).await
}
/// [`Self::open`] in the shared session, for a request that only reads.
async fn open_to_read(&self, table: &pb::Table) -> Result<Dataset, Status> {
loop {
let (session, generation) = {
let reads = self.reads.lock().unwrap();
(reads.session.clone(), reads.generation)
};
let dataset = match self.handle(table, generation).await? {
Some(dataset) => dataset,
None => {
let dataset = self.open_in(table, Some(session)).await?;
// Under the lock, so no handle of a replaced session
// lands after the replacement cleared them.
let reads = self.reads.lock().unwrap();
if table.version == 0 && reads.generation == generation {
self.handles
.insert(handle_key(table), (generation, dataset.clone()));
}
dataset
}
};
let mut reads = self.reads.lock().unwrap();
if reads.generation != generation {
continue;
}
if reads.admit(&table.location, table_id(&dataset), self.lance_cache_bytes) {
return Ok(dataset);
}
// The handles hold the replaced session and its caches.
self.handles.invalidate_all();
}
}
/// The table from the handle an earlier read of it left in this session,
/// moved to the version asked for: the latest costs a listing of its
/// versions, not a new store and manifest read.
async fn handle(&self, table: &pb::Table, generation: u64) -> Result<Option<Dataset>, Status> {
self.describe(table)?;
let key = handle_key(table);
let Some((at, mut dataset)) = self.handles.get(&key) else {
return Ok(None);
};
if at != generation {
return Ok(None);
}
let moved = match table.version {
0 => dataset.checkout_latest().await.map(|()| dataset),
version => dataset.checkout_version(version).await,
};
moved.map(Some).map_err(|err| {
self.handles.invalidate(&key);
open_status(err.into())
})
}
async fn open_in(
&self,
table: &pb::Table,
session: Option<Arc<Session>>,
) -> Result<Dataset, Status> {
let description = self.describe(table)?;
let wrapper = self.wrapper(table);
let mut dataset = dataset::open_at(&description, wrapper, session)
.await
.map_err(open_status)?;
async fn open(&self, table: &pb::Table) -> Result<Dataset> {
let opened = dataset::open_with(
&self.client,
&table.id,
&self.fallback,
self.read_cache.clone(),
)
.await?;
let mut dataset = opened.dataset;
if table.version != 0 {
dataset = dataset
.checkout_version(table.version)
.await
.map_err(|err| open_status(err.into()))?;
dataset = dataset.checkout_version(table.version).await?;
}
Ok(dataset)
}
@@ -719,47 +425,30 @@ impl VectorService for VectorServer {
return Err(Status::invalid_argument("dimension must be 1..=4096"));
}
// The gateway has already created the table through the catalog.
let description = self.describe(&table)?;
let description = self
.client
.describe_table(&table.id)
.await
.map_err(internal)?;
let options = dataset::table_options(&description, &self.fallback);
let schema = schema_for(dimension, metric, &req.non_filterable_metadata_keys);
let schema = Arc::new(Schema::new_with_metadata(
schema.fields().clone(),
HashMap::from([(
TABLE_ID_KEY.to_string(),
uuid::Uuid::new_v4().simple().to_string(),
)]),
));
let empty = RecordBatch::new_empty(schema.clone());
let reader = arrow_array::RecordBatchIterator::new(vec![Ok(empty)].into_iter(), schema);
let dataset = Dataset::write(
reader,
&description.location,
Some(WriteParams {
store_params: Some(dataset::store_params(self.wrapper(&table))),
store_params: Some(ObjectStoreParams {
storage_options_accessor: Some(Arc::new(
StorageOptionsAccessor::with_static_options(options),
)),
..Default::default()
}),
..Default::default()
}),
)
.await;
let dataset = match dataset {
Ok(dataset) => dataset,
Err(error) => match self.open(&table).await {
Ok(existing)
if matches_index_schema(
&existing,
dimension,
metric,
&req.non_filterable_metadata_keys,
) =>
{
existing
}
Ok(_) => {
return Err(Status::already_exists(
"index exists with a different schema",
));
}
Err(_) => return Err(internal(error)),
},
};
.await
.map_err(internal)?;
Ok(Response::new(pb::CreateIndexResponse {
version: dataset.version().version,
}))
@@ -773,24 +462,15 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
// describe() already refused any location but the index's own.
let description = self.describe(&table)?;
match &self.storage {
Some(storage) => storage
.remove_table(&description.location)
.await
.map_err(internal)?,
None => {
let (store, path) = lance::io::ObjectStore::from_uri_and_params(
Arc::new(lance::io::ObjectStoreRegistry::default()),
&description.location,
&dataset::store_params(self.wrapper(&table)),
)
.await
.map_err(internal)?;
store.remove_dir_all(path).await.map_err(internal)?;
}
}
dataset::drop(&self.client, &table.id, &self.fallback)
.await
.map_err(|err| {
if err.is::<dataset::DropRefused>() {
Status::failed_precondition(format!("{err:#}"))
} else {
internal(err)
}
})?;
Ok(Response::new(pb::DropIndexResponse {}))
}
@@ -802,7 +482,7 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await?;
let dataset = self.open(&table).await.map_err(open_status)?;
if req.vectors.is_empty() {
return Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
@@ -844,10 +524,12 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open_to_read(&table).await?;
let dataset = self.open(&table).await.map_err(open_status)?;
// Lease the resolved version so maintenance cannot reclaim its files
// while this query runs against it.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
.await
.map_err(internal)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
let columns = projection(req.return_data, req.return_metadata);
let batches = query::get(&dataset, &resolved, &req.keys, Some(&columns))
@@ -866,7 +548,7 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let mut dataset = self.open(&table).await?;
let mut dataset = self.open(&table).await.map_err(open_status)?;
if !req.keys.is_empty() {
dataset
.delete(&key_list(&req.keys))
@@ -892,7 +574,7 @@ impl VectorService for VectorServer {
"segment_index must be below segment_count, which is at most {MAX_SEGMENTS}"
)));
}
let dataset = self.open_to_read(&table).await?;
let dataset = self.open(&table).await.map_err(open_status)?;
let offset: u64 = if req.next_token.is_empty() {
0
} else {
@@ -912,7 +594,9 @@ impl VectorService for VectorServer {
// Data and metadata come from a second read of this version, so
// lease it as get_vectors does.
let _lease = if columns.len() > 1 {
self.leases.try_pin(&dataset).await.map_err(internal)?
weed_vector_core::maintenance::try_pin(&dataset)
.await
.map_err(internal)?
} else {
None
};
@@ -957,10 +641,12 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open_to_read(&table).await?;
let dataset = self.open(&table).await.map_err(open_status)?;
// Lease the resolved version so maintenance cannot reclaim its files
// while this query runs against it.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
.await
.map_err(internal)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
if req.query_vector.len() != resolved.dimension {
return Err(Status::invalid_argument(format!(
@@ -972,7 +658,16 @@ impl VectorService for VectorServer {
if req.top_k == 0 {
return Err(Status::invalid_argument("top_k must be positive"));
}
let distance = index::distance_metric(&dataset, VECTOR_COLUMN);
// The index's configured metric lives in the vector field's metadata.
let distance = match dataset
.schema()
.field(VECTOR_COLUMN)
.and_then(|f| f.metadata.get("distance_metric").map(String::as_str))
{
Some("COSINE") => DistanceType::Cosine,
Some("DOT_PRODUCT") => DistanceType::Dot,
_ => DistanceType::L2,
};
let query = Query {
vector: req.query_vector,
k: req.top_k as usize,
@@ -983,7 +678,7 @@ impl VectorService for VectorServer {
},
postfilter: req.postfilter,
distance,
nprobes: self.nprobes,
nprobes: None,
index_segments: None,
fragments: None,
};
@@ -1247,99 +942,45 @@ mod tests {
assert_eq!(next, None);
}
/// A location that is not the index's own is refused before anything is
/// opened or removed.
/// A catalog that answers one describe with `location`.
async fn catalog_describing(location: &str) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let body = serde_json::json!({ "location": location }).to_string();
tokio::spawn(async move {
let (mut conn, _) = listener.accept().await.unwrap();
let mut request = [0u8; 8192];
let _ = conn.read(&mut request).await;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
conn.write_all(response.as_bytes()).await.unwrap();
let _ = conn.shutdown().await;
let _ = tokio::io::copy(&mut conn, &mut tokio::io::sink()).await;
});
url
}
#[tokio::test]
async fn drop_index_refuses_a_location_outside_the_table() {
let server = VectorServer::new();
for location in [
"s3://bkt/vector",
"s3://bkt/vector/prod",
"s3://other/vector/x",
] {
for location in ["s3://bkt/vector", "s3://bkt/vector/prod"] {
let server = VectorServer::new(
NamespaceClient::new(catalog_describing(location).await),
FallbackOptions::new(),
);
let request = pb::DropIndexRequest {
table: Some(pb::Table {
id: vec!["bkt".into(), "vector".into(), "x".into()],
location: location.into(),
..Default::default()
version: 0,
}),
};
let err = server
.drop_index(Request::new(request))
.await
.expect_err(location);
assert_eq!(err.code(), tonic::Code::PermissionDenied, "{location}");
}
}
/// A table of an SSE-S3 bucket is refused before Lance opens it when the
/// storage holds no key.
#[test]
fn an_sse_s3_table_needs_the_key() {
assert!(sse_s3_ready(false, Some(false)).is_ok());
assert!(sse_s3_ready(true, Some(true)).is_ok());
assert!(
sse_s3_ready(true, None).is_ok(),
"in-process stores need no key"
);
let err = sse_s3_ready(true, Some(false)).unwrap_err();
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
assert!(err.message().contains("s3.sse.kek or s3.sse.key"));
}
/// Only a vector index at its colocated path is taken from the request.
#[test]
fn resolved_takes_only_a_colocated_vector_index() {
let table = |id: &[&str], location: &str| pb::Table {
id: id.iter().map(|s| s.to_string()).collect(),
location: location.into(),
..Default::default()
};
let s3 = &["s3"];
let index = ["bkt", "vector", "x"];
for location in ["s3://bkt/vector/x", "s3://bkt/vector/x/"] {
let description = resolved(&table(&index, location), s3).expect(location);
assert_eq!(description.location, "s3://bkt/vector/x");
assert_eq!(
description
.storage_options
.get("aws_skip_signature")
.map(String::as_str),
Some("true")
);
}
assert!(resolved(&table(&index, ""), s3).is_none());
assert!(resolved(&table(&index, "s3://other/vector/x"), s3).is_none());
assert!(resolved(&table(&index, "s3://bkt/vector/y"), s3).is_none());
assert!(resolved(&table(&index, "file://bkt/vector/x"), s3).is_none());
assert!(resolved(&table(&index, "memory://bkt/vector/x"), &["s3", "memory"]).is_some());
assert!(resolved(&table(&["bkt", "ns", "x"], "s3://bkt/ns/x"), s3).is_none());
assert!(resolved(&table(&["bkt", "vector", ".."], "s3://bkt/vector/.."), s3).is_none());
assert!(resolved(&table(&["bkt", "vector", "a/b"], "s3://bkt/vector/a/b"), s3).is_none());
assert!(resolved(&table(&["bkt", "x"], "s3://bkt/x"), s3).is_none());
}
/// A request names the table's location or is refused.
#[tokio::test]
async fn a_table_without_its_location_is_refused() {
let server = VectorServer::new();
for (location, code) in [
("", tonic::Code::InvalidArgument),
("s3://other/vector/x", tonic::Code::PermissionDenied),
] {
let err = server
.get_vectors(Request::new(pb::GetVectorsRequest {
table: Some(pb::Table {
id: vec!["bkt".into(), "vector".into(), "x".into()],
location: location.into(),
..Default::default()
}),
keys: vec!["k001".into()],
..Default::default()
}))
.await
.expect_err(location);
assert_eq!(err.code(), code, "{location}");
assert_eq!(err.code(), tonic::Code::FailedPrecondition, "{location}");
}
}
}
@@ -1,111 +0,0 @@
use std::sync::Arc;
use bytes::Bytes;
use lance::io::WrappingObjectStore;
use object_store::{ObjectStoreExt, memory::InMemory, path::Path};
use weed_vector_server::{metrics::Metrics, read_cache::ReadCache};
#[tokio::test]
async fn immutable_reads_report_hits_misses_bytes_and_weight() {
let metrics = Metrics::new().unwrap();
let cache = ReadCache::new(1024).with_metrics(metrics.clone());
let store = cache.wrap("memory", Arc::new(InMemory::new()));
let path = Path::from("data/example.lance");
store
.put(&path, Bytes::from_static(b"abc").into())
.await
.unwrap();
for _ in 0..2 {
assert_eq!(
store.get(&path).await.unwrap().bytes().await.unwrap(),
"abc"
);
}
assert_eq!(metrics.cache_requests.with_label_values(&["miss"]).get(), 1);
assert_eq!(metrics.cache_requests.with_label_values(&["hit"]).get(), 1);
assert_eq!(metrics.storage_bytes.get(), 3);
assert_eq!(metrics.storage_read_seconds.get_sample_count(), 1);
let (entries, weight) = cache.size();
assert_eq!(entries, 1);
assert!(weight >= 3);
let metrics_endpoint = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}/metrics", metrics_endpoint.local_addr().unwrap());
let task = tokio::spawn(weed_vector_server::metrics::serve_listener(
metrics,
metrics_endpoint,
Some(cache),
));
let body = reqwest::get(endpoint).await.unwrap().text().await.unwrap();
assert!(body.contains("SeaweedFS_vector_cache_entries 1"));
assert!(body.contains("SeaweedFS_vector_cache_bytes "));
task.abort();
}
#[tokio::test]
async fn cancelled_requests_are_counted_once() {
let metrics = Metrics::new().unwrap();
let guard = metrics.start("QueryVectors");
let task = tokio::spawn(async move {
let _guard = guard;
std::future::pending::<()>().await;
});
task.abort();
let _ = task.await;
assert_eq!(
metrics.in_flight.with_label_values(&["QueryVectors"]).get(),
0
);
assert_eq!(
metrics
.requests
.with_label_values(&["QueryVectors", "Cancelled"])
.get(),
1
);
assert_eq!(
metrics
.request_seconds
.with_label_values(&["QueryVectors"])
.get_sample_count(),
1
);
{
let mut guard = metrics.start("QueryVectors");
guard.complete(None);
}
assert_eq!(
metrics
.requests
.with_label_values(&["QueryVectors", "OK"])
.get(),
1
);
assert_eq!(
metrics
.requests
.with_label_values(&["QueryVectors", "Cancelled"])
.get(),
1
);
}
#[tokio::test]
async fn large_immutable_reads_report_bytes_without_caching() {
let metrics = Metrics::new().unwrap();
let cache = ReadCache::new(16 * 1024 * 1024).with_metrics(metrics.clone());
let store = cache.wrap("memory", Arc::new(InMemory::new()));
let path = Path::from("data/large.lance");
let size = 5 * 1024 * 1024;
store
.put(&path, Bytes::from(vec![0; size]).into())
.await
.unwrap();
let result = store.get(&path).await.unwrap();
assert_eq!(metrics.storage_bytes.get(), 0);
assert_eq!(metrics.storage_read_seconds.get_sample_count(), 0);
assert_eq!(result.bytes().await.unwrap().len(), size);
assert_eq!(metrics.storage_bytes.get(), size as u64);
assert_eq!(metrics.cache_requests.with_label_values(&["miss"]).get(), 1);
assert_eq!(metrics.storage_read_seconds.get_sample_count(), 1);
assert_eq!(cache.size(), (0, 0));
}
-1
View File
@@ -4608,7 +4608,6 @@ dependencies = [
"jsonwebtoken",
"kamadak-exif",
"libc",
"lru",
"md-5",
"memmap2",
"mime_guess",
-1
View File
@@ -130,7 +130,6 @@ chrono = "0.4"
hex = "0.4"
parking_lot = "0.12"
dashmap = "6"
lru = "0.16"
thiserror = "1"
anyhow = "1"
async-trait = "0.1"
-4
View File
@@ -230,10 +230,6 @@ message KeepConnectedRequest {
// A draining filer leaves the lock ring but stays a cluster member, so peers
// keep following its metadata until the stream closes.
bool leave_lock_ring = 8;
// Port of this node's Prometheus /metrics listener (-metricsPort), or 0 when
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
uint32 metrics_port = 9;
}
message VolumeLocation {
+35 -48
View File
@@ -1,7 +1,7 @@
use clap::Parser;
use std::ffi::OsString;
use std::net::UdpSocket;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use crate::security::tls::TlsPolicy;
@@ -1051,6 +1051,8 @@ pub struct SecurityConfig {
pub guard_white_list: Vec<String>,
}
const SECURITY_CONFIG_FILE_NAME: &str = "security.toml";
/// Parse a security.toml file to extract JWT signing keys and TLS configuration.
/// Format:
/// ```toml
@@ -1175,7 +1177,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
if let Some((key, value)) = trimmed.split_once('=') {
let key = key.trim();
let value: &str = &toml_value_text(value);
let value = value.trim().trim_matches('"');
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
@@ -1265,29 +1267,44 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
cfg
}
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
/// escapes decoded, literal strings kept as written, a trailing comment
/// dropped. Text TOML rejects keeps the plain quote trimming.
fn toml_value_text(raw: &str) -> String {
match format!("v = {raw}").parse::<toml::Table>() {
Ok(mut table) => match table.remove("v") {
Some(toml::Value::String(text)) => text,
Some(other) => other.to_string(),
None => String::new(),
},
Err(_) => raw.trim().trim_matches('"').to_string(),
}
}
fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBuf> {
if !path.is_empty() {
return Some(PathBuf::from(path));
}
seaweed_common::security_config::find(
default_security_config_candidates(
std::env::current_dir().ok().as_deref(),
seaweed_common::security_config::home_dir(env).as_deref(),
home_dir_from_env(env).as_deref(),
)
.into_iter()
.find(|candidate| candidate.is_file())
}
fn default_security_config_candidates(
current_dir: Option<&Path>,
home_dir: Option<&Path>,
) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Some(dir) = current_dir {
candidates.push(dir.join(SECURITY_CONFIG_FILE_NAME));
}
if let Some(home) = home_dir {
candidates.push(home.join(".seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
}
candidates.push(PathBuf::from("/usr/local/etc/seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
candidates.push(PathBuf::from("/etc/seaweedfs").join(SECURITY_CONFIG_FILE_NAME));
candidates
}
fn home_dir_from_env(env: EnvLookup<'_>) -> Option<PathBuf> {
env("HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| {
env("USERPROFILE")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
})
}
/// Apply WEED_ environment variable overrides to a SecurityConfig.
@@ -1386,9 +1403,7 @@ fn detect_host_address() -> String {
#[cfg(test)]
mod tests {
use super::*;
use seaweed_common::security_config::SECURITY_CONFIG_FILE_NAME;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Mutex, MutexGuard, OnceLock};
/// Serialises the tests that move the process working directory against
@@ -1882,34 +1897,6 @@ ui = true
assert!(cfg.access_ui);
}
#[test]
fn test_parse_security_config_reads_toml_strings() {
for (encoded, expected) in [
(r#""plain""#, "plain"),
(r#""key\n""#, "key\n"),
(r#""quote\"slash\\tab\t""#, "quote\"slash\\tab\t"),
(r#""key""#, "key"),
("'literal\\key'", "literal\\key"),
(r#""key" # comment"#, "key"),
(r#""YWJj==""#, "YWJj=="),
("unquoted", "unquoted"),
] {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
format!(
"[jwt.signing]\nkey = {encoded}\n\n[jwt.signing.read]\nkey = {encoded}\n\
expires_after_seconds = 30 # seconds\n"
),
)
.unwrap();
let cfg = parse_security_config_with_env(tmp.path().to_str().unwrap(), &|_| None);
assert_eq!(cfg.jwt_signing_key, expected.as_bytes(), "{encoded}");
assert_eq!(cfg.jwt_read_signing_key, expected.as_bytes(), "{encoded}");
assert_eq!(cfg.jwt_read_signing_expires, 30, "{encoded}");
}
}
#[test]
fn test_parse_security_config_discovers_current_directory_default() {
let _guard = process_state_lock();
+35 -185
View File
@@ -118,17 +118,6 @@ fn reject_https_downgrade(attempt: reqwest::redirect::Attempt) -> reqwest::redir
}
}
/// A peer that never answers a SYN (silent partition) must not stall new
/// outgoing connections; requests set their own overall bounds as needed.
const OUTGOING_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// Base of every outgoing HTTP client: redirect policy and connect bound.
fn outgoing_client_builder(redirect_policy: reqwest::redirect::Policy) -> reqwest::ClientBuilder {
reqwest::Client::builder()
.redirect(redirect_policy)
.connect_timeout(OUTGOING_CONNECT_TIMEOUT)
}
fn build_outgoing_http_client(
config: &VolumeServerConfig,
) -> Result<(reqwest::Client, String), Box<dyn std::error::Error>> {
@@ -140,12 +129,14 @@ fn build_outgoing_http_client(
let redirect_policy = reqwest::redirect::Policy::custom(reject_https_downgrade);
if !config.https_client_enabled {
return Ok((
outgoing_client_builder(redirect_policy).build()?,
reqwest::Client::builder()
.redirect(redirect_policy)
.build()?,
scheme.to_string(),
));
}
let mut builder = outgoing_client_builder(redirect_policy);
let mut builder = reqwest::Client::builder().redirect(redirect_policy);
if !config.https_client_ca_file.is_empty() {
let ca_pem = std::fs::read(&config.https_client_ca_file).map_err(|e| {
format!(
@@ -717,8 +708,7 @@ async fn run(
.build_v1alpha()
.expect("Failed to build gRPC reflection v1alpha service");
let result = if let Some(tls_acceptor) = grpc_tls_acceptor {
let incoming =
grpc_tls_incoming(grpc_listener, tls_acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
let incoming = grpc_tls_incoming(grpc_listener, tls_acceptor);
info!("gRPC server listening on {} (TLS enabled)", grpc_local_addr);
build_grpc_server_builder()
.layer(GrpcRequestIdLayer)
@@ -855,39 +845,40 @@ async fn run(
}))
};
// Whichever server stops first takes the other down, as a serve failure
// is fatal for the Go volume server.
// Wait for servers. Use select! with &mut so the losing handle is not
// dropped, then await it explicitly afterward.
let mut server_err: Option<String> = None;
let mut grpc_handle = grpc_handle;
let mut http_handle = http_handle;
let (http_result, grpc_result) = tokio::select! {
r = &mut grpc_handle => {
let _ = shutdown_tx.send(());
(http_handle.await, r)
}
r = &mut http_handle => {
let _ = shutdown_tx.send(());
(r, grpc_handle.await)
}
let mut grpc_handle = grpc_handle;
let grpc_finished_first = tokio::select! {
_ = &mut http_handle => false,
_ = &mut grpc_handle => true,
};
// Inspect the gRPC result (already resolved if it finished first,
// otherwise await it now).
let grpc_result = if grpc_finished_first {
grpc_handle.await
} else {
// HTTP finished first; gRPC is still running. Await it.
grpc_handle.await
};
if let Err(e) = http_result {
let msg = format!("HTTP task panicked: {}", e);
error!("{}", msg);
server_err = Some(msg);
}
match grpc_result {
Ok(Ok(())) => {}
Ok(Err(e)) => {
let msg = format!("gRPC server exited with error: {}", e);
error!("{}", msg);
server_err = Some(msg);
// serve error already sent shutdown inside the task
}
Err(e) => {
let msg = format!("gRPC task panicked: {}", e);
error!("{}", msg);
server_err = Some(msg);
let _ = shutdown_tx.send(());
}
}
// Ensure the HTTP handle completes too.
let _ = http_handle.await;
if let Some(h) = public_handle {
let _ = h.await;
}
@@ -955,64 +946,28 @@ async fn run_metrics_push_loop(
}
}
/// grpc-go's default ConnectionTimeout, which bounds a Go server's handshake.
const GRPC_TLS_HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
/// Each handshake runs on its own task, so a peer that connects and stays
/// silent holds up no other connection, as with a Go gRPC server.
fn grpc_tls_incoming(
listener: tokio::net::TcpListener,
tls_acceptor: TlsAcceptor,
handshake_timeout: std::time::Duration,
) -> impl tokio_stream::Stream<
Item = Result<tokio_rustls::server::TlsStream<tokio::net::TcpStream>, std::io::Error>,
> {
let (tx, rx) = tokio::sync::mpsc::channel(64);
tokio::spawn(async move {
let mut retry_delay = std::time::Duration::ZERO;
async_stream::stream! {
loop {
let accepted = tokio::select! {
_ = tx.closed() => return,
accepted = listener.accept() => accepted,
};
let (tcp_stream, remote_addr) = match accepted {
Ok(accepted) => {
retry_delay = std::time::Duration::ZERO;
accepted
}
Err(e) => {
// Back off and retry like grpc-go, so running out of file
// descriptors does not close the gRPC port for good.
retry_delay = (retry_delay * 2).clamp(
std::time::Duration::from_millis(5),
std::time::Duration::from_secs(1),
);
tracing::warn!("gRPC accept error: {}; retrying in {:?}", e, retry_delay);
tokio::select! {
_ = tx.closed() => return,
_ = tokio::time::sleep(retry_delay) => continue,
}
}
};
let tls_acceptor = tls_acceptor.clone();
let tx = tx.clone();
tokio::spawn(async move {
match tokio::time::timeout(handshake_timeout, tls_acceptor.accept(tcp_stream)).await
{
Ok(Ok(tls_stream)) => {
let _ = tx.send(Ok(tls_stream)).await;
}
Ok(Err(e)) => {
match listener.accept().await {
Ok((tcp_stream, remote_addr)) => match tls_acceptor.accept(tcp_stream).await {
Ok(tls_stream) => yield Ok(tls_stream),
Err(e) => {
tracing::debug!("gRPC TLS handshake failed from {}: {}", remote_addr, e);
}
Err(_) => {
tracing::debug!("gRPC TLS handshake from {} timed out", remote_addr);
}
},
Err(e) => {
yield Err(e);
break;
}
});
}
}
});
tokio_stream::wrappers::ReceiverStream::new(rx)
}
}
/// Serve an axum Router over TLS using tokio-rustls.
@@ -1119,121 +1074,16 @@ async fn serve_https<F>(
#[cfg(test)]
mod tests {
use super::{
GRPC_TLS_HANDSHAKE_TIMEOUT, build_grpc_server_tls_acceptor, effective_http_tls_policy,
grpc_tls_incoming, tls_policy_is_configured,
build_grpc_server_tls_acceptor, effective_http_tls_policy, tls_policy_is_configured,
};
use seaweed_volume::security::tls::TlsPolicy;
/// A connect that never finishes fails at the 5 s bound. It stalls in the
/// resolver, which the connect bound also covers, because that needs no
/// routing: a real unanswered SYN depends on the host's network.
#[tokio::test(start_paused = true)]
async fn outgoing_client_bounds_a_stalled_connect() {
struct Stalled;
impl reqwest::dns::Resolve for Stalled {
fn resolve(&self, _: reqwest::dns::Name) -> reqwest::dns::Resolving {
Box::pin(std::future::pending())
}
}
let client = super::outgoing_client_builder(reqwest::redirect::Policy::none())
.no_proxy()
.dns_resolver(std::sync::Arc::new(Stalled))
.build()
.unwrap();
let started = tokio::time::Instant::now();
let sent = tokio::time::timeout(
std::time::Duration::from_secs(600),
client.get("http://silent-peer.invalid:8080/status").send(),
)
.await
.expect("a stalled connect must not outlive its bound");
assert!(sent.is_err(), "a stalled connect cannot answer");
assert_eq!(started.elapsed(), super::OUTGOING_CONNECT_TIMEOUT);
}
fn write_pem(dir: &tempfile::TempDir, name: &str, body: &str) -> String {
let path = dir.path().join(name);
std::fs::write(&path, body).unwrap();
path.to_string_lossy().into_owned()
}
// A CA and a leaf it signed for localhost, usable on either side.
const TEST_CA_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBhzCCAS2gAwIBAgIUWQMpep+B+ShfbwEfk20OGMkBgpAwCgYIKoZIzj0EAwIw\nGTEXMBUGA1UEAwwOdm9sdW1lLXRlc3QtY2EwHhcNMjYxMTAzMTgzOTI2WhcNMzYx\nMDMxMTgzOTI2WjAZMRcwFQYDVQQDDA52b2x1bWUtdGVzdC1jYTBZMBMGByqGSM49\nAgEGCCqGSM49AwEHA0IABD8L549bGTiFShKDcA2UFhz2MH9wxVuFCWCfJ7OVYM2x\nweY/5uCLjBRAnFx5FuWnaNtdTWkImXBSguHe861foCajUzBRMB0GA1UdDgQWBBQH\nOSZ93m5jmlLJpS5cFzH2hicEdjAfBgNVHSMEGDAWgBQHOSZ93m5jmlLJpS5cFzH2\nhicEdjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0gAMEUCIEetcimwxiDU\n8RS0b5uaev3c/kbnOT1nOV6n2wdtplZ4AiEAlWDH77I9ssy+yqXArkdiEadePIl5\nUyXg6crXqITwUeE=\n-----END CERTIFICATE-----\n";
const TEST_LEAF_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBuTCCAV+gAwIBAgIUC4xhlzsyNZi0XHzyCwV/xquGQLkwCgYIKoZIzj0EAwIw\nGTEXMBUGA1UEAwwOdm9sdW1lLXRlc3QtY2EwHhcNMjYxMTAzMTgzOTI2WhcNMzYx\nMDMxMTgzOTI2WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggq\nhkjOPQMBBwNCAASKt0T/i1pt7Aw3DloYFRoaX8+w/reR3tIEaMo911/fIvQhqkg4\nLPCXKocq0KNw3Na3HnZeU9Ls+FLoSHynBsyIo4GJMIGGMBoGA1UdEQQTMBGCCWxv\nY2FsaG9zdIcEfwAAATAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwCQYD\nVR0TBAIwADAdBgNVHQ4EFgQUp8jNqBiE0UeYRkCny2In6SyKEKkwHwYDVR0jBBgw\nFoAUBzkmfd5uY5pSyaUuXBcx9oYnBHYwCgYIKoZIzj0EAwIDSAAwRQIhAIzNfGpS\n+rIxr3eGInfD+0DzQxSuqfcQZTkV2eGkebcuAiAIV73Y7wKg7D08qfmmrH/TaAZB\nm2wr/1assOVDaw8dMg==\n-----END CERTIFICATE-----\n";
const TEST_LEAF_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgmMs2vKPN5ymhYOXl\nztUUiSWAcmKVVWxveajzfxIwqBehRANCAASKt0T/i1pt7Aw3DloYFRoaX8+w/reR\n3tIEaMo911/fIvQhqkg4LPCXKocq0KNw3Na3HnZeU9Ls+FLoSHynBsyI\n-----END PRIVATE KEY-----\n";
fn test_grpc_tls_acceptor(dir: &tempfile::TempDir) -> tokio_rustls::TlsAcceptor {
seaweed_volume::security::tls::install_default_crypto_provider();
let ca = write_pem(dir, "ca.pem", TEST_CA_PEM);
let cert = write_pem(dir, "leaf.pem", TEST_LEAF_PEM);
let key = write_pem(dir, "leaf.key", TEST_LEAF_KEY_PEM);
build_grpc_server_tls_acceptor(&cert, &key, &ca, &TlsPolicy::default(), "", &[])
.unwrap()
.unwrap()
}
#[tokio::test]
async fn test_grpc_tls_incoming_serves_past_a_silent_peer() {
use tokio_stream::StreamExt;
let dir = tempfile::tempdir().unwrap();
let acceptor = test_grpc_tls_acceptor(&dir);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let mut incoming = Box::pin(grpc_tls_incoming(
listener,
acceptor,
GRPC_TLS_HANDSHAKE_TIMEOUT,
));
let _silent = tokio::net::TcpStream::connect(addr).await.unwrap();
let mut roots = rustls::RootCertStore::empty();
for c in rustls_pemfile::certs(&mut TEST_CA_PEM.as_bytes()) {
roots.add(c.unwrap()).unwrap();
}
let config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_client_auth_cert(
rustls_pemfile::certs(&mut TEST_LEAF_PEM.as_bytes())
.map(|c| c.unwrap())
.collect(),
rustls_pemfile::private_key(&mut TEST_LEAF_KEY_PEM.as_bytes())
.unwrap()
.unwrap(),
)
.unwrap();
let client = tokio::spawn(async move {
let tcp = tokio::net::TcpStream::connect(addr).await.unwrap();
tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
.connect("localhost".try_into().unwrap(), tcp)
.await
});
let served = tokio::time::timeout(std::time::Duration::from_secs(5), incoming.next()).await;
assert!(
matches!(served, Ok(Some(Ok(_)))),
"the handshake waited behind a silent peer"
);
client.await.unwrap().unwrap();
}
#[tokio::test]
async fn test_grpc_tls_incoming_closes_a_silent_peer_after_the_handshake_timeout() {
use tokio::io::AsyncReadExt;
let dir = tempfile::tempdir().unwrap();
let acceptor = test_grpc_tls_acceptor(&dir);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let _incoming =
grpc_tls_incoming(listener, acceptor, std::time::Duration::from_millis(100));
let mut silent = tokio::net::TcpStream::connect(addr).await.unwrap();
let mut buf = [0u8; 1];
let read =
tokio::time::timeout(std::time::Duration::from_secs(5), silent.read(&mut buf)).await;
assert!(
matches!(read, Ok(Ok(0)) | Ok(Err(_))),
"the silent peer stayed connected past the handshake timeout"
);
}
#[test]
fn test_grpc_server_tls_requires_ca() {
let dir = tempfile::tempdir().unwrap();
-16
View File
@@ -252,21 +252,6 @@ pub static SCRUB_SHARD_FAILURES: LazyLock<IntCounterVec> = LazyLock::new(|| {
.expect("metric can be created")
});
/// Reads of an EC shard interval that couldn't be read directly and were
/// served by reconstructing it from the other shards, by result. `success`
/// means the reconstruction produced data, not that the needle then passed
/// validation. Mirrors Go's VolumeServerECReconstructedIntervalCounter.
pub static EC_RECONSTRUCTED_INTERVAL_COUNTER: LazyLock<IntCounterVec> = LazyLock::new(|| {
IntCounterVec::new(
Opts::new(
"SeaweedFS_volumeServer_ec_reconstructed_interval_total",
"Reads of an EC interval served by reconstructing from other shards; success means reconstruction produced data, not that the needle passed validation.",
),
&["result"],
)
.expect("metric can be created")
});
/// Counter of storage read/write EIO errors on volumes and EC shards.
/// Mirrors Go's VolumeServerStorageIoErrorCounter.
pub static STORAGE_IO_ERROR_COUNTER: LazyLock<IntCounter> = LazyLock::new(|| {
@@ -417,7 +402,6 @@ pub fn register_metrics() {
Box::new(SCRUB_VOLUME_FAILURES.clone()),
Box::new(SCRUB_SHARD_FAILURES.clone()),
Box::new(STORAGE_IO_ERROR_COUNTER.clone()),
Box::new(EC_RECONSTRUCTED_INTERVAL_COUNTER.clone()),
Box::new(IO_QUARANTINE_GAUGE.clone()),
// Legacy metrics
Box::new(VOLUMES_TOTAL.clone()),
File diff suppressed because it is too large. Load diff
+64 -620
View File
@@ -198,8 +198,11 @@ fn read_needle_for_get(
Option<(Needle, Option<crate::storage::volume::NeedleStreamInfo>)>,
crate::storage::volume::VolumeError,
> {
let mut plan =
crate::storage::store::Store::needle_read_plan(&state.store, vid, needle_id, read_deleted)?;
let mut plan = state
.store
.read()
.unwrap()
.needle_read_plan(vid, needle_id, read_deleted)?;
let blank = || Needle {
id: needle_id,
cookie,
@@ -692,6 +695,44 @@ async fn batch_delete_file_ids(
Ok(())
}
/// Mirrors Go's checkDeleteReplicas: refuses a delete the master cannot route
/// to every replica, as the HTTP delete path does, so an offline replica does
/// not keep the needle once it returns.
pub(crate) async fn check_delete_replicas(
state: &VolumeServerState,
vid: u32,
) -> Result<(), String> {
let copy_count = {
let store = state.store.read().unwrap();
match store.find_volume(VolumeId(vid)) {
Some((_, v)) => v.super_block().replica_placement.get_copy_count(),
None => return Ok(()),
}
};
if copy_count <= 1 {
return Ok(());
}
let locations = lookup_volume(
&state.http_client,
&state.outgoing_http_scheme,
&state.current_master().await,
vid,
)
.await
.map_err(|e| format!("replicating lookup failed for {}: {}", vid, e))?;
let deletable = locations
.iter()
.filter(|loc| !loc.read_only || loc.read_only_can_delete)
.count();
if deletable < copy_count as usize {
return Err(format!(
"replication locations [{}] is less than volume {} replication copy count [{}]",
deletable, vid, copy_count
));
}
Ok(())
}
/// `query` with the fields named in `overrides` replaced by their values.
fn override_query_fields(query: &str, overrides: &[(&str, String)]) -> Result<String, String> {
let mut fields = Vec::new();
@@ -713,36 +754,6 @@ fn override_query_fields(query: &str, overrides: &[(&str, String)]) -> Result<St
Ok(fields.join("&"))
}
/// Bound on one replica forward, from connecting until its response arrives.
/// Without it a silently partitioned peer (packets dropped, no reset) holds the
/// write until TCP gives up, minutes later; with it the forward fails and the
/// writer gets "replication failed" (500). It bounds each forward after the
/// master lookup, not the whole write: the lookup has only the client's connect
/// bound. A forward with a body gets more time, see replica_request_timeout.
pub(crate) const REPLICA_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// The slowest link a replica forward's body may cross within its bound, so a
/// large write is not cut off on a link that is merely slower than a LAN.
const REPLICA_MIN_BYTES_PER_SEC: u64 = 1 << 20;
fn replica_request_timeout(body_len: usize) -> std::time::Duration {
REPLICA_REQUEST_TIMEOUT
+ std::time::Duration::from_millis(
(body_len as u64).saturating_mul(1000) / REPLICA_MIN_BYTES_PER_SEC,
)
}
fn replica_request(
client: &reqwest::Client,
method: axum::http::Method,
url: &str,
body_len: usize,
) -> reqwest::RequestBuilder {
client
.request(method, url)
.timeout(replica_request_timeout(body_len))
}
/// Helper to synchronously replicate a request to peer volume servers.
async fn do_replicated_request(
state: &VolumeServerState,
@@ -817,8 +828,7 @@ async fn do_replicated_request(
)?;
let client = state.http_client.clone();
let body_len = body.as_ref().map_or(0, |b| b.len());
let mut req_builder = replica_request(&client, method.clone(), &url, body_len);
let mut req_builder = client.request(method.clone(), &url);
// Forward relevant headers
if let Some(ct) = headers.get(axum::http::header::CONTENT_TYPE) {
@@ -2008,9 +2018,8 @@ async fn range_from_source_response(
) -> Response {
let range_str = range_str.to_string();
let tracking = track_download.then(|| state.clone());
let chunk_size = streaming_chunk_size(state.read_buffer_size_bytes, info.data_size as usize);
tokio::task::spawn_blocking(move || {
handle_range_request_from_source(&range_str, info, response_headers, tracking, chunk_size)
handle_range_request_from_source(&range_str, info, response_headers, tracking)
})
.await
.unwrap_or_else(|e| {
@@ -2354,7 +2363,6 @@ fn handle_range_request_from_source(
info: crate::storage::volume::NeedleStreamInfo,
mut headers: HeaderMap,
state: Option<Arc<VolumeServerState>>,
chunk_size: usize,
) -> Response {
let total = info.data_size as i64;
let ranges = match parse_range_header(range_str, total) {
@@ -2378,57 +2386,21 @@ fn handle_range_request_from_source(
return (StatusCode::OK, headers).into_response();
}
let block_crcs = if ranges.iter().any(|r| r.start != 0 || r.length != total) {
match info.verify_checksum(chunk_size) {
Ok(crcs) => Some(crcs),
Err(err) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
format!("range read error: {}", err),
)
.into_response();
}
}
} else {
None
};
let read_slice = |start: i64, length: i64| -> Result<Vec<u8>, std::io::Error> {
if length <= 0 {
return Ok(Vec::new());
}
let read = match &block_crcs {
Some(crcs) if length != total => {
info.read_checked_range(crcs, start as u64, length as u64)
}
_ => {
let mut buf = vec![0u8; length as usize];
info.source
.read_exact_at(&mut buf, info.data_file_offset + start as u64)
.map(|()| buf)
}
};
match read {
Ok(buf) if length == total && !info.checksum_matches(&buf) => {
metrics::HANDLER_COUNTER
.with_label_values(&[metrics::ERROR_CRC])
.inc();
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"needle data checksum mismatch for needle {}",
info.needle_id
),
))
}
let mut buf = vec![0u8; length as usize];
match info
.source
.read_exact_at(&mut buf, info.data_file_offset + start as u64)
{
// A finished range read clears the streak a failed meta read
// counted, like readNeedleDataInto's terminal report.
Ok(buf) => {
Ok(()) => {
info.io_errors.check_read_write_error(None);
Ok(buf)
}
// A block that fails its CRC leaves the streak alone, as Go's.
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => Err(e),
Err(e) => {
info.io_errors.check_read_write_error(Some(&e));
Err(e)
@@ -3457,14 +3429,10 @@ async fn write_upload_needle(
Ok(vol) => vol,
Err(refused) => return Ok(Err(refused)),
};
let pending = vol.track_pending_write(&n);
if fsync {
vol.write_pending_needles(&mut [(n, true)], &[Some(pending)])
.pop()
.unwrap_or(Err(crate::storage::volume::VolumeError::NotFound))
.map(Ok)
vol.write_needle(&mut n, true, fsync).map(Ok)
} else {
vol.write_pending_needle_unsynced(&mut n, Some(&pending))
vol.write_needle_unsynced_or_refused(&mut n)
}
}
@@ -3657,29 +3625,15 @@ pub async fn delete_handler(
// Read needle first to validate cookie (matching Go behavior)
let original_cookie = cookie;
let is_replicate = serde_urlencoded::from_str::<Vec<(String, String)>>(&del_query)
.unwrap_or_default()
.into_iter()
.find(|(name, _)| name == "type")
.is_some_and(|(_, value)| value == "replicate");
{
let vol = {
let store = state.store.read().unwrap();
store.find_volume(vid).map(|(_, vol)| vol)
};
let mut found = vol
.as_ref()
match vol
.ok_or(crate::storage::volume::VolumeError::NotFound)
.and_then(|vol| vol.read_needle_with_option(&mut n, &mut delete_read_option()));
if found.is_err()
&& is_replicate
&& let Some(vol) = &vol
.and_then(|vol| vol.read_needle_with_option(&mut n, &mut delete_read_option()))
{
// the write this delete undoes can still be queued here
vol.cancel_pending_writes(needle_id, original_cookie);
found = vol.read_needle_with_option(&mut n, &mut delete_read_option());
}
match found {
Ok(_) => {}
Err(_) => {
let result = DeleteResult { size: 0 };
@@ -3767,6 +3721,7 @@ pub async fn delete_handler(
}
};
let is_replicate = del_query.split('&').any(|p| p == "type=replicate");
if !is_replicate && delete_result.is_ok() {
let needs_replication = {
let store = state.store.read().unwrap();
@@ -5041,127 +4996,6 @@ fn parse_content_disposition_filename(value: &str) -> Option<String> {
mod tests {
use super::*;
/// A replica that reads the forward and never answers. Each request's
/// first line is sent on the returned channel.
async fn spawn_silent_replica() -> (
std::net::SocketAddr,
tokio::sync::mpsc::UnboundedReceiver<String>,
) {
use tokio::io::AsyncReadExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (received, receipts) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
loop {
let (mut socket, _) = listener.accept().await.unwrap();
let received = received.clone();
tokio::spawn(async move {
let mut request = vec![0u8; 4096];
let n = socket.read(&mut request).await.unwrap_or(0);
let text = String::from_utf8_lossy(&request[..n]).into_owned();
let _ = received.send(text.lines().next().unwrap_or("").to_string());
std::future::pending::<()>().await;
});
}
});
(addr, receipts)
}
/// The whole replicated write path, not only the request builder: the
/// replica receives the forward, never answers, and the write fails at
/// the bound for its body with an error naming that replica.
#[tokio::test]
async fn test_replicated_write_fails_at_the_bound_when_a_peer_never_answers() {
let tmp = tempfile::TempDir::new().unwrap();
let (peer, mut receipts) = spawn_silent_replica().await;
let state = remote_manifest_state(&tmp, spawn_lookup(peer).await);
let body = bytes::Bytes::from(vec![0u8; REPLICA_MIN_BYTES_PER_SEC as usize]);
let bound = replica_request_timeout(body.len());
let started = std::time::Instant::now();
let sent = do_replicated_request(
&state,
1,
axum::http::Method::POST,
"/1,01ab",
"",
&axum::http::HeaderMap::new(),
Some(body),
)
.await;
let took = started.elapsed();
let forwarded = receipts
.try_recv()
.expect("the replica never received the forward");
assert!(
forwarded.starts_with("POST /1,01ab?") && forwarded.contains("type=replicate"),
"{forwarded}"
);
let error = sent.expect_err("a silent replica cannot ack the write");
assert!(error.contains(&peer.to_string()), "{error}");
assert!(
took >= bound && took < bound + std::time::Duration::from_secs(5),
"{took:?}"
);
}
/// A peer that accepts the connection but never answers (a silent
/// partition after connect) must fail the forward at the bound, not hold
/// the write until TCP gives up.
#[tokio::test(start_paused = true)]
async fn test_replica_request_times_out_on_a_silent_peer() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let _held = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
std::future::pending::<()>().await;
drop(socket);
});
let client = reqwest::Client::new();
let url = format!("http://{}/3,01ab?type=replicate", addr);
let body = vec![0u8; 1 << 20];
let bound = replica_request_timeout(body.len());
let started = tokio::time::Instant::now();
let sent = tokio::time::timeout(
std::time::Duration::from_secs(600),
replica_request(&client, axum::http::Method::POST, &url, body.len())
.body(body)
.send(),
)
.await
.expect("replica forward must not outlive its bound");
let err = sent.expect_err("a silent peer cannot ack the replica");
assert!(err.is_timeout(), "{err}");
assert!(started.elapsed() >= bound && started.elapsed() < bound * 2);
}
/// A forward's bound grows with its body at REPLICA_MIN_BYTES_PER_SEC, so
/// a write near the file size limit is not cut off at the bodiless bound.
#[test]
fn test_replica_request_bound_grows_with_the_body() {
assert_eq!(replica_request_timeout(0), REPLICA_REQUEST_TIMEOUT);
let mib = REPLICA_MIN_BYTES_PER_SEC as usize;
assert_eq!(
replica_request_timeout(256 * mib),
REPLICA_REQUEST_TIMEOUT + std::time::Duration::from_secs(256)
);
assert_eq!(
replica_request_timeout(mib / 2),
REPLICA_REQUEST_TIMEOUT + std::time::Duration::from_millis(500)
);
let request = replica_request(
&reqwest::Client::new(),
axum::http::Method::POST,
"http://127.0.0.1:1/3,01ab?type=replicate",
64 * mib,
)
.build()
.unwrap();
assert_eq!(
request.timeout(),
Some(&(REPLICA_REQUEST_TIMEOUT + std::time::Duration::from_secs(64)))
);
}
/// The upload handler reads fsync off the decoded query fields rather than
/// matching the raw string, because Go's r.FormValue decodes and a raw
/// match would silently drop a percent-encoded value.
@@ -6434,171 +6268,6 @@ mod tests {
})
}
/// EC reconstructed-interval counter: one fresh volume per case, the needle (on
/// shard 0) EC-encoded under a known generation, the `missing` shards
/// unmounted and the shards in `corrupt` overwritten where the needle lies.
/// Returns the read's bytes and the marker lines logged at debug.
async fn read_ec_reconstructed(
vid: u32,
missing: &[crate::storage::erasure_coding::ec_shard::ShardId],
corrupt: &[crate::storage::erasure_coding::ec_shard::ShardId],
) -> (Option<Vec<u8>>, Vec<String>) {
use crate::storage::erasure_coding::ec_encoder::write_ec_files;
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::volume::{VifEcShardConfig, VifVolumeInfo, Volume, VolumeSpec};
use std::io::{Seek, SeekFrom, Write};
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let dir = tmp.path().to_str().unwrap();
let v = Volume::new(
dir,
dir,
VolumeId(vid),
NeedleMapKind::InMemory,
&VolumeSpec::default(),
)
.unwrap();
let mut n = Needle {
id: NeedleId(7),
cookie: Cookie(TEST_COOKIE),
data: b"ec degraded read".to_vec(),
data_size: 16,
..Needle::default()
};
v.write_needle(&mut n, true, false).unwrap();
v.sync_to_disk().unwrap();
v.close();
let block_size = write_ec_files(dir, dir, "", VolumeId(vid), 10, 4).unwrap();
let vif = format!("{dir}/{vid}.vif");
let mut info: VifVolumeInfo =
serde_json::from_str(&std::fs::read_to_string(&vif).unwrap()).unwrap();
info.ec_shard_config = Some(VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
encode_ts_ns: EC_GENERATION,
block_size,
});
crate::storage::store::save_vif_volume_info(&vif, &info).unwrap();
for shard in corrupt {
let mut f = std::fs::OpenOptions::new()
.write(true)
.open(format!("{dir}/{vid}.ec{shard:02}"))
.unwrap();
f.seek(SeekFrom::Start(0)).unwrap();
f.write_all(&[0xA5; 256]).unwrap();
}
let mounted: Vec<_> = (0..14).filter(|s| !missing.contains(s)).collect();
state
.store
.write()
.unwrap()
.mount_ec_shards(VolumeId(vid), "", &mounted)
.unwrap();
let out = Captured::default();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.with_writer(out.clone())
.finish();
let guard = tracing::subscriber::set_default(subscriber);
// Another test may have reached the marker's callsite first, with no
// subscriber, and cached it as never enabled.
tracing::callsite::rebuild_interest_cache();
let read = crate::server::store_ec::read_ec_shard_needle_or_miss(
&state,
VolumeId(vid),
NeedleId(7),
)
.await;
drop(guard);
let text = String::from_utf8(out.0.lock().unwrap().clone()).unwrap();
let lines = text
.lines()
.filter(|l| l.contains("ec reconstructed interval:"))
.map(|l| l.trim_end().to_string())
.collect();
(read.ok().and_then(Result::ok).map(|n| n.data), lines)
}
const EC_GENERATION: i64 = 1_700_000_000_123_456_789;
#[derive(Clone, Default)]
struct Captured(Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for Captured {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
type Writer = Captured;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
/// What the counter and line mean, case by case. A direct read logs nothing;
/// a read that rebuilds shard 0 logs and counts one success; one with 5
/// shards left fails and logs one failure; a corrupt interval read directly
/// goes to the repair path and isn't marked. `success` is not needle
/// validation: rebuilt from corrupt parity, the interval logs success while
/// the read fails.
#[tokio::test]
async fn test_ec_reconstructed_interval() {
use crate::metrics::EC_RECONSTRUCTED_INTERVAL_COUNTER as C;
let prefix = |vid: u32| {
format!(
"ec reconstructed interval: volume={vid} generation={EC_GENERATION} needle=7 shard=0 "
)
};
let data = Some(b"ec degraded read".to_vec());
assert_eq!(
read_ec_reconstructed(61, &[], &[]).await,
(data.clone(), vec![])
);
let success = C.with_label_values(&["success"]).get();
let (read, lines) = read_ec_reconstructed(62, &[0], &[]).await;
assert_eq!(read, data);
assert!(
matches!(&lines[..], [l] if l.ends_with(&(prefix(62) + "result=success error=<nil>"))),
"{lines:?}"
);
assert!(C.with_label_values(&["success"]).get() > success);
let failure = C.with_label_values(&["failure"]).get();
let (read, lines) = read_ec_reconstructed(63, &[0, 6, 7, 8, 9, 10, 11, 12, 13], &[]).await;
assert_eq!(read, None);
assert!(
matches!(&lines[..], [l] if l.contains(&(prefix(63) + "result=failure error=")) && !l.ends_with("error=")),
"{lines:?}"
);
assert!(C.with_label_values(&["failure"]).get() > failure);
let (read, lines) = read_ec_reconstructed(64, &[], &[0, 10, 11, 12, 13]).await;
assert_eq!(
(read, lines),
(None, vec![]),
"an unrepairable corrupt read was marked"
);
let success = C.with_label_values(&["success"]).get();
let (read, lines) = read_ec_reconstructed(65, &[0], &[10, 11, 12, 13]).await;
assert_eq!(read, None, "a read rebuilt from corrupt parity was served");
assert!(
matches!(&lines[..], [l] if l.ends_with(&(prefix(65) + "result=success error=<nil>"))),
"{lines:?}"
);
assert!(C.with_label_values(&["success"]).get() > success);
}
/// Write `data` as a chunk manifest on a fresh EC volume 2. Chunks stay on volume 1.
fn put_ec_manifest(
state: &VolumeServerState,
@@ -7051,145 +6720,13 @@ mod tests {
io_unavailable: Arc::default(),
io_errors: io_errors.clone(),
needle_id: NeedleId(1),
checksum: CRC::new(&data).0,
append_at_ns: 0,
load_generation: u64::MAX,
checksum: 0,
};
// The checksum pass leaves the streak to the range read.
info.verify_checksum(64).unwrap();
assert_eq!(io_errors.get_io_error_state().1, 2);
let resp =
handle_range_request_from_source("bytes=10-19", info, HeaderMap::new(), None, 64);
let resp = handle_range_request_from_source("bytes=10-19", info, HeaderMap::new(), None);
assert_eq!(resp.status(), StatusCode::PARTIAL_CONTENT);
assert_eq!(io_errors.get_io_error_state().1, 0);
}
/// A range carries no checksum of its own, so the first ranged read of a
/// needle checks the whole needle's CRC and sends none of the range on a
/// mismatch; the reader can then fall back to another replica. A verified
/// needle is checked again once the volume reloads.
#[tokio::test]
async fn test_range_read_checks_the_needle_checksum() {
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
let payload =
|seed: u32| -> Vec<u8> { (0..3000u32).map(|i| ((i * 7 + seed) % 251) as u8).collect() };
let damage = |data: &[u8]| {
let dat = tmp.path().join("1.dat");
let mut bytes = std::fs::read(&dat).unwrap();
let at = bytes.windows(data.len()).position(|w| w == data).unwrap();
bytes[at + 10] ^= 0xff;
std::fs::write(&dat, bytes).unwrap();
};
let intact = payload(1);
let path = put_test_needle(&state, 0x6e7a_0c01, &intact);
let (status, _, body) =
send_read(&state, Method::GET, &path, Some(b"bytes=1000-1499")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(body, &intact[1000..1500]);
// Damage a byte outside the range: the range itself is intact, but
// the needle is not, so this replica must not serve it.
let damaged = payload(2);
let path = put_test_needle(&state, 0x6e7a_0c02, &damaged);
damage(&damaged);
for range in [&b"bytes=1000-1499"[..], b"bytes=0-", b"bytes=0-1,1000-1001"] {
let (status, _, body) = send_read(&state, Method::GET, &path, Some(range)).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{range:?}");
assert!(
!body.windows(2).any(|w| w == &damaged[1000..1002]),
"{range:?}"
);
}
// Concurrent first ranges of a needle all see the outcome of the check.
for (seed, damage_it) in [(3, false), (4, true)] {
let data = payload(seed);
let path = put_test_needle(&state, 0x6e7a_0c00 + seed as u64, &data);
if damage_it {
damage(&data);
}
let reads = (0..8).map(|_| send_read(&state, Method::GET, &path, Some(b"bytes=10-19")));
for (status, _, _) in futures::future::join_all(reads).await {
assert_eq!(status == StatusCode::PARTIAL_CONTENT, !damage_it, "{seed}");
}
}
// A verified needle is checked again after a reload, as a compaction
// commit does; until then later ranges skip the check.
let data = payload(5);
let path = put_test_needle(&state, 0x6e7a_0c05, &data);
let (status, _, _) = send_read(&state, Method::GET, &path, Some(b"bytes=10-19")).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
let (_, v) = state
.store
.read()
.unwrap()
.find_volume(VolumeId(1))
.unwrap();
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
damage(&data);
let (status, _, _) = send_read(&state, Method::GET, &path, Some(b"bytes=10-19")).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
// Damage that appears after a needle passed its check is caught by
// the block it falls in, while ranges over intact blocks still read.
let block = 64 * 1024;
let data: Vec<u8> = (0..5 * block - 100)
.map(|i| (i * 7 + i / 251) as u8)
.collect();
let path = put_test_needle(&state, 0x6e7a_0c06, &data);
let range = |from: usize, to: usize| format!("bytes={}-{}", from, to - 1).into_bytes();
let damaged_ranges = [
(3 * block + 10, 3 * block + 110),
(block - 50, 4 * block - 50),
];
for (from, to) in damaged_ranges {
let (status, _, body) =
send_read(&state, Method::GET, &path, Some(&range(from, to))).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
assert_eq!(body, &data[from..to]);
}
let dat = tmp.path().join("1.dat");
let mut bytes = std::fs::read(&dat).unwrap();
let at = bytes.windows(64).position(|w| w == &data[..64]).unwrap();
bytes[at + 3 * block + 500] ^= 0xff;
std::fs::write(&dat, bytes).unwrap();
for (from, to) in damaged_ranges {
let (status, _, _) =
send_read(&state, Method::GET, &path, Some(&range(from, to))).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{from}-{to}");
}
for (from, to) in [
(10, 110),
(2 * block + 1, 3 * block),
(4 * block + 5, data.len()),
] {
let (status, _, body) =
send_read(&state, Method::GET, &path, Some(&range(from, to))).await;
assert_eq!(status, StatusCode::PARTIAL_CONTENT, "{from}-{to}");
assert_eq!(body, &data[from..to]);
}
}
#[test]
fn test_range_check_block_size() {
use crate::storage::volume::range_check_block_size;
let block = 64 * 1024;
let mib = 1024 * 1024;
for (size, want) in [
(0, block),
(64 * block, block),
(64 * block + 1, 2 * block),
(64 * mib, mib),
(1 << 34, mib),
] {
assert_eq!(range_check_block_size(size), want, "{size}");
}
}
/// Range is read as Go reads it: a byte its parseRange cannot parse is a
/// 416, Unicode whitespace around a range is trimmed, an empty value is no
/// range, and HEAD ignores it.
@@ -8580,13 +8117,12 @@ mod tests {
.delete_volume_needle(VolumeId(1), &mut filler)
.unwrap();
let data_offset = || {
let mut plan = crate::storage::store::Store::needle_read_plan(
&state.store,
VolumeId(1),
NeedleId(ID),
false,
)
.unwrap();
let mut plan = state
.store
.read()
.unwrap()
.needle_read_plan(VolumeId(1), NeedleId(ID), false)
.unwrap();
let mut n = Needle::default();
plan.read_meta(&mut n).unwrap();
plan.into_stream_info(&n).data_file_offset
@@ -9237,98 +8773,6 @@ mod tests {
}
}
/// A write queued behind another write's fsync is not indexed yet, so a
/// replicate delete of it finds nothing. The delete cancels the write, so
/// it is taken back when it lands instead of reviving the needle on this
/// copy alone, even when its handler was dropped while it waited in the
/// durable queue. A plain delete that finds nothing is not sent on to the
/// replicas, so it leaves the write alone.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn test_replicate_delete_cancels_a_queued_write() {
use crate::server::write_queue::{SyncBatchOption, WriteQueue};
use crate::storage::volume::VolumeError;
use std::time::{Duration, Instant};
for (id, fsync, query, abandon) in [
(0x6e7a_0c01u64, false, "?type=replicate", false),
(0x6e7a_0c02, true, "?type=replicate", false),
(0x6e7a_0c03, true, "?type=replicate", true),
(0x6e7a_0c04, false, "", false),
(0x6e7a_0c05, false, "?%74ype=replicat%65", false),
] {
let replicate = !query.is_empty();
let tmp = tempfile::TempDir::new().unwrap();
let state = volume_test_state(&tmp);
assert!(
state
.write_queue
.set(WriteQueue::new(
state.clone(),
128,
SyncBatchOption::default()
))
.is_ok()
);
let vol = state
.store
.read()
.unwrap()
.find_volume(VolumeId(1))
.unwrap()
.1;
let held = vol.sync_lock_for_test();
let mut n = Needle {
id: NeedleId(id),
cookie: Cookie(TEST_COOKIE),
data: b"late write".to_vec(),
data_size: 10,
..Needle::default()
};
n.checksum = CRC::new(&n.data);
let write = tokio::spawn({
let state = state.clone();
async move { write_upload_needle(&state, VolumeId(1), n, fsync).await }
});
let deadline = Instant::now() + Duration::from_secs(10);
while vol.pending_writes_for_test(NeedleId(id)) == 0 {
assert!(Instant::now() < deadline, "the write never registered");
tokio::time::sleep(Duration::from_millis(1)).await;
}
let path = format!("/1,{:x}{:08x}{}", id, TEST_COOKIE, query);
assert_eq!(send_delete(&state, &path).await, StatusCode::NOT_FOUND);
if abandon {
write.abort();
drop(held);
while vol.pending_writes_for_test(NeedleId(id)) > 0 {
assert!(Instant::now() < deadline, "the queued write never settled");
tokio::time::sleep(Duration::from_millis(1)).await;
}
} else {
drop(held);
let written = write.await.unwrap();
if replicate {
assert!(matches!(written, Err(VolumeError::Deleted)), "{id:x}");
} else {
assert!(matches!(written, Ok(Ok(_))), "{id:x}");
}
assert_eq!(vol.pending_writes_for_test(NeedleId(id)), 0);
}
let read = vol.read_needle(&mut Needle {
id: NeedleId(id),
..Needle::default()
});
if replicate {
assert!(read.is_err(), "{id:x}: the cancelled write is live");
} else {
assert!(read.is_ok(), "{id:x}: {read:?}");
}
}
}
/// Issue #801: an fsync upload takes the per-volume worker so its sync is
/// shared across the batch (Go's `writeNeedle2` split); a non-fsync write,
/// or an fsync write landing while the server is stopping, takes the
+74 -342
View File
@@ -64,11 +64,10 @@ pub async fn run_heartbeat_with_state(
let pulse = Duration::from_secs(config.pulse_seconds.max(1));
let mut new_leader: Option<String> = None;
let mut duplicate_retry_count: u32 = 0;
// When a stream a leader had answered last ended, `None` before first
// registration. Until then, and for a pulse after each loss, the retry
// loop reconnects promptly instead of pacing a full pulse. Mirrors Go's
// `confirmedLeaderOnce` and `leaderLostAt`.
let mut leader_lost_at: Option<tokio::time::Instant> = None;
// Whether a heartbeat stream was ever answered by a leader; before first
// registration the retry loop reconnects promptly instead of pacing a
// full pulse. Mirrors Go's `confirmedLeaderOnce`.
let mut confirmed_leader_once = false;
loop {
let mut tried_hints: HashSet<String> = HashSet::new();
@@ -111,7 +110,7 @@ pub async fn run_heartbeat_with_state(
&leader,
pulse,
&mut shutdown_rx,
&mut leader_lost_at,
&mut confirmed_leader_once,
&mut duplicate_retry_count,
)
.await;
@@ -135,7 +134,7 @@ pub async fn run_heartbeat_with_state(
master_addr,
pulse,
&mut shutdown_rx,
&mut leader_lost_at,
&mut confirmed_leader_once,
&mut duplicate_retry_count,
)
.await
@@ -169,7 +168,7 @@ async fn heartbeat_once(
target_addr: &str,
pulse: Duration,
shutdown_rx: &mut broadcast::Receiver<()>,
leader_lost_at: &mut Option<tokio::time::Instant>,
confirmed_leader_once: &mut bool,
duplicate_retry_count: &mut u32,
) -> Option<String> {
let grpc_addr = to_grpc_address(target_addr);
@@ -182,22 +181,17 @@ async fn heartbeat_once(
SleepDuplicate(Duration),
SleepPulse,
}
let mut confirmed_leader = false;
let result = do_heartbeat(
let action = match do_heartbeat(
config,
state,
&grpc_addr,
target_addr,
pulse,
shutdown_rx,
&mut confirmed_leader,
confirmed_leader_once,
)
.await
.map_err(|e| e.to_string());
if confirmed_leader {
*leader_lost_at = Some(tokio::time::Instant::now());
}
let action = match result {
{
Ok(Some(leader)) => {
info!("Master leader changed to {}", leader);
return Some(leader);
@@ -206,7 +200,10 @@ async fn heartbeat_once(
*duplicate_retry_count = 0;
return None;
}
Err(err_msg) => {
Err(e) => {
let err_msg = e.to_string();
// Drop `e` (non-Send) before any .await
drop(e);
warn!("Heartbeat to {} error: {}", grpc_addr, err_msg);
if err_msg.contains(DUPLICATE_UUID_RETRY_MESSAGE) {
@@ -239,17 +236,16 @@ async fn heartbeat_once(
// The lookup spends part of the retry delay rather than adding
// to it.
let retry_at = tokio::time::Instant::now() + pulse;
let unregistered_or_just_lost = leader_lost_at.is_none_or(|at| at.elapsed() < pulse);
let leader = refresh_leader_from_peers(config, state, target_addr, pulse).await;
let mut wait = retry_at.saturating_duration_since(tokio::time::Instant::now());
if wait > Duration::from_secs(1)
&& (!state.current_master().await.is_empty() || unregistered_or_just_lost)
&& (!state.current_master().await.is_empty() || !*confirmed_leader_once)
{
// A leader just named by the refresh usually accepts the
// next stream right away, an unregistered server has
// nothing else to do, and a master that just dropped the
// stream is usually back within a second, so reconnect
// promptly. Otherwise keep the pulse backoff.
// next stream right away, and an unregistered server has
// nothing else to do, so reconnect promptly. Once the
// server was registered and no leader is known, keep the
// pulse backoff.
wait = Duration::from_secs(1);
}
tokio::time::sleep(wait).await;
@@ -469,9 +465,6 @@ fn collect_ec_shard_delta_messages(
if quarantined {
continue;
}
// Same numbers the full EC heartbeat carries, read off the active
// generation's index and journal; one call covers every shard.
let (file_count, delete_count) = ec_vol.file_and_delete_count();
for shard in ec_vol.shards.iter().flatten() {
messages.insert(
(
@@ -488,8 +481,6 @@ fn collect_ec_shard_delta_messages(
disk_type: ec_vol.disk_type.to_string(),
expire_at_sec: ec_vol.expire_at_sec,
disk_id: disk_id as u32,
file_count,
delete_count,
encode_ts_ns: ec_vol.encode_ts_ns,
..Default::default()
},
@@ -512,17 +503,7 @@ fn diff_ec_shard_delta_messages(
let mut deleted_ec_shards = Vec::new();
for (key, message) in current {
// Counts move with every delete; the full EC heartbeat carries those,
// so only a change to the shard itself is news here.
let unchanged = previous.get(key).is_some_and(|prev| {
*message
== master_pb::VolumeEcShardInformationMessage {
file_count: message.file_count,
delete_count: message.delete_count,
..prev.clone()
}
});
if !unchanged {
if previous.get(key) != Some(message) {
new_ec_shards.push(message.clone());
}
}
@@ -568,7 +549,7 @@ async fn do_heartbeat(
current_master: &str,
pulse: Duration,
shutdown_rx: &mut broadcast::Receiver<()>,
confirmed_leader: &mut bool,
confirmed_leader_once: &mut bool,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let channel = connect_channel(
grpc_addr,
@@ -615,6 +596,7 @@ async fn do_heartbeat(
volume_tick.tick().await;
ec_tick.tick().await;
let mut confirmed_leader = false;
loop {
tokio::select! {
resp = response_stream.message() => {
@@ -632,11 +614,12 @@ async fn do_heartbeat(
publish_current_master(state, &hb_resp.leader).await;
return Ok(Some(hb_resp.leader));
}
} else if !*confirmed_leader {
} else if !confirmed_leader {
// The leader answers every new stream without
// naming a leader, so this peer is the one lookups
// go to.
*confirmed_leader = true;
confirmed_leader = true;
*confirmed_leader_once = true;
publish_current_master(state, current_master).await;
}
if !hb_resp.duplicated_uuids.is_empty() {
@@ -1068,17 +1051,15 @@ fn collect_heartbeat_with_snapshot(
master_pb::Heartbeat,
Vec<master_pb::VolumeInformationMessage>,
) {
let (_, expired_ec, mut deleted_ec_shards) =
state.store.read().unwrap().find_expired_ec_volumes();
let (_, expired_ec) = state.store.read().unwrap().find_expired_ec_volumes();
let mut deleted_ec_shards = Vec::new();
if !expired_ec.is_empty() {
deleted_ec_shards.extend(
state
.store
.write()
.unwrap()
.remove_expired_ec_volumes(expired_ec)
.0,
);
deleted_ec_shards = state
.store
.write()
.unwrap()
.remove_expired_ec_volumes(expired_ec)
.0;
}
#[cfg(test)]
{
@@ -1384,6 +1365,7 @@ fn build_heartbeat_with_ec_status(
}
let (remote_storage_name, remote_storage_key) = vol.remote_storage_name_key();
let (read_only, read_only_can_delete) = vol.reported_read_only();
let volume_message = master_pb::VolumeInformationMessage {
id: vol.id.0,
size: volume_size,
@@ -1391,8 +1373,8 @@ fn build_heartbeat_with_ec_status(
file_count: vol.file_count() as u64,
delete_count: vol.deleted_count() as u64,
deleted_byte_count: vol.deleted_size(),
read_only: vol.is_read_only(),
read_only_can_delete: vol.is_no_write_can_delete(),
read_only,
read_only_can_delete,
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(),
@@ -1838,6 +1820,43 @@ mod tests {
);
}
#[test]
fn test_build_heartbeat_low_disk_volume_reports_can_delete() {
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), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
store.locations[0]
.is_disk_space_low
.store(true, std::sync::atomic::Ordering::Relaxed);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(heartbeat.volumes[0].read_only_can_delete);
store
.find_volume(VolumeId(7))
.unwrap()
.1
.set_no_write_or_delete(true);
let heartbeat = build_heartbeat(&test_config(), &mut store);
assert!(heartbeat.volumes[0].read_only);
assert!(!heartbeat.volumes[0].read_only_can_delete);
}
#[test]
fn test_build_heartbeat_marks_empty_store_as_has_no_volumes() {
let temp_dir = tempfile::tempdir().unwrap();
@@ -2432,169 +2451,6 @@ mod tests {
assert!(volume.is_no_write_or_delete());
}
// A master that is down is redialed after about a second for a pulse after
// the stream to it was lost, since a restarting master is usually back by
// then, and at the pulse pace once the loss is older. Mirrors Go's
// TestHeartbeatOnceKeepsPulseBackoffOnceLossIsOld.
#[tokio::test]
async fn test_heartbeat_once_redials_promptly_only_for_a_pulse_after_a_loss() {
// Closing each connection fails every dial at once, where Windows takes
// about two seconds to refuse a closed port.
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
while let Ok((conn, _)) = listener.accept().await {
drop(conn);
}
});
let down = format!("127.0.0.1:{}.{}", port, port);
let pulse = Duration::from_secs(3);
let mut config = test_config();
config.master_addresses = vec![down.clone()];
config.pulse_seconds = pulse.as_secs();
let temp_dir = tempfile::tempdir().unwrap();
let state = test_state_with_store(reporting_store(temp_dir.path().to_str().unwrap(), 0));
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
for (lost_ago, prompt) in [(Duration::ZERO, true), (pulse, false)] {
let mut leader_lost_at = Some(tokio::time::Instant::now() - lost_ago);
let mut duplicate_retry_count = 0;
let started = tokio::time::Instant::now();
heartbeat_once(
&config,
&state,
&down,
pulse,
&mut shutdown_rx,
&mut leader_lost_at,
&mut duplicate_retry_count,
)
.await;
let elapsed = started.elapsed();
if prompt {
assert!(
elapsed >= Duration::from_millis(900) && elapsed < Duration::from_secs(2),
"redial right after a loss took {:?}",
elapsed
);
} else {
assert!(
elapsed >= Duration::from_millis(2500),
"redial a pulse after a loss took {:?}",
elapsed
);
}
}
}
/// A master that confirms each heartbeat stream and then ends it, the way
/// one killed right after registering this server looks. It answers
/// nothing else, so no peer names a leader.
#[derive(Clone)]
struct DroppingLeader;
impl tonic::server::NamedService for DroppingLeader {
const NAME: &'static str = "master_pb.Seaweed";
}
impl tonic::codegen::Service<tonic::codegen::http::Request<tonic::body::Body>> for DroppingLeader {
type Response = tonic::codegen::http::Response<tonic::body::Body>;
type Error = std::convert::Infallible;
type Future = tonic::codegen::BoxFuture<Self::Response, Self::Error>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&mut self, req: tonic::codegen::http::Request<tonic::body::Body>) -> Self::Future {
Box::pin(async move {
if req.uri().path() != "/master_pb.Seaweed/SendHeartbeat" {
return Ok(tonic::Status::unimplemented("").into_http());
}
let mut grpc = tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
Ok(grpc.streaming(ConfirmThenDrop, req).await)
})
}
}
struct ConfirmThenDrop;
impl tonic::server::StreamingService<master_pb::Heartbeat> for ConfirmThenDrop {
type Response = master_pb::HeartbeatResponse;
type ResponseStream = tokio_stream::Iter<
std::vec::IntoIter<Result<master_pb::HeartbeatResponse, tonic::Status>>,
>;
type Future =
tonic::codegen::BoxFuture<tonic::Response<Self::ResponseStream>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<tonic::Streaming<master_pb::Heartbeat>>,
) -> Self::Future {
Box::pin(async move {
let _ = request.into_inner().message().await;
Ok(tonic::Response::new(tokio_stream::iter(vec![
Ok(master_pb::HeartbeatResponse {
volume_size_limit: 1 << 30,
..Default::default()
}),
Err(tonic::Status::unavailable("master stopped")),
])))
})
}
}
// A server registered long ago whose master just dropped the stream
// redials after about a second, not a pulse. Mirrors Go's
// TestHeartbeatOnceRedialsPromptlyAfterLosingRegisteredStream.
#[tokio::test]
async fn test_heartbeat_once_redials_promptly_after_losing_a_registered_stream() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let master = format!("127.0.0.1:{}.{}", port, port);
tokio::spawn(
tonic::transport::Server::builder()
.add_service(DroppingLeader)
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),
);
let pulse = Duration::from_secs(3);
let mut config = test_config();
config.master_addresses = vec![master.clone()];
config.pulse_seconds = pulse.as_secs();
let temp_dir = tempfile::tempdir().unwrap();
let state = test_state_with_store(reporting_store(temp_dir.path().to_str().unwrap(), 0));
let (_shutdown_tx, mut shutdown_rx) = broadcast::channel(1);
let registered_long_ago = tokio::time::Instant::now() - 10 * pulse;
let mut leader_lost_at = Some(registered_long_ago);
let mut duplicate_retry_count = 0;
let started = tokio::time::Instant::now();
heartbeat_once(
&config,
&state,
&master,
pulse,
&mut shutdown_rx,
&mut leader_lost_at,
&mut duplicate_retry_count,
)
.await;
let elapsed = started.elapsed();
assert!(
leader_lost_at.is_some_and(|at| at >= started),
"the end of the confirmed stream was not recorded"
);
assert!(
elapsed >= Duration::from_millis(900) && elapsed < Duration::from_secs(2),
"redial after losing a registered stream took {:?}",
elapsed
);
}
// The pass only reads the store, so it must not shut out the readers that
// serve traffic while it stats every volume.
#[tokio::test]
@@ -3085,46 +2941,6 @@ mod tests {
assert_eq!(last_ec_shards.len(), 1);
}
// The volume heartbeat that quarantines an EC volume tells the master its
// shards are gone, once; neither the next delta nor the next heartbeat
// repeats it.
#[test]
fn test_ec_volume_quarantined_by_a_volume_heartbeat_is_reported_deleted_once() {
let temp_dir = tempfile::tempdir().unwrap();
let dir = temp_dir.path().to_str().unwrap();
let state = test_state_with_store(reporting_store(dir, 0));
mount_test_ec_shard(&state, dir, "ec_delta_kept", 96);
mount_test_ec_shard(&state, dir, "ec_delta_quarantined", 97);
let mut last_ec_shards = collect_ec_shard_delta_messages(&state.store.read().unwrap());
{
let store = state.store.read().unwrap();
let ec_vol = store.find_ec_volume(VolumeId(97)).unwrap();
let eio = crate::storage::volume::media_error_for_test();
for _ in 0..crate::storage::io_error::IO_ERROR_TOLERANCE {
ec_vol.check_read_write_error(Some(&eio));
}
}
let (heartbeat, new_ec_shards, deleted_ec_shards) =
ec_delta_after_volume_tick(&state, &mut last_ec_shards);
assert_eq!(
heartbeat
.deleted_ec_shards
.iter()
.map(|s| s.id)
.collect::<Vec<_>>(),
vec![97]
);
assert!(new_ec_shards.is_empty());
assert!(
deleted_ec_shards.is_empty(),
"a quarantined EC volume was reported deleted twice"
);
let (heartbeat, _, _) = ec_delta_after_volume_tick(&state, &mut last_ec_shards);
assert!(heartbeat.deleted_ec_shards.is_empty());
}
#[test]
fn test_expired_ec_volume_gone_before_removal_is_not_reported_deleted() {
let temp_dir = tempfile::tempdir().unwrap();
@@ -3153,7 +2969,7 @@ mod tests {
.expire_at_sec = 1;
}
let (ec_shards, mut expired, _) = store.find_expired_ec_volumes();
let (ec_shards, mut expired) = store.find_expired_ec_volumes();
expired.sort();
assert!(ec_shards.is_empty());
assert_eq!(expired, vec![(0, VolumeId(71)), (0, VolumeId(72))]);
@@ -3379,88 +3195,4 @@ mod tests {
assert_eq!(deleted_after_delete[0].ec_index_bits, 1);
assert_eq!(deleted_after_delete[0].shard_sizes, vec![0]);
}
#[test]
fn test_diff_ec_shard_delta_messages_ignores_count_changes() {
let key = (81, "ec_delta_case".to_string(), 0, 0);
let previous = HashMap::from([(
key.clone(),
master_pb::VolumeEcShardInformationMessage {
id: 81,
collection: "ec_delta_case".to_string(),
ec_index_bits: 1,
shard_sizes: vec![5],
file_count: 3,
..Default::default()
},
)]);
let mut current = previous.clone();
current.get_mut(&key).unwrap().file_count = 4;
current.get_mut(&key).unwrap().delete_count = 1;
let (new_ec_shards, deleted_ec_shards) = diff_ec_shard_delta_messages(&previous, &current);
assert!(new_ec_shards.is_empty());
assert!(deleted_ec_shards.is_empty());
current.get_mut(&key).unwrap().shard_sizes = vec![6];
let (new_ec_shards, _) = diff_ec_shard_delta_messages(&previous, &current);
assert_eq!(new_ec_shards.len(), 1);
assert_eq!(new_ec_shards[0].delete_count, 1);
}
/// Both EC emission paths report the counts the Go server's
/// `EcVolume.FileAndDeleteCount` defines: file_count is every entry in the
/// active .ecx (live and tombstoned alike), delete_count the needles this
/// holder deleted.
#[test]
fn test_ec_shard_messages_carry_file_and_delete_counts() {
use crate::storage::types::{NEEDLE_MAP_ENTRY_SIZE, Offset, Size, idx_entry_to_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();
std::fs::write(format!("{}/ec_counts_case_91.ec00", dir), b"shard").unwrap();
let mut ecx = Vec::new();
for (key, offset) in [(1u64, 8u32), (5, 200), (10, 500)] {
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_entry_to_bytes(
&mut entry,
NeedleId(key),
Offset::from_actual_offset(offset as i64),
Size(100),
);
ecx.extend_from_slice(&entry);
}
std::fs::write(format!("{}/ec_counts_case_91.ecx", dir), &ecx).unwrap();
store.locations[0]
.mount_ec_shards(VolumeId(91), "ec_counts_case", &[0], "")
.unwrap();
let ec_vol = store.locations[0].find_ec_volume_mut(VolumeId(91)).unwrap();
ec_vol.journal_delete(NeedleId(1)).unwrap();
let delta = collect_ec_shard_delta_messages(&store);
let message = delta
.get(&(91, "ec_counts_case".to_string(), 0, 0))
.expect("delta message for the mounted shard");
assert_eq!(message.file_count, 3);
assert_eq!(message.delete_count, 1);
let heartbeat = collect_ec_heartbeat(&test_config(), &store);
assert_eq!(heartbeat.ec_shards.len(), 1);
assert_eq!(heartbeat.ec_shards[0].file_count, 3);
assert_eq!(heartbeat.ec_shards[0].delete_count, 1);
}
}
+26 -626
View File
@@ -40,7 +40,7 @@ use tonic::Request;
use crate::pb::master_pb::{self, LookupEcVolumeRequest};
use crate::pb::volume_server_pb::{
CopyFileRequest, VolumeEcBlobDeleteRequest, VolumeEcShardReadRequest, VolumeEcShardReadResponse,
CopyFileRequest, VolumeEcBlobDeleteRequest, VolumeEcShardReadRequest,
};
use crate::server::grpc_client::{
GrpcDialOptions, connect_channel, master_client, parse_grpc_address, volume_server_client,
@@ -1035,7 +1035,7 @@ fn scrub_snapshot_under_lock(
version: ecv.version,
actual_size: get_actual_size(size, ecv.version) as usize,
size_for_parse: size,
intervals: read_local_intervals(ecv, &intervals, true),
intervals: read_local_intervals(ecv, &intervals),
encode_ts_ns: ecv.encode_ts_ns,
})
}
@@ -1052,29 +1052,20 @@ struct ScrubSnapshot {
}
/// Read any locally-held shard intervals, marking the rest `NeedRemote`. Shared
/// by the read-path `build_snapshot` and the scrub snapshot. Shards on a
/// quarantined disk count as not local unless `allow_quarantined` is set.
/// 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],
allow_quarantined: bool,
) -> Vec<IntervalResult> {
let skip_local = !allow_quarantined && ecv.get_io_error_state().2;
let mut interval_results = Vec::with_capacity(intervals.len());
for interval in intervals {
let (shard_id, shard_offset) = ecv.interval_to_shard_id_and_offset(interval);
let buf_size = interval.size as usize;
let local = ecv
.shards
.get(shard_id as usize)
.and_then(|s| s.as_ref())
.filter(|_| !skip_local);
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];
let read = shard.read_at(&mut buf, shard_offset as u64);
ecv.check_read_write_error(read.as_ref().err());
match read {
match shard.read_at(&mut buf, shard_offset as u64) {
Ok(n) if n == buf_size => interval_results.push(IntervalResult::Local(buf)),
_ => interval_results.push(IntervalResult::NeedRemote {
shard_id,
@@ -1110,7 +1101,7 @@ fn build_snapshot(
));
}
let actual = get_actual_size(size, ecv.version);
let interval_results = read_local_intervals(ecv, intervals, false);
let interval_results = read_local_intervals(ecv, intervals);
let metas = intervals
.iter()
.map(|iv| {
@@ -1365,82 +1356,7 @@ async fn fetch_one_interval(
// Reconstruct: fan-out reads to every other shard at the same
// (shard_offset, size). Mirrors `recoverOneRemoteEcShardInterval`.
let result =
recover_one_remote_ec_shard_interval(state, iv, map, &HashSet::from([iv.shard_id])).await;
note_ec_reconstructed_interval(iv, &result);
if result.is_err()
&& let Some(buf) = read_quarantined_local_interval(state, iv)
{
tracing::info!(
"read ec shard {}.{} from its quarantined disk: no healthy copy answered",
vid.0,
shard_id
);
return Ok((buf, false));
}
result
}
/// Last resort once peers and reconstruction failed: the interval from a local
/// shard skipped because its disk is quarantined. Mirrors the tail of Go's
/// `readOneEcShardInterval`.
fn read_quarantined_local_interval(
state: &Arc<VolumeServerState>,
iv: EcInterval,
) -> Option<Vec<u8>> {
let store = state.store.read().unwrap();
let ecv = store.find_ec_volume_with_shard(iv.vid, iv.shard_id)?;
if !ecv.get_io_error_state().2
|| (iv.expected_encode_ts_ns != 0 && ecv.encode_ts_ns != iv.expected_encode_ts_ns)
{
return None;
}
let shard = ecv.shards.get(iv.shard_id as usize)?.as_ref()?;
let mut buf = vec![0u8; iv.size];
let read = shard.read_at(&mut buf, iv.shard_offset as u64);
ecv.check_read_write_error(read.as_ref().err());
match read {
Ok(n) if n == iv.size => Some(buf),
result => {
tracing::info!(
"read quarantined ec shard {}.{} offset {}: {:?}",
iv.vid.0,
iv.shard_id,
iv.shard_offset,
result
);
None
}
}
}
/// Counts one interval that couldn't be read directly and was reconstructed,
/// and at debug logs it with the needle and the encode generation, which the
/// counter can't carry. `success` means the reconstruction produced data; the
/// needle is validated later. A holder's "deleted" answer with too few shards
/// rebuilt nothing, so it is a failure, as Go's reconstruct error makes it there.
fn note_ec_reconstructed_interval(iv: EcInterval, result: &io::Result<(Vec<u8>, bool)>) {
let outcome = match result {
Ok((buf, _)) if !buf.is_empty() => "success",
_ => "failure",
};
crate::metrics::EC_RECONSTRUCTED_INTERVAL_COUNTER
.with_label_values(&[outcome])
.inc();
// tracing evaluates these arguments only when debug is enabled.
tracing::debug!(
"ec reconstructed interval: volume={} generation={} needle={} shard={} result={} error={}",
iv.vid.0,
iv.expected_encode_ts_ns,
iv.needle_id,
iv.shard_id,
outcome,
match result {
Ok((buf, _)) if !buf.is_empty() => "<nil>".to_string(),
Ok(_) => "a holder reported the needle deleted".to_string(),
Err(e) => e.to_string(),
}
);
recover_one_remote_ec_shard_interval(state, iv, map, &HashSet::from([iv.shard_id])).await
}
async fn read_remote_ec_shard_interval(
@@ -1513,30 +1429,15 @@ async fn do_read_remote_ec_shard_interval(
vid.0, shard_id, source, e
))
})?;
collect_ec_shard_read(resp.into_inner(), source, iv).await
}
let mut stream = resp.into_inner();
/// Reads one `VolumeEcShardRead` reply into the interval's bytes, or the
/// holder's deleted answer, which stands even if the stream fails after it.
async fn collect_ec_shard_read(
mut stream: tonic::Streaming<VolumeEcShardReadResponse>,
source: &str,
iv: EcInterval,
) -> io::Result<(Vec<u8>, bool)> {
let EcInterval {
vid,
shard_id,
size,
expected_encode_ts_ns,
..
} = iv;
let mut out = Vec::with_capacity(size);
let mut is_deleted = false;
// A deleted answer stands even if the stream fails after it.
while let Some(msg) = match stream.message().await {
Err(_) if is_deleted => None,
msg => msg.map_err(|e| io::Error::other(format!("recv: {}", e)))?,
} {
while let Some(msg) = stream
.message()
.await
.map_err(|e| io::Error::other(format!("recv: {}", e)))?
{
// Validate the served shard's identity client-side, so the guard holds even
// against a pre-upgrade server that ignored the request field (returns 0).
// A mismatch fails the read; the caller recovers from parity.
@@ -1615,7 +1516,6 @@ async fn gather_ec_shard_intervals(
// shard_locations cache or a failed master lookup, local
// survivors still contribute.
let mut available = 0usize;
let mut quarantined = Vec::new();
{
let store = state.store.read().unwrap();
for (sid, slot) in bufs.iter_mut().enumerate() {
@@ -1641,15 +1541,13 @@ async fn gather_ec_shard_intervals(
}
_ => continue,
};
if owner.get_io_error_state().2 {
quarantined.push(sid_shard);
continue;
}
if let Some(Some(shard)) = owner.shards.get(sid) {
let mut buf = vec![0u8; size];
let read = shard.read_at(&mut buf, shard_offset as u64);
owner.check_read_write_error(read.as_ref().err());
if read.map(|n| n == size).unwrap_or(false) {
if shard
.read_at(&mut buf, shard_offset as u64)
.map(|n| n == size)
.unwrap_or(false)
{
*slot = Some(buf);
available += 1;
}
@@ -1725,31 +1623,6 @@ async fn gather_ec_shard_intervals(
}
}
// Healthy sources fell short: fill in from the quarantined local disk.
for sid in quarantined {
if any_deleted || available >= want {
break;
}
if bufs[sid as usize].is_some() {
continue;
}
if let Some(buf) = read_quarantined_local_interval(
state,
EcInterval {
shard_id: sid,
..iv
},
) {
tracing::debug!(
"recover: read ec shard {}.{} from its quarantined disk",
vid.0,
sid
);
bufs[sid as usize] = Some(buf);
available += 1;
}
}
(bufs, any_deleted)
}
@@ -1894,11 +1767,10 @@ async fn try_ec_shard_needle_candidate(
/// Repair a needle whose reassembled bytes failed to parse — Go's
/// `rebuildEcShardNeedle`. Every interval's source shard is a suspect: rebuild
/// all suspect ranges at once while parity covers the suspect set, then search
/// the sets of shards that may be corrupt, then rebuild one suspect at a time,
/// and let a successful parse arbitrate which copy was corrupt. A holder's
/// deleted report stops the search: the needle is gone whatever the local index
/// says.
/// all suspect ranges at once while parity covers the suspect set, or one
/// suspect at a time when the needle spans more shards than that, and let a
/// successful parse arbitrate which copy was corrupt. A holder's deleted report
/// stops the search: the needle is gone whatever the local index says.
async fn rebuild_ec_shard_needle(
state: &Arc<VolumeServerState>,
metas: &[EcInterval],
@@ -1936,19 +1808,9 @@ async fn rebuild_ec_shard_needle(
return (Some(candidate), false);
}
}
}
let (candidate, is_deleted) = rebuild_ec_needle_from_corrupt_sets(
state, metas, map, corrupted, &suspects, offset, size, version, needle_id,
)
.await;
if is_deleted {
return (None, true);
}
if let Some(candidate) = candidate {
return (Some(candidate), false);
}
if suspects.len() == 1 {
return (None, false);
if suspects.len() == 1 {
return (None, false);
}
}
for shard_id in suspects {
let (candidate, is_deleted) = try_ec_shard_needle_candidate(
@@ -2092,239 +1954,6 @@ async fn rebuild_ec_needle_from_dropped_inputs(
(None, false)
}
/// Bounds on one needle's corrupt-set search, as Go's `ecRebuildMaxSets` and
/// `ecRebuildMaxBytes`: sets enumerated, and needle bytes rebuilt and parsed
/// past the single-shard sets. 10+4 has 1470 sets of at most four shards.
const EC_REBUILD_MAX_SETS: usize = 4096;
const EC_REBUILD_MAX_BYTES: usize = 1 << 30;
/// Handle a rebuild the retries above could not repair: more shards than one
/// can be corrupt over the same ranges and get read as reconstruction inputs.
/// Each interval is gathered once from every other shard that answers, then
/// `search_ec_corrupt_sets` tries the candidate corrupt sets. `None` when that
/// gather would outgrow the recovery budget. Mirrors Go's
/// `rebuildEcNeedleFromCorruptSets`.
async fn rebuild_ec_needle_from_corrupt_sets(
state: &Arc<VolumeServerState>,
metas: &[EcInterval],
map: EcShardMap<'_>,
corrupted: &[u8],
suspects: &HashSet<ShardId>,
offset: i64,
size: Size,
version: Version,
needle_id: NeedleId,
) -> (Option<Vec<u8>>, bool) {
let EcShardMap {
data_shards,
parity_shards,
..
} = map;
let total_shards = data_shards + parity_shards;
let total_size: usize = metas.iter().map(|iv| iv.size).sum();
if total_size * (total_shards - 1) > EC_RECOVER_BUDGET {
return (None, false);
}
let Ok(permit) = EC_RECOVER_SEM
.acquire_many((total_size * total_shards).min(EC_RECOVER_BUDGET) as u32)
.await
else {
return (None, false);
};
let mut gathers: Vec<Vec<Option<Vec<u8>>>> = Vec::with_capacity(metas.len());
for iv in metas {
let (bufs, is_deleted) =
gather_ec_shard_intervals(state, *iv, map, &HashSet::from([iv.shard_id]), total_shards)
.await;
if is_deleted {
return (None, true);
}
gathers.push(bufs);
}
// The search can run hundreds of decodes, so keep it off the runtime. The
// permit goes with it: a dropped read does not stop a blocking task.
let (metas_owned, corrupted, suspects) = (metas.to_vec(), corrupted.to_vec(), suspects.clone());
let search = tokio::task::spawn_blocking(move || {
let _permit = permit;
let rs = ReedSolomon::new(data_shards, parity_shards).ok()?;
search_ec_corrupt_sets(
&mut gathers,
&metas_owned,
&rs,
&corrupted,
&suspects,
|candidate| {
let mut check = Needle {
id: needle_id,
..Needle::default()
};
check.read_bytes(candidate, offset, size, version).is_ok() && check.id == needle_id
},
)
});
let Ok(Some((candidate, convicted))) = search.await else {
return (None, false);
};
if let Some(first) = metas.first() {
for shard_id in convicted {
forget_shard_location(state, first.vid, shard_id);
}
}
(Some(candidate), false)
}
/// Try each set of up to `parity_shards` shards holding a suspect as the
/// corrupt set, smallest first: suspect ranges inside it are rebuilt from the
/// shards outside it, the rest keep the bytes read, and `parses` arbitrates. A
/// set whose decodes read the same inputs as one already tried is skipped.
/// Returns the candidate with the shards it convicts: every differing range,
/// and every other shard the set kept out of the decodes.
fn search_ec_corrupt_sets(
gathers: &mut [Vec<Option<Vec<u8>>>],
metas: &[EcInterval],
rs: &ReedSolomon,
corrupted: &[u8],
suspects: &HashSet<ShardId>,
parses: impl Fn(&[u8]) -> bool,
) -> Option<(Vec<u8>, Vec<ShardId>)> {
let data_shards = rs.data_shard_count();
let total_shards = rs.total_shard_count();
let mut candidate = corrupted.to_vec();
let mut scratch: Vec<Vec<u8>> = vec![Vec::new(); data_shards];
let mut inputs = vec![0u64; metas.len()];
let mut tried: HashSet<Vec<u64>> = HashSet::new();
// Records in `inputs` the shards each interval's decode reads when `set`
// is excluded, 0 for an interval that keeps its bytes. False when an
// interval has too few shards left, or the same decodes were tried before.
let mut plan = |set: u64, inputs: &mut [u64], gathers: &[Vec<Option<Vec<u8>>>]| {
for (i, iv) in metas.iter().enumerate() {
inputs[i] = 0;
if set & (1 << iv.shard_id) == 0 {
continue;
}
let mut taken = 0;
for (sid, slot) in gathers[i].iter().enumerate() {
if taken == data_shards {
break;
}
if set & (1 << sid) == 0 && slot.is_some() {
inputs[i] |= 1 << sid;
taken += 1;
}
}
if taken < data_shards {
return false;
}
}
tried.insert(inputs.to_vec())
};
// Rebuilds the planned intervals into `candidate`; reset on failure.
let mut decode =
|inputs: &[u64], candidate: &mut [u8], gathers: &mut [Vec<Option<Vec<u8>>>]| {
let mut pos = 0usize;
for (i, iv) in metas.iter().enumerate() {
let end = pos + iv.size;
if inputs[i] != 0 {
let Some(buf) =
decode_ec_interval(rs, &mut gathers[i], inputs[i], &mut scratch, iv)
else {
candidate.copy_from_slice(corrupted);
return false;
};
candidate[pos..end].copy_from_slice(buf);
}
pos = end;
}
if parses(candidate) {
return true;
}
candidate.copy_from_slice(corrupted);
false
};
let (mut sets, mut spent) = (0usize, 0usize);
for k in 1..=rs.parity_shard_count().min(total_shards) {
let mut members: Vec<usize> = (0..k).collect();
loop {
let set = members.iter().fold(0u64, |set, &sid| set | 1 << sid);
let holds_suspect = members
.iter()
.any(|&sid| suspects.contains(&(sid as ShardId)));
if holds_suspect {
sets += 1;
if sets > EC_REBUILD_MAX_SETS {
return None;
}
if plan(set, &mut inputs, gathers) {
if k > 1 {
if spent >= EC_REBUILD_MAX_BYTES {
return None;
}
spent += corrupted.len();
}
if decode(&inputs, &mut candidate, gathers) {
let mut convicted: Vec<ShardId> = Vec::new();
let mut pos = 0usize;
for iv in metas {
let end = pos + iv.size;
if candidate[pos..end] != corrupted[pos..end] {
convicted.push(iv.shard_id);
}
pos = end;
}
convicted.extend(
members
.iter()
.map(|&sid| sid as ShardId)
.filter(|sid| !suspects.contains(sid)),
);
return Some((candidate, convicted));
}
}
}
let Some(j) = (0..k).rev().find(|&j| members[j] != total_shards - k + j) else {
break;
};
members[j] += 1;
for m in j + 1..k {
members[m] = members[m - 1] + 1;
}
}
}
None
}
/// Decode `iv`'s data shard from the gathered shards in `inputs`, using
/// `scratch`, one buffer per data shard, for every data shard it lacks.
fn decode_ec_interval<'a>(
rs: &ReedSolomon,
slots: &mut [Option<Vec<u8>>],
inputs: u64,
scratch: &'a mut [Vec<u8>],
iv: &EcInterval,
) -> Option<&'a [u8]> {
let mut spare = scratch.iter_mut();
let mut view: Vec<(&mut [u8], bool)> = slots
.iter_mut()
.enumerate()
.map(|(sid, slot)| match (slot, spare.next()) {
(Some(shard), _) if inputs & (1 << sid) != 0 => (shard.as_mut_slice(), true),
(_, Some(buf)) => {
buf.resize(iv.size, 0);
(buf.as_mut_slice(), false)
}
_ => (&mut [][..], false),
})
.collect();
rs.reconstruct_data(&mut view).ok()?;
drop(view);
Some(&scratch[iv.shard_id as usize])
}
// parse_grpc_address lives in `grpc_client.rs` and is re-exported
// here via the use above so this module shares a single
// HTTP↔gRPC port-translation routine with grpc_server.rs.
@@ -2533,7 +2162,7 @@ async fn fetch_ec_index_from_one_peer(
match client.copy_file(copy_req(".vif", true)).await {
Ok(resp) => {
if let Err(e) = drain_optional_copy_stream(resp.into_inner(), vif_path).await {
if let Err(e) = drain_copy_stream(resp.into_inner(), vif_path).await {
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .vif: {}", e);
}
}
@@ -2543,48 +2172,6 @@ async fn fetch_ec_index_from_one_peer(
Ok(())
}
/// Drain an optional CopyFile stream into `<dest_path>.copying` and rename it
/// into place only once the source sent bytes, so a peer without the file or a
/// failed stream leaves an existing destination untouched, as Go's writeToFile
/// does for ignore_source_file_not_found.
pub(crate) async fn drain_optional_copy_stream(
stream: tonic::Streaming<crate::pb::volume_server_pb::CopyFileResponse>,
dest_path: &str,
) -> io::Result<()> {
let staging = format!("{}.copying", dest_path);
let mut incomplete = RemoveIncomplete::new(&staging);
let drained = drain_copy_stream(stream, &staging).await;
let has_bytes = fs::metadata(&staging).is_ok_and(|meta| meta.len() > 0);
if drained.is_ok() && has_bytes {
fs::rename(&staging, dest_path)
.map_err(|e| io::Error::other(format!("commit {}: {}", dest_path, e)))?;
incomplete.committed();
}
drained
}
/// Removes a staged copy unless it was committed, including when the copy is
/// dropped mid-stream because its RPC was cancelled.
pub(crate) struct RemoveIncomplete(Option<String>);
impl RemoveIncomplete {
pub(crate) fn new(staging: &str) -> Self {
Self(Some(staging.to_string()))
}
pub(crate) fn committed(&mut self) {
self.0 = None;
}
}
impl Drop for RemoveIncomplete {
fn drop(&mut self) {
if let Some(staging) = self.0.take() {
let _ = fs::remove_file(staging);
}
}
}
/// Drain a CopyFile stream into a local file, truncating it first.
async fn drain_copy_stream(
mut stream: tonic::Streaming<crate::pb::volume_server_pb::CopyFileResponse>,
@@ -2623,139 +2210,6 @@ mod tests {
);
}
const BLOCK: usize = 4096;
/// One row of 10+4 shards holding a needle at `dat_offset`, the needle's
/// intervals, and its bytes.
fn ec_row_with_needle(
dat_offset: usize,
data_len: usize,
) -> (Vec<Vec<u8>>, Vec<EcInterval>, Vec<u8>, Needle) {
let mut n = Needle {
id: NeedleId(7),
data: (0..data_len).map(|i| (i * 31 + 7) as u8).collect(),
..Needle::default()
};
let bytes = n.write_bytes(VERSION_3);
let mut dat = vec![0u8; 10 * BLOCK];
dat[dat_offset..dat_offset + bytes.len()].copy_from_slice(&bytes);
let mut shards: Vec<Vec<u8>> = dat.chunks(BLOCK).map(|c| c.to_vec()).collect();
shards.resize(14, vec![0u8; BLOCK]);
ReedSolomon::new(10, 4)
.unwrap()
.encode(&mut shards)
.unwrap();
let mut metas = Vec::new();
let (mut pos, end) = (dat_offset, dat_offset + bytes.len());
while pos < end {
let size = (BLOCK - pos % BLOCK).min(end - pos);
metas.push(EcInterval {
vid: VolumeId(1),
needle_id: n.id,
shard_id: (pos / BLOCK) as ShardId,
shard_offset: (pos % BLOCK) as i64,
size,
expected_encode_ts_ns: 0,
});
pos += size;
}
(shards, metas, bytes, n)
}
fn corrupt(shards: &mut [Vec<u8>], shard_ids: &[ShardId], metas: &[EcInterval]) {
for &sid in shard_ids {
for iv in metas {
let start = iv.shard_offset as usize;
for b in &mut shards[sid as usize][start..start + iv.size] {
*b ^= 0xFF;
}
}
}
}
fn search(
shards: &[Vec<u8>],
metas: &[EcInterval],
n: &Needle,
dat_offset: usize,
) -> Option<(Vec<u8>, Vec<ShardId>)> {
let mut corrupted = Vec::new();
let mut gathers = Vec::new();
for iv in metas {
let range = iv.shard_offset as usize..iv.shard_offset as usize + iv.size;
corrupted.extend_from_slice(&shards[iv.shard_id as usize][range.clone()]);
gathers.push(
shards
.iter()
.enumerate()
.map(|(sid, shard)| {
(sid != iv.shard_id as usize).then(|| shard[range.clone()].to_vec())
})
.collect(),
);
}
let suspects: HashSet<ShardId> = metas.iter().map(|iv| iv.shard_id).collect();
let rs = ReedSolomon::new(10, 4).unwrap();
search_ec_corrupt_sets(
&mut gathers,
metas,
&rs,
&corrupted,
&suspects,
|candidate| {
let mut check = Needle {
id: n.id,
..Needle::default()
};
check
.read_bytes(candidate, dat_offset as i64, n.size, VERSION_3)
.is_ok()
&& check.id == n.id
},
)
}
#[test]
fn search_ec_corrupt_sets_rebuilds_with_parity_many_shards_corrupt() {
let dat_offset = 2 * BLOCK + 100;
let (mut shards, metas, bytes, n) = ec_row_with_needle(dat_offset, 1000);
assert_eq!(metas.len(), 1);
// The needle's own shard and the lowest-numbered survivors, which every
// first decode reads.
corrupt(&mut shards, &[2, 0, 1, 3], &metas);
let (rebuilt, mut convicted) = search(&shards, &metas, &n, dat_offset).unwrap();
assert_eq!(rebuilt, bytes);
convicted.sort();
assert_eq!(convicted, vec![0, 1, 2, 3]);
}
#[test]
fn search_ec_corrupt_sets_keeps_a_clean_suspect_as_input() {
let dat_offset = BLOCK - 300;
let (mut shards, metas, bytes, n) = ec_row_with_needle(dat_offset, 1000);
assert_eq!(metas.len(), 2);
// Shard 0 is corrupt and shard 1 clean; rebuilding both would exceed
// parity with three other shards corrupt too.
corrupt(&mut shards, &[0], &metas[..1]);
corrupt(&mut shards, &[2, 3, 4], &metas);
let (rebuilt, mut convicted) = search(&shards, &metas, &n, dat_offset).unwrap();
assert_eq!(rebuilt, bytes);
convicted.sort();
assert_eq!(convicted, vec![0, 2, 3, 4]);
}
#[test]
fn search_ec_corrupt_sets_fails_past_parity() {
let dat_offset = 100;
let (mut shards, metas, _, n) = ec_row_with_needle(dat_offset, 1000);
corrupt(&mut shards, &[0, 1, 2, 3, 4], &metas);
assert!(search(&shards, &metas, &n, dat_offset).is_none());
}
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
(0..count)
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
@@ -2781,58 +2235,4 @@ mod tests {
// An unrefreshed cache always looks up.
assert!(needs_refresh(&locations(0), None, false, 10, 14));
}
struct FailAfterFrame(Option<bytes::Bytes>);
impl http_body::Body for FailAfterFrame {
type Data = bytes::Bytes;
type Error = tonic::Status;
fn poll_frame(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>>
{
std::task::Poll::Ready(Some(match self.0.take() {
Some(frame) => Ok(http_body::Frame::data(frame)),
None => Err(tonic::Status::unavailable(
"stream failed after the deleted answer",
)),
}))
}
}
/// A holder's deleted answer stands even when its stream fails afterwards,
/// so a later source or the quarantined shard cannot answer for the needle.
#[tokio::test]
async fn test_collect_ec_shard_read_keeps_deletion_when_the_stream_fails() {
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
is_deleted: true,
..Default::default()
});
let mut frame = vec![0u8];
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
frame.extend_from_slice(&message);
let stream = tonic::Streaming::new_response(
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
FailAfterFrame(Some(frame.into())),
tonic::codegen::http::StatusCode::OK,
None,
None,
);
let iv = EcInterval {
vid: VolumeId(7),
needle_id: NeedleId(42),
shard_id: 0,
shard_offset: 0,
size: 64,
expected_encode_ts_ns: 0,
};
let (buf, is_deleted) = collect_ec_shard_read(stream, "peer:18080", iv)
.await
.unwrap();
assert!(is_deleted);
assert!(buf.is_empty());
}
}
+14 -42
View File
@@ -18,7 +18,7 @@ use tracing::debug;
use crate::storage::needle::needle::Needle;
use crate::storage::types::{Size, VolumeId};
use crate::storage::volume::{PendingWrite, VolumeError};
use crate::storage::volume::VolumeError;
use super::volume_server::VolumeServerState;
@@ -26,12 +26,7 @@ use super::volume_server::VolumeServerState;
pub type WriteResult = Result<(u64, Size, bool), VolumeError>;
/// The needles queued for one volume, each with the durability it asked for.
type VolumeBatch = Vec<(
Needle,
bool,
oneshot::Sender<WriteResult>,
Option<PendingWrite>,
)>;
type VolumeBatch = Vec<(Needle, bool, oneshot::Sender<WriteResult>)>;
/// A request to write a needle, submitted to the write queue.
pub struct WriteRequest {
@@ -43,8 +38,6 @@ pub struct WriteRequest {
/// that cancels `submit` after the send must not free the slot while the
/// worker still holds the needle.
pub queue_permit: Option<OwnedSemaphorePermit>,
/// Tracked from submission, so a delete cancels the write while it waits.
pub pending: Option<PendingWrite>,
}
/// Maximum number of write requests to batch together.
@@ -174,13 +167,12 @@ impl WriteQueue {
#[cfg(test)]
self.submits
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let pending = {
{
let store = self.state.store.read().unwrap();
match store.find_volume(volume_id) {
Some((_, vol)) => vol.track_pending_write(&needle),
None => return Err(VolumeError::NotFound),
if store.find_volume(volume_id).is_none() {
return Err(VolumeError::NotFound);
}
};
}
// The permit travels inside the request, so the global queued bound
// covers the request until the worker drops it — including after a
// canceled submit.
@@ -197,7 +189,6 @@ impl WriteQueue {
fsync,
response_tx,
queue_permit: Some(queue_permit),
pending: Some(pending),
};
// A send fails only against a retiring worker's closed channel; the
@@ -354,11 +345,10 @@ fn process_batch(state: Arc<VolumeServerState>, batch: Vec<WriteRequest>) {
for req in batch {
let vid = req.volume_id;
let entry = (req.needle, req.fsync, req.response_tx, req.pending);
if let Some(group) = groups.iter_mut().find(|(v, _)| *v == vid) {
group.1.push(entry);
group.1.push((req.needle, req.fsync, req.response_tx));
} else {
groups.push((vid, vec![entry]));
groups.push((vid, vec![(req.needle, req.fsync, req.response_tx)]));
}
}
@@ -366,29 +356,16 @@ fn process_batch(state: Arc<VolumeServerState>, batch: Vec<WriteRequest>) {
// the group's I/O with the guard released — one volume's write must not
// block admission on another volume's.
for (vid, entries) in groups {
let (mut writes, senders): (Vec<_>, Vec<_>) = entries
.into_iter()
.map(|(needle, fsync, response_tx)| ((needle, fsync), response_tx))
.unzip();
let vol = {
let store = state.store.read().unwrap();
store.writable_volume(vid)
};
let mut writes = Vec::with_capacity(entries.len());
let mut senders = Vec::with_capacity(entries.len());
let mut pendings = Vec::with_capacity(entries.len());
for (needle, fsync, response_tx, pending) in entries {
// A delete reaching a remounted volume cannot cancel a write
// queued for the old one.
if let (Ok(vol), Some(tracked)) = (&vol, &pending)
&& !vol.tracks_pending_write(tracked)
{
drop(pending);
let _ = response_tx.send(Err(VolumeError::NotFound));
continue;
}
writes.push((needle, fsync));
senders.push(response_tx);
pendings.push(pending);
}
let results: Vec<WriteResult> = match vol {
Ok(vol) => vol.write_pending_needles(&mut writes, &pendings),
let results = match vol {
Ok(vol) => vol.write_needles_grouped(&mut writes),
Err(e) => writes
.iter()
.map(|_| match e {
@@ -397,9 +374,6 @@ fn process_batch(state: Arc<VolumeServerState>, batch: Vec<WriteRequest>) {
})
.collect(),
};
// Untrack before replying, as Go does: a caller that sees its write
// finish must not still find it pending.
drop(pendings);
for (response_tx, result) in senders.into_iter().zip(results) {
// Send result back; ignore error if receiver dropped.
let _ = response_tx.send(result);
@@ -603,7 +577,6 @@ mod tests {
fsync: true,
response_tx,
queue_permit: None,
pending: None,
}
})
.collect();
@@ -696,7 +669,6 @@ mod tests {
fsync: false,
response_tx,
queue_permit: None,
pending: None,
}];
let writer = {
let state = state.clone();
@@ -581,51 +581,6 @@ pub fn verify_shard_blocks(
Ok(mismatched)
}
/// Checks the data shards a decode reads against the volume's bitrot
/// protection: a corrupt shard copied into the .dat is lost for good once the
/// caller deletes the parity that could repair it. Mirrors Go's
/// `VerifyEcVolumeDataShards`.
pub fn verify_ec_volume_data_shards(
prot: Option<&EcBitrotProtection>,
status: BitrotStatus,
shard_paths: &[String],
) -> io::Result<()> {
let prot = match (status, prot) {
(BitrotStatus::Off, _) => return Ok(()),
(BitrotStatus::On, Some(prot)) => prot,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"bitrot sidecar is malformed or unverifiable",
));
}
};
for (shard_id, path) in shard_paths.iter().enumerate() {
let Some(entry) = shard_checksums(prot, shard_id as u32) else {
continue;
};
let mismatched =
verify_shard_file_blocks(path, entry, prot.block_size as i64).map_err(|e| {
io::Error::new(
e.kind(),
format!("verify data shard {} {}: {}", shard_id, path, e),
)
})?;
if !mismatched.is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"data shard {} {} fails its bitrot checksum in {} blocks",
shard_id,
path,
mismatched.len()
),
));
}
}
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, block_size: i64) -> EcShardConfig {
@@ -238,8 +238,8 @@ pub struct EcVolume {
/// no encode identity, so provenance is the only signal that a loaded
/// manifest may describe a different encode run. Same purpose as
/// `ecx_actual_dir`. Empty when no sidecar was found. Always committed in
/// the same step as `bitrot`/`bitrot_status`, so a reload whose `Err` a
/// caller ignores cannot leave this describing a
/// the same step as `bitrot`/`bitrot_status`, so a reload whose `Err` gets
/// swallowed by `reload_bitrot_sidecar` cannot leave this describing a
/// sidecar other than the one those two fields actually hold.
pub(crate) bitrot_source_dir: String,
@@ -802,17 +802,14 @@ impl EcVolume {
/// shard delivery can bring the manifest with it, and the receive path only
/// writes the file, so without this the in-memory volume keeps the
/// protection state it resolved at mount (off) until a remount.
/// Returns the layout-mismatch error a mount would fail on.
pub fn reload_bitrot_sidecar(&mut self, additional_dirs: &[String]) -> io::Result<()> {
let result = self.load_active_bitrot_sidecar(additional_dirs);
if let Err(e) = &result {
pub fn reload_bitrot_sidecar(&mut self, additional_dirs: &[String]) {
if let Err(e) = self.load_active_bitrot_sidecar(additional_dirs) {
tracing::warn!(
volume_id = self.volume_id.0,
error = %e,
"reload bitrot sidecar",
);
}
result
}
/// Load the generation-0 checksum sidecar into `self.bitrot`/`self.bitrot_status`.
@@ -891,8 +888,8 @@ impl EcVolume {
self.parity_shards as usize,
);
// Provenance is committed together with the sidecar it describes, so a
// reload whose `Err` above a caller ignores cannot leave them
// disagreeing: the geometry-mismatch return
// swallowed reload (`reload_bitrot_sidecar` logs and discards the `Err`
// above) cannot leave them disagreeing: the geometry-mismatch return
// happens before this point, so `bitrot`/`bitrot_status` below and
// `bitrot_source_dir` here always describe the same load attempt.
// Only a path that actually exists is a real source: `path` falls back
@@ -937,31 +934,6 @@ impl EcVolume {
(self.bitrot.clone(), self.bitrot_status)
}
/// The protection of a volume's per-disk runtimes: the first `On`, else
/// `Invalid`, else `Off`. After a restart only the runtime whose disk holds
/// the sidecar resolves it. Mirrors Go's `SelectBitrotProtection`.
pub(crate) fn select_bitrot_protection(
volumes: &[&EcVolume],
) -> (
Option<crate::pb::volume_server_pb::EcBitrotProtection>,
crate::storage::erasure_coding::ec_bitrot::BitrotStatus,
) {
use crate::storage::erasure_coding::ec_bitrot::BitrotStatus;
let mut invalid = false;
for v in volumes {
match v.bitrot_protection() {
(prot, BitrotStatus::On) => return (prot, BitrotStatus::On),
(_, BitrotStatus::Invalid) => invalid = true,
_ => {}
}
}
if invalid {
(None, BitrotStatus::Invalid)
} else {
(None, BitrotStatus::Off)
}
}
/// Read-only EC bitrot checksum scrub of the LOCAL shards of this volume's
/// active generation.
///
@@ -165,8 +165,7 @@ impl SortedFileNeedleMap {
return Ok(None);
}
let file = pooled_index_files().borrow(&self.db_file_name, true)?;
let Some((entry_index, needle_offset, size)) =
search_sorted_index(&file, self.db_file_size, key)?
let Some((entry_index, _, size)) = search_sorted_index(&file, self.db_file_size, key)?
else {
return Ok(None);
};
@@ -183,14 +182,22 @@ impl SortedFileNeedleMap {
// already counts as deleted.
self.append_to_index_file(key, offset, TOMBSTONE_FILE_SIZE)?;
// Count against the `.idx` append, not the `.sdx` mark below: the
// append is what a reload counts, and the retry path returns early
// once the overlay records it, so a failed mark must not strand the
// counters at their pre-delete values.
self.metric.on_delete(&NeedleValue {
offset: needle_offset,
size,
});
// Move the counters to where a reload would put them, so the heartbeat
// does not report this volume as garbage-free until it restarts. The
// tombstone is one more .idx row, and under the rule index_metric
// applies both it and the row it supersedes count as deletions; the
// bytes leave the live set without leaving the .idx.
//
// This belongs to the `.idx` append, not to the `.sdx` mark below: the
// append is what makes the delete durable and what a reload would
// count, and the retry path returns early once the overlay records it.
// Leaving the counters until after the mark would strand them at their
// pre-delete values whenever the mark fails.
self.metric.file_count.fetch_add(1, Ordering::Relaxed);
self.metric.deletion_count.fetch_add(2, Ordering::Relaxed);
self.metric
.deletion_byte_count
.fetch_add(size.0.max(0) as u64, Ordering::Relaxed);
// From here the delete is durable in `.idx`, so no lookup may report
// this needle live again. Record it before touching `.sdx` and clear
@@ -442,11 +449,11 @@ fn write_sorted_file_from_idx(
/// its bloom filter — and so without its false positives or its per-volume
/// allocation.
///
/// Go counts every `.idx` put row in `FileCounter` and tombstones in neither
/// counter, so a key costs one deletion per put that is no longer its live
/// row. The live rows are exactly the unmarked entries `.sdx` holds, so
/// `DeletionCounter = puts - live` and
/// `DeletionByteCounter = put bytes in .idx - live bytes in .sdx`, each
/// Go counts every `.idx` row in `FileCounter`, and counts a row in
/// `DeletionCounter` when it is not the last, still-valid row for its key. The
/// rows that *are* the last valid row for their key are exactly the entries
/// `.sdx` holds, so `DeletionCounter = rows - live` and
/// `DeletionByteCounter = valid bytes in .idx - live bytes in .sdx`, each
/// computable in one sequential pass with no per-key state.
fn index_metric(
index_file_name: &str,
@@ -455,17 +462,15 @@ fn index_metric(
) -> io::Result<NeedleMapMetric> {
let metric = NeedleMapMetric::default();
let is_put = |offset: Offset, size: Size| !offset.is_zero() && !size.is_deleted();
let mut puts: i64 = 0;
let mut put_bytes: u64 = 0;
let mut rows: i64 = 0;
let mut valid_bytes: u64 = 0;
let mut index_file = File::open(index_file_name)?;
idx::walk_index_file(&mut index_file, 0, |key, offset, size| {
rows += 1;
metric.maybe_set_max_file_key(key);
metric.maybe_set_max_needle_end(offset, size, version);
if is_put(offset, size) {
puts += 1;
put_bytes += size.0 as u64;
if size.is_valid() {
valid_bytes += size.0 as u64;
}
Ok(())
})?;
@@ -473,22 +478,22 @@ fn index_metric(
let mut live: i64 = 0;
let mut live_bytes: u64 = 0;
let mut db_file = File::open(db_file_name)?;
idx::walk_index_file(&mut db_file, 0, |_, offset, size| {
if is_put(offset, size) {
idx::walk_index_file(&mut db_file, 0, |_, _, size| {
if size.is_valid() {
live += 1;
live_bytes += size.0 as u64;
}
Ok(())
})?;
metric.file_count.store(puts, Ordering::Relaxed);
metric.file_byte_count.store(put_bytes, Ordering::Relaxed);
metric.file_count.store(rows, Ordering::Relaxed);
metric.file_byte_count.store(valid_bytes, Ordering::Relaxed);
metric
.deletion_count
.store((puts - live).max(0), Ordering::Relaxed);
.store((rows - live).max(0), Ordering::Relaxed);
metric
.deletion_byte_count
.store(put_bytes.saturating_sub(live_bytes), Ordering::Relaxed);
.store(valid_bytes.saturating_sub(live_bytes), Ordering::Relaxed);
Ok(metric)
}
@@ -612,11 +617,11 @@ mod tests {
);
let m = SortedFileNeedleMap::open(&base, version()).unwrap();
// Every put row counts, matching Go's FileCounter; the tombstone does not.
assert_eq!(m.file_count(), 4);
// Every row counts, matching Go's FileCounter.
assert_eq!(m.file_count(), 5);
assert_eq!(m.content_size(), 100 + 200 + 150 + 300);
// Superseded row for key 1, plus the put of the deleted key 2.
assert_eq!(m.deleted_count(), 2);
// Superseded row for key 1, plus both rows for the deleted key 2.
assert_eq!(m.deleted_count(), 3);
assert_eq!(m.deleted_size(), 100 + 200);
assert_eq!(m.max_file_key(), NeedleId(3));
}
@@ -704,8 +709,8 @@ mod tests {
// already agree with it or the heartbeat jumps at every restart.
drop(m);
let reloaded = SortedFileNeedleMap::open(&base, version()).unwrap();
assert_eq!(reloaded.file_count(), 3);
assert_eq!(reloaded.deleted_count(), 1);
assert_eq!(reloaded.file_count(), 4);
assert_eq!(reloaded.deleted_count(), 2);
assert_eq!(reloaded.deleted_size(), 200);
assert_eq!(reloaded.content_size(), 600);
@@ -713,7 +718,7 @@ mod tests {
reloaded
.delete(NeedleId(2), Offset::from_actual_offset(16))
.unwrap();
assert_eq!((reloaded.file_count(), reloaded.deleted_count()), (3, 1));
assert_eq!((reloaded.file_count(), reloaded.deleted_count()), (4, 2));
}
#[test]
@@ -955,7 +960,7 @@ mod tests {
assert_eq!(
m.deleted_count(),
deleted_before + 1,
deleted_before + 2,
"a durable tombstone must move the deletion count"
);
assert_eq!(
@@ -974,7 +979,7 @@ mod tests {
.unwrap(),
None
);
assert_eq!(m.deleted_count(), deleted_before + 1);
assert_eq!(m.deleted_count(), deleted_before + 2);
assert_eq!(m.deleted_size(), bytes_before + 100);
}
+24 -257
View File
@@ -948,39 +948,14 @@ impl Store {
vol.read_needle_opt(n, read_deleted)
}
/// Resolve a needle read with the store guard held only for the lookup:
/// the plan can wait on a vacuum commit's data-file lease, and waiting
/// under the guard would park store writers, and every reader queued
/// behind them, on that commit. A handle closed while the plan waited is
/// looked up again, a bounded number of times.
/// Resolve a needle read under this guard, to run after it is released.
pub(crate) fn needle_read_plan(
store: &std::sync::RwLock<Store>,
&self,
vid: VolumeId,
id: NeedleId,
read_deleted: bool,
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
let find = || {
let store = store.read().unwrap();
store
.find_volume(vid)
.map(|(_, vol)| vol)
.ok_or(VolumeError::NotFound)
};
Self::plan_on_open_handle(find, id, read_deleted)
}
fn plan_on_open_handle(
mut find: impl FnMut() -> Result<Arc<Volume>, VolumeError>,
id: NeedleId,
read_deleted: bool,
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
let mut vol = find()?;
for _ in 0..3 {
match vol.needle_read_plan(id, read_deleted) {
Err(_) if vol.is_closed() => vol = find()?,
plan => return plan,
}
}
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
vol.needle_read_plan(id, read_deleted)
}
@@ -1182,14 +1157,13 @@ impl Store {
/// Matches Go's Store.MountEcShards which mounts one shard at a time.
/// `source_disk_type` is the source volume's disk type from the
/// `VolumeEcShardsMount` RPC (#9423); pass `""` for non-RPC paths.
/// Returns the index of the disk the shard mounted on.
pub fn mount_ec_shard(
&mut self,
vid: VolumeId,
collection: &str,
shard_id: ShardId,
source_disk_type: &str,
) -> Result<usize, VolumeError> {
) -> Result<(), VolumeError> {
self.stamp_allocated_vid(vid);
// The .ecx may live on a different disk than the shard being mounted
// (ec.balance / ec.rebuild can spread shards across sibling disks), so
@@ -1202,7 +1176,7 @@ impl Store {
// next. Like Go, a NotFound just means "not this disk"; anything else
// is collected so an all-disks-fail error names every disk tried.
let mut failures: Vec<(String, VolumeError)> = Vec::new();
for (disk, loc) in self.locations.iter_mut().enumerate() {
for loc in &mut self.locations {
// Check if the shard file exists on this location
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
if !std::path::Path::new(&shard.file_name()).exists() {
@@ -1227,7 +1201,7 @@ impl Store {
&idx_dir,
source_disk_type,
) {
Ok(()) => return Ok(disk),
Ok(()) => return Ok(()),
Err(VolumeError::Io(e)) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => failures.push((loc.directory.clone(), e)),
}
@@ -1492,27 +1466,22 @@ impl Store {
Vec<master_pb::VolumeEcShardInformationMessage>,
Vec<master_pb::VolumeEcShardInformationMessage>,
) {
let (mut ec_shards, expired, quarantined) = self.find_expired_ec_volumes();
let (mut deleted, still_held) = self.remove_expired_ec_volumes(expired);
let (mut ec_shards, expired) = self.find_expired_ec_volumes();
let (deleted, still_held) = self.remove_expired_ec_volumes(expired);
ec_shards.extend(still_held);
deleted.extend(quarantined);
(ec_shards, deleted)
}
/// The read half of `delete_expired_ec_volumes`: the shards to report, the
/// expired EC volumes, by disk index, for `remove_expired_ec_volumes`, and
/// the shards of volumes this pass quarantined, which go out as deleted
/// once so the master drops them before the next full EC heartbeat.
/// The read half of `delete_expired_ec_volumes`: the shards to report, and
/// the expired EC volumes, by disk index, for `remove_expired_ec_volumes`.
pub fn find_expired_ec_volumes(
&self,
) -> (
Vec<master_pb::VolumeEcShardInformationMessage>,
Vec<(usize, VolumeId)>,
Vec<master_pb::VolumeEcShardInformationMessage>,
) {
let mut ec_shards = Vec::new();
let mut expired = Vec::new();
let mut quarantined_now = Vec::new();
for (disk_id, loc) in self.locations.iter().enumerate() {
for (vid, ec_vol) in loc.ec_volumes() {
@@ -1527,8 +1496,6 @@ impl Store {
io_count,
"ec volume quarantined after consecutive IO errors"
);
quarantined_now
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
}
} else {
ec_shards
@@ -1537,7 +1504,7 @@ impl Store {
}
}
(ec_shards, expired, quarantined_now)
(ec_shards, expired)
}
/// The write half of `delete_expired_ec_volumes`: destroys each volume that
@@ -1807,7 +1774,7 @@ impl Store {
{
match self.begin_compact_volume(vid, preallocate)? {
Some(job) => job.run(progress_fn),
None => Err(crate::storage::volume::compacting_error(vid)),
None => Ok(()),
}
}
@@ -3072,7 +3039,6 @@ mod tests {
#[test]
fn test_maybe_adjust_volume_max_reserves_plain_volumes_while_preallocating() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
@@ -3081,7 +3047,7 @@ mod tests {
.add_location(
dir,
dir,
5,
2,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
@@ -3098,13 +3064,15 @@ mod tests {
)
.unwrap();
// Room for 2.5 volumes above the 1% floor: the plain volume claims one,
// leaving one more slot.
let limit = 1024 * MIB;
FAKE_ALL.store(100 * limit, Ordering::Relaxed);
FAKE_FREE.store(limit + limit * 5 / 2, Ordering::Relaxed);
store.disk_stats_of = fake_disk_stats;
store.volume_size_limit.store(limit, Ordering::Relaxed);
// Room for 2.5 volumes: the plain volume claims one, leaving one more slot.
let (_, free) = crate::storage::disk_location::get_disk_stats(dir);
let volume_size_limit = (free as f64 / 2.5) as u64;
if volume_size_limit == 0 {
return; // cannot determine free disk space
}
store
.volume_size_limit
.store(volume_size_limit, Ordering::Relaxed);
store.locations[0].original_max_volume_count = 0;
store.set_preallocate(true);
@@ -3417,207 +3385,6 @@ mod tests {
assert_eq!(v.dat_file_size().unwrap(), volume_size);
}
/// A volume `vid` holding needle 1, compacted and ready to commit, behind
/// the store lock the server's handlers use.
fn store_ready_to_commit(
dir: &str,
vid: VolumeId,
kind: NeedleMapKind,
) -> Arc<std::sync::RwLock<Store>> {
let mut store = make_test_store(&[dir]);
store.needle_map_kind = kind;
store
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
write_test_needle(&mut store, vid, 1, b"live needle");
store.compact_volume(vid, 0, 0, |_| true).unwrap();
Arc::new(std::sync::RwLock::new(store))
}
/// Commits as the vacuum-commit RPC does: the volume is looked up under
/// the store guard, which is dropped before the commit takes its locks.
/// The result comes back on a channel, so a deadlock fails a test by
/// timing out instead of hanging it.
fn commit_like_the_rpc(
store: Arc<std::sync::RwLock<Store>>,
vid: VolumeId,
) -> std::sync::mpsc::Receiver<Result<(), VolumeError>> {
let (committed, result) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let (_, vol) = store.read().unwrap().find_volume(vid).unwrap();
let _sync_guard = vol.data_file_sync_lock().lock().unwrap();
let _lease = vol.instance().write_lock();
let _ = committed.send(vol.commit_compact_held());
});
result
}
/// Holds the next commit of `vid` inside its swap window, where the needle
/// map is closed, until the returned sender is used.
fn hold_commit_in_swap_window(
vid: VolumeId,
) -> (
crate::storage::volume::commit_swap_hook::Registration,
std::sync::mpsc::Receiver<()>,
std::sync::mpsc::Sender<()>,
) {
let (entered, in_window) = std::sync::mpsc::channel();
let (release, released) = std::sync::mpsc::channel::<()>();
let released = std::sync::Mutex::new(released);
let entered = std::sync::Mutex::new(entered);
let hook = crate::storage::volume::commit_swap_hook::register(vid, move || {
entered.lock().unwrap().send(()).unwrap();
released.lock().unwrap().recv().unwrap();
});
(hook, in_window, release)
}
/// Plans and reads needle 1 of `vid` on another thread, and returns once
/// the plan holds the volume handle, so a timed check cannot pass on a
/// late start.
fn plan_in_background(
store: &Arc<std::sync::RwLock<Store>>,
vid: VolumeId,
) -> std::sync::mpsc::Receiver<Result<Vec<u8>, VolumeError>> {
let (_, vol) = store.read().unwrap().find_volume(vid).unwrap();
let handles = Arc::strong_count(&vol);
let (planned, plan) = std::sync::mpsc::channel();
let reader = store.clone();
std::thread::spawn(move || {
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(1),
..Needle::default()
};
let read = Store::needle_read_plan(&reader, vid, NeedleId(1), false)
.and_then(|mut plan| plan.read_full(&mut n))
.map(|()| n.data);
let _ = planned.send(read);
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while Arc::strong_count(&vol) == handles {
assert!(
std::time::Instant::now() < deadline,
"the plan never looked up the volume"
);
std::thread::sleep(std::time::Duration::from_millis(1));
}
plan
}
/// A GET planned while a vacuum commit has the needle map closed waits for
/// the commit, as Go's readNeedle does, instead of answering NotFound for a
/// live needle.
fn check_read_plan_waits_out_a_commit_swap_window(kind: NeedleMapKind, vid: VolumeId) {
let tmp = TempDir::new().unwrap();
let store = store_ready_to_commit(tmp.path().to_str().unwrap(), vid, kind);
let (_hook, in_window, release) = hold_commit_in_swap_window(vid);
let commit = commit_like_the_rpc(store.clone(), vid);
in_window
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the commit never reached its swap window");
let plan = plan_in_background(&store, vid);
if let Ok(early) = plan.recv_timeout(std::time::Duration::from_millis(300)) {
release.send(()).unwrap();
panic!("planned during the swap window instead of waiting: {early:?}");
}
release.send(()).unwrap();
commit
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the commit never finished")
.unwrap();
let after = plan
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the plan still waits after the commit finished");
assert_eq!(after.unwrap(), b"live needle");
}
#[test]
fn test_read_plan_waits_out_a_commit_swap_window_in_memory() {
check_read_plan_waits_out_a_commit_swap_window(NeedleMapKind::InMemory, VolumeId(81));
}
#[test]
fn test_read_plan_waits_out_a_commit_swap_window_redb() {
check_read_plan_waits_out_a_commit_swap_window(NeedleMapKind::Redb, VolumeId(83));
}
/// A plan on a handle an unmount closed looks the volume up again and
/// reads the remounted volume.
#[test]
fn test_read_plan_retries_a_handle_closed_by_a_remount() {
let tmp = TempDir::new().unwrap();
let vid = VolumeId(1);
let mut store = make_test_store(&[tmp.path().to_str().unwrap()]);
store
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
write_test_needle(&mut store, vid, 1, b"live needle");
let (_, stale) = store.find_volume(vid).unwrap();
assert!(store.unmount_volume(vid).unwrap());
store.mount_volume(vid, "", DiskType::HardDrive).unwrap();
let mut stale = Some(stale);
let mut plan = Store::plan_on_open_handle(
|| match stale.take() {
Some(vol) => Ok(vol),
None => store
.find_volume(vid)
.map(|(_, vol)| vol)
.ok_or(VolumeError::NotFound),
},
NeedleId(1),
false,
)
.unwrap();
let mut n = Needle {
id: NeedleId(1),
cookie: Cookie(1),
..Needle::default()
};
plan.read_full(&mut n).unwrap();
assert_eq!(n.data, b"live needle");
}
/// A plan waiting for a commit holds no store guard, so a store writer
/// finishes while the commit is still in its swap window.
#[test]
fn test_read_plan_waiting_on_a_commit_does_not_block_a_store_writer() {
let tmp = TempDir::new().unwrap();
let vid = VolumeId(82);
let store =
store_ready_to_commit(tmp.path().to_str().unwrap(), vid, NeedleMapKind::InMemory);
let (_hook, in_window, release) = hold_commit_in_swap_window(vid);
let commit = commit_like_the_rpc(store.clone(), vid);
in_window
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the commit never reached its swap window");
let plan = plan_in_background(&store, vid);
let (wrote, written) = std::sync::mpsc::channel();
let writer = store.clone();
std::thread::spawn(move || {
let _guard = writer.write().unwrap();
let _ = wrote.send(());
});
let writer_done = written.recv_timeout(std::time::Duration::from_secs(10));
let planned_early = plan.try_recv().is_ok();
release.send(()).unwrap();
writer_done.expect("a store writer waited on the commit");
assert!(!planned_early, "planned during the swap window");
let committed = commit
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the commit never finished");
assert!(committed.is_ok(), "{committed:?}");
let after = plan
.recv_timeout(std::time::Duration::from_secs(10))
.expect("the plan still waits after the commit finished");
assert_eq!(after.unwrap(), b"live needle");
}
fn write_test_needle(store: &mut Store, vid: VolumeId, id: u64, data: &[u8]) {
let mut n = Needle {
id: NeedleId(id),
@@ -3671,8 +3438,8 @@ mod tests {
assert!(store.cleanup_compact_volume(vid).is_err());
let (_, v) = store.find_volume(vid).unwrap();
assert!(v.relocate_index_to(other.path().to_str().unwrap()).is_err());
assert!(store.commit_compact_volume(vid).is_err());
assert!(store.compact_volume(vid, 0, 0, |_| true).is_err());
// Go parity: a commit that finds the volume compacting is a no-op.
store.commit_compact_volume(vid).unwrap();
let (_, v) = store.find_volume(vid).expect("still mounted");
assert!(v.is_compacting());
File diff suppressed because it is too large. Load diff
+9 -779
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -6,7 +6,7 @@
# sorting jobs share, so that two of them cannot drift on what an order means.
[workspace]
resolver = "2"
members = ["crates/core", "crates/lance", "crates/sort", "crates/sw-client"]
members = ["crates/core", "crates/lance", "crates/sort"]
[workspace.package]
version = "0.1.0"
+13 -22
View File
@@ -35,7 +35,7 @@ binary for the runner's platform, resolved from the version in `Cargo.lock`.
## Running
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535
The admin's *HTTP* address is what an operator has; the gRPC port is derived
from it the way the Go side does. Dialling the HTTP port fails as "frame with
@@ -49,7 +49,7 @@ Released builds do not need a toolchain. The worker ships inside the SeaweedFS
image, beside the Rust volume server, under the verb that mirrors
`volume-rust`:
docker run chrislusf/seaweedfs worker-rust --admin admin:12535 --masters master:9333
docker run chrislusf/seaweedfs worker-rust --admin admin:12535
and as `weed-worker_linux_{amd64,arm64}.tar.gz` on each GitHub release. Both are
linux amd64/arm64 only — lance, arrow and datafusion make every extra target an
@@ -59,7 +59,7 @@ entrypoint says so rather than failing as "not found".
## Metrics
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333 --metrics-port 9328
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --metrics-port 9328
Serves `/health`, `/ready` and `/metrics` on that port, the same three the Go
worker serves under `weed worker -metricsPort`, so one scrape config covers
@@ -89,22 +89,16 @@ running but is not going to do anything.
## Credentials
The worker holds no S3 credentials. The namespace tells it where a table is;
its files are read and written on the cluster's filers and volume servers,
which `--masters` names the masters of (`--filer-group` picks the filers). What
that takes comes from the same security.toml the weed processes use:
`grpc.client` for the filers, `https.client` for volume servers under HTTPS,
`jwt.signing.read.key` where volume reads are signed, and `s3.sse.kek` or
`s3.sse.key` where a bucket encrypts with SSE-S3. Chunks are encrypted for the
volume servers when the filer is (`weed filer -encryptVolumeData`), as the S3
gateway's are.
The worker holds none. It asks the namespace to describe a table with
`vend_credentials` and hands the `storage_options` that come back to lance. A
gateway without STS configured vends no credentials at all, so `--access-key`
and `--secret-key` supply a fallback; anything the namespace does vend wins over
them.
The namespace authenticates the worker by the cluster token it derives from
`jwt.filer_signing.key`; the same key signs the admin stream when admin requires
it. The worker reads it from where `weed worker` does: `WEED_JWT_FILER_SIGNING_KEY`,
or `[jwt.filer_signing]` in the security.toml found in the working directory,
`~/.seaweedfs`, `/usr/local/etc/seaweedfs` or `/etc/seaweedfs`.
`--filer-signing-key` overrides both.
In a vector bucket's `vector` namespace the gateway vends write credentials only
to a caller that proves it holds `jwt.filer_signing.key`. Pass that key with
`--filer-signing-key` so compaction, cleanup and index builds can rewrite
vector indexes.
## State
@@ -116,10 +110,7 @@ All three jobs are implemented and tested end to end against a live gateway:
`cargo test -p weed-lance-worker` runs them when `WEED_LANCE_NAMESPACE` names a
live namespace and skips otherwise, the way the Go integration tests skip
without Docker. A live namespace needs `WEED_MASTERS` naming its cluster's
masters, and `WEED_JWT_FILER_SIGNING_KEY` (or security.toml) where the
namespace authenticates cluster processes; the tests fail without the first
and are refused without the second. Each test seeds the table it needs, including building a vector
without Docker. Each test seeds the table it needs, including building a vector
index and then appending rows outside it, so a run does not depend on what the
previous one left behind — the first version of these did, and quietly stopped
testing anything once it had done its job.
-5
View File
@@ -16,8 +16,6 @@ seaweed-common = { path = "../../../seaweed-common" }
# admin token can sign with the same HMAC the Go worker uses.
aws-lc-rs = "1"
base64 = "0.22"
# The same requirement seaweed-volume states for its security.toml reader.
toml = "0.8"
anyhow.workspace = true
async-trait.workspace = true
prost.workspace = true
@@ -30,9 +28,6 @@ axum.workspace = true
prometheus.workspace = true
tracing.workspace = true
[dev-dependencies]
tempfile = "3"
[build-dependencies]
tonic-prost-build.workspace = true
# Ships protoc with the build so neither CI nor a developer needs a system
-1
View File
@@ -11,7 +11,6 @@ pub mod config;
pub mod config_form;
pub mod metrics;
pub mod registry;
pub mod security_config;
pub mod senders;
pub mod stream;
pub mod token;
@@ -1,249 +0,0 @@
//! The admin-stream signing key, read from where the Go worker reads it.
//!
//! `weed worker` takes `jwt.filer_signing` from security.toml, with the
//! `WEED_JWT_FILER_SIGNING_*` environment variables overriding the file the
//! way viper does. A Rust worker started beside it, from the same image with
//! the same mounts, has to find the key in the same places or it connects
//! with no token and admin turns it away.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use seaweed_common::security_config as location;
/// `jwt.filer_signing` as the Go worker resolves it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FilerSigning {
pub key: String,
/// Zero mints a token without an expiry, the Go default.
pub expires_after_seconds: u64,
/// Where the key came from, for the startup log.
pub source: String,
}
/// The key from the process environment and the discovered security.toml, or
/// None when neither configures one.
pub fn filer_signing() -> Option<FilerSigning> {
let env = |key: &str| std::env::var_os(key);
filer_signing_in(&env, std::env::current_dir().ok().as_deref())
}
fn filer_signing_in(
env: &dyn Fn(&str) -> Option<OsString>,
current_dir: Option<&Path>,
) -> Option<FilerSigning> {
let file = location::find(current_dir, location::home_dir(env).as_deref());
filer_signing_from(env, file.as_deref())
}
fn filer_signing_from(
env: &dyn Fn(&str) -> Option<OsString>,
file: Option<&Path>,
) -> Option<FilerSigning> {
// Viper treats an empty environment value as unset.
let env_string = |key: &str| {
env(key)
.and_then(|v| v.into_string().ok())
.filter(|v| !v.is_empty())
};
let (file_key, file_expires) = file.map(read_file).unwrap_or_default();
let (key, source) = match env_string("WEED_JWT_FILER_SIGNING_KEY") {
Some(key) => (key, "WEED_JWT_FILER_SIGNING_KEY".to_string()),
None => (file_key?, file.map(PathBuf::from)?.display().to_string()),
};
if key.is_empty() {
return None;
}
let expires_after_seconds = env_string("WEED_JWT_FILER_SIGNING_EXPIRES_AFTER_SECONDS")
.and_then(|v| v.parse().ok())
.or(file_expires)
.unwrap_or(0);
Some(FilerSigning {
key,
expires_after_seconds,
source,
})
}
/// `[jwt.filer_signing]` key and expires_after_seconds from one file. A file
/// that cannot be read or parsed configures nothing, as it does for viper,
/// which also logs a warning.
fn read_file(path: &Path) -> (Option<String>, Option<u64>) {
// The message alone: the full parse error quotes the offending line,
// which can hold a key.
let parsed = std::fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|content| {
content
.parse::<toml::Table>()
.map_err(|e| e.message().to_string())
});
let table = match parsed {
Ok(table) => table,
Err(error) => {
tracing::warn!(path = %path.display(), %error, "skipping unreadable security.toml");
return (None, None);
}
};
let section = table
.get("jwt")
.and_then(|jwt| jwt.get("filer_signing"))
.and_then(|section| section.as_table());
let Some(section) = section else {
return (None, None);
};
let key = section
.get("key")
.and_then(|v| v.as_str())
.map(str::to_string);
// Viper's GetInt also reads a quoted number and truncates a float.
let expires = section.get("expires_after_seconds").and_then(|v| match v {
toml::Value::Integer(n) => u64::try_from(*n).ok(),
toml::Value::Float(f) if f.is_finite() && *f >= 0.0 => Some(*f as u64),
toml::Value::String(s) => s.trim().parse().ok(),
_ => None,
});
(key, expires)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
let map: HashMap<String, OsString> = pairs
.iter()
.map(|(k, v)| (k.to_string(), OsString::from(v)))
.collect();
move |key: &str| map.get(key).cloned()
}
fn write(dir: &tempfile::TempDir, content: &str) -> PathBuf {
let path = dir.path().join(location::SECURITY_CONFIG_FILE_NAME);
std::fs::write(&path, content).unwrap();
path
}
#[test]
fn reads_the_section_the_go_worker_reads() {
let dir = tempfile::TempDir::new().unwrap();
let path = write(
&dir,
r#"
[jwt.signing]
key = "volume-key"
[jwt.filer_signing]
key = "cluster-key"
expires_after_seconds = 300
[jwt.filer_signing.read]
key = "read-key"
"#,
);
let got = filer_signing_from(&env_of(&[]), Some(&path)).unwrap();
assert_eq!(got.key, "cluster-key");
assert_eq!(got.expires_after_seconds, 300);
assert_eq!(got.source, path.display().to_string());
}
#[test]
fn quoted_expiry_reads_as_a_number() {
let dir = tempfile::TempDir::new().unwrap();
let path = write(
&dir,
"[jwt.filer_signing]\nkey = \"k\"\nexpires_after_seconds = \"300\"\n",
);
let got = filer_signing_from(&env_of(&[]), Some(&path)).unwrap();
assert_eq!(got.expires_after_seconds, 300);
}
#[test]
fn float_expiry_truncates_to_seconds() {
let dir = tempfile::TempDir::new().unwrap();
let path = write(
&dir,
"[jwt.filer_signing]\nkey = \"k\"\nexpires_after_seconds = 300.9\n",
);
let got = filer_signing_from(&env_of(&[]), Some(&path)).unwrap();
assert_eq!(got.expires_after_seconds, 300);
}
#[test]
fn environment_overrides_the_file() {
let dir = tempfile::TempDir::new().unwrap();
let path = write(
&dir,
"[jwt.filer_signing]\nkey = \"file-key\"\nexpires_after_seconds = 5\n",
);
let env = env_of(&[
("WEED_JWT_FILER_SIGNING_KEY", "env-key"),
("WEED_JWT_FILER_SIGNING_EXPIRES_AFTER_SECONDS", "60"),
]);
let got = filer_signing_from(&env, Some(&path)).unwrap();
assert_eq!(got.key, "env-key");
assert_eq!(got.expires_after_seconds, 60);
assert_eq!(got.source, "WEED_JWT_FILER_SIGNING_KEY");
}
#[test]
fn environment_key_alone_is_enough() {
let got =
filer_signing_from(&env_of(&[("WEED_JWT_FILER_SIGNING_KEY", "k")]), None).unwrap();
assert_eq!(got.key, "k");
assert_eq!(got.expires_after_seconds, 0);
}
#[test]
fn empty_environment_values_fall_back_to_the_file() {
let dir = tempfile::TempDir::new().unwrap();
let path = write(
&dir,
"[jwt.filer_signing]\nkey = \"file-key\"\nexpires_after_seconds = 5\n",
);
let env = env_of(&[
("WEED_JWT_FILER_SIGNING_KEY", ""),
("WEED_JWT_FILER_SIGNING_EXPIRES_AFTER_SECONDS", ""),
]);
let got = filer_signing_from(&env, Some(&path)).unwrap();
assert_eq!(got.key, "file-key");
assert_eq!(got.expires_after_seconds, 5);
assert_eq!(got.source, path.display().to_string());
}
#[test]
fn discovers_the_file_in_the_working_directory_then_home() {
let work = tempfile::TempDir::new().unwrap();
let home = tempfile::TempDir::new().unwrap();
std::fs::create_dir(home.path().join(".seaweedfs")).unwrap();
let in_home = home
.path()
.join(".seaweedfs")
.join(location::SECURITY_CONFIG_FILE_NAME);
std::fs::write(&in_home, "[jwt.filer_signing]\nkey = \"home-key\"\n").unwrap();
let vars = [("HOME", home.path().to_str().unwrap())];
let env = env_of(&vars);
let got = filer_signing_in(&env, Some(work.path())).unwrap();
assert_eq!(got.key, "home-key");
assert_eq!(got.source, in_home.display().to_string());
write(&work, "[jwt.filer_signing]\nkey = \"work-key\"\n");
assert_eq!(
filer_signing_in(&env, Some(work.path())).unwrap().key,
"work-key"
);
}
#[test]
fn nothing_configured_is_none() {
let dir = tempfile::TempDir::new().unwrap();
let other_section = write(&dir, "[jwt.signing]\nkey = \"volume-key\"\n");
assert_eq!(filer_signing_from(&env_of(&[]), Some(&other_section)), None);
assert_eq!(filer_signing_from(&env_of(&[]), None), None);
let empty = env_of(&[("WEED_JWT_FILER_SIGNING_KEY", "")]);
assert_eq!(filer_signing_from(&empty, None), None);
}
}
+2 -15
View File
@@ -3,9 +3,6 @@ use std::time::{SystemTime, UNIX_EPOCH};
use aws_lc_rs::hmac;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
/// 9999-12-31T23:59:59Z; golang-jwt reads `exp` through float64 and time.Unix.
const MAX_EXP_SECS: u64 = 253_402_300_799;
/// Mints the HS256 Bearer token the admin control stream requires when
/// jwt.filer_signing.key is configured, matching the SeaweedFilerAdminClaims
/// the Go worker sends: registered claims only, no session id.
@@ -18,8 +15,7 @@ pub fn admin_token(signing_key: &[u8], expires_after_secs: u64) -> Option<String
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or_default()
.saturating_add(expires_after_secs)
.min(MAX_EXP_SECS);
+ expires_after_secs;
format!("{{\"exp\":{exp}}}")
} else {
"{}".to_string()
@@ -46,7 +42,7 @@ pub fn derive_key(signing_key: &[u8], purpose: &str) -> Vec<u8> {
#[cfg(test)]
mod tests {
use super::{admin_token, derive_key, MAX_EXP_SECS};
use super::{admin_token, derive_key};
#[test]
fn derive_key_matches_the_go_derivation() {
@@ -79,13 +75,4 @@ mod tests {
let claims = URL_SAFE_NO_PAD.decode(payload).unwrap();
assert_eq!(claims, b"{}");
}
#[test]
fn huge_expiry_is_capped() {
let token = admin_token(b"secret", u64::MAX).unwrap();
let payload = token.split('.').nth(1).unwrap();
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
let claims = URL_SAFE_NO_PAD.decode(payload).unwrap();
assert_eq!(claims, format!("{{\"exp\":{MAX_EXP_SECS}}}").as_bytes());
}
}
+1 -41
View File
@@ -22,14 +22,11 @@ path = "src/main.rs"
seaweed-common = { path = "../../../seaweed-common" }
seaweed-worker-core = { path = "../core" }
seaweed-worker-sort = { path = "../sort" }
sw-client = { path = "../sw-client" }
prometheus.workspace = true
# Only the S3 backend: the other object stores lance enables by default are
# build time this worker never spends.
lance = { version = "10", default-features = false, features = ["aws"] }
lance-index = "10"
lance-linalg = "10"
roaring = "0.11"
# For the manifest's own fragment type, which the sort marker summarises.
lance-table = "10"
# For the execution options the sort needs; the scanner's own stream helper
@@ -48,51 +45,14 @@ serde_json = "1"
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
# Reads straight from the filer and volume servers: object_store's trait,
# the gateway's object attributes and ETags, and a read JWT per volume read.
object_store = "0.13"
bytes = "1"
moka = { version = "0.12", features = ["sync"] }
jsonwebtoken = { version = "10", features = ["rust_crypto"] }
md-5 = "0.10"
hex = "0.4"
base64 = "0.22"
# The S3 gateway's SSE-S3 envelope: AES-256-GCM wraps keys, AES-256-CTR wraps
# bytes, HMAC-SHA256 commits them; the filer's volume encryption is AES-256-GCM.
aes = "0.8"
ctr = "0.9"
aes-gcm = "0.10"
hmac = "0.12"
sha2 = "0.10"
hkdf = "0.12"
flate2 = "1"
zstd = "0.13"
# security.toml and the gRPC TLS weed processes use with it: the client
# connector with the server allowlist, and the acceptor the engine serves with.
toml = "0.8"
rustls = "0.23"
tokio-rustls = "0.26"
x509-parser = "0.16"
tower = "0.5"
hyper-util = { version = "0.1", features = ["tokio"] }
http = "1"
tonic.workspace = true
tonic-prost.workspace = true
prost.workspace = true
tokio-stream.workspace = true
[build-dependencies]
tonic-prost-build.workspace = true
protoc-bin-vendored = "3"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
tokio = { workspace = true }
tonic.workspace = true
arrow-array = "58"
arrow-schema = "58"
arrow-cast = "58"
lance-linalg = "10"
tempfile = "3"
[lints]
workspace = true
-29
View File
@@ -1,29 +0,0 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Use the protoc that ships with protoc-bin-vendored rather than a system
// one, so the build needs no package manager and always sees the same
// version. An explicit PROTOC still wins, for packagers supplying their own
// and for the lance crates, whose own build scripts read the same variable.
if std::env::var_os("PROTOC").is_none() {
// SAFETY: a build script's main runs single-threaded before anything
// else in this process, so no other thread can be reading the
// environment concurrently.
unsafe {
std::env::set_var("PROTOC", protoc_bin_vendored::protoc_bin_path()?);
}
}
// The master's ListClusterNodes, for the filers; master.proto brings the
// two it imports.
tonic_prost_build::configure()
.build_server(false)
.build_client(true)
.compile_protos(
&[
"../../../weed/pb/master.proto",
"../../../weed/pb/volume_server.proto",
"../../../weed/pb/remote.proto",
],
&["../../../weed/pb/"],
)?;
println!("cargo:rerun-if-changed=../../../weed/pb/master.proto");
Ok(())
}
@@ -67,6 +67,7 @@ struct ListTablesResponse {
pub struct NamespaceClient {
base_url: String,
http: reqwest::Client,
api_key: Option<String>,
signing_key: Option<SigningKey>,
}
@@ -103,10 +104,29 @@ impl NamespaceClient {
Self {
base_url: base_url.into().trim_end_matches('/').to_string(),
http,
api_key: None,
signing_key: None,
}
}
/// The catalog accepts an S3 credential as `x-api-key`; where the worker
/// already holds one for storage it authenticates the namespace calls too.
pub fn with_fallback(mut self, fallback: &crate::dataset::FallbackOptions) -> Self {
if let (Some(access), Some(secret)) = (
fallback.get("aws_access_key_id"),
fallback.get("aws_secret_access_key"),
) {
if !protected_transport(&self.base_url) {
tracing::warn!(
"catalog url {} exposes the x-api-key credential in cleartext",
self.base_url
);
}
self.api_key = Some(format!("{access}:{secret}"));
}
self
}
pub fn with_signing_key(mut self, signing_key: Option<&SigningKey>) -> Self {
if signing_key.is_some() && !protected_transport(&self.base_url) {
tracing::warn!(
@@ -119,6 +139,10 @@ impl NamespaceClient {
}
fn authed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
let request = match &self.api_key {
Some(key) => request.header("x-api-key", key),
None => request,
};
match self.signing_key.as_ref().and_then(SigningKey::token) {
Some(token) => request.header(CLUSTER_TOKEN_HEADER, token),
None => request,
-293
View File
@@ -1,293 +0,0 @@
//! The cluster as a Lance process joins it: the masters dialed as weed
//! clients dial them, the filers they list, and the storage connection built
//! from them and security.toml that the engine, the worker and the CLI share.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use tonic::transport::{Channel, Endpoint};
use crate::direct_read::{Connection, DirectReads, FilerDialer};
use crate::grpc_tls;
use crate::master_pb::{ListClusterNodesRequest, seaweed_client::SeaweedClient};
use crate::security::{GrpcTls, Security};
/// Masters are configured by their HTTP address; gRPC lives +10000 like the
/// weed conventions (server_address.ToGrpcAddress).
// A master address may carry an explicit gRPC port as `host:http.grpc` —
// use it directly; otherwise the gRPC port is http + 10000.
pub fn grpc_addr(master: &str) -> Result<String> {
let (scheme, rest) = master.split_once("://").unwrap_or(("http", master));
if let Some((host, port)) = rest.rsplit_once(':') {
if let Some((_, grpc)) = port.split_once('.') {
if let Ok(grpc) = grpc.parse::<u64>() {
let grpc = u16::try_from(grpc)
.with_context(|| format!("master {master}: gRPC port {grpc} is past 65535"))?;
return Ok(format!("{scheme}://{host}:{grpc}"));
}
}
if let Ok(port) = port.parse::<u64>() {
let grpc = port
.checked_add(10000)
.and_then(|grpc| u16::try_from(grpc).ok())
.with_context(|| {
format!(
"master {master}: gRPC port {port}+10000 is past 65535; \
give it explicitly as {host}:{port}.<grpc port>"
)
})?;
return Ok(format!("{scheme}://{host}:{grpc}"));
}
}
Ok(format!("{scheme}://{rest}"))
}
/// Bounds the credential reads and the connect, TLS handshake included, and
/// then the master's first answer, the 5s wdclient gives a master call; a
/// black-holed or silent master otherwise holds up the other masters.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// A channel to the master's gRPC, over TLS with `grpc.client`'s credentials
/// when the cluster has them.
pub async fn connect(master: &str, tls: Option<&GrpcTls>) -> Result<Channel> {
let addr = grpc_addr(master)?;
tokio::time::timeout(CONNECT_TIMEOUT, async {
Ok(match tls {
None => Endpoint::new(addr)?.connect().await?,
// The connector does the TLS; tonic adds its own only for an
// https URI, which it refuses without a tls_config.
Some(tls) => {
Endpoint::new(addr.replacen("https://", "http://", 1))?
.connect_with_connector(grpc_tls::connector(tls.clone()))
.await?
}
})
})
.await
.context("master did not complete the connection")?
}
/// The filers of `filer_group` registered with the masters, as gRPC
/// `host:port`s, in registration order; the masters are all asked, since a
/// follower may know fewer than the leader. An error means no master answered.
pub async fn list_filers(
masters: &[String],
filer_group: &str,
tls: Option<&GrpcTls>,
) -> Result<Vec<String>> {
let mut filers = Vec::new();
let mut answered = false;
let mut last = None;
for master in masters {
match filers_of(master, filer_group, tls).await {
Ok(found) => {
answered = true;
for filer in found {
if !filers.contains(&filer) {
filers.push(filer);
}
}
}
Err(err) => {
tracing::warn!("master {master}: listing filers: {err:#}");
last = Some(err);
}
}
}
match (answered, last) {
(false, Some(err)) => Err(err),
(false, None) => Err(anyhow::anyhow!("no master given")),
_ => Ok(filers),
}
}
async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Result<Vec<String>> {
let channel = connect(master, tls).await?;
let request = ListClusterNodesRequest {
client_type: "filer".into(),
filer_group: filer_group.into(),
..Default::default()
};
let nodes = tokio::time::timeout(
CONNECT_TIMEOUT,
SeaweedClient::new(channel).list_cluster_nodes(request),
)
.await
.context("master did not answer")??
.into_inner()
.cluster_nodes;
Ok(nodes
.iter()
.filter_map(|node| match filer_grpc_addr(&node.address) {
Ok(addr) => Some(addr),
Err(err) => {
tracing::warn!("master {master} lists filer {:?}: {err:#}", node.address);
None
}
})
.collect())
}
/// A filer registers as `host:port.grpc`, or `host:port` with its gRPC at
/// port + 10000.
pub fn filer_grpc_addr(address: &str) -> Result<String> {
let addr = grpc_addr(address)?;
Ok(addr
.split_once("://")
.map_or(addr.as_str(), |(_, rest)| rest)
.to_string())
}
/// How often the masters are asked for the filers.
const FILER_REFRESH: Duration = Duration::from_secs(30);
/// How long startup waits for a filer to be registered.
const FILER_WAIT: Duration = Duration::from_secs(120);
/// The filers the masters list, waiting for the first to register.
async fn discover_filers(
masters: &[String],
filer_group: &str,
tls: Option<&GrpcTls>,
) -> Result<Vec<String>> {
let deadline = tokio::time::Instant::now() + FILER_WAIT;
loop {
match list_filers(masters, filer_group, tls).await {
Ok(filers) if !filers.is_empty() => return Ok(filers),
Ok(_) => tracing::warn!("no filer is registered with the masters yet"),
Err(err) => tracing::warn!("listing filers: {err:#}"),
}
if tokio::time::Instant::now() >= deadline {
anyhow::bail!("no filer registered with the masters within {FILER_WAIT:?}");
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
async fn follow_filers(
reads: DirectReads,
masters: Vec<String>,
filer_group: String,
tls: Option<GrpcTls>,
) {
loop {
tokio::time::sleep(FILER_REFRESH).await;
match list_filers(&masters, &filer_group, tls.as_ref()).await {
Ok(filers) if !filers.is_empty() => {
if let Err(err) = reads.set_filers(&filers) {
tracing::warn!("filers {}: {err:#}", filers.join(","));
}
}
// Keep the last known filers while the masters list none.
Ok(_) => tracing::warn!("the masters list no filer; keeping the known ones"),
Err(err) => tracing::warn!("listing filers: {err:#}"),
}
}
}
/// The comma-separated masters, each with a valid gRPC address.
pub fn master_addresses(masters: &str) -> Result<Vec<String>> {
let masters: Vec<String> = masters
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
if masters.is_empty() {
anyhow::bail!("the master list names no master address");
}
for master in &masters {
grpc_addr(master)?;
}
Ok(masters)
}
/// What the cluster's storage is reached with: the filers the masters list,
/// dialed as the masters are, and the keys security.toml holds.
pub struct Cluster {
pub masters: Vec<String>,
pub filer_group: String,
/// `grpc.client`'s credentials for the masters, when the cluster has them.
pub master_tls: Option<GrpcTls>,
}
impl Cluster {
pub fn new(masters: &str, filer_group: &str, security: &Security) -> Result<Self> {
Ok(Self {
masters: master_addresses(masters)?,
filer_group: filer_group.to_string(),
master_tls: security.grpc_client_tls("grpc.client", "grpc.master")?,
})
}
/// Connects to the cluster's storage and follows the masters' filer list.
/// Chunks are encrypted for the volume servers when the filer is
/// configured to (`weed filer -encryptVolumeData`), as `weed s3` does.
pub async fn storage(&self, security: &Security) -> Result<DirectReads> {
// The filers are dialed as the masters are: grpc.client's credentials
// and server allowlist, through this crate's own connector.
let filer_dialer: Option<FilerDialer> = security
.grpc_client_tls("grpc.client", "grpc.filer")?
.map(|tls| {
Arc::new(move |addr: &str| {
let channel = Endpoint::new(format!("http://{addr}"))?
.connect_timeout(Duration::from_secs(10))
.connect_with_connector_lazy(grpc_tls::connector(tls.clone()));
Ok(sw_client::FilerClient::from_channel(addr, channel))
}) as FilerDialer
});
let conn = Connection {
filers: discover_filers(&self.masters, &self.filer_group, self.master_tls.as_ref())
.await?,
read_jwt_key: security.jwt_read_key(),
sse: security.sse(),
grpc_tls: None,
https_tls: security.https_client_tls()?,
filer_dialer,
filer_group: self.filer_group.clone(),
};
let storage = DirectReads::connect(&conn)
.await
.context("direct storage")?;
tracing::info!(
"tables kept through {storage:?}; filer gRPC {}, volume servers {}; SSE-S3 objects {}",
if conn.filer_dialer.is_some() {
"over TLS"
} else {
"plaintext"
},
if conn.https_tls.is_some() {
"over HTTPS"
} else {
"over HTTP"
},
if storage.sse_s3_configured() {
"are readable"
} else {
"need s3.sse.kek or s3.sse.key"
},
);
tokio::spawn(follow_filers(
storage.clone(),
self.masters.clone(),
self.filer_group.clone(),
self.master_tls.clone(),
));
Ok(storage)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_master_list_is_refused() {
assert!(master_addresses("").is_err());
assert!(master_addresses(" , ").is_err());
assert_eq!(
master_addresses(" m1:9333,,m2:9333 ").unwrap(),
["m1:9333", "m2:9333"]
);
}
}
+109 -78
View File
@@ -1,9 +1,9 @@
//! Opening a Lance dataset on the cluster's storage.
//! Opening a Lance dataset with credentials the namespace vended.
//!
//! The namespace says where a table is; its files are read and written on the
//! filers and volume servers through [`DirectReads`]. The S3 store lance builds
//! for the location is unsigned and never dialed, so no process here holds S3
//! credentials. Tests on an in-process store open without storage.
//! The worker holds no storage credentials of its own: it asks the namespace to
//! describe a table with `vend_credentials`, and the `storage_options` that come
//! back are handed to lance as-is. They expire, so a job that runs longer than
//! their lifetime re-describes rather than carrying one set throughout.
use std::collections::HashMap;
use std::sync::Arc;
@@ -15,10 +15,8 @@ use lance::io::{
ObjectStore, ObjectStoreParams, ObjectStoreRegistry, StorageOptionsAccessor,
WrappingObjectStore,
};
use lance::session::Session;
use crate::catalog::{NamespaceClient, TableDescription};
use crate::direct_read::DirectReads;
/// A table the worker is about to work on.
pub struct OpenTable {
@@ -39,43 +37,27 @@ pub struct TableStats {
pub schema: Option<String>,
}
/// Where tables are kept: the cluster's filers and volume servers, or, for
/// tests on an in-process store, nowhere in particular.
#[derive(Clone, Default)]
pub struct Storage(pub Option<DirectReads>);
impl Storage {
/// The store wrapper for a table at `location`, writing as the table's
/// bucket declares.
pub async fn wrapper(&self, location: &str) -> Result<Option<Arc<dyn WrappingObjectStore>>> {
let Some(direct) = &self.0 else {
return Ok(None);
};
let bucket = location
.strip_prefix("s3://")
.and_then(|rest| rest.split('/').next())
.with_context(|| format!("{location} names no bucket"))?;
let sse_s3 = direct.bucket_encrypts(bucket).await?;
Ok(Some(Arc::new(direct.encrypting(sse_s3))))
}
}
/// What lance builds its own S3 store with: unsigned, so it looks for no
/// credentials, and never dialed.
pub fn unsigned_options() -> HashMap<String, String> {
HashMap::from([
("aws_skip_signature".to_string(), "true".to_string()),
("aws_region".to_string(), "us-east-1".to_string()),
("aws_access_key_id".to_string(), String::new()),
("aws_secret_access_key".to_string(), String::new()),
])
}
/// Storage options an operator supplies for deployments that vend none.
pub type FallbackOptions = HashMap<String, String>;
/// Resolve a table through the namespace and open it.
pub async fn open(client: &NamespaceClient, id: &[String], storage: &Storage) -> Result<OpenTable> {
pub async fn open(
client: &NamespaceClient,
id: &[String],
fallback: &FallbackOptions,
) -> Result<OpenTable> {
open_with(client, id, fallback, None).await
}
/// [`open`] with the dataset's object store wrapped, e.g. by a read cache.
pub async fn open_with(
client: &NamespaceClient,
id: &[String],
fallback: &FallbackOptions,
wrapper: Option<Arc<dyn WrappingObjectStore>>,
) -> Result<OpenTable> {
let description = client.describe_table(id).await?;
let wrapper = storage.wrapper(&description.location).await?;
let dataset = open_at(&description, wrapper, None).await?;
let dataset = open_at(&description, fallback, wrapper).await?;
Ok(OpenTable {
id: id.to_vec(),
location: description.location,
@@ -83,57 +65,73 @@ pub async fn open(client: &NamespaceClient, id: &[String], storage: &Storage) ->
})
}
/// Open a table the caller has already resolved, with the store wrapped, in
/// `session` when given, otherwise in a session of its own.
pub async fn open_at(
/// The object_store options for a table. The namespace vends object_store's own
/// option names, so they pass straight through. What it vends always wins: the
/// fallback exists because a deployment without STS vends no credentials at
/// all, and then the worker has no other way to reach the data.
pub fn table_options(
description: &TableDescription,
wrapper: Option<Arc<dyn WrappingObjectStore>>,
session: Option<Arc<Session>>,
) -> Result<Dataset> {
let mut builder =
DatasetBuilder::from_uri(&description.location).with_store_params(store_params(wrapper));
if let Some(session) = session {
builder = builder.with_session(session);
fallback: &FallbackOptions,
) -> HashMap<String, String> {
let mut options: HashMap<String, String> = fallback.clone();
options.extend(description.storage_options.clone());
// A store that takes unsigned requests needs no credentials, but without
// any lance builds the AWS default chain, and that probes instance
// metadata on every open.
if options
.get("aws_skip_signature")
.is_some_and(|v| v == "true")
{
options.entry("aws_access_key_id".into()).or_default();
options.entry("aws_secret_access_key".into()).or_default();
}
builder
options
}
async fn open_at(
description: &TableDescription,
fallback: &FallbackOptions,
wrapper: Option<Arc<dyn WrappingObjectStore>>,
) -> Result<Dataset> {
DatasetBuilder::from_uri(&description.location)
.with_store_params(ObjectStoreParams {
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
table_options(description, fallback),
))),
object_store_wrapper: wrapper,
..Default::default()
})
.load()
.await
.with_context(|| format!("open lance dataset at {}", description.location))
}
/// The store parameters every open and write uses.
pub fn store_params(wrapper: Option<Arc<dyn WrappingObjectStore>>) -> ObjectStoreParams {
ObjectStoreParams {
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
unsigned_options(),
))),
object_store_wrapper: wrapper,
..Default::default()
}
}
/// Remove every object under a table's location. A table the catalog can no
/// longer describe is already dropped, so the call stays idempotent.
pub async fn drop(client: &NamespaceClient, id: &[String], storage: &Storage) -> Result<()> {
pub async fn drop(
client: &NamespaceClient,
id: &[String],
fallback: &FallbackOptions,
) -> Result<()> {
let description = match client.describe_table(id).await {
Ok(description) => description,
Err(err) if describe_not_found(&err) => return Ok(()),
Err(err) => return Err(err),
};
check_drop_location(id, &description.location)?;
match &storage.0 {
Some(direct) => direct.remove_table(&description.location).await,
None => {
let (store, path) = ObjectStore::from_uri_and_params(
Arc::new(ObjectStoreRegistry::default()),
&description.location,
&store_params(None),
)
.await?;
store.remove_dir_all(path).await?;
Ok(())
}
}
let (store, path) = ObjectStore::from_uri_and_params(
Arc::new(ObjectStoreRegistry::default()),
&description.location,
&ObjectStoreParams {
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
table_options(&description, fallback),
))),
..Default::default()
},
)
.await?;
store.remove_dir_all(path).await?;
Ok(())
}
/// Where the catalog puts a table it was given no location for, as the
@@ -220,12 +218,45 @@ fn schema_json(dataset: &Dataset) -> Option<String> {
#[cfg(test)]
mod tests {
use super::{check_drop_location, table_location};
use super::{FallbackOptions, check_drop_location, table_location, table_options};
use crate::catalog::TableDescription;
fn id(parts: &[&str]) -> Vec<String> {
parts.iter().map(|part| part.to_string()).collect()
}
fn options(pairs: &[(&str, &str)]) -> FallbackOptions {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
#[test]
fn table_options_keep_an_unsigned_store_off_the_aws_default_chain() {
let described = |vended: &[(&str, &str)]| TableDescription {
location: "s3://bkt/vector/x".into(),
storage_options: options(vended),
managed_versioning: false,
};
let unsigned = described(&[("aws_skip_signature", "true")]);
let got = table_options(&unsigned, &FallbackOptions::new());
assert_eq!(got.get("aws_access_key_id").map(String::as_str), Some(""));
assert_eq!(
got.get("aws_secret_access_key").map(String::as_str),
Some("")
);
let fallback = options(&[("aws_access_key_id", "k"), ("aws_secret_access_key", "s")]);
let got = table_options(&unsigned, &fallback);
assert_eq!(got.get("aws_access_key_id").map(String::as_str), Some("k"));
let signed = described(&[("aws_endpoint", "http://s3:8333")]);
let got = table_options(&signed, &FallbackOptions::new());
assert!(!got.contains_key("aws_access_key_id"), "{got:?}");
}
#[test]
fn table_location_matches_the_gateway_layout() {
assert_eq!(
File diff suppressed because it is too large. Load diff
-948
View File
@@ -1,948 +0,0 @@
//! gRPC TLS the way weed processes do it.
//!
//! Serving: every client must present a certificate chaining to `grpc.ca`,
//! `allowed_commonNames` and `allowed_wildcard_domain` restrict which client
//! identities are served, and the certificate, key and CA files are re-read
//! on a timer and on SIGHUP so rotated files take effect without a restart.
//!
//! Dialing: the server's certificate must chain to `grpc.ca`; it is not
//! checked against the host dialed (weed clients verify the chain only, as
//! `advancedtls.CertVerification`), and `allowed_server_commonNames` /
//! `allowed_server_wildcard_domain` restrict which server identities are
//! accepted. The files are re-read at every dial.
use std::collections::HashSet;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use futures::Stream;
use http::Uri;
use hyper_util::rt::TokioIo;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::verify_server_cert_signed_by_trust_anchor;
use rustls::crypto::{CryptoProvider, aws_lc_rs};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::server::{ParsedCertificate, WebPkiClientVerifier};
use rustls::{
ClientConfig, DigitallySignedStruct, DistinguishedName, RootCertStore, ServerConfig,
SignatureScheme,
};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::server::TlsStream;
use tokio_rustls::{TlsAcceptor, TlsConnector};
use x509_parser::extensions::GeneralName;
use x509_parser::prelude::{FromDer, X509Certificate};
use crate::security::{GrpcServerTls, GrpcTls};
/// `WEED_TLS_CERT_REFRESH_INTERVAL`, the cadence weed's PEM providers re-read
/// certificate files at; a Go duration such as `30m` or `500ms`.
pub const REFRESH_INTERVAL_ENV: &str = "WEED_TLS_CERT_REFRESH_INTERVAL";
const DEFAULT_REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 3600);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// How often the files are re-read: the environment's value, else weed's
/// default of five hours.
pub fn refresh_interval() -> Duration {
std::env::var(REFRESH_INTERVAL_ENV)
.ok()
.and_then(|s| parse_go_duration(&s))
.filter(|d| !d.is_zero())
.unwrap_or(DEFAULT_REFRESH_INTERVAL)
}
/// `time.ParseDuration`, with its arithmetic: an optional `+`, then a
/// sequence of `<number><unit>`, summed in whole nanoseconds (a fraction of
/// one is dropped) up to `i64::MAX`. A negative value is `None`, as weed
/// ignores one.
fn parse_go_duration(s: &str) -> Option<Duration> {
const LIMIT: u64 = 1 << 63;
let digits = |s: &str| s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
let mut rest = s.strip_prefix('+').unwrap_or(s);
if rest == "0" {
return Some(Duration::ZERO);
}
if rest.is_empty() {
return None;
}
let mut total: u64 = 0;
while !rest.is_empty() {
let (whole, tail) = rest.split_at(digits(rest));
let mut v: u64 = 0;
for c in whole.bytes() {
if v > LIMIT / 10 {
return None;
}
v = v * 10 + u64::from(c - b'0');
if v > LIMIT {
return None;
}
}
let (mut fraction, mut scale) = (0u64, 1f64);
let (fraction_digits, tail) = match tail.strip_prefix('.') {
Some(tail) => tail.split_at(digits(tail)),
None => ("", tail),
};
let mut overflow = false;
for c in fraction_digits.bytes() {
if overflow || fraction > (LIMIT - 1) / 10 {
overflow = true;
continue;
}
let next = fraction * 10 + u64::from(c - b'0');
if next > LIMIT {
overflow = true;
continue;
}
fraction = next;
scale *= 10.0;
}
if whole.is_empty() && fraction_digits.is_empty() {
return None;
}
let unit_len = tail
.find(|c: char| c == '.' || c.is_ascii_digit())
.unwrap_or(tail.len());
let (unit, tail) = tail.split_at(unit_len);
let unit: u64 = match unit {
"ns" => 1,
"us" | "\u{b5}s" | "\u{3bc}s" => 1_000,
"ms" => 1_000_000,
"s" => 1_000_000_000,
"m" => 60_000_000_000,
"h" => 3_600_000_000_000,
_ => return None,
};
if v > LIMIT / unit {
return None;
}
v *= unit;
if fraction > 0 {
v += (fraction as f64 * (unit as f64 / scale)) as u64;
if v > LIMIT {
return None;
}
}
total = total.checked_add(v).filter(|&total| total <= LIMIT)?;
rest = tail;
}
(total < LIMIT).then(|| Duration::from_nanos(total))
}
/// The listener's TLS configuration, rebuilt from the files whenever they
/// change.
pub struct ServerTls {
files: GrpcServerTls,
config: RwLock<Arc<ServerConfig>>,
/// The file contents the current configuration was built from.
loaded: Mutex<Vec<u8>>,
}
impl std::fmt::Debug for ServerTls {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServerTls")
.field("files", &self.files)
.finish_non_exhaustive()
}
}
fn read(key: &str, path: &str) -> Result<Vec<u8>> {
std::fs::read(path).with_context(|| format!("{key} = {path:?}"))
}
fn read_all(files: &GrpcServerTls) -> Result<Vec<u8>> {
let mut all = Vec::new();
for (key, path) in [
("cert", &files.cert_path),
("key", &files.key_path),
("grpc.ca", &files.ca_path),
] {
all.extend(read(key, path)?);
all.push(0);
}
Ok(all)
}
fn cert_chain(key: &str, path: &str, pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(pem)
.collect::<Result<_, _>>()
.with_context(|| format!("{key} = {path:?}"))?;
if chain.is_empty() {
bail!("{key} = {path:?} holds no certificate");
}
Ok(chain)
}
fn private_key(key: &str, path: &str, pem: &[u8]) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_slice(pem).with_context(|| format!("{key} = {path:?}"))
}
fn root_store(path: &str, pem: &[u8]) -> Result<RootCertStore> {
let mut roots = RootCertStore::empty();
for cert in cert_chain("grpc.ca", path, pem)? {
roots
.add(cert)
.with_context(|| format!("grpc.ca = {path:?}"))?;
}
Ok(roots)
}
/// Builds the configuration `security.LoadServerTLS` would: the identity in
/// `cert`/`key`, every client verified against `grpc.ca`, and the client's
/// common name checked against the allowlist when one is set.
fn build_config(files: &GrpcServerTls) -> Result<ServerConfig> {
let cert_chain = cert_chain("cert", &files.cert_path, &read("cert", &files.cert_path)?)?;
let key = private_key("key", &files.key_path, &read("key", &files.key_path)?)?;
let roots = root_store(&files.ca_path, &read("grpc.ca", &files.ca_path)?)?;
let verifier = WebPkiClientVerifier::builder(Arc::new(roots))
.build()
.context("client certificate verifier")?;
let verifier: Arc<dyn ClientCertVerifier> =
if files.allowed_common_names.is_empty() && files.allowed_wildcard_domain.is_empty() {
verifier
} else {
Arc::new(CommonNameVerifier {
inner: verifier,
allowed_common_names: files.allowed_common_names.iter().cloned().collect(),
allowed_wildcard_domain: files.allowed_wildcard_domain.clone(),
})
};
let mut config = ServerConfig::builder()
.with_client_cert_verifier(verifier)
.with_single_cert(cert_chain, key)
.context("server certificate")?;
config.alpn_protocols = vec![b"h2".to_vec()];
Ok(config)
}
impl ServerTls {
pub fn load(files: GrpcServerTls) -> Result<Arc<Self>> {
crate::tls::install_default_crypto_provider();
let loaded = read_all(&files)?;
let config = build_config(&files)?;
Ok(Arc::new(Self {
files,
config: RwLock::new(Arc::new(config)),
loaded: Mutex::new(loaded),
}))
}
pub fn files(&self) -> &GrpcServerTls {
&self.files
}
/// Re-reads the files; when they changed, the next handshake uses them.
/// Returns whether they had. A file that no longer parses is an error,
/// and the configuration in use stays.
pub fn reload(&self) -> Result<bool> {
let current = read_all(&self.files)?;
let mut loaded = self.loaded.lock().unwrap_or_else(|e| e.into_inner());
if *loaded == current {
return Ok(false);
}
let config = build_config(&self.files)?;
*self.config.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(config);
*loaded = current;
Ok(true)
}
pub fn acceptor(&self) -> TlsAcceptor {
TlsAcceptor::from(
self.config
.read()
.unwrap_or_else(|e| e.into_inner())
.clone(),
)
}
/// Connections accepted on `listener` and taken through the TLS
/// handshake with the configuration current at that moment. Each
/// handshake runs on its own task under `HANDSHAKE_TIMEOUT`, so a peer
/// that connects and stays silent holds up nobody else; a failed
/// handshake is logged and skipped, as the Rust volume server does.
pub fn incoming(
self: &Arc<Self>,
listener: TcpListener,
) -> impl Stream<Item = std::io::Result<TlsStream<TcpStream>>> + Send + 'static {
let tls = self.clone();
let (tx, rx) = tokio::sync::mpsc::channel(64);
tokio::spawn(async move {
loop {
let accepted = tokio::select! {
_ = tx.closed() => return,
accepted = listener.accept() => accepted,
};
let (stream, peer) = match accepted {
Ok(accepted) => accepted,
Err(err) => {
let _ = tx.send(Err(err)).await;
continue;
}
};
let _ = stream.set_nodelay(true);
let acceptor = tls.acceptor();
let tx = tx.clone();
tokio::spawn(async move {
match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)).await {
Ok(Ok(stream)) => {
let _ = tx.send(Ok(stream)).await;
}
Ok(Err(err)) => tracing::debug!("gRPC TLS handshake from {peer}: {err}"),
Err(_) => tracing::debug!("gRPC TLS handshake from {peer} timed out"),
}
});
}
});
tokio_stream::wrappers::ReceiverStream::new(rx)
}
/// Re-reads the files every `every`, and at once on SIGHUP.
pub async fn refresh(self: Arc<Self>, every: Duration) {
#[cfg(unix)]
let mut hangup =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup()).ok();
loop {
#[cfg(unix)]
{
tokio::select! {
_ = tokio::time::sleep(every) => {}
_ = async { match hangup.as_mut() { Some(h) => h.recv().await, None => std::future::pending().await } } => {
tracing::info!("SIGHUP: re-reading gRPC TLS files");
}
}
}
#[cfg(not(unix))]
tokio::time::sleep(every).await;
match self.reload() {
Ok(true) => tracing::info!("gRPC TLS files changed; new handshakes use them"),
Ok(false) => {}
Err(err) => tracing::warn!("gRPC TLS files not reloaded: {err:#}"),
}
}
}
}
/// `security.Authenticator` for client certificates: after the chain is
/// verified, the subject common name must be allowed, or lie under the
/// wildcard domain.
#[derive(Debug)]
struct CommonNameVerifier {
inner: Arc<dyn ClientCertVerifier>,
allowed_common_names: HashSet<String>,
allowed_wildcard_domain: String,
}
impl ClientCertVerifier for CommonNameVerifier {
fn offer_client_auth(&self) -> bool {
self.inner.offer_client_auth()
}
fn client_auth_mandatory(&self) -> bool {
self.inner.client_auth_mandatory()
}
fn root_hint_subjects(&self) -> &[DistinguishedName] {
self.inner.root_hint_subjects()
}
fn verify_client_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
now: UnixTime,
) -> Result<ClientCertVerified, rustls::Error> {
self.inner
.verify_client_cert(end_entity, intermediates, now)?;
let common_name = parse_common_name(end_entity).map_err(|e| {
rustls::Error::General(format!("parse client certificate common name failed: {e}"))
})?;
if common_name_is_allowed(
&common_name,
&self.allowed_common_names,
&self.allowed_wildcard_domain,
) {
return Ok(ClientCertVerified::assertion());
}
Err(rustls::Error::General(format!(
"Authenticate: invalid subject client common name: {common_name}"
)))
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
self.inner.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
self.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.inner.supported_verify_schemes()
}
}
/// The client configuration `security.LoadClientTLS` would build, from the
/// CA, certificate and key as `pems` holds them.
fn client_config(
files: &GrpcTls,
(ca, cert, key): (Vec<u8>, Vec<u8>, Vec<u8>),
) -> Result<ClientConfig> {
crate::tls::install_default_crypto_provider();
let verifier = ServerIdentityVerifier {
roots: Arc::new(root_store(&files.ca_path, &ca)?),
provider: Arc::new(aws_lc_rs::default_provider()),
allowed_names: files.allowed_server_names.iter().cloned().collect(),
allowed_wildcard_domain: files.allowed_server_wildcard_domain.clone(),
};
let mut config = ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier))
.with_client_auth_cert(
cert_chain("cert", &files.cert_path, &cert)?,
private_key("key", &files.key_path, &key)?,
)
.context("client certificate")?;
config.alpn_protocols = vec![b"h2".to_vec()];
Ok(config)
}
/// The host of a gRPC address, without an IPv6 address's brackets.
fn dialed_host(uri: &Uri) -> Option<&str> {
Some(uri.host()?.trim_matches(|c| c == '[' || c == ']'))
}
/// A tonic connector for `Endpoint::connect_with_connector`: the files read
/// as they are now, so rotated credentials are picked up, then TCP to the
/// URI's host and port and the handshake under [`client_config`].
pub fn connector(
files: GrpcTls,
) -> impl tower::Service<
Uri,
Response = TokioIo<tokio_rustls::client::TlsStream<TcpStream>>,
Error = Box<dyn std::error::Error + Send + Sync>,
Future = impl Send,
> + Clone
+ Send
+ 'static {
tower::service_fn(move |uri: Uri| {
let files = files.clone();
async move {
let host = dialed_host(&uri).ok_or("no host in gRPC address")?;
let port = uri.port_u16().unwrap_or(443);
let config = Arc::new(client_config(&files, files.pems().await?)?);
let stream = TcpStream::connect((host, port)).await?;
let _ = stream.set_nodelay(true);
let name = ServerName::try_from(host.to_string())?;
let stream = TlsConnector::from(config).connect(name, stream).await?;
Ok(TokioIo::new(stream))
}
})
}
/// `security.Authenticator.AuthenticateServer`: the chain must reach
/// `grpc.ca`, the host dialed is not checked, and when an allowlist is set the
/// common name or a DNS SAN must be allowed or lie under the wildcard domain,
/// while a URI SAN must be allowed exactly.
#[derive(Debug)]
struct ServerIdentityVerifier {
roots: Arc<RootCertStore>,
provider: Arc<CryptoProvider>,
allowed_names: HashSet<String>,
allowed_wildcard_domain: String,
}
impl ServerCertVerifier for ServerIdentityVerifier {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
let cert = ParsedCertificate::try_from(end_entity)?;
verify_server_cert_signed_by_trust_anchor(
&cert,
&self.roots,
intermediates,
now,
self.provider.signature_verification_algorithms.all,
)?;
if self.allowed_names.is_empty() && self.allowed_wildcard_domain.is_empty() {
return Ok(ServerCertVerified::assertion());
}
let (names, uris) = server_identities(end_entity)
.map_err(|e| rustls::Error::General(format!("parse server certificate failed: {e}")))?;
if names.iter().any(|name| {
self.allowed_names.contains(name)
|| wildcard_domain_matches(name, &self.allowed_wildcard_domain)
}) || uris.iter().any(|uri| self.allowed_names.contains(uri))
{
return Ok(ServerCertVerified::assertion());
}
Err(rustls::Error::General(format!(
"AuthenticateServer: untrusted server identity {:?}",
names.into_iter().chain(uris).collect::<Vec<_>>()
)))
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
}
/// The common name and DNS SANs, and the URI SANs, of a certificate.
fn server_identities(cert: &CertificateDer<'_>) -> Result<(Vec<String>, Vec<String>)> {
let (_, certificate) = X509Certificate::from_der(cert.as_ref())
.map_err(|e| anyhow::anyhow!("parse X.509 certificate failed: {e}"))?;
let mut names = vec![
certificate
.subject()
.iter_common_name()
.next()
.and_then(|common_name| common_name.as_str().ok())
.unwrap_or_default()
.to_string(),
];
let mut uris = Vec::new();
if let Ok(Some(san)) = certificate.subject_alternative_name() {
for name in &san.value.general_names {
match name {
GeneralName::DNSName(dns) => names.push(dns.to_string()),
GeneralName::URI(uri) => uris.push(uri.to_string()),
_ => {}
}
}
}
Ok((names, uris))
}
fn parse_common_name(cert: &CertificateDer<'_>) -> Result<String> {
let (_, certificate) = X509Certificate::from_der(cert.as_ref())
.map_err(|e| anyhow::anyhow!("parse X.509 certificate failed: {e}"))?;
Ok(certificate
.subject()
.iter_common_name()
.next()
.and_then(|common_name| common_name.as_str().ok())
.map(str::to_string)
.unwrap_or_default())
}
fn common_name_is_allowed(
common_name: &str,
allowed_common_names: &HashSet<String>,
allowed_wildcard_domain: &str,
) -> bool {
allowed_common_names.contains(common_name)
|| wildcard_domain_matches(common_name, allowed_wildcard_domain)
}
// Mirrors the Go wildcard check: the name must end with the domain, carry a
// non-empty label in front of it, and be a valid DNS name so a CA-signed name
// like ".example.com" cannot satisfy the suffix check. A leading "*." label
// is allowed so wildcard certs keep matching. One trailing root dot is
// ignored on both sides so absolute DNS names still match.
fn wildcard_domain_matches(name: &str, wildcard_domain: &str) -> bool {
let name = name.strip_suffix('.').unwrap_or(name);
let wildcard_domain = wildcard_domain.strip_suffix('.').unwrap_or(wildcard_domain);
if wildcard_domain.is_empty()
|| name.len() <= wildcard_domain.len()
|| !name.ends_with(wildcard_domain)
{
return false;
}
if !wildcard_domain.starts_with('.')
&& name.as_bytes()[name.len() - wildcard_domain.len() - 1] != b'.'
{
return false;
}
is_domain_name(name.strip_prefix("*.").unwrap_or(name))
}
// Mirrors Go's net.IsDomainName: non-empty labels of letters, digits, '-',
// '_', each up to 63 chars and not '-'-edged, with at least one non-digit so
// a bare IP cannot pass a domain wildcard.
fn is_domain_name(name: &str) -> bool {
if name.is_empty() || name.len() > 253 {
return false;
}
let mut non_numeric = false;
let valid = name.split('.').all(|label| {
non_numeric |= label.bytes().any(|c| !c.is_ascii_digit());
!label.is_empty()
&& label.len() <= 63
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
});
valid && non_numeric
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
/// `tests/tls`: a CA and two leaves it signed, `engine-a` and `engine-b`.
fn fixture(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/tls")
.join(name)
}
fn install(dir: &Path, leaf: &str) -> GrpcServerTls {
for (from, to) in [
(format!("{leaf}.pem"), "cert.pem"),
(format!("{leaf}.key"), "key.pem"),
("ca.pem".to_string(), "ca.pem"),
] {
std::fs::copy(fixture(&from), dir.join(to)).unwrap();
}
GrpcServerTls {
cert_path: dir.join("cert.pem").display().to_string(),
key_path: dir.join("key.pem").display().to_string(),
ca_path: dir.join("ca.pem").display().to_string(),
allowed_common_names: Vec::new(),
allowed_wildcard_domain: String::new(),
}
}
#[test]
fn rotated_files_are_picked_up_and_broken_ones_are_not() {
let dir = tempfile::tempdir().unwrap();
let tls = ServerTls::load(install(dir.path(), "a")).unwrap();
assert!(!tls.reload().unwrap(), "unchanged files are not a reload");
let before = tls.acceptor();
install(dir.path(), "b");
assert!(tls.reload().unwrap());
let after = tls.acceptor();
assert!(!Arc::ptr_eq(before.config(), after.config()));
std::fs::write(dir.path().join("key.pem"), "not a key").unwrap();
assert!(tls.reload().is_err());
assert!(
Arc::ptr_eq(after.config(), tls.acceptor().config()),
"a broken file leaves the working configuration in place"
);
}
#[tokio::test]
async fn a_silent_peer_does_not_hold_up_the_next_handshake() {
use futures::StreamExt;
crate::tls::install_default_crypto_provider();
let dir = tempfile::tempdir().unwrap();
let tls = ServerTls::load(install(dir.path(), "a")).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let mut incoming = Box::pin(tls.incoming(listener));
let _silent = TcpStream::connect(addr).await.unwrap();
let mut roots = RootCertStore::empty();
for cert in CertificateDer::pem_file_iter(fixture("ca.pem")).unwrap() {
roots.add(cert.unwrap()).unwrap();
}
let config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_client_auth_cert(
vec![CertificateDer::from_pem_file(fixture("a.pem")).unwrap()],
PrivateKeyDer::from_pem_file(fixture("a.key")).unwrap(),
)
.unwrap();
let client = tokio::spawn(async move {
let tcp = TcpStream::connect(addr).await.unwrap();
tokio_rustls::TlsConnector::from(Arc::new(config))
.connect("localhost".try_into().unwrap(), tcp)
.await
});
let served = tokio::time::timeout(Duration::from_secs(5), incoming.next()).await;
assert!(
matches!(served, Ok(Some(Ok(_)))),
"the handshake waited behind a silent peer"
);
client.await.unwrap().unwrap();
}
#[test]
fn missing_or_empty_files_are_refused() {
let dir = tempfile::tempdir().unwrap();
let mut files = install(dir.path(), "a");
files.ca_path = dir.path().join("absent.pem").display().to_string();
assert!(ServerTls::load(files.clone()).is_err());
std::fs::write(dir.path().join("empty.pem"), "").unwrap();
files.ca_path = dir.path().join("empty.pem").display().to_string();
assert!(ServerTls::load(files).is_err());
}
#[test]
fn client_common_names_follow_the_allowlist() {
crate::tls::install_default_crypto_provider();
let mut roots = RootCertStore::empty();
for cert in CertificateDer::pem_file_iter(fixture("ca.pem")).unwrap() {
roots.add(cert.unwrap()).unwrap();
}
let inner = WebPkiClientVerifier::builder(Arc::new(roots))
.build()
.unwrap();
let leaf = |name: &str| CertificateDer::from_pem_file(fixture(name)).unwrap();
let now = UnixTime::now();
// Without an allowlist any certificate the CA signed is served.
assert!(inner.verify_client_cert(&leaf("a.pem"), &[], now).is_ok());
assert!(inner.verify_client_cert(&leaf("b.pem"), &[], now).is_ok());
let verifier = CommonNameVerifier {
inner,
allowed_common_names: ["engine-a".to_string()].into_iter().collect(),
allowed_wildcard_domain: String::new(),
};
assert!(
verifier
.verify_client_cert(&leaf("a.pem"), &[], now)
.is_ok()
);
let err = verifier
.verify_client_cert(&leaf("b.pem"), &[], now)
.unwrap_err();
assert!(err.to_string().contains("engine-b"), "{err}");
assert_eq!(parse_common_name(&leaf("b.pem")).unwrap(), "engine-b");
}
#[test]
fn server_identities_follow_the_allowlist() {
crate::tls::install_default_crypto_provider();
let leaf = |name: &str| CertificateDer::from_pem_file(fixture(name)).unwrap();
let verifier = |allowed: &[&str], wildcard: &str| ServerIdentityVerifier {
roots: Arc::new(
root_store("ca.pem", &std::fs::read(fixture("ca.pem")).unwrap()).unwrap(),
),
provider: Arc::new(aws_lc_rs::default_provider()),
allowed_names: allowed.iter().map(|s| s.to_string()).collect(),
allowed_wildcard_domain: wildcard.into(),
};
let name = ServerName::try_from("nothing.example").unwrap();
let check = |v: &ServerIdentityVerifier, cert: &str| {
v.verify_server_cert(&leaf(cert), &[], &name, &[], UnixTime::now())
};
// The chain is checked; the host dialed is not.
assert!(check(&verifier(&[], ""), "a.pem").is_ok());
assert!(check(&verifier(&[], ""), "b.pem").is_ok());
assert!(
check(&verifier(&[], ""), "ca.pem").is_err(),
"a root is not a server"
);
// The common name or a DNS SAN must be allowed.
assert!(check(&verifier(&["engine-a"], ""), "a.pem").is_ok());
assert!(check(&verifier(&["localhost"], ""), "b.pem").is_ok());
let err = check(&verifier(&["engine-a"], ""), "b.pem").unwrap_err();
assert!(err.to_string().contains("engine-b"), "{err}");
assert!(check(&verifier(&[], ".example"), "b.pem").is_err());
assert_eq!(
server_identities(&leaf("a.pem")).unwrap(),
(
vec!["engine-a".to_string(), "localhost".to_string()],
vec![]
)
);
}
#[test]
fn the_dialed_host_drops_ipv6_brackets() {
for (addr, host) in [
("http://m1:19333", "m1"),
("http://master.example", "master.example"),
("http://127.0.0.1:19333", "127.0.0.1"),
("http://[::1]:19333", "::1"),
] {
let uri: Uri = addr.parse().unwrap();
assert_eq!(dialed_host(&uri), Some(host), "{addr}");
}
}
fn client(leaf: &str, allowed: &[&str]) -> GrpcTls {
GrpcTls {
ca_path: fixture("ca.pem").display().to_string(),
cert_path: fixture(&format!("{leaf}.pem")).display().to_string(),
key_path: fixture(&format!("{leaf}.key")).display().to_string(),
allowed_server_names: allowed.iter().map(|s| s.to_string()).collect(),
allowed_server_wildcard_domain: String::new(),
}
}
async fn handshake(port: u16, files: &GrpcTls) -> Result<()> {
let config = Arc::new(client_config(files, files.pems().await?)?);
let stream = TcpStream::connect(("127.0.0.1", port)).await?;
let name = ServerName::try_from("127.0.0.1").unwrap();
let mut stream = TlsConnector::from(config).connect(name, stream).await?;
// A server that rejected the client certificate says so after the
// handshake, on the first read.
let mut byte = [0u8; 1];
match tokio::time::timeout(
Duration::from_secs(1),
tokio::io::AsyncReadExt::read(&mut stream, &mut byte),
)
.await
{
Ok(Err(err)) => Err(err.into()),
_ => Ok(()),
}
}
#[tokio::test]
async fn both_sides_check_identities() {
use futures::StreamExt;
let dir = tempfile::tempdir().unwrap();
let mut files = install(dir.path(), "a");
files.allowed_common_names = vec!["engine-b".into()];
let tls = ServerTls::load(files).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let mut incoming = Box::pin(tls.incoming(listener));
// engine-b, trusting the CA, accepts engine-a by name, dialed by IP.
let allowed = client("b", &["engine-a"]);
let (served, dialed) = tokio::join!(
tokio::time::timeout(Duration::from_secs(5), incoming.next()),
handshake(port, &allowed)
);
assert!(dialed.is_ok(), "{dialed:?}");
assert!(matches!(served, Ok(Some(Ok(_)))));
// The client refuses a server outside its allowlist.
let err = handshake(port, &client("b", &["engine-z"]))
.await
.unwrap_err();
assert!(
err.to_string().contains("untrusted server identity"),
"{err}"
);
// The server refuses a client outside its allowlist: engine-a is not
// engine-b.
let outsider = client("a", &[]);
let (served, dialed) = tokio::join!(
tokio::time::timeout(Duration::from_secs(1), incoming.next()),
handshake(port, &outsider)
);
assert!(
dialed.is_err(),
"the server must cut off a client it does not allow"
);
assert!(served.is_err(), "nothing is served for a refused client");
}
#[test]
fn wildcard_domain_matches_like_go() {
let none = HashSet::new();
assert!(common_name_is_allowed("a.internal", &none, ".internal"));
assert!(common_name_is_allowed("a.internal", &none, "internal"));
assert!(common_name_is_allowed("*.internal", &none, ".internal"));
assert!(!common_name_is_allowed("internal", &none, ".internal"));
assert!(!common_name_is_allowed("xinternal", &none, "internal"));
assert!(!common_name_is_allowed("10.0.0.1", &none, "0.0.1"));
assert!(!common_name_is_allowed("a.internal", &none, ""));
let names: HashSet<String> = ["gateway".to_string()].into_iter().collect();
assert!(common_name_is_allowed("gateway", &names, ""));
assert!(!common_name_is_allowed("other", &names, ""));
}
#[test]
fn refresh_interval_reads_go_durations() {
assert_eq!(parse_go_duration("30m"), Some(Duration::from_secs(1800)));
assert_eq!(parse_go_duration("500ms"), Some(Duration::from_millis(500)));
assert_eq!(parse_go_duration("1h30m"), Some(Duration::from_secs(5400)));
assert_eq!(parse_go_duration("2.5s"), Some(Duration::from_millis(2500)));
assert_eq!(parse_go_duration("+2s"), Some(Duration::from_secs(2)));
assert_eq!(
parse_go_duration("1500us"),
Some(Duration::from_micros(1500))
);
assert_eq!(
parse_go_duration("3\u{b5}s"),
Some(Duration::from_micros(3))
);
assert_eq!(
parse_go_duration("3\u{3bc}s"),
Some(Duration::from_micros(3))
);
assert_eq!(parse_go_duration("1s20ns"), Some(Duration::new(1, 20)));
assert_eq!(parse_go_duration("-5m"), None);
assert_eq!(parse_go_duration("99999999999999999999h"), None);
assert_eq!(
parse_go_duration("4000000000000000h4000000000000000h"),
None
);
assert_eq!(parse_go_duration("2d"), None);
assert_eq!(parse_go_duration(""), None);
assert_eq!(parse_go_duration("0"), Some(Duration::ZERO));
assert_eq!(parse_go_duration("0.3s"), Some(Duration::from_millis(300)));
assert_eq!(parse_go_duration("1.1s"), Some(Duration::from_millis(1100)));
assert_eq!(parse_go_duration(".5h"), Some(Duration::from_secs(1800)));
assert_eq!(parse_go_duration("5.s"), Some(Duration::from_secs(5)));
assert_eq!(parse_go_duration(".s"), None);
assert_eq!(parse_go_duration("1.2.3s"), None);
assert_eq!(parse_go_duration(" 30m"), None);
// A fraction of a nanosecond is dropped, so this is zero and the
// default applies, as in weed.
assert_eq!(parse_go_duration("0.9ns"), Some(Duration::ZERO));
assert_eq!(parse_go_duration("1.9ns"), Some(Duration::from_nanos(1)));
// The longest time.Duration, and past it.
assert_eq!(
parse_go_duration("2562047h47m16.854775807s"),
Some(Duration::from_nanos(i64::MAX as u64))
);
assert_eq!(
parse_go_duration("9223372036854775807ns"),
Some(Duration::from_nanos(i64::MAX as u64))
);
assert_eq!(parse_go_duration("9223372036854775808ns"), None);
assert_eq!(parse_go_duration("2562048h"), None);
assert_eq!(parse_go_duration("3000000h"), None);
}
}
@@ -31,7 +31,7 @@ const MAX_MIN_VERSIONS: i64 = 1000;
/// the cluster owned the policy than each writer.
pub struct CleanupVersionsHandler {
namespace_url: String,
storage: dataset::Storage,
fallback: dataset::FallbackOptions,
signing_key: Option<SigningKey>,
metrics: Option<crate::metrics::LanceMetrics>,
}
@@ -40,7 +40,7 @@ impl CleanupVersionsHandler {
pub fn new(namespace_url: String) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
fallback: dataset::FallbackOptions::new(),
signing_key: None,
metrics: None,
}
@@ -51,8 +51,8 @@ impl CleanupVersionsHandler {
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
self.fallback = fallback;
self
}
@@ -62,7 +62,9 @@ impl CleanupVersionsHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
NamespaceClient::new(self.namespace_url.clone())
.with_fallback(&self.fallback)
.with_signing_key(self.signing_key.as_ref())
}
}
@@ -158,7 +160,7 @@ impl JobHandler for CleanupVersionsHandler {
let mut proposals = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &self.fallback).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -254,7 +256,7 @@ impl JobHandler for CleanupVersionsHandler {
) as usize;
let client = self.client();
let table = dataset::open(&client, &id, &self.storage).await?;
let table = dataset::open(&client, &id, &self.fallback).await?;
let before = table.stats().await?;
// The floor is a promise about how much history survives, so it has to
@@ -34,7 +34,7 @@ const MIN_FRAGMENTS_CEILING: i64 = 4096;
/// accumulates small files the same way an Iceberg table does.
pub struct CompactHandler {
namespace_url: String,
storage: dataset::Storage,
fallback: dataset::FallbackOptions,
signing_key: Option<SigningKey>,
metrics: Option<crate::metrics::LanceMetrics>,
}
@@ -43,7 +43,7 @@ impl CompactHandler {
pub fn new(namespace_url: String) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
fallback: dataset::FallbackOptions::new(),
signing_key: None,
metrics: None,
}
@@ -55,8 +55,8 @@ impl CompactHandler {
}
/// Storage options to use where the namespace vends none.
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
self.fallback = fallback;
self
}
@@ -66,7 +66,9 @@ impl CompactHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
NamespaceClient::new(self.namespace_url.clone())
.with_fallback(&self.fallback)
.with_signing_key(self.signing_key.as_ref())
}
}
@@ -152,7 +154,7 @@ impl JobHandler for CompactHandler {
let mut observations = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &self.fallback).await {
Ok(table) => table,
Err(err) => {
// A table that cannot be opened is the next run's problem,
@@ -269,7 +271,7 @@ impl JobHandler for CompactHandler {
let client = self.client();
// Re-resolve rather than trusting the location detection saw: the table
// may have been repointed, and the vended credentials have expired.
let mut table = dataset::open(&client, &id, &self.storage).await?;
let mut table = dataset::open(&client, &id, &self.fallback).await?;
let before = table.stats().await?;
sender.send_progress(JobProgressUpdate {
+34 -131
View File
@@ -6,8 +6,8 @@ use lance::index::DatasetIndexExt;
use lance_index::optimize::OptimizeOptions;
use seaweed_worker_core::config_form::{form, int_or, int_value, number_field};
use seaweed_worker_core::pb::{
AdminRuntimeDefaults, ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest,
JobCompleted, JobProgressUpdate, JobProposal, JobResult, JobTypeCapability, JobTypeDescriptor,
ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest, JobCompleted,
JobProgressUpdate, JobProposal, JobResult, JobTypeCapability, JobTypeDescriptor,
RunDetectionRequest,
};
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
@@ -15,13 +15,9 @@ use tracing::warn;
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
use crate::dataset::{self, OpenTable};
use crate::jobs::vector_index::is_vector_table;
use crate::jobs::{clamp, string_list, table_id};
use crate::vector_index;
pub const JOB_TYPE: &str = "lance_optimize_indices";
/// The vector column the S3 Vectors API writes.
const VECTOR_COLUMN: &str = "vector";
const DEFAULT_MAX_UNINDEXED_ROWS: i64 = 100_000;
@@ -38,7 +34,7 @@ const MAX_UNINDEXED_CEILING: i64 = 100_000_000;
/// slow one.
pub struct OptimizeIndicesHandler {
namespace_url: String,
storage: dataset::Storage,
fallback: dataset::FallbackOptions,
signing_key: Option<SigningKey>,
metrics: Option<crate::metrics::LanceMetrics>,
}
@@ -47,7 +43,7 @@ impl OptimizeIndicesHandler {
pub fn new(namespace_url: String) -> Self {
Self {
namespace_url,
storage: dataset::Storage::default(),
fallback: dataset::FallbackOptions::new(),
signing_key: None,
metrics: None,
}
@@ -58,8 +54,8 @@ impl OptimizeIndicesHandler {
self
}
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
self.storage = storage;
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
self.fallback = fallback;
self
}
@@ -69,38 +65,22 @@ impl OptimizeIndicesHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
NamespaceClient::new(self.namespace_url.clone())
.with_fallback(&self.fallback)
.with_signing_key(self.signing_key.as_ref())
}
}
/// Rows the table's indices cover and rows they miss. A vector table's indices
/// are taken together, since a sharded build gives one name per shard; any
/// other table reports the index that misses the most. A table with no
/// indices at all has nothing to optimize, which is different from a table
/// whose indices have fallen behind.
struct IndexRows {
indexed: u64,
unindexed: u64,
}
async fn index_rows(table: &OpenTable, vector_table: bool) -> Result<Option<IndexRows>> {
if vector_table {
return Ok(vector_index::coverage(&table.dataset, VECTOR_COLUMN)
.await?
.map(|cover| IndexRows {
indexed: cover.indexed_rows,
unindexed: cover.unindexed_rows,
}));
}
/// Rows no index covers, summed across a table's indices. A table with no
/// indices at all has nothing to optimize, which is different from a table whose
/// indices have fallen behind.
async fn unindexed_rows(table: &OpenTable) -> Result<Option<u64>> {
let indices = table.dataset.load_indices().await?;
if indices.is_empty() {
return Ok(None);
}
let mut worst = IndexRows {
indexed: 0,
unindexed: 0,
};
let mut worst = 0u64;
let mut names: Vec<String> = indices.iter().map(|index| index.name.clone()).collect();
names.sort();
names.dedup();
@@ -108,27 +88,15 @@ async fn index_rows(table: &OpenTable, vector_table: bool) -> Result<Option<Inde
let raw = table.dataset.index_statistics(&name).await?;
let stats: serde_json::Value = serde_json::from_str(&raw)
.with_context(|| format!("parse index statistics for {name}"))?;
let count = |key: &str| stats.get(key).and_then(|value| value.as_u64()).unwrap_or(0);
if count("num_unindexed_rows") >= worst.unindexed {
worst = IndexRows {
indexed: count("num_indexed_rows"),
unindexed: count("num_unindexed_rows"),
};
}
let unindexed = stats
.get("num_unindexed_rows")
.and_then(|value| value.as_u64())
.unwrap_or(0);
worst = worst.max(unindexed);
}
Ok(Some(worst))
}
/// A vector index also reindexes once a tenth of it is uncovered, so a small
/// index does not wait for the absolute budget.
fn effective_budget(budget: u64, rows: &IndexRows, vector_table: bool) -> u64 {
if vector_table {
budget.min(rows.indexed / 10)
} else {
budget
}
}
#[async_trait]
impl JobHandler for OptimizeIndicesHandler {
fn capability(&self) -> JobTypeCapability {
@@ -170,12 +138,6 @@ impl JobHandler for OptimizeIndicesHandler {
defaults.clone(),
)),
worker_default_values: defaults,
// A retrain is a whole build, so it gets a build's time.
admin_runtime_defaults: Some(AdminRuntimeDefaults {
job_type_max_runtime_seconds: super::vector_index::EXECUTION_TIMEOUT_SECONDS,
execution_timeout_seconds: super::vector_index::EXECUTION_TIMEOUT_SECONDS,
..Default::default()
}),
..Default::default()
}
}
@@ -200,7 +162,7 @@ impl JobHandler for OptimizeIndicesHandler {
let mut proposals = Vec::new();
for encoded in &tables {
let id = parse_id(encoded);
let table = match dataset::open(&client, &id, &self.storage).await {
let table = match dataset::open(&client, &id, &self.fallback).await {
Ok(table) => table,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -213,9 +175,8 @@ impl JobHandler for OptimizeIndicesHandler {
if let Some(counters) = &self.metrics {
counters.worker.object_seen(JOB_TYPE);
}
let vector_table = is_vector_table(&id);
let rows = match index_rows(&table, vector_table).await {
Ok(Some(rows)) => rows,
let unindexed = match unindexed_rows(&table).await {
Ok(Some(unindexed)) => unindexed,
Ok(None) => continue,
Err(err) => {
if let Some(counters) = &self.metrics {
@@ -225,17 +186,11 @@ impl JobHandler for OptimizeIndicesHandler {
continue;
}
};
let budget = effective_budget(budget, &rows, vector_table);
let unindexed = rows.unindexed;
if unindexed <= budget {
continue;
}
let mut parameters: HashMap<String, ConfigValue> = HashMap::new();
parameters.insert("table_id".to_string(), string_list(&id));
if vector_table {
// The run may turn out to be a retrain.
super::vector_index::declare_build_runtime(&mut parameters);
}
proposals.push(JobProposal {
proposal_id: format!("{JOB_TYPE}:{encoded}"),
dedupe_key: format!("{JOB_TYPE}:{encoded}"),
@@ -282,47 +237,28 @@ impl JobHandler for OptimizeIndicesHandler {
.ok_or_else(|| anyhow!("job {} carried no table_id", job.job_id))?;
let client = self.client();
let mut table = dataset::open(&client, &id, &self.storage).await?;
let vector_table = is_vector_table(&id);
let before = index_rows(&table, vector_table)
.await?
.map_or(0, |rows| rows.unindexed);
// A vector index whose table has outgrown its partitions is built
// again with partitions for the rows it now holds.
let retrain =
vector_table && vector_index::retrain_due(&table.dataset, VECTOR_COLUMN).await?;
let mut table = dataset::open(&client, &id, &self.fallback).await?;
let before = unindexed_rows(&table).await?.unwrap_or(0);
sender.send_progress(JobProgressUpdate {
request_id: request.request_id.clone(),
job_id: job.job_id.clone(),
job_type: JOB_TYPE.to_string(),
progress_percent: 10.0,
stage: if retrain {
"retraining the vector index".to_string()
} else {
format!("indexing {before} uncovered rows")
},
stage: format!("indexing {before} uncovered rows"),
..Default::default()
})?;
if vector_table {
vector_index::optimize(&mut table.dataset, VECTOR_COLUMN, retrain)
.await
.with_context(|| format!("optimize the vector index of {}", table.location))?;
} else {
// Merging every delta keeps read latency from drifting as the table
// is reindexed again and again; leaving them unmerged is how an
// index ends up fast to write and slow to search.
table
.dataset
.optimize_indices(&OptimizeOptions::default())
.await
.with_context(|| format!("optimize indices of {}", table.location))?;
}
// Merging every delta keeps read latency from drifting as the table is
// reindexed again and again; leaving them unmerged is how an index ends
// up fast to write and slow to search.
table
.dataset
.optimize_indices(&OptimizeOptions::default())
.await
.with_context(|| format!("optimize indices of {}", table.location))?;
let after = index_rows(&table, vector_table)
.await?
.map_or(0, |rows| rows.unindexed);
let after = unindexed_rows(&table).await?.unwrap_or(0);
if let Some(counters) = &self.metrics {
counters.rows_indexed.inc_by(before.saturating_sub(after));
}
@@ -332,10 +268,6 @@ impl JobHandler for OptimizeIndicesHandler {
int_value(before as i64),
);
output.insert("unindexed_rows_after".to_string(), int_value(after as i64));
output.insert(
"retrained".to_string(),
seaweed_worker_core::config_form::bool_value(retrain),
);
sender.send_completed(JobCompleted {
request_id: request.request_id.clone(),
@@ -352,32 +284,3 @@ impl JobHandler for OptimizeIndicesHandler {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_retrain_gets_a_builds_execution_timeout() {
let descriptor = OptimizeIndicesHandler::new(String::new()).descriptor();
let defaults = descriptor.admin_runtime_defaults.unwrap();
assert_eq!(defaults.execution_timeout_seconds, 3600);
assert_eq!(defaults.job_type_max_runtime_seconds, 3600);
assert!(!defaults.enabled);
}
#[test]
fn vector_tables_reindex_at_a_tenth_of_their_rows() {
let small = IndexRows {
indexed: 60_000,
unindexed: 0,
};
assert_eq!(effective_budget(100_000, &small, true), 6_000);
assert_eq!(effective_budget(100_000, &small, false), 100_000);
let large = IndexRows {
indexed: 5_000_000,
unindexed: 0,
};
assert_eq!(effective_budget(100_000, &large, true), 100_000);
}
}
+5 -12
View File
@@ -10,7 +10,6 @@ pub mod cleanup;
pub mod compact;
pub mod indices;
pub mod sort;
pub mod vector_index;
use std::collections::HashMap;
use std::sync::Arc;
@@ -42,38 +41,32 @@ pub(crate) fn table_id(parameters: &HashMap<String, ConfigValue>) -> Option<Vec<
/// types, which is why WorkerHello carries a list.
pub fn handlers(
namespace_url: String,
storage: crate::dataset::Storage,
fallback: crate::dataset::FallbackOptions,
signing_key: Option<crate::catalog::SigningKey>,
metrics: Option<crate::metrics::LanceMetrics>,
) -> Vec<Arc<dyn JobHandler>> {
vec![
Arc::new(
compact::CompactHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_fallback(fallback.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
indices::OptimizeIndicesHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
vector_index::VectorIndexHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_fallback(fallback.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
sort::SortHandler::new(namespace_url.clone())
.with_storage(storage.clone())
.with_fallback(fallback.clone())
.with_signing_key(signing_key.clone())
.with_metrics(metrics.clone()),
),
Arc::new(
cleanup::CleanupVersionsHandler::new(namespace_url)
.with_storage(storage)
.with_fallback(fallback)
.with_signing_key(signing_key)
.with_metrics(metrics),
),
Loaded 100 of 784 files, more files were not shown because too many files have changed in this diff. Show more