mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 05:37:12 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ab66fb76d | ||
|
|
76fddab5ef | ||
|
|
35e98177d9 | ||
|
|
0705e20fe9 | ||
|
|
c147b775f9 | ||
|
|
4e12c13416 | ||
|
|
87627c2d72 | ||
|
|
af299655e7 | ||
|
|
cd616a48a8 | ||
|
|
10ea662522 | ||
|
|
f99cc6ca94 | ||
|
|
73fa85f54f | ||
|
|
4f24b756ba | ||
|
|
55a4a5974c | ||
|
|
78a3bc9dc3 | ||
|
|
554593796e | ||
|
|
195f8156de | ||
|
|
985706cc32 | ||
|
|
d0b5529a2d | ||
|
|
5cd38527ba | ||
|
|
5b1450b06b | ||
|
|
b650303aee | ||
|
|
2fe480a6e2 | ||
|
|
7beac0e8ea | ||
|
|
fd81a50c57 | ||
|
|
7d6680c7a4 | ||
|
|
99539484b6 | ||
|
|
1c4fe61fcd | ||
|
|
cdea7e79e0 | ||
|
|
728b476ba2 | ||
|
|
8c22336944 | ||
|
|
5ba97b4432 | ||
|
|
7fc33e7fe3 | ||
|
|
86db60b669 | ||
|
|
1176f975b3 | ||
|
|
2be4498c04 | ||
|
|
9af736da62 | ||
|
|
2df7d435f2 | ||
|
|
206d7b1418 | ||
|
|
1406335301 | ||
|
|
f71c0fe523 | ||
|
|
c84c43f3da | ||
|
|
7b3983f154 | ||
|
|
3e64326f2b | ||
|
|
3a579ece3b | ||
|
|
a8766f5177 | ||
|
|
d127be610f | ||
|
|
0dd33f5f0f | ||
|
|
878979af70 | ||
|
|
e44c16802d | ||
|
|
80f32bc074 | ||
|
|
c971252871 | ||
|
|
8c8d0f1cdf | ||
|
|
120d17a092 | ||
|
|
23598afb31 | ||
|
|
aab947b65e | ||
|
|
fe1cf5263f | ||
|
|
247e010865 | ||
|
|
8cc3a8ae21 | ||
|
|
fcf62db8d0 | ||
|
|
85232f7414 | ||
|
|
b74111ea2f | ||
|
|
48df16ea0d | ||
|
|
e465880ee8 | ||
|
|
b5951c5c7c | ||
|
|
f0f0ba85ae | ||
|
|
8350f297af | ||
|
|
cd10b4a5c1 | ||
|
|
683c5ad4d3 | ||
|
|
7047d3947a | ||
|
|
3d411c6a6c | ||
|
|
3cbace2471 | ||
|
|
c437791991 | ||
|
|
0742d316aa | ||
|
|
51ee165279 | ||
|
|
8f29e38837 | ||
|
|
d6c65cd924 | ||
|
|
15ff5c113a | ||
|
|
d727c6970f | ||
|
|
a0f30afe5f | ||
|
|
92bdfeaf29 | ||
|
|
ba3fd257a3 | ||
|
|
329ccb8bc0 | ||
|
|
cd82e663ad | ||
|
|
995084f71e | ||
|
|
5dfda3645e | ||
|
|
ca15fdbff6 | ||
|
|
b0c6297041 | ||
|
|
ca4ce2c581 | ||
|
|
9b5f7bf65b | ||
|
|
de4a71665e | ||
|
|
ab6aa9b645 | ||
|
|
836c60b2c9 | ||
|
|
5063aa9be2 | ||
|
|
30f0364256 | ||
|
|
eeb8aefe70 | ||
|
|
2ec0623073 | ||
|
|
d5e359d0e2 | ||
|
|
3b7706bad8 | ||
|
|
cadb614630 | ||
|
|
8461ae2fe9 | ||
|
|
5c99744e00 | ||
|
|
5df7faf0e3 | ||
|
|
d13d975b6e | ||
|
|
76198d15cf | ||
|
|
e8b284fef5 | ||
|
|
222cfa8e2e | ||
|
|
e5bc658eb7 | ||
|
|
af45ab8f2a | ||
|
|
199b2e2dd9 | ||
|
|
c2ca83c0bf | ||
|
|
cc71cc9585 | ||
|
|
9b45aae2eb | ||
|
|
794cebe7b0 | ||
|
|
8125a1549a | ||
|
|
97e03f5a9f | ||
|
|
b91de44615 | ||
|
|
20c8876a52 | ||
|
|
a670553813 | ||
|
|
9ae31fa425 | ||
|
|
e166629f9b | ||
|
|
b7b2a5947f | ||
|
|
a074538c8f | ||
|
|
0176231ea4 | ||
|
|
ec968aa016 | ||
|
|
690aabda0e | ||
|
|
d650abe0e7 | ||
|
|
1637941368 | ||
|
|
7298b4ed37 |
No files matched your search
@@ -9,6 +9,8 @@ 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
|
||||
|
||||
@@ -22,6 +24,28 @@ 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():
|
||||
@@ -38,7 +62,7 @@ def fetch_stargazers():
|
||||
"User-Agent": "seaweedfs-star-history",
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
with open_url(req) as resp:
|
||||
batch = json.load(resp)
|
||||
if not batch:
|
||||
break
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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()
|
||||
@@ -76,24 +76,42 @@ jobs:
|
||||
|
||||
|
||||
vectors-e2e:
|
||||
name: S3 Vectors Integration (${{ matrix.volume }} volume)
|
||||
name: S3 Vectors Integration (${{ matrix.volume }} volume${{ matrix.hardened && ', hardened' || '' }}${{ matrix.worker && ', worker' || '' }})
|
||||
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: ["", "1"]
|
||||
worker: [""]
|
||||
# Worker: the admin server and the Lance maintenance worker join the
|
||||
# cluster, for the tests that build vector indexes through a job.
|
||||
include:
|
||||
- volume: go
|
||||
hardened: ""
|
||||
worker: "1"
|
||||
- volume: rust
|
||||
hardened: ""
|
||||
worker: "1"
|
||||
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_TLS: ${{ matrix.hardened }}
|
||||
VECTOR_READ_JWT: ${{ matrix.hardened }}
|
||||
VECTOR_ENCRYPT_VOLUMES: ${{ matrix.hardened }}
|
||||
VECTOR_WORKER: ${{ matrix.worker }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
@@ -116,6 +134,18 @@ 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
|
||||
@@ -124,7 +154,8 @@ jobs:
|
||||
set -e
|
||||
make ./weed ./weed-vector CARGO_PROFILE=dev
|
||||
if [ "${{ matrix.volume }}" = "rust" ]; then make ./weed-volume CARGO_PROFILE=dev; fi
|
||||
- uses: actions/setup-python@v5
|
||||
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"
|
||||
- name: Install test dependencies
|
||||
@@ -147,7 +178,7 @@ jobs:
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: vectors-e2e-diagnostics-${{ matrix.volume }}
|
||||
name: vectors-e2e-diagnostics-${{ matrix.volume }}${{ matrix.hardened && '-hardened' || '' }}${{ matrix.worker && '-worker' || '' }}
|
||||
path: |
|
||||
${{ runner.temp }}/vector-tests
|
||||
${{ runner.temp }}/vector-results.xml
|
||||
|
||||
@@ -148,5 +148,7 @@ __pycache__/
|
||||
/test/s3vectors/weed
|
||||
/test/s3vectors/weed-vector
|
||||
/test/s3vectors/weed-vector-worker
|
||||
/test/s3vectors/weed-vector-cli
|
||||
/test/s3vectors/weed-worker
|
||||
/test/s3vectors/weed-volume
|
||||
.pytest_cache/
|
||||
@@ -32,7 +32,7 @@ require (
|
||||
github.com/google/btree v1.1.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/google/wire v0.7.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.24.1 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.27.0 // indirect
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
@@ -53,7 +53,7 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
github.com/peterh/liner v1.2.2
|
||||
github.com/peterh/liner v1.2.3
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/posener/complete v1.2.3
|
||||
@@ -65,7 +65,7 @@ require (
|
||||
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.3
|
||||
github.com/seaweedfs/raft v1.2.4
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
@@ -99,8 +99,8 @@ require (
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.297.0
|
||||
google.golang.org/genproto v0.0.0-20260904194346-d0f1323225a4 // indirect
|
||||
google.golang.org/api v0.310.0
|
||||
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 // indirect
|
||||
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/inf.v0 v0.9.1 // indirect
|
||||
@@ -111,7 +111,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/kms v1.35.0
|
||||
cloud.google.com/go/kms v1.36.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
@@ -122,8 +122,7 @@ 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/armon/go-metrics v0.4.1
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3
|
||||
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,6 +133,7 @@ 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
|
||||
@@ -159,7 +159,7 @@ require (
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.155.1
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.3
|
||||
go.uber.org/atomic v1.12.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/tools/godoc v0.1.0-deprecated
|
||||
@@ -169,7 +169,7 @@ require (
|
||||
require github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
|
||||
|
||||
require (
|
||||
cloud.google.com/go/longrunning v1.2.0 // indirect
|
||||
cloud.google.com/go/longrunning v1.3.0 // indirect
|
||||
cloud.google.com/go/pubsub/v2 v2.7.0 // indirect
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
|
||||
@@ -278,20 +278,21 @@ require (
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/zipkin v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
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.5 // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/mod v0.42.0 // indirect
|
||||
gonum.org/v1/gonum v0.17.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
cel.dev/expr v0.25.3 // indirect
|
||||
cloud.google.com/go/auth v0.23.2 // indirect
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
|
||||
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a // indirect
|
||||
cloud.google.com/go/auth/oauth2adapt v0.3.0 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.10.0 // indirect
|
||||
cloud.google.com/go/iam v1.13.0 // indirect
|
||||
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.23.3
|
||||
@@ -321,19 +322,19 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sns v1.46.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sqs v1.51.0 // indirect
|
||||
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.1
|
||||
github.com/aws/smithy-go v1.28.5
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
|
||||
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
|
||||
@@ -379,8 +380,8 @@ require (
|
||||
github.com/gofrs/flock v0.13.0 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
|
||||
github.com/google/s2a-go v0.1.9 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.21 // indirect
|
||||
github.com/google/s2a-go v0.1.11 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.24 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
@@ -389,7 +390,6 @@ 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
|
||||
@@ -412,7 +412,7 @@ require (
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260627054121-477a66015f15 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.31 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
|
||||
@@ -484,17 +484,17 @@ require (
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.46.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect
|
||||
go.opentelemetry.io/otel v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
golang.org/x/term v0.47.0
|
||||
golang.org/x/time v0.16.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b
|
||||
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
|
||||
|
||||
@@ -4,20 +4,20 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
|
||||
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
|
||||
cloud.google.com/go/auth v0.23.2 h1:pxSCpfiji41hpzpPdMCftEUCezpgpqmmDdYiAjCKXxo=
|
||||
cloud.google.com/go/auth v0.23.2/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
|
||||
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a h1:jW1ZLFy9oa5ai8LOI40z6s+DL1cO/L1KSm9hVGnibn8=
|
||||
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.3.0 h1:FY8oSZpCYoUNv6QxVODuMjQz4IlSOVeiQtZ08vLPz88=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.3.0/go.mod h1:7+2uCm7++XFO+/lN06c2HXpDXb/NMNn2/UwyBPbTnkk=
|
||||
cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY=
|
||||
cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk=
|
||||
cloud.google.com/go/iam v1.13.0 h1:ufT3FPT5rFFXu6UtLkNoxaOaV5EuA1dsSkmemCSTo6U=
|
||||
cloud.google.com/go/iam v1.13.0/go.mod h1:gHXdDEiPDvqd1q1KwBDGQlgZY/BwY760zU2LhOZS5w0=
|
||||
cloud.google.com/go/kms v1.35.0 h1:nJ/ktaqspx1nPM9vIcO0SHbhqCAm8nvAxL1siuVgKm0=
|
||||
cloud.google.com/go/kms v1.35.0/go.mod h1:0++71pIHvJL+GmMa8K4jOWFq7gNOX3jm2PRMSJwTKJw=
|
||||
cloud.google.com/go/logging v1.19.1 h1:7SsLhyTDBDrJw+Ll6Ns3I2mByqHXvJUc3rGjSlwiWgU=
|
||||
cloud.google.com/go/logging v1.19.1/go.mod h1:2IkQ/d8jVJqV2qW8ZUGUiMjdZG1gkLD2JReGbZ8isqg=
|
||||
cloud.google.com/go/longrunning v1.2.0 h1:WjYH3YHBGCxGJP9M4dWGHBfXr/cFIjMkNgWcJj7/iMM=
|
||||
cloud.google.com/go/longrunning v1.2.0/go.mod h1:5KMQALFGOCtFoi2xSOA1u3H7WKlhmckgiyFw7+LGQp0=
|
||||
cloud.google.com/go/iam v1.14.0 h1:YRIB1/4xxwJ+NfI6RQr1WaOoHHeV0MizJEj940nBXJA=
|
||||
cloud.google.com/go/iam v1.14.0/go.mod h1:JTPZfbHdGXJrOYREtkRoFzCDGaBdbA7ILLKO/DDuav0=
|
||||
cloud.google.com/go/kms v1.36.1 h1:jIXDoN/lxjVt/zc219tIwqAWPVWVzcLJ7s6Oq3n0Y5U=
|
||||
cloud.google.com/go/kms v1.36.1/go.mod h1:1oVAwTvmgswE8PiQeyffdNxpRLw2F0UfQlLwTrYlRNg=
|
||||
cloud.google.com/go/logging v1.20.0 h1:l7yzCB8/JSY5PHT9RsaqdT1jaBGbM6KlSJDX210HlXM=
|
||||
cloud.google.com/go/logging v1.20.0/go.mod h1:ALUaJQZM691Eeujy9kFx0xREq3AMPuGd+pTRZuTYv+w=
|
||||
cloud.google.com/go/longrunning v1.3.0 h1:lZ6c8SJJBmILp/Wnr3vGnBLa0q+cYfSHRCcUfVI2hpI=
|
||||
cloud.google.com/go/longrunning v1.3.0/go.mod h1:wpgLxCn+UA3/TZ1bj/fW39mfDpwVlMPu1xKJyoMt7V0=
|
||||
cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY=
|
||||
cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM=
|
||||
cloud.google.com/go/pubsub v1.51.1 h1:R3G1wCOxBO7jRpL8x2pdZMv1GAJDF6ax/m2zPOtvTNE=
|
||||
@@ -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.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
|
||||
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=
|
||||
@@ -187,18 +187,18 @@ github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHA
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3 h1:vsFkmFrfzODkxVbyuPLscv5j5lC8KbG48LZwV+p56Y0=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3/go.mod h1:pjQYVtvVBEtlsf2p6nXMsjPuDaWs9GM44FMdHbmnmYU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4 h1:CLq4+8UHCI+ZZYl/EuJxXovaIVN2xeeT8JV+dsApQ5E=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.4/go.mod h1:Wv4q5sAM04xAMkoOedxLx2inVf6K5FdxYp+A61L+q/0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4 h1:dD4MR81I7YkpEBRk6UP9rocC2QnT3qVuXwzlYTtfGEs=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.4/go.mod h1:EcXV1kAFd5XwSkDHlj94gnF3q5CkJyYiIJfH8N0VmrE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4 h1:7Wo47d/xn/7KttCSBd8EGYeZ7ULRFRkUHr6vkZPBzVQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.4/go.mod h1:tDB2IVC1xC3vX8o+6uRlzhTxP3g1b77CZXFX/oD2FnQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4 h1:29SvnfGhXjTl8ONxFwbj2rs6lbhiFXD2CgFQmbT/bXY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.4/go.mod h1:wm04I5DMuNVvZHFe/dHnUxincvNbbK7AiNBbYsQivek=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.1 h1:9T6eO8/WXhij4PQaa2WaYsdekSCmT9Hw66Pw0S8do0Q=
|
||||
@@ -213,10 +213,10 @@ github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NL
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg=
|
||||
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.1 h1:0HOqZXRvMytH6bFHVIc0oJX07sZjfhz0zXtjs6gdE8s=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.1/go.mod h1:26zA0GhDrLo+yiLI2yXWxqB1PdsShfLikoI7GOEgugM=
|
||||
github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
|
||||
github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
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.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=
|
||||
@@ -619,8 +619,8 @@ github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9
|
||||
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/s2a-go v0.1.11 h1:7v1V1TraNGP63WptsAkNqr2w8jgm4vM6A6qx6Lsw9iM=
|
||||
github.com/google/s2a-go v0.1.11/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
@@ -629,10 +629,10 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
|
||||
github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.21 h1:OFdQ3tnCX/zaQ0Cedur3D3z7kI6HiLX9g3TiAN4/DFU=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
|
||||
github.com/googleapis/gax-go/v2 v2.24.1 h1:AtqTN21IXMMWo99LiEVAiBfNNQmO40d8xUfZI640mc0=
|
||||
github.com/googleapis/gax-go/v2 v2.24.1/go.mod h1:bWeBei0NVwaNZKb2y1HUBS7gLXIF3/Tu3pq7j8D2Tb0=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.24 h1:G9iCJIY+AYVmUskKdjX8FVy7sG+nbzjOQ41cvlmhcvg=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.24/go.mod h1:hEjCmnoakQzv5ImLUp6alkY7XgLlNoAxwTXmhHHNIsI=
|
||||
github.com/googleapis/gax-go/v2 v2.27.0 h1:qe2iQOUzxb3fd6x6ewpIEixPQhJ+0Ihc/RRZhKA/2g0=
|
||||
github.com/googleapis/gax-go/v2 v2.27.0/go.mod h1:RofiqDw3ehcG4L0H1zO3D2Itpwd3/uS/7wdmbNDF1DE=
|
||||
github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g=
|
||||
github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
@@ -840,9 +840,8 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
|
||||
github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo=
|
||||
github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
|
||||
github.com/mattn/go-shellwords v1.0.13 h1:DC0OMEpGjm6LfNFU4ckYcvbQKyp2vE8atyFGXNtDcf4=
|
||||
github.com/mattn/go-shellwords v1.0.13/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
|
||||
@@ -962,7 +961,6 @@ 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=
|
||||
@@ -971,8 +969,8 @@ github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdD
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 h1:XeOYlK9W1uCmhjJSsY78Mcuh7MVkNjTzmHx1yBzizSU=
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14/go.mod h1:jVblp62SafmidSkvWrXyxAme3gaTfEtWwRPGz5cpvHg=
|
||||
github.com/peterh/liner v1.2.2 h1:aJ4AOodmL+JxOZZEL2u9iJf8omNRpqHc/EbrK+3mAXw=
|
||||
github.com/peterh/liner v1.2.2/go.mod h1:xFwJyiKIXJZUKItq5dGHZSTBRAuG/CpeNpWLyiNRNwI=
|
||||
github.com/peterh/liner v1.2.3 h1:JF4G03iaZjtPyJE7gdOk76/fvs4OObMJWQHwR3wphxE=
|
||||
github.com/peterh/liner v1.2.3/go.mod h1:IC6gIBWLzuPGXmiX/86/ieO9K+9ITsaE6SKm1XkU9uw=
|
||||
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o=
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 h1:KPpdlQLZcHfTMQRi6bFQ7ogNO0ltFT4PmtwTLW4W+14=
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
@@ -1106,8 +1104,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.3 h1:/NMrdhztjx8ojeu+aAPa2GmuVShQXp8YwmNmsMPU63E=
|
||||
github.com/seaweedfs/raft v1.2.3/go.mod h1:fgs/rAVEzjQ7e04XMzG3eJhwZZRmBW+2uRtjakeCGeU=
|
||||
github.com/seaweedfs/raft v1.2.4 h1:lEBQ9seDSGrJNs2WitMgfYpaDxLgh9qukm1IJTEV1hk=
|
||||
github.com/seaweedfs/raft v1.2.4/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=
|
||||
@@ -1353,8 +1351,8 @@ go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
|
||||
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
|
||||
go.etcd.io/etcd/api/v3 v3.7.1 h1:KJG0/DcWGfe3Y1otDf/fsBf0TSSgpxZ5RO/L8SFt73E=
|
||||
go.etcd.io/etcd/api/v3 v3.7.1/go.mod h1:8bXIpCMeV7E3/XL0Ix123ATn3dB+0V7d9zklHbB0m78=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1 h1:rKYsj3pRkR0eK3yjT3XOgrhqfmIfj9pzNgxjh7mfFv4=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1/go.mod h1:cnzZGIUzSfjEwLC6UBVsSXlEK1eepS/JUD7wE6PLRT0=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.3 h1:5zMwNu3ycrzCeA5NwOfQbxFRhqq974chq1DrYMua4QI=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.3/go.mod h1:/OhzqYrF0U7d1NOk55VMyUQGbYD1WoIe4bJwxb47wOk=
|
||||
go.etcd.io/etcd/client/v3 v3.7.1 h1:0PEMMC0KuZmVIN+RAbdqfkZ45pYTgKVtmBEbRCvZFUg=
|
||||
go.etcd.io/etcd/client/v3 v3.7.1/go.mod h1:ffNqALa8tRCYhYo1F9oR489y23K39Gz+BSR3ApAGYq0=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
@@ -1371,8 +1369,8 @@ go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.46.0 h1:qkDYCAFiZXLcs1L4aY+tP2wguQ4kURANqHOQMA2et2s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.46.0/go.mod h1:tkipS4DRzmpAmvg+Gw4++O1IdDq6TVDnvnYU6cmbQVs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0 h1:RuynHbfU8JUEw7DyONgkVYg2SVtsoF28y0LGIr69jgA=
|
||||
@@ -1387,16 +1385,18 @@ go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.46.0 h1:PR9eAf7o0dQs3h
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.46.0/go.mod h1:2Z4KyNdH1uuzivdinyfGsxzNNT/Rl45pwtVwfYVI0xk=
|
||||
go.opentelemetry.io/otel/exporters/zipkin v1.45.0 h1:KN3btaILMTxR4QDHVGAO87lq5ButzK7l+kIfLuxQ1oA=
|
||||
go.opentelemetry.io/otel/exporters/zipkin v1.45.0/go.mod h1:yNcodmUclM4InyWoOwX/YW4Jri0Gj5FWAlM+NqCrtqY=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/metric/x v0.68.0 h1:TA/cBT23D3MnxYPwHL7YFOdYGdx0A0v+s7Mzotpd1dU=
|
||||
go.opentelemetry.io/otel/metric/x v0.68.0/go.mod h1:agudOmvWhwUTjgibWDzxD2PoWYnpw5Ht5jISYOD2Hd4=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
@@ -1468,8 +1468,8 @@ golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@@ -1545,7 +1545,6 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
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=
|
||||
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220408201424-a24fb2fb8a0f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -1620,8 +1619,8 @@ golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhS
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/api v0.297.0 h1:WktxTsnnx0yZNnsR6j0q6hR21RnnK81FHTOPy/ux4OE=
|
||||
google.golang.org/api v0.297.0/go.mod h1:S4m8x0M6OkQpkOzGk1y9JG2sm4fFQrMh6dxzjCTszhE=
|
||||
google.golang.org/api v0.310.0 h1:537ccDDmbwuwX1iof3Vtdz9vow6uJCgrSZJWedAWM0I=
|
||||
google.golang.org/api v0.310.0/go.mod h1:5NUthU+LmGMKzYgRaScb+TTe1Lo7x4A+J7g+Yj8BRzA=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
@@ -1631,12 +1630,12 @@ google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfG
|
||||
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
|
||||
google.golang.org/genproto v0.0.0-20260904194346-d0f1323225a4 h1:6QRNo34FxJcE1LG6XfnmaQ17m6w21oXaKlKoBaF+UqE=
|
||||
google.golang.org/genproto v0.0.0-20260904194346-d0f1323225a4/go.mod h1:eifJ91nefXnfP/bMkZsACVGm14ZtEL4eUXRLTryfbY4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 h1:GS9OIt/j7c8bvBjYNgnKQysVfmV7e4jM0H8ZK95G4t8=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459/go.mod h1:PX5/4vemwVoXtwEcRDWwcR1/r0qrosfx3qoVADMwnVE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 h1:b0xCahf3FK2m2Cv0p4vTozGPWncCvLfwV86UNg8xWU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 h1:CXq2XEi5aEyLjjPZIwqrmQH8ZY4ctUwK7uyAx3mjX/U=
|
||||
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941/go.mod h1:3gK0ehnhP0V7/x3ypGoLyT3d0n6TSi/EcsphIjHrcz4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 h1:DS/w3N8rsfrwxwgGSj6WhMsPo7aNQGmDx74J81zd0NQ=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941/go.mod h1:AuGAdi9KnXss7xbLxIKhCvk+Ro/SxpET/iS45DNYN+M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.52"
|
||||
appVersion: "4.53"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.52.0
|
||||
version: 4.53.0
|
||||
@@ -239,6 +239,22 @@ 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"
|
||||
@@ -256,6 +272,10 @@ 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 \
|
||||
@@ -268,10 +288,20 @@ 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/
|
||||
|
||||
@@ -1744,6 +1744,14 @@ 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: ""
|
||||
|
||||
+1048
-1008
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,9 @@
|
||||
//! 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;
|
||||
@@ -0,0 +1,79 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
Generated
+781
-10
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,339 @@
|
||||
# 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.
|
||||
@@ -13,6 +13,8 @@ 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,
|
||||
@@ -28,6 +30,7 @@ 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;
|
||||
@@ -36,6 +39,9 @@ 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();
|
||||
@@ -58,6 +64,7 @@ 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,
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
//! 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()),
|
||||
¶ms,
|
||||
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, ¶ms)
|
||||
.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, ¶ms, 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, ¶ms)
|
||||
.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
pub mod coverage;
|
||||
mod filter;
|
||||
pub mod index;
|
||||
pub mod maintenance;
|
||||
pub mod query;
|
||||
pub mod segments;
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use weed_lance_worker::catalog::{NamespaceClient, parse_id};
|
||||
use weed_lance_worker::dataset::{self, FallbackOptions};
|
||||
use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id};
|
||||
use weed_lance_worker::dataset::{self, Storage};
|
||||
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 is WEED_LANCE_NAMESPACE and the fallback storage credentials are
|
||||
/// the same env vars.
|
||||
/// namespace that says where a table is, and the masters whose filers hold
|
||||
/// it.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "weed-vector", about = "SeaweedFS vector query spike")]
|
||||
#[command(
|
||||
name = "weed-vector",
|
||||
about = "Describe, query and index S3 Vectors tables"
|
||||
)]
|
||||
struct Args {
|
||||
/// Lance namespace the tables live in.
|
||||
#[arg(
|
||||
@@ -21,12 +25,29 @@ struct Args {
|
||||
)]
|
||||
namespace: String,
|
||||
|
||||
/// Storage credentials to use where the namespace vends none.
|
||||
#[arg(long, env = "WEED_S3_ACCESS_KEY")]
|
||||
access_key: Option<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>,
|
||||
|
||||
#[arg(long, env = "WEED_S3_SECRET_KEY")]
|
||||
secret_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>,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
@@ -91,24 +112,67 @@ enum Command {
|
||||
#[arg(long)]
|
||||
key_column: Option<String>,
|
||||
},
|
||||
/// Build or extend the vector index, then print its coverage.
|
||||
Index {
|
||||
#[command(subcommand)]
|
||||
action: IndexAction,
|
||||
},
|
||||
}
|
||||
|
||||
/// `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.
|
||||
#[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.
|
||||
async fn open_dataset(
|
||||
client: &NamespaceClient,
|
||||
id: &str,
|
||||
fallback: &FallbackOptions,
|
||||
storage: &Storage,
|
||||
) -> Result<lance::Dataset> {
|
||||
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}"));
|
||||
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}"));
|
||||
}
|
||||
let table = dataset::open(client, &parse_id(id), fallback).await?;
|
||||
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?).await;
|
||||
}
|
||||
let table = dataset::open(client, &parse_id(id), storage).await?;
|
||||
Ok(table.dataset)
|
||||
}
|
||||
|
||||
@@ -116,6 +180,7 @@ 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")),
|
||||
@@ -123,12 +188,21 @@ async fn main() -> Result<()> {
|
||||
.init();
|
||||
let args = Args::parse();
|
||||
|
||||
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);
|
||||
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(),
|
||||
};
|
||||
|
||||
match args.command {
|
||||
Command::Describe {
|
||||
@@ -136,7 +210,7 @@ async fn main() -> Result<()> {
|
||||
vector_column,
|
||||
key_column,
|
||||
} => {
|
||||
let dataset = open_dataset(&client, &id, &fallback).await?;
|
||||
let dataset = open_dataset(&client, &id, &storage).await?;
|
||||
let schema: arrow_schema::Schema = dataset.schema().into();
|
||||
let resolved =
|
||||
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
|
||||
@@ -176,7 +250,7 @@ async fn main() -> Result<()> {
|
||||
vector_column,
|
||||
key_column,
|
||||
} => {
|
||||
let dataset = open_dataset(&client, &id, &fallback).await?;
|
||||
let dataset = open_dataset(&client, &id, &storage).await?;
|
||||
let vector =
|
||||
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
|
||||
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
|
||||
@@ -188,7 +262,7 @@ async fn main() -> Result<()> {
|
||||
vector_column,
|
||||
key_column,
|
||||
} => {
|
||||
let dataset = open_dataset(&client, &id, &fallback).await?;
|
||||
let dataset = open_dataset(&client, &id, &storage).await?;
|
||||
let vector =
|
||||
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
|
||||
for batch in query::get(&dataset, &vector, &keys, None).await? {
|
||||
@@ -208,7 +282,7 @@ async fn main() -> Result<()> {
|
||||
key_column,
|
||||
nprobes,
|
||||
} => {
|
||||
let opened = open_dataset(&client, &id, &fallback).await?;
|
||||
let opened = open_dataset(&client, &id, &storage).await?;
|
||||
let dataset = match version {
|
||||
Some(v) => opened.checkout_version(v).await?,
|
||||
None => opened,
|
||||
@@ -243,6 +317,49 @@ 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(())
|
||||
}
|
||||
@@ -272,6 +389,58 @@ 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 [
|
||||
|
||||
@@ -178,8 +178,7 @@ 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;
|
||||
@@ -379,7 +378,10 @@ 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();
|
||||
|
||||
@@ -120,8 +120,28 @@ async fn scanner(
|
||||
crate::filter::apply(&mut scanner, filter)?;
|
||||
scanner.prefilter(!query.postfilter);
|
||||
}
|
||||
if let Some(nprobes) = query.nprobes {
|
||||
scanner.nprobes(nprobes);
|
||||
// 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
let segments = query.index_segments.as_deref().unwrap_or(&[]);
|
||||
if use_index && !segments.is_empty() {
|
||||
|
||||
@@ -66,6 +66,40 @@ 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)
|
||||
|
||||
@@ -15,6 +15,7 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
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"
|
||||
@@ -32,7 +33,7 @@ bytes = "1"
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
futures = "0.3"
|
||||
moka = { version = "0.12", features = ["sync"] }
|
||||
object_store = "0.13"
|
||||
object_store = { version = "0.13", features = ["aws"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -13,6 +13,12 @@ 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 {
|
||||
|
||||
@@ -1,47 +1,54 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::server::TcpIncoming;
|
||||
use weed_lance_worker::catalog::{NamespaceClient, SigningKey};
|
||||
use weed_lance_worker::dataset::FallbackOptions;
|
||||
use weed_lance_worker::cluster::Cluster;
|
||||
use weed_vector_server::master_client;
|
||||
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};
|
||||
|
||||
/// 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,
|
||||
/// 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).
|
||||
/// Comma-separated master addresses. The engine registers with them, so
|
||||
/// the gateway finds it, and asks them for the filers it keeps tables
|
||||
/// through.
|
||||
#[arg(long, alias = "master", env = "WEED_VECTOR_MASTERS")]
|
||||
masters: Option<String>,
|
||||
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,
|
||||
/// 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,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
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())
|
||||
/// 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>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
// weed tools take Go-style single-dash long flags; normalize_args converts
|
||||
@@ -105,40 +112,100 @@ fn advertised_addr(listen: &str, masters: &[String]) -> String {
|
||||
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 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,
|
||||
));
|
||||
}
|
||||
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);
|
||||
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 mut service = VectorServer::new()
|
||||
.with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get))
|
||||
.with_storage(reads);
|
||||
if args.read_cache_mb > 0 {
|
||||
service = service.with_read_cache(ReadCache::new(args.read_cache_mb << 20));
|
||||
}
|
||||
tracing::info!(namespace = %args.namespace, listen = %args.listen, "weed-vector");
|
||||
Server::builder()
|
||||
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);
|
||||
tokio::spawn(master_client::keep_connected(
|
||||
cluster.masters.clone(),
|
||||
advertise,
|
||||
cluster.master_tls.clone(),
|
||||
));
|
||||
let router = 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(service)
|
||||
.max_decoding_message_size(1 << 30)
|
||||
.max_encoding_message_size(1 << 30),
|
||||
)
|
||||
.serve_with_incoming(incoming)
|
||||
.await?;
|
||||
);
|
||||
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?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,10 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::time::sleep;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
use crate::master_pb::{KeepConnectedRequest, seaweed_client::SeaweedClient};
|
||||
use crate::security::GrpcTls;
|
||||
pub use weed_lance_worker::cluster::{CONNECT_TIMEOUT, connect, grpc_addr};
|
||||
|
||||
fn registration(client_addr: &str) -> KeepConnectedRequest {
|
||||
KeepConnectedRequest {
|
||||
@@ -24,36 +25,6 @@ fn registration(client_addr: &str) -> KeepConnectedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -68,11 +39,12 @@ 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) {
|
||||
pub async fn keep_connected(masters: Vec<String>, client_addr: String, tls: Option<GrpcTls>) {
|
||||
let client_addr = client_addr.as_str();
|
||||
let tls = tls.as_ref();
|
||||
loop {
|
||||
try_all_masters(&masters, |master| async move {
|
||||
stream_to(&master, client_addr).await
|
||||
stream_to(&master, client_addr, tls).await
|
||||
})
|
||||
.await;
|
||||
sleep(Duration::from_secs(3)).await;
|
||||
@@ -108,16 +80,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// 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?;
|
||||
async fn stream_to(
|
||||
master: &str,
|
||||
client_addr: &str,
|
||||
tls: Option<&GrpcTls>,
|
||||
) -> Result<Option<String>> {
|
||||
let channel = connect(master, tls).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);
|
||||
@@ -215,7 +183,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 dial = stream_to("192.0.2.1:9333", "127.0.0.1:8080");
|
||||
let dial = stream_to("192.0.2.1:9333", "127.0.0.1:8080", None);
|
||||
let result = tokio::time::timeout(CONNECT_TIMEOUT * 3, dial).await;
|
||||
assert!(matches!(result, Ok(Err(_))), "dial was not bounded");
|
||||
}
|
||||
@@ -229,13 +197,83 @@ mod tests {
|
||||
let _ = tokio::io::copy(&mut conn, &mut tokio::io::sink()).await;
|
||||
});
|
||||
let master = format!("127.0.0.1:9333.{port}");
|
||||
let open = stream_to(&master, "127.0.0.1:8080");
|
||||
let open = stream_to(&master, "127.0.0.1:8080", None);
|
||||
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 open = stream_to(&master, "127.0.0.1:8080", Some(&tls));
|
||||
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 open = stream_to(&master, "127.0.0.1:8080", Some(&tls));
|
||||
let result = tokio::time::timeout(CONNECT_TIMEOUT * 3, open).await;
|
||||
// A read+write open of a FIFO does not block, and it lets the
|
||||
// blocked read finish so the runtime can shut down.
|
||||
drop(
|
||||
std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(&fifo),
|
||||
);
|
||||
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");
|
||||
|
||||
@@ -37,26 +37,40 @@ struct Entry {
|
||||
|
||||
/// Wraps each object store Lance opens; clones share one cache.
|
||||
#[derive(Clone)]
|
||||
pub struct ReadCache(moka::sync::Cache<Key, Entry>);
|
||||
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>,
|
||||
}
|
||||
|
||||
impl ReadCache {
|
||||
pub fn new(capacity_bytes: u64) -> Self {
|
||||
Self(
|
||||
moka::sync::Cache::builder()
|
||||
Self {
|
||||
cache: 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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same cache, keyed apart under `scope`.
|
||||
pub fn scoped(&self, scope: &str) -> Self {
|
||||
Self {
|
||||
cache: self.cache.clone(),
|
||||
scope: scope.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ReadCache {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ReadCache")
|
||||
.field("entries", &self.0.entry_count())
|
||||
.field("bytes", &self.0.weighted_size())
|
||||
.field("entries", &self.cache.entry_count())
|
||||
.field("bytes", &self.cache.weighted_size())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -65,8 +79,8 @@ impl WrappingObjectStore for ReadCache {
|
||||
fn wrap(&self, store_prefix: &str, original: Arc<dyn ObjectStore>) -> Arc<dyn ObjectStore> {
|
||||
Arc::new(CachedStore {
|
||||
inner: original,
|
||||
store: store_prefix.into(),
|
||||
cache: self.0.clone(),
|
||||
store: format!("{}|{store_prefix}", self.scope).into(),
|
||||
cache: self.cache.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -277,8 +291,6 @@ mod tests {
|
||||
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)
|
||||
@@ -373,8 +385,8 @@ mod tests {
|
||||
.unwrap();
|
||||
read(&store, &path, 0..(8 << 10)).await;
|
||||
}
|
||||
cache.0.run_pending_tasks();
|
||||
assert!(cache.0.weighted_size() <= 64 << 10, "{cache:?}");
|
||||
cache.cache.run_pending_tasks();
|
||||
assert!(cache.cache.weighted_size() <= 64 << 10, "{cache:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -392,40 +404,15 @@ 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.0.get(&key).unwrap().bytes;
|
||||
let cached = cache.cache.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(),
|
||||
@@ -492,15 +479,15 @@ 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 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 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 table = pb::Table {
|
||||
id: vec!["bkt".into(), "vector".into(), "x".into()],
|
||||
version: 0,
|
||||
id: vec![bucket, "vector".into(), "x".into()],
|
||||
location: location.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
create(&server, &table, 4).await;
|
||||
|
||||
@@ -8,17 +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::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;
|
||||
use tonic::{Request, Response, Status};
|
||||
use weed_lance_worker::catalog::NamespaceClient;
|
||||
use weed_lance_worker::dataset::{self, FallbackOptions};
|
||||
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::query::{self, Query};
|
||||
use weed_vector_core::table::VectorTable;
|
||||
|
||||
@@ -35,17 +35,14 @@ fn invalid(err: impl Into<anyhow::Error>) -> Status {
|
||||
|
||||
fn open_status(err: anyhow::Error) -> Status {
|
||||
let missing = err.chain().any(|cause| {
|
||||
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 { .. }
|
||||
)
|
||||
})
|
||||
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))
|
||||
@@ -58,7 +55,6 @@ const KEY_COLUMN: &str = "key";
|
||||
const METADATA_COLUMN: &str = "metadata";
|
||||
const VECTOR_COLUMN: &str = "vector";
|
||||
const ROW_ID_COLUMN: &str = "_rowid";
|
||||
|
||||
fn schema_for(
|
||||
dimension: usize,
|
||||
metric: pb::DistanceMetric,
|
||||
@@ -370,38 +366,141 @@ 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,
|
||||
})
|
||||
}
|
||||
|
||||
pub struct VectorServer {
|
||||
client: NamespaceClient,
|
||||
fallback: FallbackOptions,
|
||||
read_cache: Option<Arc<dyn WrappingObjectStore>>,
|
||||
storage: Option<DirectReads>,
|
||||
read_cache: Option<ReadCache>,
|
||||
nprobes: Option<usize>,
|
||||
/// URI schemes a table's location may have.
|
||||
schemes: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl Default for VectorServer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl VectorServer {
|
||||
pub fn new(client: NamespaceClient, fallback: FallbackOptions) -> Self {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
client,
|
||||
fallback,
|
||||
storage: None,
|
||||
read_cache: None,
|
||||
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
|
||||
}
|
||||
|
||||
/// Serve repeated reads of write-once table files from `cache`.
|
||||
pub fn with_read_cache(mut self, cache: ReadCache) -> Self {
|
||||
self.read_cache = Some(Arc::new(cache));
|
||||
self.read_cache = Some(cache);
|
||||
self
|
||||
}
|
||||
|
||||
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;
|
||||
/// 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> {
|
||||
let description = self.describe(table)?;
|
||||
let wrapper = self.wrapper(table);
|
||||
let mut dataset = dataset::open_at(&description, wrapper)
|
||||
.await
|
||||
.map_err(open_status)?;
|
||||
if table.version != 0 {
|
||||
dataset = dataset.checkout_version(table.version).await?;
|
||||
dataset = dataset
|
||||
.checkout_version(table.version)
|
||||
.await
|
||||
.map_err(|err| open_status(err.into()))?;
|
||||
}
|
||||
Ok(dataset)
|
||||
}
|
||||
@@ -425,12 +524,7 @@ 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
|
||||
.client
|
||||
.describe_table(&table.id)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let options = dataset::table_options(&description, &self.fallback);
|
||||
let description = self.describe(&table)?;
|
||||
let schema = schema_for(dimension, metric, &req.non_filterable_metadata_keys);
|
||||
let empty = RecordBatch::new_empty(schema.clone());
|
||||
let reader = arrow_array::RecordBatchIterator::new(vec![Ok(empty)].into_iter(), schema);
|
||||
@@ -438,12 +532,7 @@ impl VectorService for VectorServer {
|
||||
reader,
|
||||
&description.location,
|
||||
Some(WriteParams {
|
||||
store_params: Some(ObjectStoreParams {
|
||||
storage_options_accessor: Some(Arc::new(
|
||||
StorageOptionsAccessor::with_static_options(options),
|
||||
)),
|
||||
..Default::default()
|
||||
}),
|
||||
store_params: Some(dataset::store_params(self.wrapper(&table))),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
@@ -462,15 +551,24 @@ impl VectorService for VectorServer {
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
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)
|
||||
}
|
||||
})?;
|
||||
// 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)?;
|
||||
}
|
||||
}
|
||||
Ok(Response::new(pb::DropIndexResponse {}))
|
||||
}
|
||||
|
||||
@@ -482,7 +580,7 @@ impl VectorService for VectorServer {
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
let dataset = self.open(&table).await?;
|
||||
if req.vectors.is_empty() {
|
||||
return Ok(Response::new(pb::PutVectorsResponse {
|
||||
version: dataset.version().version,
|
||||
@@ -524,7 +622,7 @@ impl VectorService for VectorServer {
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
let dataset = self.open(&table).await?;
|
||||
// Lease the resolved version so maintenance cannot reclaim its files
|
||||
// while this query runs against it.
|
||||
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
|
||||
@@ -548,7 +646,7 @@ impl VectorService for VectorServer {
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let mut dataset = self.open(&table).await.map_err(open_status)?;
|
||||
let mut dataset = self.open(&table).await?;
|
||||
if !req.keys.is_empty() {
|
||||
dataset
|
||||
.delete(&key_list(&req.keys))
|
||||
@@ -574,7 +672,7 @@ impl VectorService for VectorServer {
|
||||
"segment_index must be below segment_count, which is at most {MAX_SEGMENTS}"
|
||||
)));
|
||||
}
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
let dataset = self.open(&table).await?;
|
||||
let offset: u64 = if req.next_token.is_empty() {
|
||||
0
|
||||
} else {
|
||||
@@ -641,7 +739,7 @@ impl VectorService for VectorServer {
|
||||
let table = req
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
let dataset = self.open(&table).await?;
|
||||
// Lease the resolved version so maintenance cannot reclaim its files
|
||||
// while this query runs against it.
|
||||
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
|
||||
@@ -658,16 +756,7 @@ impl VectorService for VectorServer {
|
||||
if req.top_k == 0 {
|
||||
return Err(Status::invalid_argument("top_k must be positive"));
|
||||
}
|
||||
// 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 distance = index::distance_metric(&dataset, VECTOR_COLUMN);
|
||||
let query = Query {
|
||||
vector: req.query_vector,
|
||||
k: req.top_k as usize,
|
||||
@@ -678,7 +767,7 @@ impl VectorService for VectorServer {
|
||||
},
|
||||
postfilter: req.postfilter,
|
||||
distance,
|
||||
nprobes: None,
|
||||
nprobes: self.nprobes,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
@@ -942,45 +1031,99 @@ mod tests {
|
||||
assert_eq!(next, None);
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// A location that is not the index's own is refused before anything is
|
||||
/// opened or removed.
|
||||
#[tokio::test]
|
||||
async fn drop_index_refuses_a_location_outside_the_table() {
|
||||
for location in ["s3://bkt/vector", "s3://bkt/vector/prod"] {
|
||||
let server = VectorServer::new(
|
||||
NamespaceClient::new(catalog_describing(location).await),
|
||||
FallbackOptions::new(),
|
||||
);
|
||||
let server = VectorServer::new();
|
||||
for location in [
|
||||
"s3://bkt/vector",
|
||||
"s3://bkt/vector/prod",
|
||||
"s3://other/vector/x",
|
||||
] {
|
||||
let request = pb::DropIndexRequest {
|
||||
table: Some(pb::Table {
|
||||
id: vec!["bkt".into(), "vector".into(), "x".into()],
|
||||
version: 0,
|
||||
location: location.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let err = server
|
||||
.drop_index(Request::new(request))
|
||||
.await
|
||||
.expect_err(location);
|
||||
assert_eq!(err.code(), tonic::Code::FailedPrecondition, "{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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+1
@@ -4608,6 +4608,7 @@ dependencies = [
|
||||
"jsonwebtoken",
|
||||
"kamadak-exif",
|
||||
"libc",
|
||||
"lru",
|
||||
"md-5",
|
||||
"memmap2",
|
||||
"mime_guess",
|
||||
|
||||
@@ -130,6 +130,7 @@ chrono = "0.4"
|
||||
hex = "0.4"
|
||||
parking_lot = "0.12"
|
||||
dashmap = "6"
|
||||
lru = "0.16"
|
||||
thiserror = "1"
|
||||
anyhow = "1"
|
||||
async-trait = "0.1"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use clap::Parser;
|
||||
use std::ffi::OsString;
|
||||
use std::net::UdpSocket;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::security::tls::TlsPolicy;
|
||||
|
||||
@@ -1051,8 +1051,6 @@ 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
|
||||
@@ -1272,39 +1270,10 @@ fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBu
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
|
||||
default_security_config_candidates(
|
||||
seaweed_common::security_config::find(
|
||||
std::env::current_dir().ok().as_deref(),
|
||||
home_dir_from_env(env).as_deref(),
|
||||
seaweed_common::security_config::home_dir(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.
|
||||
@@ -1403,7 +1372,9 @@ 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
|
||||
|
||||
@@ -143,12 +143,12 @@ fn flip_horizontal_if(img: DynamicImage, do_flip: bool) -> DynamicImage {
|
||||
DynamicImage::ImageRgba8(out)
|
||||
}
|
||||
|
||||
/// Returns true if the given MIME type or file path extension indicates a JPEG file.
|
||||
pub fn is_jpeg(mime_type: &str, path: &str) -> bool {
|
||||
/// Returns true if the given MIME type or file name extension indicates a JPEG file.
|
||||
pub fn is_jpeg(mime_type: &str, filename: &str) -> bool {
|
||||
if mime_type == "image/jpeg" {
|
||||
return true;
|
||||
}
|
||||
let lower = path.to_lowercase();
|
||||
let lower = filename.to_lowercase();
|
||||
lower.ends_with(".jpg") || lower.ends_with(".jpeg")
|
||||
}
|
||||
|
||||
|
||||
+185
-35
@@ -118,6 +118,17 @@ 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>> {
|
||||
@@ -129,14 +140,12 @@ fn build_outgoing_http_client(
|
||||
let redirect_policy = reqwest::redirect::Policy::custom(reject_https_downgrade);
|
||||
if !config.https_client_enabled {
|
||||
return Ok((
|
||||
reqwest::Client::builder()
|
||||
.redirect(redirect_policy)
|
||||
.build()?,
|
||||
outgoing_client_builder(redirect_policy).build()?,
|
||||
scheme.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut builder = reqwest::Client::builder().redirect(redirect_policy);
|
||||
let mut builder = outgoing_client_builder(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!(
|
||||
@@ -708,7 +717,8 @@ 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);
|
||||
let incoming =
|
||||
grpc_tls_incoming(grpc_listener, tls_acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
|
||||
info!("gRPC server listening on {} (TLS enabled)", grpc_local_addr);
|
||||
build_grpc_server_builder()
|
||||
.layer(GrpcRequestIdLayer)
|
||||
@@ -845,40 +855,39 @@ async fn run(
|
||||
}))
|
||||
};
|
||||
|
||||
// Wait for servers. Use select! with &mut so the losing handle is not
|
||||
// dropped, then await it explicitly afterward.
|
||||
// Whichever server stops first takes the other down, as a serve failure
|
||||
// is fatal for the Go volume server.
|
||||
let mut server_err: Option<String> = None;
|
||||
let mut http_handle = http_handle;
|
||||
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
|
||||
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)
|
||||
}
|
||||
};
|
||||
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;
|
||||
}
|
||||
@@ -946,28 +955,64 @@ 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>,
|
||||
> {
|
||||
async_stream::stream! {
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
tokio::spawn(async move {
|
||||
let mut retry_delay = std::time::Duration::ZERO;
|
||||
loop {
|
||||
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) => {
|
||||
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)) => {
|
||||
tracing::debug!("gRPC TLS handshake failed from {}: {}", remote_addr, e);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
yield Err(e);
|
||||
break;
|
||||
Err(_) => {
|
||||
tracing::debug!("gRPC TLS handshake from {} timed out", remote_addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
tokio_stream::wrappers::ReceiverStream::new(rx)
|
||||
}
|
||||
|
||||
/// Serve an axum Router over TLS using tokio-rustls.
|
||||
@@ -1074,16 +1119,121 @@ async fn serve_https<F>(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
build_grpc_server_tls_acceptor, effective_http_tls_policy, tls_policy_is_configured,
|
||||
GRPC_TLS_HANDSHAKE_TIMEOUT, build_grpc_server_tls_acceptor, effective_http_tls_policy,
|
||||
grpc_tls_incoming, 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();
|
||||
|
||||
@@ -252,6 +252,21 @@ 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(|| {
|
||||
@@ -402,6 +417,7 @@ 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
File diff suppressed because it is too large.
Load diff
@@ -64,10 +64,11 @@ 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;
|
||||
// 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;
|
||||
// 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;
|
||||
|
||||
loop {
|
||||
let mut tried_hints: HashSet<String> = HashSet::new();
|
||||
@@ -110,7 +111,7 @@ pub async fn run_heartbeat_with_state(
|
||||
&leader,
|
||||
pulse,
|
||||
&mut shutdown_rx,
|
||||
&mut confirmed_leader_once,
|
||||
&mut leader_lost_at,
|
||||
&mut duplicate_retry_count,
|
||||
)
|
||||
.await;
|
||||
@@ -134,7 +135,7 @@ pub async fn run_heartbeat_with_state(
|
||||
master_addr,
|
||||
pulse,
|
||||
&mut shutdown_rx,
|
||||
&mut confirmed_leader_once,
|
||||
&mut leader_lost_at,
|
||||
&mut duplicate_retry_count,
|
||||
)
|
||||
.await
|
||||
@@ -168,7 +169,7 @@ async fn heartbeat_once(
|
||||
target_addr: &str,
|
||||
pulse: Duration,
|
||||
shutdown_rx: &mut broadcast::Receiver<()>,
|
||||
confirmed_leader_once: &mut bool,
|
||||
leader_lost_at: &mut Option<tokio::time::Instant>,
|
||||
duplicate_retry_count: &mut u32,
|
||||
) -> Option<String> {
|
||||
let grpc_addr = to_grpc_address(target_addr);
|
||||
@@ -181,17 +182,22 @@ async fn heartbeat_once(
|
||||
SleepDuplicate(Duration),
|
||||
SleepPulse,
|
||||
}
|
||||
let action = match do_heartbeat(
|
||||
let mut confirmed_leader = false;
|
||||
let result = do_heartbeat(
|
||||
config,
|
||||
state,
|
||||
&grpc_addr,
|
||||
target_addr,
|
||||
pulse,
|
||||
shutdown_rx,
|
||||
confirmed_leader_once,
|
||||
&mut confirmed_leader,
|
||||
)
|
||||
.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);
|
||||
@@ -200,10 +206,7 @@ async fn heartbeat_once(
|
||||
*duplicate_retry_count = 0;
|
||||
return None;
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg = e.to_string();
|
||||
// Drop `e` (non-Send) before any .await
|
||||
drop(e);
|
||||
Err(err_msg) => {
|
||||
warn!("Heartbeat to {} error: {}", grpc_addr, err_msg);
|
||||
|
||||
if err_msg.contains(DUPLICATE_UUID_RETRY_MESSAGE) {
|
||||
@@ -236,16 +239,17 @@ 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() || !*confirmed_leader_once)
|
||||
&& (!state.current_master().await.is_empty() || unregistered_or_just_lost)
|
||||
{
|
||||
// A leader just named by the refresh usually accepts the
|
||||
// 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.
|
||||
// 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.
|
||||
wait = Duration::from_secs(1);
|
||||
}
|
||||
tokio::time::sleep(wait).await;
|
||||
@@ -465,6 +469,9 @@ 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(
|
||||
(
|
||||
@@ -481,6 +488,8 @@ 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()
|
||||
},
|
||||
@@ -503,7 +512,17 @@ fn diff_ec_shard_delta_messages(
|
||||
let mut deleted_ec_shards = Vec::new();
|
||||
|
||||
for (key, message) in current {
|
||||
if previous.get(key) != Some(message) {
|
||||
// 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 {
|
||||
new_ec_shards.push(message.clone());
|
||||
}
|
||||
}
|
||||
@@ -549,7 +568,7 @@ async fn do_heartbeat(
|
||||
current_master: &str,
|
||||
pulse: Duration,
|
||||
shutdown_rx: &mut broadcast::Receiver<()>,
|
||||
confirmed_leader_once: &mut bool,
|
||||
confirmed_leader: &mut bool,
|
||||
) -> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let channel = connect_channel(
|
||||
grpc_addr,
|
||||
@@ -596,7 +615,6 @@ async fn do_heartbeat(
|
||||
volume_tick.tick().await;
|
||||
ec_tick.tick().await;
|
||||
|
||||
let mut confirmed_leader = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
resp = response_stream.message() => {
|
||||
@@ -614,12 +632,11 @@ 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_once = true;
|
||||
*confirmed_leader = true;
|
||||
publish_current_master(state, current_master).await;
|
||||
}
|
||||
if !hb_resp.duplicated_uuids.is_empty() {
|
||||
@@ -1051,15 +1068,17 @@ fn collect_heartbeat_with_snapshot(
|
||||
master_pb::Heartbeat,
|
||||
Vec<master_pb::VolumeInformationMessage>,
|
||||
) {
|
||||
let (_, expired_ec) = state.store.read().unwrap().find_expired_ec_volumes();
|
||||
let mut deleted_ec_shards = Vec::new();
|
||||
let (_, expired_ec, mut deleted_ec_shards) =
|
||||
state.store.read().unwrap().find_expired_ec_volumes();
|
||||
if !expired_ec.is_empty() {
|
||||
deleted_ec_shards = state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.remove_expired_ec_volumes(expired_ec)
|
||||
.0;
|
||||
deleted_ec_shards.extend(
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.remove_expired_ec_volumes(expired_ec)
|
||||
.0,
|
||||
);
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
@@ -2413,6 +2432,169 @@ 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]
|
||||
@@ -2903,6 +3085,46 @@ 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();
|
||||
@@ -2931,7 +3153,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))]);
|
||||
@@ -3157,4 +3379,88 @@ 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, ¤t);
|
||||
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, ¤t);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ use tonic::Request;
|
||||
|
||||
use crate::pb::master_pb::{self, LookupEcVolumeRequest};
|
||||
use crate::pb::volume_server_pb::{
|
||||
CopyFileRequest, VolumeEcBlobDeleteRequest, VolumeEcShardReadRequest,
|
||||
CopyFileRequest, VolumeEcBlobDeleteRequest, VolumeEcShardReadRequest, VolumeEcShardReadResponse,
|
||||
};
|
||||
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),
|
||||
intervals: read_local_intervals(ecv, &intervals, true),
|
||||
encode_ts_ns: ecv.encode_ts_ns,
|
||||
})
|
||||
}
|
||||
@@ -1052,20 +1052,29 @@ struct ScrubSnapshot {
|
||||
}
|
||||
|
||||
/// Read any locally-held shard intervals, marking the rest `NeedRemote`. Shared
|
||||
/// by the read-path `build_snapshot` and the scrub snapshot.
|
||||
/// by the read-path `build_snapshot` and the scrub snapshot. Shards on a
|
||||
/// quarantined disk count as not local unless `allow_quarantined` is set.
|
||||
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());
|
||||
let local = ecv
|
||||
.shards
|
||||
.get(shard_id as usize)
|
||||
.and_then(|s| s.as_ref())
|
||||
.filter(|_| !skip_local);
|
||||
match local {
|
||||
Some(shard) => {
|
||||
let mut buf = vec![0u8; buf_size];
|
||||
match shard.read_at(&mut buf, shard_offset as u64) {
|
||||
let read = shard.read_at(&mut buf, shard_offset as u64);
|
||||
ecv.check_read_write_error(read.as_ref().err());
|
||||
match read {
|
||||
Ok(n) if n == buf_size => interval_results.push(IntervalResult::Local(buf)),
|
||||
_ => interval_results.push(IntervalResult::NeedRemote {
|
||||
shard_id,
|
||||
@@ -1101,7 +1110,7 @@ fn build_snapshot(
|
||||
));
|
||||
}
|
||||
let actual = get_actual_size(size, ecv.version);
|
||||
let interval_results = read_local_intervals(ecv, intervals);
|
||||
let interval_results = read_local_intervals(ecv, intervals, false);
|
||||
let metas = intervals
|
||||
.iter()
|
||||
.map(|iv| {
|
||||
@@ -1356,7 +1365,82 @@ async fn fetch_one_interval(
|
||||
|
||||
// Reconstruct: fan-out reads to every other shard at the same
|
||||
// (shard_offset, size). Mirrors `recoverOneRemoteEcShardInterval`.
|
||||
recover_one_remote_ec_shard_interval(state, iv, map, &HashSet::from([iv.shard_id])).await
|
||||
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(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async fn read_remote_ec_shard_interval(
|
||||
@@ -1429,15 +1513,30 @@ async fn do_read_remote_ec_shard_interval(
|
||||
vid.0, shard_id, source, e
|
||||
))
|
||||
})?;
|
||||
let mut stream = resp.into_inner();
|
||||
collect_ec_shard_read(resp.into_inner(), source, iv).await
|
||||
}
|
||||
|
||||
/// 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;
|
||||
while let Some(msg) = stream
|
||||
.message()
|
||||
.await
|
||||
.map_err(|e| io::Error::other(format!("recv: {}", e)))?
|
||||
{
|
||||
// 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)))?,
|
||||
} {
|
||||
// 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.
|
||||
@@ -1516,6 +1615,7 @@ 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() {
|
||||
@@ -1541,13 +1641,15 @@ 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];
|
||||
if shard
|
||||
.read_at(&mut buf, shard_offset as u64)
|
||||
.map(|n| n == size)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
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) {
|
||||
*slot = Some(buf);
|
||||
available += 1;
|
||||
}
|
||||
@@ -1623,6 +1725,31 @@ 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)
|
||||
}
|
||||
|
||||
@@ -1767,10 +1894,11 @@ 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, 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.
|
||||
/// 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.
|
||||
async fn rebuild_ec_shard_needle(
|
||||
state: &Arc<VolumeServerState>,
|
||||
metas: &[EcInterval],
|
||||
@@ -1808,9 +1936,19 @@ async fn rebuild_ec_shard_needle(
|
||||
return (Some(candidate), false);
|
||||
}
|
||||
}
|
||||
if suspects.len() == 1 {
|
||||
return (None, 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);
|
||||
}
|
||||
for shard_id in suspects {
|
||||
let (candidate, is_deleted) = try_ec_shard_needle_candidate(
|
||||
@@ -1954,6 +2092,239 @@ 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.
|
||||
@@ -2162,7 +2533,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_copy_stream(resp.into_inner(), vif_path).await {
|
||||
if let Err(e) = drain_optional_copy_stream(resp.into_inner(), vif_path).await {
|
||||
tracing::warn!(volume_id = m.vid.0, peer = %peer, "copy .vif: {}", e);
|
||||
}
|
||||
}
|
||||
@@ -2172,6 +2543,48 @@ 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>,
|
||||
@@ -2210,6 +2623,139 @@ 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()]))
|
||||
@@ -2235,4 +2781,58 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ use tracing::debug;
|
||||
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::types::{Size, VolumeId};
|
||||
use crate::storage::volume::VolumeError;
|
||||
use crate::storage::volume::{PendingWrite, VolumeError};
|
||||
|
||||
use super::volume_server::VolumeServerState;
|
||||
|
||||
@@ -26,7 +26,12 @@ 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>)>;
|
||||
type VolumeBatch = Vec<(
|
||||
Needle,
|
||||
bool,
|
||||
oneshot::Sender<WriteResult>,
|
||||
Option<PendingWrite>,
|
||||
)>;
|
||||
|
||||
/// A request to write a needle, submitted to the write queue.
|
||||
pub struct WriteRequest {
|
||||
@@ -38,6 +43,8 @@ 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.
|
||||
@@ -167,12 +174,13 @@ impl WriteQueue {
|
||||
#[cfg(test)]
|
||||
self.submits
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
{
|
||||
let pending = {
|
||||
let store = self.state.store.read().unwrap();
|
||||
if store.find_volume(volume_id).is_none() {
|
||||
return Err(VolumeError::NotFound);
|
||||
match store.find_volume(volume_id) {
|
||||
Some((_, vol)) => vol.track_pending_write(&needle),
|
||||
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.
|
||||
@@ -189,6 +197,7 @@ 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
|
||||
@@ -345,10 +354,11 @@ 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((req.needle, req.fsync, req.response_tx));
|
||||
group.1.push(entry);
|
||||
} else {
|
||||
groups.push((vid, vec![(req.needle, req.fsync, req.response_tx)]));
|
||||
groups.push((vid, vec![entry]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,16 +366,28 @@ 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 results = match vol {
|
||||
Ok(vol) => vol.write_needles_grouped(&mut writes),
|
||||
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(pending)) = (&vol, &pending)
|
||||
&& !vol.tracks_pending_write(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),
|
||||
Err(e) => writes
|
||||
.iter()
|
||||
.map(|_| match e {
|
||||
@@ -577,6 +599,7 @@ mod tests {
|
||||
fsync: true,
|
||||
response_tx,
|
||||
queue_permit: None,
|
||||
pending: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -669,6 +692,7 @@ mod tests {
|
||||
fsync: false,
|
||||
response_tx,
|
||||
queue_permit: None,
|
||||
pending: None,
|
||||
}];
|
||||
let writer = {
|
||||
let state = state.clone();
|
||||
|
||||
@@ -581,6 +581,51 @@ 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` gets
|
||||
/// swallowed by `reload_bitrot_sidecar` cannot leave this describing a
|
||||
/// the same step as `bitrot`/`bitrot_status`, so a reload whose `Err` a
|
||||
/// caller ignores cannot leave this describing a
|
||||
/// sidecar other than the one those two fields actually hold.
|
||||
pub(crate) bitrot_source_dir: String,
|
||||
|
||||
@@ -802,14 +802,17 @@ 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.
|
||||
pub fn reload_bitrot_sidecar(&mut self, additional_dirs: &[String]) {
|
||||
if let Err(e) = self.load_active_bitrot_sidecar(additional_dirs) {
|
||||
/// 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 {
|
||||
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`.
|
||||
@@ -888,8 +891,8 @@ impl EcVolume {
|
||||
self.parity_shards as usize,
|
||||
);
|
||||
// Provenance is committed together with the sidecar it describes, so a
|
||||
// swallowed reload (`reload_bitrot_sidecar` logs and discards the `Err`
|
||||
// above) cannot leave them disagreeing: the geometry-mismatch return
|
||||
// reload whose `Err` above a caller ignores 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
|
||||
@@ -934,6 +937,31 @@ 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,7 +165,8 @@ impl SortedFileNeedleMap {
|
||||
return Ok(None);
|
||||
}
|
||||
let file = pooled_index_files().borrow(&self.db_file_name, true)?;
|
||||
let Some((entry_index, _, size)) = search_sorted_index(&file, self.db_file_size, key)?
|
||||
let Some((entry_index, needle_offset, size)) =
|
||||
search_sorted_index(&file, self.db_file_size, key)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -182,22 +183,14 @@ impl SortedFileNeedleMap {
|
||||
// already counts as deleted.
|
||||
self.append_to_index_file(key, offset, TOMBSTONE_FILE_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);
|
||||
// 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,
|
||||
});
|
||||
|
||||
// From here the delete is durable in `.idx`, so no lookup may report
|
||||
// this needle live again. Record it before touching `.sdx` and clear
|
||||
@@ -449,11 +442,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` 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
|
||||
/// 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
|
||||
/// computable in one sequential pass with no per-key state.
|
||||
fn index_metric(
|
||||
index_file_name: &str,
|
||||
@@ -462,15 +455,17 @@ fn index_metric(
|
||||
) -> io::Result<NeedleMapMetric> {
|
||||
let metric = NeedleMapMetric::default();
|
||||
|
||||
let mut rows: i64 = 0;
|
||||
let mut valid_bytes: u64 = 0;
|
||||
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 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 size.is_valid() {
|
||||
valid_bytes += size.0 as u64;
|
||||
if is_put(offset, size) {
|
||||
puts += 1;
|
||||
put_bytes += size.0 as u64;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -478,22 +473,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, |_, _, size| {
|
||||
if size.is_valid() {
|
||||
idx::walk_index_file(&mut db_file, 0, |_, offset, size| {
|
||||
if is_put(offset, size) {
|
||||
live += 1;
|
||||
live_bytes += size.0 as u64;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
metric.file_count.store(rows, Ordering::Relaxed);
|
||||
metric.file_byte_count.store(valid_bytes, Ordering::Relaxed);
|
||||
metric.file_count.store(puts, Ordering::Relaxed);
|
||||
metric.file_byte_count.store(put_bytes, Ordering::Relaxed);
|
||||
metric
|
||||
.deletion_count
|
||||
.store((rows - live).max(0), Ordering::Relaxed);
|
||||
.store((puts - live).max(0), Ordering::Relaxed);
|
||||
metric
|
||||
.deletion_byte_count
|
||||
.store(valid_bytes.saturating_sub(live_bytes), Ordering::Relaxed);
|
||||
.store(put_bytes.saturating_sub(live_bytes), Ordering::Relaxed);
|
||||
Ok(metric)
|
||||
}
|
||||
|
||||
@@ -617,11 +612,11 @@ mod tests {
|
||||
);
|
||||
|
||||
let m = SortedFileNeedleMap::open(&base, version()).unwrap();
|
||||
// Every row counts, matching Go's FileCounter.
|
||||
assert_eq!(m.file_count(), 5);
|
||||
// Every put row counts, matching Go's FileCounter; the tombstone does not.
|
||||
assert_eq!(m.file_count(), 4);
|
||||
assert_eq!(m.content_size(), 100 + 200 + 150 + 300);
|
||||
// Superseded row for key 1, plus both rows for the deleted key 2.
|
||||
assert_eq!(m.deleted_count(), 3);
|
||||
// Superseded row for key 1, plus the put of the deleted key 2.
|
||||
assert_eq!(m.deleted_count(), 2);
|
||||
assert_eq!(m.deleted_size(), 100 + 200);
|
||||
assert_eq!(m.max_file_key(), NeedleId(3));
|
||||
}
|
||||
@@ -709,8 +704,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(), 4);
|
||||
assert_eq!(reloaded.deleted_count(), 2);
|
||||
assert_eq!(reloaded.file_count(), 3);
|
||||
assert_eq!(reloaded.deleted_count(), 1);
|
||||
assert_eq!(reloaded.deleted_size(), 200);
|
||||
assert_eq!(reloaded.content_size(), 600);
|
||||
|
||||
@@ -718,7 +713,7 @@ mod tests {
|
||||
reloaded
|
||||
.delete(NeedleId(2), Offset::from_actual_offset(16))
|
||||
.unwrap();
|
||||
assert_eq!((reloaded.file_count(), reloaded.deleted_count()), (4, 2));
|
||||
assert_eq!((reloaded.file_count(), reloaded.deleted_count()), (3, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -960,7 +955,7 @@ mod tests {
|
||||
|
||||
assert_eq!(
|
||||
m.deleted_count(),
|
||||
deleted_before + 2,
|
||||
deleted_before + 1,
|
||||
"a durable tombstone must move the deletion count"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -979,7 +974,7 @@ mod tests {
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(m.deleted_count(), deleted_before + 2);
|
||||
assert_eq!(m.deleted_count(), deleted_before + 1);
|
||||
assert_eq!(m.deleted_size(), bytes_before + 100);
|
||||
}
|
||||
|
||||
|
||||
@@ -948,14 +948,39 @@ impl Store {
|
||||
vol.read_needle_opt(n, read_deleted)
|
||||
}
|
||||
|
||||
/// Resolve a needle read under this guard, to run after it is released.
|
||||
/// 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.
|
||||
pub(crate) fn needle_read_plan(
|
||||
&self,
|
||||
store: &std::sync::RwLock<Store>,
|
||||
vid: VolumeId,
|
||||
id: NeedleId,
|
||||
read_deleted: bool,
|
||||
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
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,
|
||||
}
|
||||
}
|
||||
vol.needle_read_plan(id, read_deleted)
|
||||
}
|
||||
|
||||
@@ -1157,13 +1182,14 @@ 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<(), VolumeError> {
|
||||
) -> Result<usize, 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
|
||||
@@ -1176,7 +1202,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 loc in &mut self.locations {
|
||||
for (disk, loc) in self.locations.iter_mut().enumerate() {
|
||||
// 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() {
|
||||
@@ -1201,7 +1227,7 @@ impl Store {
|
||||
&idx_dir,
|
||||
source_disk_type,
|
||||
) {
|
||||
Ok(()) => return Ok(()),
|
||||
Ok(()) => return Ok(disk),
|
||||
Err(VolumeError::Io(e)) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => failures.push((loc.directory.clone(), e)),
|
||||
}
|
||||
@@ -1466,22 +1492,27 @@ impl Store {
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let (mut ec_shards, expired) = self.find_expired_ec_volumes();
|
||||
let (deleted, still_held) = self.remove_expired_ec_volumes(expired);
|
||||
let (mut ec_shards, expired, quarantined) = self.find_expired_ec_volumes();
|
||||
let (mut 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, and
|
||||
/// the expired EC volumes, by disk index, for `remove_expired_ec_volumes`.
|
||||
/// 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.
|
||||
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() {
|
||||
@@ -1496,6 +1527,8 @@ 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
|
||||
@@ -1504,7 +1537,7 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
(ec_shards, expired)
|
||||
(ec_shards, expired, quarantined_now)
|
||||
}
|
||||
|
||||
/// The write half of `delete_expired_ec_volumes`: destroys each volume that
|
||||
@@ -3039,6 +3072,7 @@ 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();
|
||||
|
||||
@@ -3047,7 +3081,7 @@ mod tests {
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
2,
|
||||
5,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
@@ -3064,15 +3098,13 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// 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);
|
||||
// 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);
|
||||
store.locations[0].original_max_volume_count = 0;
|
||||
store.set_preallocate(true);
|
||||
|
||||
@@ -3385,6 +3417,207 @@ 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),
|
||||
|
||||
@@ -24,6 +24,7 @@ use crate::storage::disk_location::is_read_only_mount;
|
||||
use crate::storage::idx;
|
||||
use crate::storage::io::read_exact_at;
|
||||
use crate::storage::io_error::{IoErrorTracker, StreakMark};
|
||||
use crate::storage::needle::crc::CRC;
|
||||
use crate::storage::needle::needle::{self, Needle, NeedleError, get_actual_size};
|
||||
use crate::storage::needle_map::sorted_file::SortedFileNeedleMap;
|
||||
use crate::storage::needle_map::{CompactNeedleMap, NeedleMap, NeedleMapKind, RedbNeedleMap};
|
||||
@@ -552,6 +553,43 @@ pub(crate) mod needle_read_hook {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod commit_swap_hook {
|
||||
use super::VolumeId;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
type Hook = Arc<dyn Fn() + Send + Sync>;
|
||||
static HOOKS: Mutex<Vec<(VolumeId, Hook)>> = Mutex::new(Vec::new());
|
||||
|
||||
pub(crate) struct Registration(VolumeId);
|
||||
|
||||
impl Drop for Registration {
|
||||
fn drop(&mut self) {
|
||||
HOOKS.lock().unwrap().retain(|(id, _)| *id != self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs inside a compaction commit, after the needle map is closed and
|
||||
/// before the swap. Volume ids are the key, so parallel tests must use
|
||||
/// distinct ones.
|
||||
pub(crate) fn register(id: VolumeId, hook: impl Fn() + Send + Sync + 'static) -> Registration {
|
||||
HOOKS.lock().unwrap().push((id, Arc::new(hook)));
|
||||
Registration(id)
|
||||
}
|
||||
|
||||
pub(crate) fn fire(id: VolumeId) {
|
||||
let hook = HOOKS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|(hook_id, _)| *hook_id == id)
|
||||
.map(|(_, hook)| hook.clone());
|
||||
if let Some(hook) = hook {
|
||||
hook();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod needle_write_hook {
|
||||
use super::NeedleId;
|
||||
@@ -797,9 +835,8 @@ impl IoUnavailable {
|
||||
}
|
||||
}
|
||||
|
||||
/// A needle read resolved under a store guard and run after it is released;
|
||||
/// the handle pins the inode, as for `DatScanPlan`. It takes no data-file
|
||||
/// lease: writers wait for one while holding the store write lock.
|
||||
/// A needle read resolved under the data-file read lease and run after it is
|
||||
/// released; the handle pins the inode, as for `DatScanPlan`.
|
||||
pub(crate) struct NeedleReadPlan {
|
||||
source: NeedleStreamSource,
|
||||
offset: i64,
|
||||
@@ -809,6 +846,7 @@ pub(crate) struct NeedleReadPlan {
|
||||
data_file_access_control: Arc<DataFileAccessControl>,
|
||||
io_errors: Arc<IoErrorTracker>,
|
||||
io_unavailable: Arc<IoUnavailable>,
|
||||
load_generation: u64,
|
||||
}
|
||||
|
||||
impl NeedleReadPlan {
|
||||
@@ -888,6 +926,8 @@ impl NeedleReadPlan {
|
||||
io_errors: self.io_errors,
|
||||
needle_id: self.needle_id,
|
||||
checksum: n.checksum.0,
|
||||
append_at_ns: n.append_at_ns,
|
||||
load_generation: self.load_generation,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1169,6 +1209,224 @@ pub struct NeedleStreamInfo {
|
||||
/// Checksum stored in the needle tail, verified once the last chunk has
|
||||
/// been read — before that frame is emitted.
|
||||
pub checksum: u32,
|
||||
pub(crate) append_at_ns: u64,
|
||||
pub(crate) load_generation: u64,
|
||||
}
|
||||
|
||||
/// A range carries no checksum of its own, so a ranged read checks the whole
|
||||
/// needle's CRC the first time any range of it is read, recording the CRC of
|
||||
/// each block on the way. `VERIFIED_NEEDLES` keeps those block CRCs, and later
|
||||
/// ranges check just the blocks they cover, so damage that appears after the
|
||||
/// first check is still caught. Entries are per volume load, so a remounted
|
||||
/// copy or a compaction is checked again, and concurrent first reads of a
|
||||
/// needle share one check.
|
||||
static VERIFIED_NEEDLES: LazyLock<Mutex<lru::LruCache<VerifiedNeedle, Arc<[u32]>>>> =
|
||||
LazyLock::new(|| {
|
||||
Mutex::new(lru::LruCache::new(
|
||||
std::num::NonZeroUsize::new(64 * 1024).unwrap(),
|
||||
))
|
||||
});
|
||||
static VERIFYING_NEEDLES: LazyLock<Mutex<HashMap<VerifiedNeedle, Arc<VerifyingNeedle>>>> =
|
||||
LazyLock::new(Default::default);
|
||||
static VOLUME_LOADS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct VerifiedNeedle {
|
||||
load_generation: u64,
|
||||
id: NeedleId,
|
||||
append_at_ns: u64,
|
||||
checksum: u32,
|
||||
}
|
||||
|
||||
const RANGE_CHECK_BLOCKS: u64 = 64;
|
||||
const MIN_RANGE_CHECK_BLOCK_SIZE: u64 = 64 * 1024;
|
||||
const MAX_RANGE_CHECK_BLOCK_SIZE: u64 = 1024 * 1024;
|
||||
|
||||
/// Keeps a needle to 64 blocks, each 64 KiB to 1 MiB, as Go's
|
||||
/// rangeCheckBlockSize.
|
||||
pub(crate) fn range_check_block_size(data_size: u64) -> u64 {
|
||||
let mut block_size = MIN_RANGE_CHECK_BLOCK_SIZE;
|
||||
while block_size < MAX_RANGE_CHECK_BLOCK_SIZE && data_size > RANGE_CHECK_BLOCKS * block_size {
|
||||
block_size *= 2;
|
||||
}
|
||||
block_size
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct VerifyingNeedle {
|
||||
outcome: Mutex<Option<Result<Arc<[u32]>, (io::ErrorKind, String)>>>,
|
||||
done: Condvar,
|
||||
}
|
||||
|
||||
/// Publishes the check's outcome to the readers waiting on it, also when the
|
||||
/// check unwinds.
|
||||
struct VerifyingNeedleGuard {
|
||||
key: VerifiedNeedle,
|
||||
call: Arc<VerifyingNeedle>,
|
||||
}
|
||||
|
||||
impl Drop for VerifyingNeedleGuard {
|
||||
fn drop(&mut self) {
|
||||
let mut outcome = self.call.outcome.lock().unwrap_or_else(|e| e.into_inner());
|
||||
outcome.get_or_insert_with(|| {
|
||||
Err((
|
||||
io::ErrorKind::Other,
|
||||
"needle checksum check did not finish".into(),
|
||||
))
|
||||
});
|
||||
drop(outcome);
|
||||
self.call.done.notify_all();
|
||||
VERIFYING_NEEDLES
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.remove(&self.key);
|
||||
}
|
||||
}
|
||||
|
||||
impl NeedleStreamInfo {
|
||||
/// Whether `data`, the whole payload, matches the checksum in the tail.
|
||||
pub(crate) fn checksum_matches(&self, data: &[u8]) -> bool {
|
||||
let crc = CRC::new(data);
|
||||
self.checksum == crc.0 || self.checksum == crc.legacy_value()
|
||||
}
|
||||
|
||||
/// Check the whole needle's CRC before any byte of a range is sent, so a
|
||||
/// damaged replica fails the read and the reader tries another copy, and
|
||||
/// return the CRC of each block for `read_checked_range`.
|
||||
pub(crate) fn verify_checksum(&self, chunk_size: usize) -> io::Result<Arc<[u32]>> {
|
||||
let key = VerifiedNeedle {
|
||||
load_generation: self.load_generation,
|
||||
id: self.needle_id,
|
||||
append_at_ns: self.append_at_ns,
|
||||
checksum: self.checksum,
|
||||
};
|
||||
if let Some(crcs) = VERIFIED_NEEDLES
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.get(&key)
|
||||
{
|
||||
return Ok(crcs.clone());
|
||||
}
|
||||
let (call, leader) = {
|
||||
let mut calls = VERIFYING_NEEDLES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match calls.get(&key) {
|
||||
Some(call) => (call.clone(), false),
|
||||
None => {
|
||||
let call = Arc::new(VerifyingNeedle::default());
|
||||
calls.insert(key, call.clone());
|
||||
(call, true)
|
||||
}
|
||||
}
|
||||
};
|
||||
if !leader {
|
||||
let mut outcome = call.outcome.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while outcome.is_none() {
|
||||
outcome = call.done.wait(outcome).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
return outcome
|
||||
.clone()
|
||||
.unwrap()
|
||||
.map_err(|(kind, msg)| io::Error::new(kind, msg));
|
||||
}
|
||||
let guard = VerifyingNeedleGuard { key, call };
|
||||
let result = self.read_checksum(chunk_size);
|
||||
if let Ok(crcs) = &result {
|
||||
VERIFIED_NEEDLES
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.put(key, crcs.clone());
|
||||
}
|
||||
*guard.call.outcome.lock().unwrap_or_else(|e| e.into_inner()) = Some(
|
||||
result
|
||||
.as_ref()
|
||||
.map(Arc::clone)
|
||||
.map_err(|e| (e.kind(), e.to_string())),
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
/// Read the whole payload in chunks and compare its CRC, recording the CRC
|
||||
/// of each block. A read failure counts toward the io error streak; a pass
|
||||
/// leaves the streak to the range read that follows.
|
||||
fn read_checksum(&self, chunk_size: usize) -> io::Result<Arc<[u32]>> {
|
||||
let total = self.data_size as usize;
|
||||
let block_size = range_check_block_size(self.data_size as u64) as usize;
|
||||
let mut buf = vec![0u8; chunk_size.clamp(1, total.max(1))];
|
||||
let mut crc = CRC(0);
|
||||
let mut block_crc = CRC(0);
|
||||
let mut crcs = Vec::with_capacity(total.div_ceil(block_size));
|
||||
let mut pos = 0;
|
||||
while pos < total {
|
||||
let len = buf
|
||||
.len()
|
||||
.min(total - pos)
|
||||
.min(block_size - pos % block_size);
|
||||
if let Err(e) = self
|
||||
.source
|
||||
.read_exact_at(&mut buf[..len], self.data_file_offset + pos as u64)
|
||||
{
|
||||
self.io_errors.check_read_write_error(Some(&e));
|
||||
return Err(e);
|
||||
}
|
||||
crc = crc.update(&buf[..len]);
|
||||
block_crc = block_crc.update(&buf[..len]);
|
||||
pos += len;
|
||||
if pos % block_size == 0 || pos == total {
|
||||
crcs.push(block_crc.0);
|
||||
block_crc = CRC(0);
|
||||
}
|
||||
}
|
||||
if self.checksum != crc.0 && self.checksum != crc.legacy_value() {
|
||||
crate::metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[crate::metrics::ERROR_CRC])
|
||||
.inc();
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"needle data checksum {} expected {} for needle {}",
|
||||
crc.0, self.checksum, self.needle_id
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(crcs.into())
|
||||
}
|
||||
|
||||
/// Read whole blocks around `[start, start + length)`, check each against
|
||||
/// the CRC `verify_checksum` recorded, and return the range's bytes, so
|
||||
/// damage that appears after the needle passed its check is not served.
|
||||
pub(crate) fn read_checked_range(
|
||||
&self,
|
||||
crcs: &[u32],
|
||||
start: u64,
|
||||
length: u64,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
let block_size = range_check_block_size(self.data_size as u64);
|
||||
let span_start = start / block_size * block_size;
|
||||
let span_end = (start + length).div_ceil(block_size) * block_size;
|
||||
let span_end = span_end.min(self.data_size as u64);
|
||||
let mut buf = vec![0u8; (span_end - span_start) as usize];
|
||||
self.source
|
||||
.read_exact_at(&mut buf, self.data_file_offset + span_start)?;
|
||||
for (i, block) in buf.chunks(block_size as usize).enumerate() {
|
||||
let index = (span_start / block_size) as usize + i;
|
||||
if crcs.get(index) != Some(&CRC::new(block).0) {
|
||||
crate::metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[crate::metrics::ERROR_CRC])
|
||||
.inc();
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"checksum mismatch in block {} of needle {}",
|
||||
index, self.needle_id
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
let from = (start - span_start) as usize;
|
||||
buf.truncate(from + length as usize);
|
||||
buf.drain(..from);
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -1368,6 +1626,8 @@ pub struct Volume {
|
||||
/// `data_file_sync_lock` -> `data_file_access_control` -> `io`.
|
||||
data_file_sync_lock: std::sync::Mutex<()>,
|
||||
|
||||
pending_writes: Arc<PendingWrites>,
|
||||
|
||||
/// Go's superBlockAccessLock.
|
||||
super_block: RwLock<SuperBlock>,
|
||||
|
||||
@@ -1404,6 +1664,9 @@ pub struct Volume {
|
||||
/// for volume health monitoring.
|
||||
io_errors: Arc<IoErrorTracker>,
|
||||
|
||||
/// Changes on every load, including a compaction commit.
|
||||
load_generation: AtomicU64,
|
||||
|
||||
/// Protobuf VolumeInfo for tiered storage (.vif file), Go's
|
||||
/// volumeInfoRWLock domain.
|
||||
///
|
||||
@@ -1417,6 +1680,36 @@ pub struct Volume {
|
||||
const NO_WRITE_OR_DELETE: u8 = 1;
|
||||
const NO_WRITE_CAN_DELETE: u8 = 2;
|
||||
|
||||
#[derive(Default)]
|
||||
struct PendingWrites(Mutex<HashMap<NeedleId, Vec<Arc<CancelFlag>>>>);
|
||||
|
||||
struct CancelFlag {
|
||||
cookie: Cookie,
|
||||
cancelled: AtomicBool,
|
||||
}
|
||||
|
||||
/// A write that has entered the volume but not returned yet. A delete of its
|
||||
/// needle in that window cancels it: the write may still be queued behind the
|
||||
/// volume locks, and landing after the delete would revive the needle on this
|
||||
/// copy alone. Dropping it untracks the write.
|
||||
pub struct PendingWrite {
|
||||
writes: Arc<PendingWrites>,
|
||||
id: NeedleId,
|
||||
flag: Arc<CancelFlag>,
|
||||
}
|
||||
|
||||
impl Drop for PendingWrite {
|
||||
fn drop(&mut self) {
|
||||
let mut by_id = self.writes.0.lock().unwrap();
|
||||
if let Some(writes) = by_id.get_mut(&self.id) {
|
||||
writes.retain(|w| !Arc::ptr_eq(w, &self.flag));
|
||||
if writes.is_empty() {
|
||||
by_id.remove(&self.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a volume is created with beyond its id, directories and index kind:
|
||||
/// the tail of Go's `NewVolume` argument list. The default is an empty
|
||||
/// collection with no replication, no TTL and no preallocation at the
|
||||
@@ -1491,6 +1784,7 @@ impl Volume {
|
||||
needle_map_kind,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
data_file_sync_lock: std::sync::Mutex::new(()),
|
||||
pending_writes: Arc::default(),
|
||||
super_block: RwLock::new(SuperBlock {
|
||||
replica_placement: replica_placement.unwrap_or_default(),
|
||||
ttl: ttl.unwrap_or(crate::storage::needle::ttl::TTL::EMPTY),
|
||||
@@ -1505,6 +1799,7 @@ impl Volume {
|
||||
closed: AtomicBool::new(false),
|
||||
compaction_byte_per_second: AtomicI64::new(0),
|
||||
io_errors: Arc::default(),
|
||||
load_generation: AtomicU64::new(0),
|
||||
volume_info: RwLock::new(PbVolumeInfo::default()),
|
||||
};
|
||||
|
||||
@@ -1548,6 +1843,7 @@ impl Volume {
|
||||
needle_map_kind: NeedleMapKind::InMemory,
|
||||
data_file_access_control: Arc::new(DataFileAccessControl::default()),
|
||||
data_file_sync_lock: std::sync::Mutex::new(()),
|
||||
pending_writes: Arc::default(),
|
||||
super_block: RwLock::new(SuperBlock::default()),
|
||||
no_write: AtomicU8::new(0),
|
||||
io_unavailable: Arc::default(),
|
||||
@@ -1558,6 +1854,7 @@ impl Volume {
|
||||
closed: AtomicBool::new(false),
|
||||
compaction_byte_per_second: AtomicI64::new(0),
|
||||
io_errors: Arc::default(),
|
||||
load_generation: AtomicU64::new(0),
|
||||
volume_info: RwLock::new(PbVolumeInfo::default()),
|
||||
}
|
||||
}
|
||||
@@ -1682,6 +1979,10 @@ impl Volume {
|
||||
preallocate: u64,
|
||||
version: Version,
|
||||
) -> Result<(), VolumeError> {
|
||||
self.load_generation.store(
|
||||
VOLUME_LOADS.fetch_add(1, Ordering::Relaxed) + 1,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
let dat_path = self.file_name(".dat");
|
||||
let mut already_has_super_block = false;
|
||||
|
||||
@@ -2641,12 +2942,17 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve a needle read under the caller's store guard, without data I/O.
|
||||
/// Resolve a needle read without data I/O. It takes the data-file read
|
||||
/// lease, as `read_needle_with_option` does, so a plan made 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.
|
||||
/// Callers must not hold the store guard; see `Store::needle_read_plan`.
|
||||
pub(crate) fn needle_read_plan(
|
||||
&self,
|
||||
id: NeedleId,
|
||||
read_deleted: bool,
|
||||
) -> Result<NeedleReadPlan, VolumeError> {
|
||||
let _guard = self.data_file_access_control.read_lock();
|
||||
if let Some(e) = self.unavailable_error() {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -2683,6 +2989,7 @@ impl Volume {
|
||||
data_file_access_control: self.data_file_access_control.clone(),
|
||||
io_errors: self.io_errors.clone(),
|
||||
io_unavailable: self.io_unavailable.clone(),
|
||||
load_generation: self.load_generation.load(Ordering::Relaxed),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2735,6 +3042,15 @@ impl Volume {
|
||||
pub fn write_needle_unsynced_or_refused(
|
||||
&self,
|
||||
n: &mut Needle,
|
||||
) -> Result<Result<(u64, Size, bool), VolumeError>, VolumeError> {
|
||||
self.write_pending_needle_unsynced(n, None)
|
||||
}
|
||||
|
||||
/// write_needle_unsynced_or_refused for a write a delete can cancel.
|
||||
pub fn write_pending_needle_unsynced(
|
||||
&self,
|
||||
n: &mut Needle,
|
||||
pending: Option<&PendingWrite>,
|
||||
) -> Result<Result<(u64, Size, bool), VolumeError>, VolumeError> {
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
@@ -2742,7 +3058,9 @@ impl Volume {
|
||||
if let Err(refused) = self.check_writable() {
|
||||
return Ok(Err(refused));
|
||||
}
|
||||
self.do_write_request(&mut io, n, true, false).map(Ok)
|
||||
let written = self.do_write_request(&mut io, n, true, false)?;
|
||||
self.drop_cancelled_write(&mut io, pending, n, &written)?;
|
||||
Ok(Ok(written))
|
||||
}
|
||||
|
||||
/// Write a batch of needles the way Go's processBatch does: one .dat
|
||||
@@ -2756,6 +3074,16 @@ impl Volume {
|
||||
pub fn write_needles_grouped(
|
||||
&self,
|
||||
writes: &mut [(Needle, bool)],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
self.write_pending_needles(writes, &[])
|
||||
}
|
||||
|
||||
/// write_needles_grouped for writes a delete can cancel, `pending[i]`
|
||||
/// tracking `writes[i]`.
|
||||
pub fn write_pending_needles(
|
||||
&self,
|
||||
writes: &mut [(Needle, bool)],
|
||||
pending: &[Option<PendingWrite>],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
// The sync lock serializes a .dat mutation with the flush that makes
|
||||
// it durable: a failed sync's rollback can never clobber an append
|
||||
@@ -2770,16 +3098,21 @@ impl Volume {
|
||||
let mut ids = HashSet::new();
|
||||
let len = rest.iter().take_while(|(n, _)| ids.insert(n.id)).count();
|
||||
let (run, tail) = std::mem::take(&mut rest).split_at_mut(len);
|
||||
let tracked = pending.get(results.len()..).unwrap_or_default();
|
||||
if run.iter().any(|(_, fsync)| *fsync) {
|
||||
results.extend(self.write_synced_run(run));
|
||||
results.extend(self.write_synced_run(run, tracked));
|
||||
} else {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
for (n, _) in run.iter_mut() {
|
||||
results.push(
|
||||
self.check_writable()
|
||||
.and_then(|()| self.do_write_request(&mut io, n, true, false)),
|
||||
);
|
||||
for (i, (n, _)) in run.iter_mut().enumerate() {
|
||||
let written = self
|
||||
.check_writable()
|
||||
.and_then(|()| self.do_write_request(&mut io, n, true, false));
|
||||
results.push(written.and_then(|written| {
|
||||
let pending = tracked.get(i).and_then(Option::as_ref);
|
||||
self.drop_cancelled_write(&mut io, pending, n, &written)
|
||||
.map(|()| written)
|
||||
}));
|
||||
}
|
||||
}
|
||||
rest = tail;
|
||||
@@ -2790,6 +3123,7 @@ impl Volume {
|
||||
fn write_synced_run(
|
||||
&self,
|
||||
run: &mut [(Needle, bool)],
|
||||
pending: &[Option<PendingWrite>],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
// Per entry: Some(offset) once appended, None when it dedups.
|
||||
let mut staged = Vec::with_capacity(run.len());
|
||||
@@ -2833,6 +3167,7 @@ impl Volume {
|
||||
}
|
||||
}
|
||||
|
||||
let mut took_back = false;
|
||||
{
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
@@ -2849,24 +3184,37 @@ impl Volume {
|
||||
// writes, so the entries after it are refused the way a lone
|
||||
// write would be.
|
||||
let mut refused = false;
|
||||
for ((n, fsync), r) in run.iter().zip(staged.iter_mut()) {
|
||||
for (i, ((n, fsync), r)) in run.iter().zip(staged.iter_mut()).enumerate() {
|
||||
if refused {
|
||||
*r = Err(self
|
||||
.check_writable()
|
||||
.err()
|
||||
.unwrap_or(VolumeError::ReadOnly(self.id)));
|
||||
} else if let Ok(Some(offset)) = *r
|
||||
&& let Err(e) = self.publish_write(&mut io, n, offset, *fsync)
|
||||
{
|
||||
*r = Err(e);
|
||||
refused = *fsync;
|
||||
} else if let Ok(Some(offset)) = *r {
|
||||
if let Err(e) = self.publish_write(&mut io, n, offset, *fsync) {
|
||||
*r = Err(e);
|
||||
refused = *fsync;
|
||||
} else if let Err(e) = self.drop_cancelled_write(
|
||||
&mut io,
|
||||
pending.get(i).and_then(Option::as_ref),
|
||||
n,
|
||||
&(offset, n.size, false),
|
||||
) {
|
||||
took_back |= matches!(e, VolumeError::Deleted);
|
||||
*r = Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sync {
|
||||
let io = self.io.read().unwrap();
|
||||
if let Err(e) = self.flush_idx(&io) {
|
||||
let flushed = if took_back {
|
||||
self.flush_taken_back(&io)
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
if let Err(e) = flushed.and_then(|()| self.flush_idx(&io)) {
|
||||
return staged
|
||||
.into_iter()
|
||||
.map(|r| r.and_then(|_| Err(run_error(&e))))
|
||||
@@ -2987,6 +3335,17 @@ impl Volume {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Flush the tombstones drop_cancelled_write appended after the .dat sync,
|
||||
/// so their .idx rows never outlive them. Like flush_idx, a failure cannot
|
||||
/// be undone and stops the volume taking writes.
|
||||
fn flush_taken_back(&self, io: &VolumeIo) -> Result<(), VolumeError> {
|
||||
self.flush_dat(io).map_err(|e| {
|
||||
self.check_read_write_error(Some(&e));
|
||||
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
|
||||
VolumeError::Io(e)
|
||||
})
|
||||
}
|
||||
|
||||
/// Take an unflushed append back off the .dat after its sync failed.
|
||||
pub(crate) fn truncate_dat(&self, io: &VolumeIo, len: u64) -> io::Result<()> {
|
||||
#[cfg(test)]
|
||||
@@ -3369,10 +3728,79 @@ impl Volume {
|
||||
Ok((offset, n.size, actual_size))
|
||||
}
|
||||
|
||||
pub fn track_pending_write(&self, n: &Needle) -> PendingWrite {
|
||||
let flag = Arc::new(CancelFlag {
|
||||
cookie: n.cookie,
|
||||
cancelled: AtomicBool::new(false),
|
||||
});
|
||||
self.pending_writes
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(n.id)
|
||||
.or_default()
|
||||
.push(flag.clone());
|
||||
PendingWrite {
|
||||
writes: self.pending_writes.clone(),
|
||||
id: n.id,
|
||||
flag,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the write was tracked on this volume rather than on one that
|
||||
/// has since been unmounted under the same id.
|
||||
pub fn tracks_pending_write(&self, pending: &PendingWrite) -> bool {
|
||||
Arc::ptr_eq(&pending.writes, &self.pending_writes)
|
||||
}
|
||||
|
||||
/// Cancels the writes of the needle that are in flight. A caller that found
|
||||
/// the needle missing must look it up again afterwards: a write that
|
||||
/// finished in between is no longer pending.
|
||||
pub fn cancel_pending_writes(&self, id: NeedleId, cookie: Cookie) {
|
||||
if let Some(writes) = self.pending_writes.0.lock().unwrap().get(&id) {
|
||||
for w in writes.iter().filter(|w| w.cookie == cookie) {
|
||||
w.cancelled.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tombstones a cancelled write right after it is published, under the
|
||||
/// same lock hold, so no reader, later write or compaction sees it live
|
||||
/// in between.
|
||||
fn drop_cancelled_write(
|
||||
&self,
|
||||
io: &mut VolumeIo,
|
||||
pending: Option<&PendingWrite>,
|
||||
n: &Needle,
|
||||
written: &(u64, Size, bool),
|
||||
) -> Result<(), VolumeError> {
|
||||
let (offset, _, unchanged) = *written;
|
||||
if unchanged || !pending.is_some_and(|p| p.flag.cancelled.load(Ordering::Acquire)) {
|
||||
return Ok(());
|
||||
}
|
||||
let live = match io.nm.as_ref() {
|
||||
Some(nm) => nm.get(n.id)?.is_some_and(|nv| {
|
||||
!nv.size.is_deleted() && nv.offset == Offset::from_actual_offset(offset as i64)
|
||||
}),
|
||||
None => false,
|
||||
};
|
||||
if !live {
|
||||
return Ok(());
|
||||
}
|
||||
let mut tombstone = Needle {
|
||||
id: n.id,
|
||||
cookie: n.cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
self.do_delete_request(io, &mut tombstone)?;
|
||||
Err(VolumeError::Deleted)
|
||||
}
|
||||
|
||||
// ---- Delete ----
|
||||
|
||||
/// Delete a needle from the volume.
|
||||
pub fn delete_needle(&self, n: &mut Needle) -> Result<Size, VolumeError> {
|
||||
self.cancel_pending_writes(n.id, n.cookie);
|
||||
let _sync_guard = self.data_file_sync_lock.lock().unwrap();
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
let mut io = self.io.write().unwrap();
|
||||
@@ -5558,6 +5986,8 @@ impl Volume {
|
||||
io.dat_file = None;
|
||||
io.remote_dat_file = None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
commit_swap_hook::fire(self.id);
|
||||
|
||||
// makeup_diff has fsynced the .cpd/.cpx contents. Persist a durable .cpc
|
||||
// commit marker BEFORE the renames so the two-rename swap is atomic
|
||||
@@ -6115,6 +6545,22 @@ impl Volume {
|
||||
self.io.read().unwrap()
|
||||
}
|
||||
|
||||
/// Holds the lock a write waits on behind another write's fsync.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn sync_lock_for_test(&self) -> std::sync::MutexGuard<'_, ()> {
|
||||
self.data_file_sync_lock.lock().unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pending_writes_for_test(&self, id: NeedleId) -> usize {
|
||||
self.pending_writes
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&id)
|
||||
.map_or(0, Vec::len)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn fail_next_fsync_for_test(&self, fail: bool) {
|
||||
self.io.write().unwrap().fail_fsync_for_test = fail;
|
||||
@@ -8441,6 +8887,171 @@ mod tests {
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
}
|
||||
|
||||
fn pending_needle(id: u64, data: &[u8]) -> Needle {
|
||||
Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(0xcc),
|
||||
data: data.to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn write_pending(
|
||||
v: &Volume,
|
||||
n: Needle,
|
||||
fsync: bool,
|
||||
pending: PendingWrite,
|
||||
) -> Result<(u64, Size, bool), VolumeError> {
|
||||
v.write_pending_needles(&mut [(n, fsync)], &[Some(pending)])
|
||||
.pop()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A delete that finds nothing can still have the write it undoes in
|
||||
/// flight. That write must not land live afterwards.
|
||||
#[test]
|
||||
fn test_delete_of_missing_needle_cancels_pending_write() {
|
||||
for fsync in [false, true] {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
|
||||
let n = pending_needle(1, b"late write");
|
||||
let pending = v.track_pending_write(&n);
|
||||
v.delete_needle(&mut pending_needle(1, b"")).unwrap();
|
||||
let err = write_pending(&v, n, fsync, pending).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
|
||||
let err = v.read_needle(&mut pending_needle(1, b"")).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
assert!(v.pending_writes.0.lock().unwrap().is_empty());
|
||||
|
||||
v.close();
|
||||
let v = Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
&VolumeSpec::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(v.read_needle(&mut pending_needle(1, b"")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// The unsynced write path takes a cancelled write back the same way.
|
||||
#[test]
|
||||
fn test_unsynced_write_cancelled_by_delete() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let v = make_test_volume(tmp.path().to_str().unwrap());
|
||||
|
||||
let mut n = pending_needle(1, b"late write");
|
||||
let pending = v.track_pending_write(&n);
|
||||
v.cancel_pending_writes(n.id, n.cookie);
|
||||
let err = v
|
||||
.write_pending_needle_unsynced(&mut n, Some(&pending))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
let err = v.read_needle(&mut pending_needle(1, b"")).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
}
|
||||
|
||||
/// A delete that finds a copy also cancels a retry of the same write that
|
||||
/// is still in flight, so the retry does not bring the needle back.
|
||||
#[test]
|
||||
fn test_delete_cancels_pending_rewrite() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
|
||||
v.write_needle(&mut pending_needle(1, b"first"), true, false)
|
||||
.unwrap();
|
||||
let rewrite = pending_needle(1, b"retry");
|
||||
let pending = v.track_pending_write(&rewrite);
|
||||
v.delete_needle(&mut pending_needle(1, b"")).unwrap();
|
||||
let err = write_pending(&v, rewrite, false, pending).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
let err = v.read_needle(&mut pending_needle(1, b"")).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
}
|
||||
|
||||
/// Only writes already in flight and carrying the delete's cookie are
|
||||
/// cancelled.
|
||||
#[test]
|
||||
fn test_pending_write_cancel_leaves_later_writes() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let v = make_test_volume(dir);
|
||||
|
||||
v.delete_needle(&mut pending_needle(1, b"")).unwrap();
|
||||
let n = pending_needle(1, b"after the delete");
|
||||
let pending = v.track_pending_write(&n);
|
||||
write_pending(&v, n, false, pending).unwrap();
|
||||
let mut got = pending_needle(1, b"");
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, b"after the delete");
|
||||
|
||||
let n = pending_needle(2, b"other cookie");
|
||||
let pending = v.track_pending_write(&n);
|
||||
v.cancel_pending_writes(n.id, Cookie(n.cookie.0 + 1));
|
||||
write_pending(&v, n, false, pending).unwrap();
|
||||
let mut got = pending_needle(2, b"");
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, b"other cookie");
|
||||
}
|
||||
|
||||
/// The cancelled write is taken back before the next write of the needle
|
||||
/// runs, so an identical write sent after the delete appends its own copy
|
||||
/// instead of matching the record about to be deleted.
|
||||
#[test]
|
||||
fn test_write_after_cancelled_write_stays_live() {
|
||||
for fsync in [false, true] {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let v = make_test_volume(tmp.path().to_str().unwrap());
|
||||
|
||||
let first = pending_needle(1, b"same bytes");
|
||||
let first_pending = v.track_pending_write(&first);
|
||||
v.cancel_pending_writes(first.id, first.cookie);
|
||||
let retry = pending_needle(1, b"same bytes");
|
||||
let retry_pending = v.track_pending_write(&retry);
|
||||
let mut results = v.write_pending_needles(
|
||||
&mut [(first, fsync), (retry, fsync)],
|
||||
&[Some(first_pending), Some(retry_pending)],
|
||||
);
|
||||
let retried = results.pop().unwrap().unwrap();
|
||||
assert!(
|
||||
!retried.2,
|
||||
"fsync={fsync}: the retry matched the cancelled write"
|
||||
);
|
||||
assert!(matches!(results.pop().unwrap(), Err(VolumeError::Deleted)));
|
||||
|
||||
let mut got = pending_needle(1, b"");
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, b"same bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/// A durable write taken back appends its tombstone after the .dat sync;
|
||||
/// the tombstone is flushed before the .idx row that points at it.
|
||||
#[test]
|
||||
fn test_taken_back_tombstone_is_synced() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let v = make_test_volume(tmp.path().to_str().unwrap());
|
||||
|
||||
let n = pending_needle(1, b"late write");
|
||||
let pending = v.track_pending_write(&n);
|
||||
v.cancel_pending_writes(n.id, n.cookie);
|
||||
let err = write_pending(&v, n, true, pending).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Deleted));
|
||||
assert_eq!(v.sync_counts_for_test(), (2, 1));
|
||||
|
||||
let n = pending_needle(2, b"kept");
|
||||
let pending = v.track_pending_write(&n);
|
||||
write_pending(&v, n, true, pending).unwrap();
|
||||
assert_eq!(v.sync_counts_for_test(), (3, 2));
|
||||
}
|
||||
|
||||
// Guard the Rust integrity-check tombstone path against the Go regression
|
||||
// where verifyDeletedNeedleIntegrity forwarded TombstoneFileSize into the
|
||||
// needle-size check, mismatched against the on-disk Size=0 header, and
|
||||
@@ -11430,6 +12041,75 @@ mod tests {
|
||||
v.write_needle(&mut n, true, false).unwrap();
|
||||
}
|
||||
|
||||
// After a restart a canDelete volume is served from .sdx; its deletes must
|
||||
// still move the counters volume.deleteEmpty and vacuum read, and land them
|
||||
// where the next reload would.
|
||||
#[test]
|
||||
fn test_read_only_can_delete_counts_deletes_after_restart() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let ids = 1..=3u64;
|
||||
{
|
||||
let v = make_test_volume(dir);
|
||||
for id in ids.clone() {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data: b"payload".to_vec(),
|
||||
data_size: 7,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true, false).unwrap();
|
||||
}
|
||||
v.set_read_only_persist(true, true).unwrap();
|
||||
v.close();
|
||||
}
|
||||
let reopen = || {
|
||||
Volume::new(
|
||||
dir,
|
||||
dir,
|
||||
VolumeId(1),
|
||||
NeedleMapKind::InMemory,
|
||||
&VolumeSpec::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let counters = |v: &Volume| {
|
||||
(
|
||||
v.file_count(),
|
||||
v.deleted_count(),
|
||||
v.content_size(),
|
||||
v.deleted_size(),
|
||||
)
|
||||
};
|
||||
|
||||
let v = reopen();
|
||||
assert!(matches!(
|
||||
v.io.read().unwrap().nm,
|
||||
Some(NeedleMap::SortedFile(_))
|
||||
));
|
||||
for id in ids.clone() {
|
||||
v.delete_needle(&mut Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
..Needle::default()
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let after_deletes = counters(&v);
|
||||
assert_eq!(after_deletes.0, 3);
|
||||
assert_eq!(
|
||||
after_deletes.0, after_deletes.1,
|
||||
"an emptied volume must report every file deleted"
|
||||
);
|
||||
assert_eq!(after_deletes.2, after_deletes.3);
|
||||
v.close();
|
||||
drop(v);
|
||||
|
||||
let v = reopen();
|
||||
assert_eq!(counters(&v), after_deletes);
|
||||
}
|
||||
|
||||
// Upgrading a volume that booted plain persisted-readonly to canDelete
|
||||
// must attach the missing .idx writer, or delete tombstones cannot append.
|
||||
#[test]
|
||||
|
||||
Generated
+779
-9
File diff suppressed because it is too large.
Load diff
@@ -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"]
|
||||
members = ["crates/core", "crates/lance", "crates/sort", "crates/sw-client"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
|
||||
+22
-13
@@ -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
|
||||
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333
|
||||
|
||||
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
|
||||
docker run chrislusf/seaweedfs worker-rust --admin admin:12535 --masters master:9333
|
||||
|
||||
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 --metrics-port 9328
|
||||
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333 --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,16 +89,22 @@ running but is not going to do anything.
|
||||
|
||||
## Credentials
|
||||
|
||||
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 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## State
|
||||
|
||||
@@ -110,7 +116,10 @@ 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. Each test seeds the table it needs, including building a vector
|
||||
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
|
||||
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.
|
||||
|
||||
@@ -16,6 +16,8 @@ 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
|
||||
@@ -28,6 +30,9 @@ 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
|
||||
|
||||
@@ -11,6 +11,7 @@ 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;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@ 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.
|
||||
@@ -15,7 +18,8 @@ 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()
|
||||
+ expires_after_secs;
|
||||
.saturating_add(expires_after_secs)
|
||||
.min(MAX_EXP_SECS);
|
||||
format!("{{\"exp\":{exp}}}")
|
||||
} else {
|
||||
"{}".to_string()
|
||||
@@ -42,7 +46,7 @@ pub fn derive_key(signing_key: &[u8], purpose: &str) -> Vec<u8> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{admin_token, derive_key};
|
||||
use super::{admin_token, derive_key, MAX_EXP_SECS};
|
||||
|
||||
#[test]
|
||||
fn derive_key_matches_the_go_derivation() {
|
||||
@@ -75,4 +79,13 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,14 @@ 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
|
||||
@@ -45,14 +48,51 @@ 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 }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tonic.workspace = true
|
||||
arrow-array = "58"
|
||||
arrow-schema = "58"
|
||||
arrow-cast = "58"
|
||||
lance-linalg = "10"
|
||||
tempfile = "3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,29 @@
|
||||
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,7 +67,6 @@ struct ListTablesResponse {
|
||||
pub struct NamespaceClient {
|
||||
base_url: String,
|
||||
http: reqwest::Client,
|
||||
api_key: Option<String>,
|
||||
signing_key: Option<SigningKey>,
|
||||
}
|
||||
|
||||
@@ -104,29 +103,10 @@ 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!(
|
||||
@@ -139,10 +119,6 @@ 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,
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! 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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Opening a Lance dataset with credentials the namespace vended.
|
||||
//! Opening a Lance dataset on the cluster's 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.
|
||||
//! 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.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -17,6 +17,7 @@ use lance::io::{
|
||||
};
|
||||
|
||||
use crate::catalog::{NamespaceClient, TableDescription};
|
||||
use crate::direct_read::DirectReads;
|
||||
|
||||
/// A table the worker is about to work on.
|
||||
pub struct OpenTable {
|
||||
@@ -37,27 +38,43 @@ pub struct TableStats {
|
||||
pub schema: Option<String>,
|
||||
}
|
||||
|
||||
/// Storage options an operator supplies for deployments that vend none.
|
||||
pub type FallbackOptions = HashMap<String, 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>);
|
||||
|
||||
/// Resolve a table through the namespace and open it.
|
||||
pub async fn open(
|
||||
client: &NamespaceClient,
|
||||
id: &[String],
|
||||
fallback: &FallbackOptions,
|
||||
) -> Result<OpenTable> {
|
||||
open_with(client, id, fallback, None).await
|
||||
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))))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`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> {
|
||||
/// 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()),
|
||||
])
|
||||
}
|
||||
|
||||
/// Resolve a table through the namespace and open it.
|
||||
pub async fn open(client: &NamespaceClient, id: &[String], storage: &Storage) -> Result<OpenTable> {
|
||||
let description = client.describe_table(id).await?;
|
||||
let dataset = open_at(&description, fallback, wrapper).await?;
|
||||
let wrapper = storage.wrapper(&description.location).await?;
|
||||
let dataset = open_at(&description, wrapper).await?;
|
||||
Ok(OpenTable {
|
||||
id: id.to_vec(),
|
||||
location: description.location,
|
||||
@@ -65,73 +82,51 @@ pub async fn open_with(
|
||||
})
|
||||
}
|
||||
|
||||
/// 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(
|
||||
/// Open a table the caller has already resolved, with the store wrapped.
|
||||
pub async fn open_at(
|
||||
description: &TableDescription,
|
||||
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();
|
||||
}
|
||||
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()
|
||||
})
|
||||
.with_store_params(store_params(wrapper))
|
||||
.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],
|
||||
fallback: &FallbackOptions,
|
||||
) -> Result<()> {
|
||||
pub async fn drop(client: &NamespaceClient, id: &[String], storage: &Storage) -> 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)?;
|
||||
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(())
|
||||
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(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the catalog puts a table it was given no location for, as the
|
||||
@@ -218,45 +213,12 @@ fn schema_json(dataset: &Dataset) -> Option<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FallbackOptions, check_drop_location, table_location, table_options};
|
||||
use crate::catalog::TableDescription;
|
||||
use super::{check_drop_location, table_location};
|
||||
|
||||
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
@@ -0,0 +1,948 @@
|
||||
//! 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,
|
||||
fallback: dataset::FallbackOptions,
|
||||
storage: dataset::Storage,
|
||||
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,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
storage: dataset::Storage::default(),
|
||||
signing_key: None,
|
||||
metrics: None,
|
||||
}
|
||||
@@ -51,8 +51,8 @@ impl CleanupVersionsHandler {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
|
||||
self.storage = storage;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -62,9 +62,7 @@ impl CleanupVersionsHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
.with_fallback(&self.fallback)
|
||||
.with_signing_key(self.signing_key.as_ref())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +158,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.fallback).await {
|
||||
let table = match dataset::open(&client, &id, &self.storage).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
@@ -256,7 +254,7 @@ impl JobHandler for CleanupVersionsHandler {
|
||||
) as usize;
|
||||
|
||||
let client = self.client();
|
||||
let table = dataset::open(&client, &id, &self.fallback).await?;
|
||||
let table = dataset::open(&client, &id, &self.storage).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,
|
||||
fallback: dataset::FallbackOptions,
|
||||
storage: dataset::Storage,
|
||||
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,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
storage: dataset::Storage::default(),
|
||||
signing_key: None,
|
||||
metrics: None,
|
||||
}
|
||||
@@ -55,8 +55,8 @@ impl CompactHandler {
|
||||
}
|
||||
|
||||
/// Storage options to use where the namespace vends none.
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
|
||||
self.storage = storage;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -66,9 +66,7 @@ impl CompactHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
.with_fallback(&self.fallback)
|
||||
.with_signing_key(self.signing_key.as_ref())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,7 +152,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.fallback).await {
|
||||
let table = match dataset::open(&client, &id, &self.storage).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
// A table that cannot be opened is the next run's problem,
|
||||
@@ -271,7 +269,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.fallback).await?;
|
||||
let mut table = dataset::open(&client, &id, &self.storage).await?;
|
||||
let before = table.stats().await?;
|
||||
|
||||
sender.send_progress(JobProgressUpdate {
|
||||
|
||||
@@ -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::{
|
||||
ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest, JobCompleted,
|
||||
JobProgressUpdate, JobProposal, JobResult, JobTypeCapability, JobTypeDescriptor,
|
||||
AdminRuntimeDefaults, ConfigValue, DetectionComplete, DetectionProposals, ExecuteJobRequest,
|
||||
JobCompleted, JobProgressUpdate, JobProposal, JobResult, JobTypeCapability, JobTypeDescriptor,
|
||||
RunDetectionRequest,
|
||||
};
|
||||
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
|
||||
@@ -15,9 +15,13 @@ 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;
|
||||
|
||||
@@ -34,7 +38,7 @@ const MAX_UNINDEXED_CEILING: i64 = 100_000_000;
|
||||
/// slow one.
|
||||
pub struct OptimizeIndicesHandler {
|
||||
namespace_url: String,
|
||||
fallback: dataset::FallbackOptions,
|
||||
storage: dataset::Storage,
|
||||
signing_key: Option<SigningKey>,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
@@ -43,7 +47,7 @@ impl OptimizeIndicesHandler {
|
||||
pub fn new(namespace_url: String) -> Self {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
storage: dataset::Storage::default(),
|
||||
signing_key: None,
|
||||
metrics: None,
|
||||
}
|
||||
@@ -54,8 +58,8 @@ impl OptimizeIndicesHandler {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
|
||||
self.storage = storage;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -65,22 +69,38 @@ impl OptimizeIndicesHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
.with_fallback(&self.fallback)
|
||||
.with_signing_key(self.signing_key.as_ref())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
/// 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,
|
||||
}));
|
||||
}
|
||||
let indices = table.dataset.load_indices().await?;
|
||||
if indices.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut worst = 0u64;
|
||||
let mut worst = IndexRows {
|
||||
indexed: 0,
|
||||
unindexed: 0,
|
||||
};
|
||||
let mut names: Vec<String> = indices.iter().map(|index| index.name.clone()).collect();
|
||||
names.sort();
|
||||
names.dedup();
|
||||
@@ -88,15 +108,27 @@ async fn unindexed_rows(table: &OpenTable) -> Result<Option<u64>> {
|
||||
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 unindexed = stats
|
||||
.get("num_unindexed_rows")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(0);
|
||||
worst = worst.max(unindexed);
|
||||
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"),
|
||||
};
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -138,6 +170,12 @@ 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()
|
||||
}
|
||||
}
|
||||
@@ -162,7 +200,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.fallback).await {
|
||||
let table = match dataset::open(&client, &id, &self.storage).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
@@ -175,8 +213,9 @@ impl JobHandler for OptimizeIndicesHandler {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_seen(JOB_TYPE);
|
||||
}
|
||||
let unindexed = match unindexed_rows(&table).await {
|
||||
Ok(Some(unindexed)) => unindexed,
|
||||
let vector_table = is_vector_table(&id);
|
||||
let rows = match index_rows(&table, vector_table).await {
|
||||
Ok(Some(rows)) => rows,
|
||||
Ok(None) => continue,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
@@ -186,11 +225,17 @@ 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}"),
|
||||
@@ -237,28 +282,47 @@ 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.fallback).await?;
|
||||
let before = unindexed_rows(&table).await?.unwrap_or(0);
|
||||
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?;
|
||||
|
||||
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: format!("indexing {before} uncovered rows"),
|
||||
stage: if retrain {
|
||||
"retraining the vector index".to_string()
|
||||
} else {
|
||||
format!("indexing {before} uncovered rows")
|
||||
},
|
||||
..Default::default()
|
||||
})?;
|
||||
|
||||
// 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))?;
|
||||
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))?;
|
||||
}
|
||||
|
||||
let after = unindexed_rows(&table).await?.unwrap_or(0);
|
||||
let after = index_rows(&table, vector_table)
|
||||
.await?
|
||||
.map_or(0, |rows| rows.unindexed);
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.rows_indexed.inc_by(before.saturating_sub(after));
|
||||
}
|
||||
@@ -268,6 +332,10 @@ 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(),
|
||||
@@ -284,3 +352,32 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod cleanup;
|
||||
pub mod compact;
|
||||
pub mod indices;
|
||||
pub mod sort;
|
||||
pub mod vector_index;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -41,32 +42,38 @@ 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,
|
||||
fallback: crate::dataset::FallbackOptions,
|
||||
storage: crate::dataset::Storage,
|
||||
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_fallback(fallback.clone())
|
||||
.with_storage(storage.clone())
|
||||
.with_signing_key(signing_key.clone())
|
||||
.with_metrics(metrics.clone()),
|
||||
),
|
||||
Arc::new(
|
||||
indices::OptimizeIndicesHandler::new(namespace_url.clone())
|
||||
.with_fallback(fallback.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_signing_key(signing_key.clone())
|
||||
.with_metrics(metrics.clone()),
|
||||
),
|
||||
Arc::new(
|
||||
sort::SortHandler::new(namespace_url.clone())
|
||||
.with_fallback(fallback.clone())
|
||||
.with_storage(storage.clone())
|
||||
.with_signing_key(signing_key.clone())
|
||||
.with_metrics(metrics.clone()),
|
||||
),
|
||||
Arc::new(
|
||||
cleanup::CleanupVersionsHandler::new(namespace_url)
|
||||
.with_fallback(fallback)
|
||||
.with_storage(storage)
|
||||
.with_signing_key(signing_key)
|
||||
.with_metrics(metrics),
|
||||
),
|
||||
|
||||
@@ -53,7 +53,7 @@ const BYTES_PER_MB: u64 = 1024 * 1024;
|
||||
/// rewrite restores it once rows have been appended.
|
||||
pub struct SortHandler {
|
||||
namespace_url: String,
|
||||
fallback: dataset::FallbackOptions,
|
||||
storage: dataset::Storage,
|
||||
signing_key: Option<SigningKey>,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
@@ -62,7 +62,7 @@ impl SortHandler {
|
||||
pub fn new(namespace_url: String) -> Self {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback: dataset::FallbackOptions::new(),
|
||||
storage: dataset::Storage::default(),
|
||||
signing_key: None,
|
||||
metrics: None,
|
||||
}
|
||||
@@ -74,8 +74,8 @@ impl SortHandler {
|
||||
}
|
||||
|
||||
/// Storage options to use where the namespace vends none.
|
||||
pub fn with_fallback(mut self, fallback: dataset::FallbackOptions) -> Self {
|
||||
self.fallback = fallback;
|
||||
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
|
||||
self.storage = storage;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -85,9 +85,7 @@ impl SortHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
.with_fallback(&self.fallback)
|
||||
.with_signing_key(self.signing_key.as_ref())
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +205,7 @@ impl JobHandler for SortHandler {
|
||||
let mut observations = Vec::new();
|
||||
for encoded in &tables {
|
||||
let id = parse_id(encoded);
|
||||
let table = match dataset::open(&client, &id, &self.fallback).await {
|
||||
let table = match dataset::open(&client, &id, &self.storage).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
// One unreadable table must not end the sweep: the tables
|
||||
@@ -361,7 +359,7 @@ impl JobHandler for SortHandler {
|
||||
// Re-resolve rather than trusting what detection saw: the table may have
|
||||
// been repointed, its declared order changed, and the vended credentials
|
||||
// have expired.
|
||||
let table = dataset::open(&client, &id, &self.fallback).await?;
|
||||
let table = dataset::open(&client, &id, &self.storage).await?;
|
||||
let before = table.stats().await?;
|
||||
let config = table.dataset.config().clone();
|
||||
let spec = resolve(
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use async_trait::async_trait;
|
||||
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,
|
||||
RunDetectionRequest,
|
||||
};
|
||||
use seaweed_worker_core::{DetectionSender, ExecutionSender, JobHandler};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::catalog::{NamespaceClient, SigningKey, parse_id};
|
||||
use crate::dataset::{self, OpenTable};
|
||||
use crate::jobs::{clamp, string_list, table_id};
|
||||
use crate::vector_index::{INDEX_NAME, build, index_names, partitions_for};
|
||||
|
||||
pub const JOB_TYPE: &str = "lance_vector_index";
|
||||
|
||||
const DEFAULT_MIN_ROWS: i64 = 50_000;
|
||||
const MIN_ROWS_FLOOR: i64 = 1;
|
||||
const MIN_ROWS_CEILING: i64 = 1_000_000_000;
|
||||
/// The namespace an S3 Vectors bucket keeps its indexes in.
|
||||
const VECTOR_NAMESPACE: &str = "vector";
|
||||
/// The column S3 Vectors writes its vectors to.
|
||||
const VECTOR_COLUMN: &str = "vector";
|
||||
/// A build trains on the whole table, so the admin's 90 seconds are not enough.
|
||||
/// The run window is as long, or it would cut an attempt short first.
|
||||
pub(crate) const EXECUTION_TIMEOUT_SECONDS: i32 = 3600;
|
||||
|
||||
/// Declares a build's time on a proposal. A run started by hand while the
|
||||
/// schedule is off has no policy to take the timeout from, and the admin
|
||||
/// gives a job at least the runtime its proposal declares.
|
||||
pub(crate) fn declare_build_runtime(parameters: &mut HashMap<String, ConfigValue>) {
|
||||
parameters.insert(
|
||||
"estimated_runtime_seconds".to_string(),
|
||||
int_value(EXECUTION_TIMEOUT_SECONDS as i64),
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the vector index of an S3 Vectors table once it holds enough rows
|
||||
/// for an exact scan to be the slow way. Tables below the threshold, and rows
|
||||
/// written after a build, are searched exactly; `lance_optimize_indices` then
|
||||
/// keeps the index covering.
|
||||
pub struct VectorIndexHandler {
|
||||
namespace_url: String,
|
||||
storage: dataset::Storage,
|
||||
signing_key: Option<SigningKey>,
|
||||
metrics: Option<crate::metrics::LanceMetrics>,
|
||||
}
|
||||
|
||||
impl VectorIndexHandler {
|
||||
pub fn new(namespace_url: String) -> Self {
|
||||
Self {
|
||||
namespace_url,
|
||||
storage: dataset::Storage::default(),
|
||||
signing_key: None,
|
||||
metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_metrics(mut self, metrics: Option<crate::metrics::LanceMetrics>) -> Self {
|
||||
self.metrics = metrics;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_storage(mut self, storage: dataset::Storage) -> Self {
|
||||
self.storage = storage;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_signing_key(mut self, signing_key: Option<SigningKey>) -> Self {
|
||||
self.signing_key = signing_key;
|
||||
self
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_signing_key(self.signing_key.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// `<bucket>$vector$<index>`: a table the S3 Vectors API created.
|
||||
pub fn is_vector_table(id: &[String]) -> bool {
|
||||
id.len() == 3 && id[1] == VECTOR_NAMESPACE
|
||||
}
|
||||
|
||||
fn has_vector_column(table: &OpenTable) -> bool {
|
||||
table.dataset.schema().field(VECTOR_COLUMN).is_some()
|
||||
}
|
||||
|
||||
async fn is_indexed(table: &OpenTable) -> Result<bool> {
|
||||
Ok(!index_names(&table.dataset, VECTOR_COLUMN).await?.is_empty())
|
||||
}
|
||||
|
||||
/// Why an execution leaves the table as it is, if it does: the table may have
|
||||
/// changed since it was proposed.
|
||||
fn skip_reason(indexed: bool, rows: usize) -> Option<&'static str> {
|
||||
if indexed {
|
||||
Some("already indexed")
|
||||
} else if rows == 0 {
|
||||
Some("no rows to index")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl JobHandler for VectorIndexHandler {
|
||||
fn capability(&self) -> JobTypeCapability {
|
||||
JobTypeCapability {
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
can_detect: true,
|
||||
can_execute: true,
|
||||
max_detection_concurrency: 1,
|
||||
max_execution_concurrency: 1,
|
||||
display_name: "Lance Vector Index".to_string(),
|
||||
description:
|
||||
"Build the vector index of S3 Vectors tables that have grown past the threshold"
|
||||
.to_string(),
|
||||
weight: 40,
|
||||
}
|
||||
}
|
||||
|
||||
fn descriptor(&self) -> JobTypeDescriptor {
|
||||
let mut defaults: HashMap<String, ConfigValue> = HashMap::new();
|
||||
defaults.insert("min_rows".to_string(), int_value(DEFAULT_MIN_ROWS));
|
||||
|
||||
JobTypeDescriptor {
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
display_name: "Lance Vector Index".to_string(),
|
||||
description:
|
||||
"Build an IVF index for S3 Vectors tables so queries stop scanning every row"
|
||||
.to_string(),
|
||||
icon: "fas fa-project-diagram".to_string(),
|
||||
descriptor_version: 1,
|
||||
worker_config_form: Some(form(
|
||||
"lance-vector-index-worker",
|
||||
"Vector index",
|
||||
vec![number_field(
|
||||
"min_rows",
|
||||
"Row threshold",
|
||||
"Build the index once a table holds at least this many rows",
|
||||
MIN_ROWS_FLOOR,
|
||||
MIN_ROWS_CEILING,
|
||||
)],
|
||||
defaults.clone(),
|
||||
)),
|
||||
worker_default_values: defaults,
|
||||
admin_runtime_defaults: Some(AdminRuntimeDefaults {
|
||||
job_type_max_runtime_seconds: EXECUTION_TIMEOUT_SECONDS,
|
||||
execution_timeout_seconds: EXECUTION_TIMEOUT_SECONDS,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn detect(
|
||||
&self,
|
||||
request: &RunDetectionRequest,
|
||||
sender: &dyn DetectionSender,
|
||||
) -> Result<()> {
|
||||
let min_rows = clamp(
|
||||
int_or(&request.worker_config_values, "min_rows", DEFAULT_MIN_ROWS),
|
||||
MIN_ROWS_FLOOR,
|
||||
MIN_ROWS_CEILING,
|
||||
) as usize;
|
||||
let max_results = usize::try_from(request.max_results).unwrap_or(0);
|
||||
let client = self.client();
|
||||
let tables = client.list_all_tables().await?;
|
||||
|
||||
let mut proposals = Vec::new();
|
||||
let mut has_more = false;
|
||||
for encoded in &tables {
|
||||
let id = parse_id(encoded);
|
||||
if !is_vector_table(&id) {
|
||||
continue;
|
||||
}
|
||||
let table = match dataset::open(&client, &id, &self.storage).await {
|
||||
Ok(table) => table,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "open");
|
||||
}
|
||||
warn!("skipping {encoded}: {err:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_seen(JOB_TYPE);
|
||||
}
|
||||
if !has_vector_column(&table) {
|
||||
continue;
|
||||
}
|
||||
match is_indexed(&table).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) => continue,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "indices");
|
||||
}
|
||||
warn!("skipping {encoded}: reading its indices failed: {err:#}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let rows = match table.dataset.count_rows(None).await {
|
||||
Ok(rows) => rows,
|
||||
Err(err) => {
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.worker.object_skipped(JOB_TYPE, "rows");
|
||||
}
|
||||
warn!("skipping {encoded}: counting its rows failed: {err:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if rows < min_rows {
|
||||
continue;
|
||||
}
|
||||
if max_results > 0 && proposals.len() >= max_results {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
let mut parameters: HashMap<String, ConfigValue> = HashMap::new();
|
||||
parameters.insert("table_id".to_string(), string_list(&id));
|
||||
declare_build_runtime(&mut parameters);
|
||||
proposals.push(JobProposal {
|
||||
proposal_id: format!("{JOB_TYPE}:{encoded}"),
|
||||
dedupe_key: format!("{JOB_TYPE}:{encoded}"),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
summary: format!("Index {encoded} ({rows} rows)"),
|
||||
detail: format!(
|
||||
"{rows} rows are searched by an exact scan on every query; the policy \
|
||||
indexes tables from {min_rows} rows"
|
||||
),
|
||||
parameters,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
let total = proposals.len() as i32;
|
||||
sender.send_proposals(DetectionProposals {
|
||||
request_id: request.request_id.clone(),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
proposals,
|
||||
has_more,
|
||||
})?;
|
||||
sender.send_complete(DetectionComplete {
|
||||
request_id: request.request_id.clone(),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
success: true,
|
||||
error_message: String::new(),
|
||||
total_proposals: total,
|
||||
skipped_reason: String::new(),
|
||||
eligible_after: None,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
request: &ExecuteJobRequest,
|
||||
sender: &dyn ExecutionSender,
|
||||
) -> Result<()> {
|
||||
let job = request
|
||||
.job
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow!("execute request carried no job"))?;
|
||||
let id = table_id(&job.parameters)
|
||||
.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 rows = table.dataset.count_rows(None).await?;
|
||||
let partitions = partitions_for(rows);
|
||||
let mut output: HashMap<String, ConfigValue> = HashMap::new();
|
||||
output.insert("rows".to_string(), int_value(rows as i64));
|
||||
output.insert("partitions".to_string(), int_value(partitions as i64));
|
||||
|
||||
if !has_vector_column(&table) {
|
||||
bail!("the table has no {VECTOR_COLUMN} column to index");
|
||||
}
|
||||
if let Some(reason) = skip_reason(is_indexed(&table).await?, rows) {
|
||||
sender.send_completed(JobCompleted {
|
||||
request_id: request.request_id.clone(),
|
||||
job_id: job.job_id.clone(),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
success: true,
|
||||
result: Some(JobResult {
|
||||
output_values: output,
|
||||
summary: reason.to_string(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
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: format!("indexing {rows} rows into {partitions} partitions"),
|
||||
..Default::default()
|
||||
})?;
|
||||
|
||||
build(
|
||||
&mut table.dataset,
|
||||
VECTOR_COLUMN,
|
||||
INDEX_NAME,
|
||||
partitions,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
if let Some(counters) = &self.metrics {
|
||||
counters.indexes_built.inc();
|
||||
}
|
||||
|
||||
sender.send_completed(JobCompleted {
|
||||
request_id: request.request_id.clone(),
|
||||
job_id: job.job_id.clone(),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
success: true,
|
||||
result: Some(JobResult {
|
||||
output_values: output,
|
||||
summary: format!("{rows} rows indexed into {partitions} partitions"),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_vector_bucket_tables_qualify() {
|
||||
assert!(is_vector_table(&parse_id("media$vector$movies")));
|
||||
assert!(!is_vector_table(&parse_id("media$ml$events")));
|
||||
assert!(!is_vector_table(&parse_id("vector$movies")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_indexed_or_emptied_since_detection_is_left_alone() {
|
||||
assert_eq!(skip_reason(true, 60_000), Some("already indexed"));
|
||||
assert_eq!(skip_reason(true, 0), Some("already indexed"));
|
||||
assert_eq!(skip_reason(false, 0), Some("no rows to index"));
|
||||
assert_eq!(skip_reason(false, 60_000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proposal_declares_a_builds_runtime() {
|
||||
let mut parameters = HashMap::new();
|
||||
declare_build_runtime(&mut parameters);
|
||||
assert_eq!(
|
||||
seaweed_worker_core::config_form::int_or(¶meters, "estimated_runtime_seconds", 0),
|
||||
3600
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_build_gets_longer_than_the_default_execution_timeout() {
|
||||
let descriptor = VectorIndexHandler::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);
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,27 @@
|
||||
//! three read and rewrite Lance files. This crate is the worker that can.
|
||||
|
||||
pub mod catalog;
|
||||
pub mod cluster;
|
||||
pub mod dataset;
|
||||
pub mod direct_read;
|
||||
pub mod grpc_tls;
|
||||
pub mod jobs;
|
||||
pub mod metrics;
|
||||
pub mod preview;
|
||||
pub mod security;
|
||||
pub mod sse;
|
||||
pub mod tls;
|
||||
pub mod vector_index;
|
||||
|
||||
pub use jobs::handlers;
|
||||
|
||||
/// The master's protocol, for the filers it lists.
|
||||
pub mod master_pb {
|
||||
tonic::include_proto!("master_pb");
|
||||
}
|
||||
pub mod volume_server_pb {
|
||||
tonic::include_proto!("volume_server_pb");
|
||||
}
|
||||
pub mod remote_pb {
|
||||
tonic::include_proto!("remote_pb");
|
||||
}
|
||||
@@ -36,13 +36,22 @@ struct Args {
|
||||
#[arg(long, default_value = "1")]
|
||||
max_concurrency: i32,
|
||||
|
||||
/// Storage credentials to use where the namespace vends none. A gateway
|
||||
/// with STS configured vends its own and these are ignored.
|
||||
#[arg(long, env = "WEED_S3_ACCESS_KEY")]
|
||||
access_key: Option<String>,
|
||||
|
||||
#[arg(long, env = "WEED_S3_SECRET_KEY")]
|
||||
secret_key: Option<String>,
|
||||
/// Comma-separated master addresses: the worker asks them for the filers
|
||||
/// it keeps tables through.
|
||||
#[arg(long, alias = "master", env = "WEED_MASTERS")]
|
||||
masters: String,
|
||||
/// The filer group whose filers the worker uses.
|
||||
#[arg(
|
||||
long,
|
||||
alias = "filer.group",
|
||||
env = "WEED_FILER_GROUP",
|
||||
default_value = ""
|
||||
)]
|
||||
filer_group: String,
|
||||
/// The cluster's security.toml; by default the file weed processes find
|
||||
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
|
||||
#[arg(long, env = "WEED_WORKER_SECURITY_TOML")]
|
||||
security_toml: Option<std::path::PathBuf>,
|
||||
|
||||
/// mTLS for the admin stream, the same certificates the Go worker reads
|
||||
/// from the [grpc.worker] section of security.toml. All three together, or
|
||||
@@ -61,18 +70,20 @@ struct Args {
|
||||
#[arg(long)]
|
||||
tls_server_name: Option<String>,
|
||||
|
||||
/// Shared secret for the admin control stream, the `jwt.filer_signing.key`
|
||||
/// value the Go worker reads from its config file. Required by admins that
|
||||
/// authenticate the worker stream with a signing key. The Lance namespace
|
||||
/// takes it too: only a holder gets write credentials to vector indexes.
|
||||
/// The cluster's `jwt.filer_signing.key`. The Lance namespace knows the
|
||||
/// worker by a token derived from it, and admins that authenticate the
|
||||
/// worker stream with a signing key require it. When not given, read from
|
||||
/// where the Go worker reads it: WEED_JWT_FILER_SIGNING_KEY, then
|
||||
/// security.toml.
|
||||
#[arg(long, env = "WEED_FILER_SIGNING_KEY")]
|
||||
filer_signing_key: Option<String>,
|
||||
|
||||
/// Lifetime of the token minted from the signing key, mirroring
|
||||
/// `jwt.filer_signing.expires_after_seconds`. Zero mints a token with no
|
||||
/// expiry.
|
||||
#[arg(long, default_value = "0")]
|
||||
filer_signing_key_expires_after_seconds: u64,
|
||||
/// expiry. When not given, the expiry configured beside a discovered key,
|
||||
/// else zero.
|
||||
#[arg(long)]
|
||||
filer_signing_key_expires_after_seconds: Option<u64>,
|
||||
|
||||
/// Serve /health, /ready and /metrics on this port, the way
|
||||
/// `weed worker -metricsPort` does. Zero, the default, serves nothing.
|
||||
@@ -137,7 +148,28 @@ async fn main() -> Result<()> {
|
||||
|
||||
let args = Args::parse();
|
||||
let tls = args.tls()?;
|
||||
let signing_key = weed_lance_worker::catalog::SigningKey::new(args.filer_signing_key.clone());
|
||||
// One security.toml for everything: the admin stream's and the catalog's
|
||||
// signing key, and the cluster connection.
|
||||
let security =
|
||||
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
|
||||
let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) {
|
||||
Some(key) => Some((key, 0)),
|
||||
None => security
|
||||
.get("jwt.filer_signing.key")
|
||||
.filter(|key| !key.is_empty())
|
||||
.map(|key| {
|
||||
if let Some(path) = security.path() {
|
||||
tracing::info!(source = %path.display(), "using jwt.filer_signing.key");
|
||||
}
|
||||
let expires = security
|
||||
.get("jwt.filer_signing.expires_after_seconds")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0);
|
||||
(key, expires)
|
||||
}),
|
||||
};
|
||||
let (filer_signing_key, configured_expiry) = filer_signing.unzip();
|
||||
let signing_key = weed_lance_worker::catalog::SigningKey::new(filer_signing_key.clone());
|
||||
let options = WorkerOptions {
|
||||
admin_address: args.admin,
|
||||
worker_id: args.id,
|
||||
@@ -145,16 +177,17 @@ async fn main() -> Result<()> {
|
||||
max_detection_concurrency: args.max_concurrency,
|
||||
max_execution_concurrency: args.max_concurrency,
|
||||
tls,
|
||||
signing_key: args.filer_signing_key,
|
||||
signing_key_expires_after_seconds: args.filer_signing_key_expires_after_seconds,
|
||||
signing_key: filer_signing_key,
|
||||
signing_key_expires_after_seconds: args
|
||||
.filer_signing_key_expires_after_seconds
|
||||
.or(configured_expiry)
|
||||
.unwrap_or(0),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut fallback = weed_lance_worker::dataset::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 cluster =
|
||||
weed_lance_worker::cluster::Cluster::new(&args.masters, &args.filer_group, &security)?;
|
||||
let storage = weed_lance_worker::dataset::Storage(Some(cluster.storage(&security).await?));
|
||||
|
||||
let metrics = Metrics::new(&options.worker_id, &options.worker_version)?;
|
||||
let lance_metrics = LanceMetrics::new(&metrics)?;
|
||||
@@ -166,10 +199,10 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
let mut registry = Registry::new().with_preview(Arc::new(
|
||||
weed_lance_worker::preview::LancePreview::new(args.namespace.clone(), fallback.clone())
|
||||
weed_lance_worker::preview::LancePreview::new(args.namespace.clone(), storage.clone())
|
||||
.with_signing_key(signing_key.clone()),
|
||||
));
|
||||
for handler in handlers(args.namespace, fallback, signing_key, Some(lance_metrics)) {
|
||||
for handler in handlers(args.namespace, storage, signing_key, Some(lance_metrics)) {
|
||||
registry = registry.register(handler);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ pub struct LanceMetrics {
|
||||
pub worker: Metrics,
|
||||
pub fragments_removed: IntCounter,
|
||||
pub rows_indexed: IntCounter,
|
||||
pub indexes_built: IntCounter,
|
||||
pub rows_sorted: IntCounter,
|
||||
pub versions_removed: IntCounter,
|
||||
pub bytes_reclaimed: IntCounter,
|
||||
@@ -35,6 +36,10 @@ impl LanceMetrics {
|
||||
"lance_rows_indexed_total",
|
||||
"Rows brought under an index that did not cover them.",
|
||||
)?,
|
||||
indexes_built: metrics.counter(
|
||||
"lance_vector_indexes_built_total",
|
||||
"Vector indexes built for S3 Vectors tables.",
|
||||
)?,
|
||||
rows_sorted: metrics.counter(
|
||||
"lance_rows_sorted_total",
|
||||
"Rows rewritten into their table's declared order.",
|
||||
|
||||
@@ -11,20 +11,20 @@ use futures::TryStreamExt;
|
||||
use seaweed_worker_core::{Preview, PreviewProvider};
|
||||
|
||||
use crate::catalog::{NamespaceClient, SigningKey};
|
||||
use crate::dataset::{self, FallbackOptions};
|
||||
use crate::dataset::{self, Storage};
|
||||
use crate::jobs::FORMAT;
|
||||
|
||||
pub struct LancePreview {
|
||||
namespace_url: String,
|
||||
fallback: FallbackOptions,
|
||||
storage: Storage,
|
||||
signing_key: Option<SigningKey>,
|
||||
}
|
||||
|
||||
impl LancePreview {
|
||||
pub fn new(namespace_url: String, fallback: FallbackOptions) -> Self {
|
||||
pub fn new(namespace_url: String, storage: Storage) -> Self {
|
||||
Self {
|
||||
namespace_url,
|
||||
fallback,
|
||||
storage,
|
||||
signing_key: None,
|
||||
}
|
||||
}
|
||||
@@ -43,9 +43,8 @@ impl PreviewProvider for LancePreview {
|
||||
|
||||
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview> {
|
||||
let client = NamespaceClient::new(self.namespace_url.clone())
|
||||
.with_fallback(&self.fallback)
|
||||
.with_signing_key(self.signing_key.as_ref());
|
||||
let table = dataset::open(&client, object_id, &self.fallback).await?;
|
||||
let table = dataset::open(&client, object_id, &self.storage).await?;
|
||||
|
||||
let total_rows = table.dataset.count_rows(None).await.unwrap_or(0) as i64;
|
||||
let mut scanner = table.dataset.scan();
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
//! The cluster's `security.toml`, found and read the way weed processes do:
|
||||
//! the file in `-config_dir`, `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs`
|
||||
//! or `/etc/seaweedfs`, with `WEED_*` environment variables over it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::sse::SseConfig;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sw_client::HttpsTls;
|
||||
|
||||
const FILE_NAME: &str = "security.toml";
|
||||
|
||||
/// What a weed gRPC server is dialed with, as `security.LoadClientTLS` reads
|
||||
/// it: the files, re-read at every dial, and the server identities allowed.
|
||||
/// The server's certificate must chain to `grpc.ca`; like weed clients, this
|
||||
/// one does not check it against the host dialed, only against the allowlist
|
||||
/// when one is set.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GrpcTls {
|
||||
/// `grpc.ca`
|
||||
pub ca_path: String,
|
||||
/// The component's `client_cert` and `client_key`, else its `cert` and
|
||||
/// `key`.
|
||||
pub cert_path: String,
|
||||
pub key_path: String,
|
||||
/// `allowed_server_commonNames`: when set, the server certificate's common
|
||||
/// name or a DNS SAN must be one of these or lie under the wildcard
|
||||
/// domain; a URI SAN must be one of these exactly.
|
||||
pub allowed_server_names: Vec<String>,
|
||||
/// `allowed_server_wildcard_domain`
|
||||
pub allowed_server_wildcard_domain: String,
|
||||
}
|
||||
|
||||
impl GrpcTls {
|
||||
/// The CA, certificate and key as the files hold them now, so a dial
|
||||
/// after the files rotate presents the new pair.
|
||||
pub async fn pems(&self) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
|
||||
async fn read(path: &str) -> Result<Vec<u8>> {
|
||||
tokio::fs::read(path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path}"))
|
||||
}
|
||||
Ok((
|
||||
read(&self.ca_path).await?,
|
||||
read(&self.cert_path).await?,
|
||||
read(&self.key_path).await?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a gRPC listener serves with, as `security.LoadServerTLS` reads it:
|
||||
/// the files, re-read when they change, and the client identities allowed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GrpcServerTls {
|
||||
pub cert_path: String,
|
||||
pub key_path: String,
|
||||
/// `grpc.ca`, which every client certificate must chain to.
|
||||
pub ca_path: String,
|
||||
/// `<component>.allowed_commonNames`: when set, the client certificate's
|
||||
/// common name must be one of these, or lie under the wildcard domain.
|
||||
pub allowed_common_names: Vec<String>,
|
||||
/// `grpc.allowed_wildcard_domain`
|
||||
pub allowed_wildcard_domain: String,
|
||||
}
|
||||
|
||||
pub struct Security {
|
||||
path: Option<PathBuf>,
|
||||
table: toml::Table,
|
||||
env: Box<dyn Fn(&str) -> Option<String> + Send + Sync>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Security {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Security")
|
||||
.field("path", &self.path)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// weed's util.ResolvePath for "~" and "~/..."
|
||||
fn resolve_path(path: &Path, home: Option<&Path>) -> PathBuf {
|
||||
match (path.strip_prefix("~"), home) {
|
||||
(Ok(rest), Some(home)) => home.join(rest),
|
||||
_ => path.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
fn candidates(
|
||||
config_dir: Option<&Path>,
|
||||
current_dir: Option<&Path>,
|
||||
home: Option<&Path>,
|
||||
) -> Vec<PathBuf> {
|
||||
let mut found = Vec::new();
|
||||
if let Some(dir) = config_dir {
|
||||
found.push(resolve_path(dir, home).join(FILE_NAME));
|
||||
}
|
||||
if let Some(dir) = current_dir {
|
||||
found.push(dir.join(FILE_NAME));
|
||||
}
|
||||
if let Some(home) = home {
|
||||
found.push(home.join(".seaweedfs").join(FILE_NAME));
|
||||
}
|
||||
found.push(PathBuf::from("/usr/local/etc/seaweedfs").join(FILE_NAME));
|
||||
found.push(PathBuf::from("/etc/seaweedfs").join(FILE_NAME));
|
||||
found
|
||||
}
|
||||
|
||||
/// A comma-separated list such as `allowed_commonNames`, trimmed, without
|
||||
/// empties.
|
||||
fn names(list: Option<String>) -> Vec<String> {
|
||||
list.unwrap_or_default()
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
// viper keys are case-insensitive; of two spellings, a set value wins over an
|
||||
// empty one
|
||||
fn entry<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> {
|
||||
let set = |v: &&toml::Value| v.as_str() != Some("");
|
||||
table.get(key).filter(set).or_else(|| {
|
||||
table
|
||||
.iter()
|
||||
.filter(|(k, _)| k.eq_ignore_ascii_case(key))
|
||||
.map(|(_, v)| v)
|
||||
.find(set)
|
||||
})
|
||||
}
|
||||
|
||||
impl Security {
|
||||
/// Reads `path`, or the first `security.toml` where weed looks: the
|
||||
/// `-config_dir`, then `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs`
|
||||
/// and `/etc/seaweedfs`. Without one, only the environment applies.
|
||||
pub fn load(path: Option<&Path>, config_dir: Option<&Path>) -> Result<Self> {
|
||||
let path = match path {
|
||||
Some(path) => Some(path.to_path_buf()),
|
||||
None => {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
candidates(
|
||||
config_dir,
|
||||
std::env::current_dir().ok().as_deref(),
|
||||
home.as_deref(),
|
||||
)
|
||||
.into_iter()
|
||||
.find(|p| p.is_file())
|
||||
}
|
||||
};
|
||||
Self::from_file(path, Box::new(|name| std::env::var(name).ok()))
|
||||
}
|
||||
|
||||
fn from_file(
|
||||
path: Option<PathBuf>,
|
||||
env: Box<dyn Fn(&str) -> Option<String> + Send + Sync>,
|
||||
) -> Result<Self> {
|
||||
let table = match &path {
|
||||
Some(path) => std::fs::read_to_string(path)
|
||||
.with_context(|| format!("reading {}", path.display()))?
|
||||
.parse::<toml::Table>()
|
||||
.with_context(|| format!("parsing {}", path.display()))?,
|
||||
None => toml::Table::new(),
|
||||
};
|
||||
Ok(Self { path, table, env })
|
||||
}
|
||||
|
||||
pub fn path(&self) -> Option<&Path> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
fn raw(&self, key: &str) -> Option<String> {
|
||||
let env_name = format!("WEED_{}", key.to_uppercase().replace('.', "_"));
|
||||
// viper treats an empty variable as unset
|
||||
if let Some(value) = (self.env)(&env_name).filter(|v| !v.is_empty()) {
|
||||
return Some(value);
|
||||
}
|
||||
let mut parts = key.split('.');
|
||||
let mut value = entry(&self.table, parts.next()?)?;
|
||||
for part in parts {
|
||||
value = entry(value.as_table()?, part)?;
|
||||
}
|
||||
match value {
|
||||
toml::Value::String(s) => Some(s.clone()),
|
||||
toml::Value::Boolean(b) => Some(b.to_string()),
|
||||
toml::Value::Integer(i) => Some(i.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A dotted key such as `grpc.ca`, from `WEED_GRPC_CA` when set, else
|
||||
/// the file; empty counts as unset.
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
self.raw(key).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// A boolean as weed reads one: viper accepts what Go's strconv.ParseBool
|
||||
/// does, `1`, `t`, `T`, `TRUE`, `true` and `True`.
|
||||
pub fn get_bool(&self, key: &str) -> bool {
|
||||
self.raw(key)
|
||||
.is_some_and(|v| matches!(v.trim(), "1" | "t" | "T" | "TRUE" | "true" | "True"))
|
||||
}
|
||||
|
||||
/// The file a key names, read whole.
|
||||
pub fn read(&self, key: &str, path: &str) -> Result<Vec<u8>> {
|
||||
std::fs::read(path).with_context(|| format!("{key} = {path:?}"))
|
||||
}
|
||||
|
||||
fn pair(&self, cert: &str, key: &str) -> Result<Option<(String, String)>> {
|
||||
match (self.get(cert), self.get(key)) {
|
||||
(Some(cert), Some(key)) => Ok(Some((cert, key))),
|
||||
(None, None) => Ok(None),
|
||||
_ => bail!("{cert} and {key} must both be set"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The credentials `component` (such as `grpc.client`) dials `target`
|
||||
/// (such as `grpc.master`) with, following `security.LoadClientTLS`: a
|
||||
/// dedicated client certificate is preferred over the component's own,
|
||||
/// and once either pair is set `grpc.ca` is required. The server
|
||||
/// allowlist comes from `<component>.<target>_allowed_server_commonNames`,
|
||||
/// else `<component>.allowed_server_commonNames`, else
|
||||
/// `grpc.allowed_server_commonNames`, and the wildcard domain likewise.
|
||||
/// `None` keeps plaintext.
|
||||
pub fn grpc_client_tls(&self, component: &str, target: &str) -> Result<Option<GrpcTls>> {
|
||||
let client = (
|
||||
format!("{component}.client_cert"),
|
||||
format!("{component}.client_key"),
|
||||
);
|
||||
let own = (format!("{component}.cert"), format!("{component}.key"));
|
||||
let (cert, key) = match self.pair(&client.0, &client.1)? {
|
||||
Some(pair) => pair,
|
||||
None => match self.pair(&own.0, &own.1)? {
|
||||
Some(pair) => pair,
|
||||
None => return Ok(None),
|
||||
},
|
||||
};
|
||||
let ca = self
|
||||
.get("grpc.ca")
|
||||
.with_context(|| format!("{component} cert and key are set but grpc.ca is not"))?;
|
||||
self.read("grpc.ca", &ca)?;
|
||||
self.read(&format!("{component} cert"), &cert)?;
|
||||
self.read(&format!("{component} key"), &key)?;
|
||||
let prefix = if target == component {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{}_", target.trim_start_matches("grpc."))
|
||||
};
|
||||
let first = |suffix: &str| {
|
||||
[
|
||||
format!("{component}.{prefix}{suffix}"),
|
||||
format!("{component}.{suffix}"),
|
||||
format!("grpc.{suffix}"),
|
||||
]
|
||||
.iter()
|
||||
.find_map(|key| self.get(key))
|
||||
};
|
||||
Ok(Some(GrpcTls {
|
||||
ca_path: ca,
|
||||
cert_path: cert,
|
||||
key_path: key,
|
||||
allowed_server_names: names(first("allowed_server_commonNames")),
|
||||
allowed_server_wildcard_domain: first("allowed_server_wildcard_domain")
|
||||
.unwrap_or_default(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The identity `component` (such as `grpc.vector`) serves with, following
|
||||
/// `security.LoadServerTLS`: its `cert` and `key`, with `grpc.ca` as the
|
||||
/// root every client certificate must chain to, and the component's
|
||||
/// `allowed_commonNames`. `None` keeps plaintext. The files are read by
|
||||
/// [`crate::tls::ServerTls`], which keeps re-reading them.
|
||||
pub fn grpc_server_tls(&self, component: &str) -> Result<Option<GrpcServerTls>> {
|
||||
let allowed = format!("{component}.allowed_commonNames");
|
||||
let Some((cert_path, key_path)) =
|
||||
self.pair(&format!("{component}.cert"), &format!("{component}.key"))?
|
||||
else {
|
||||
if self.get(&allowed).is_some() {
|
||||
bail!("{allowed} is set but {component}.cert and {component}.key are not");
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let ca_path = self
|
||||
.get("grpc.ca")
|
||||
.with_context(|| format!("{component} cert and key are set but grpc.ca is not"))?;
|
||||
Ok(Some(GrpcServerTls {
|
||||
cert_path,
|
||||
key_path,
|
||||
ca_path,
|
||||
allowed_common_names: names(self.get(&allowed)),
|
||||
allowed_wildcard_domain: self.get("grpc.allowed_wildcard_domain").unwrap_or_default(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Security {
|
||||
/// `https.client` for volume servers; `None` unless enabled.
|
||||
pub fn https_client_tls(&self) -> Result<Option<HttpsTls>> {
|
||||
if !self.get_bool("https.client.enabled") {
|
||||
return Ok(None);
|
||||
}
|
||||
let (cert, key) = match (self.get("https.client.cert"), self.get("https.client.key")) {
|
||||
(Some(cert), Some(key)) => (
|
||||
Some(self.read("https.client.cert", &cert)?),
|
||||
Some(self.read("https.client.key", &key)?),
|
||||
),
|
||||
(None, None) => (None, None),
|
||||
_ => bail!("https.client.cert and https.client.key must both be set"),
|
||||
};
|
||||
Ok(Some(HttpsTls {
|
||||
ca_pem: match self.get("https.client.ca") {
|
||||
Some(ca) => Some(self.read("https.client.ca", &ca)?),
|
||||
None => None,
|
||||
},
|
||||
cert_pem: cert,
|
||||
key_pem: key,
|
||||
insecure_skip_verify: self.get_bool("https.client.insecure_skip_verify"),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `jwt.signing.read.key`, which volume reads must be signed with.
|
||||
pub fn jwt_read_key(&self) -> Option<String> {
|
||||
self.get("jwt.signing.read.key")
|
||||
}
|
||||
|
||||
/// The S3 gateway's SSE-S3 settings.
|
||||
pub fn sse(&self) -> SseConfig {
|
||||
SseConfig {
|
||||
kek_hex: self.get("s3.sse.kek"),
|
||||
key: self.get("s3.sse.key"),
|
||||
passphrase: self.get("s3.sse.kek.passphrase"),
|
||||
require_commitment: self.get_bool("s3.require_key_commitment"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn security(toml: &str, env: &[(&str, &str)]) -> Security {
|
||||
let env: HashMap<String, String> = env
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect();
|
||||
Security {
|
||||
path: None,
|
||||
table: toml.parse().unwrap(),
|
||||
env: Box::new(move |name| env.get(name).cloned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder credential files: the loader reads them, it does not
|
||||
/// parse them.
|
||||
fn files() -> (tempfile::TempDir, String, String, String, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut paths = Vec::new();
|
||||
for (name, body) in [
|
||||
("ca.pem", "CA"),
|
||||
("cert.pem", "CERT"),
|
||||
("key.pem", "KEY"),
|
||||
("client.pem", "CLIENT"),
|
||||
] {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, body).unwrap();
|
||||
paths.push(path.display().to_string());
|
||||
}
|
||||
let [ca, cert, key, client]: [String; 4] = paths.try_into().unwrap();
|
||||
(dir, ca, cert, key, client)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_environment_wins_over_the_file() {
|
||||
let s = security(
|
||||
"[jwt.signing.read]\nkey = \"from-file\"\n[https.client]\nenabled = true\n",
|
||||
&[("WEED_JWT_SIGNING_READ_KEY", "from-env")],
|
||||
);
|
||||
assert_eq!(s.get("jwt.signing.read.key").as_deref(), Some("from-env"));
|
||||
assert!(s.get_bool("https.client.enabled"));
|
||||
let s = security("[jwt.signing.read]\nkey = \"from-file\"\n", &[]);
|
||||
assert_eq!(s.get("jwt.signing.read.key").as_deref(), Some("from-file"));
|
||||
let s = security(
|
||||
"[jwt.signing.read]\nkey = \"from-file\"\n",
|
||||
&[("WEED_JWT_SIGNING_READ_KEY", "")],
|
||||
);
|
||||
assert_eq!(s.get("jwt.signing.read.key").as_deref(), Some("from-file"));
|
||||
let s = security("[grpc.vector]\nallowed_commonnames = \"s3\"\n", &[]);
|
||||
assert_eq!(
|
||||
s.get("grpc.vector.allowed_commonNames").as_deref(),
|
||||
Some("s3")
|
||||
);
|
||||
let s = security(
|
||||
"[grpc.client]\nallowed_server_commonNames = \"\"\nallowed_server_commonnames = \"master\"\n",
|
||||
&[],
|
||||
);
|
||||
assert_eq!(
|
||||
s.get("grpc.client.allowed_server_commonNames").as_deref(),
|
||||
Some("master")
|
||||
);
|
||||
assert!(security("", &[]).get("jwt.signing.read.key").is_none());
|
||||
assert!(
|
||||
security("[grpc]\nca = \"\"\n", &[])
|
||||
.get("grpc.ca")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_credentials_follow_the_gateways_rules() {
|
||||
let (_dir, ca, cert, key, client) = files();
|
||||
assert!(
|
||||
security("", &[])
|
||||
.grpc_client_tls("grpc.client", "grpc.master")
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
|
||||
let tls = security(
|
||||
&format!("[grpc]\nca = {ca:?}\n[grpc.client]\ncert = {cert:?}\nkey = {key:?}\n"),
|
||||
&[],
|
||||
)
|
||||
.grpc_client_tls("grpc.client", "grpc.master")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tls,
|
||||
GrpcTls {
|
||||
ca_path: ca.clone(),
|
||||
cert_path: cert.clone(),
|
||||
key_path: key.clone(),
|
||||
allowed_server_names: Vec::new(),
|
||||
allowed_server_wildcard_domain: String::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
tls.pems().await.unwrap(),
|
||||
(b"CA".to_vec(), b"CERT".to_vec(), b"KEY".to_vec())
|
||||
);
|
||||
// Each dial reads the files, so a rotated pair is picked up.
|
||||
std::fs::write(&cert, "ROTATED").unwrap();
|
||||
assert_eq!(tls.pems().await.unwrap().1, b"ROTATED");
|
||||
|
||||
// A dedicated client certificate is preferred, and the environment
|
||||
// can supply it.
|
||||
let tls = security(
|
||||
&format!("[grpc]\nca = {ca:?}\n[grpc.client]\ncert = {cert:?}\nkey = {key:?}\n"),
|
||||
&[
|
||||
("WEED_GRPC_CLIENT_CLIENT_CERT", &client),
|
||||
("WEED_GRPC_CLIENT_CLIENT_KEY", &key),
|
||||
],
|
||||
)
|
||||
.grpc_client_tls("grpc.client", "grpc.master")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(tls.pems().await.unwrap().1, b"CLIENT");
|
||||
|
||||
for broken in [
|
||||
format!("[grpc.client]\ncert = {cert:?}\nkey = {key:?}\n"),
|
||||
format!("[grpc]\nca = {ca:?}\n[grpc.client]\ncert = {cert:?}\n"),
|
||||
format!("[grpc]\nca = {ca:?}\n[grpc.client]\nclient_key = {key:?}\n"),
|
||||
] {
|
||||
assert!(
|
||||
security(&broken, &[])
|
||||
.grpc_client_tls("grpc.client", "grpc.master")
|
||||
.is_err(),
|
||||
"{broken}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_allowlists_fall_back_from_target_to_component_to_grpc() {
|
||||
let (_dir, ca, cert, key, _client) = files();
|
||||
let base = format!("[grpc.client]\ncert = {cert:?}\nkey = {key:?}\n");
|
||||
let load = |grpc: &str, client_extra: &str| {
|
||||
security(
|
||||
&format!("[grpc]\nca = {ca:?}\n{grpc}{base}{client_extra}"),
|
||||
&[],
|
||||
)
|
||||
.grpc_client_tls("grpc.client", "grpc.master")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
let tls = load(
|
||||
"allowed_server_commonNames = \"any\"\nallowed_server_wildcard_domain = \".any\"\n",
|
||||
"",
|
||||
);
|
||||
assert_eq!(tls.allowed_server_names, ["any"]);
|
||||
assert_eq!(tls.allowed_server_wildcard_domain, ".any");
|
||||
let tls = load(
|
||||
"allowed_server_commonNames = \"any\"\n",
|
||||
"allowed_server_commonNames = \"client, wide\"\n",
|
||||
);
|
||||
assert_eq!(tls.allowed_server_names, ["client", "wide"]);
|
||||
let tls = load(
|
||||
"allowed_server_commonNames = \"any\"\n",
|
||||
"allowed_server_commonNames = \"client\"\nmaster_allowed_server_commonNames = \"master\"\n",
|
||||
);
|
||||
assert_eq!(tls.allowed_server_names, ["master"]);
|
||||
assert!(tls.allowed_server_wildcard_domain.is_empty());
|
||||
// An empty spelling falls through, as firstConfigString skips "".
|
||||
let tls = load(
|
||||
"allowed_server_commonNames = \"any\"\n",
|
||||
"master_allowed_server_commonNames = \"\"\n",
|
||||
);
|
||||
assert_eq!(tls.allowed_server_names, ["any"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_identity_needs_both_halves_and_the_ca() {
|
||||
let (_dir, ca, cert, key, _client) = files();
|
||||
assert!(
|
||||
security("", &[])
|
||||
.grpc_server_tls("grpc.vector")
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let tls = security(
|
||||
&format!("[grpc]\nca = {ca:?}\n[grpc.vector]\ncert = {cert:?}\nkey = {key:?}\n"),
|
||||
&[],
|
||||
)
|
||||
.grpc_server_tls("grpc.vector")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tls,
|
||||
GrpcServerTls {
|
||||
cert_path: cert.clone(),
|
||||
key_path: key.clone(),
|
||||
ca_path: ca.clone(),
|
||||
allowed_common_names: Vec::new(),
|
||||
allowed_wildcard_domain: String::new(),
|
||||
}
|
||||
);
|
||||
let tls = security(
|
||||
&format!(
|
||||
"[grpc]\nca = {ca:?}\nallowed_wildcard_domain = \".internal\"\n[grpc.vector]\ncert = {cert:?}\nkey = {key:?}\nallowed_commonNames = \"gateway, s3 ,\"\n"
|
||||
),
|
||||
&[],
|
||||
)
|
||||
.grpc_server_tls("grpc.vector")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(tls.allowed_common_names, ["gateway", "s3"]);
|
||||
assert_eq!(tls.allowed_wildcard_domain, ".internal");
|
||||
for broken in [
|
||||
format!("[grpc.vector]\ncert = {cert:?}\nkey = {key:?}\n"),
|
||||
format!("[grpc]\nca = {ca:?}\n[grpc.vector]\nkey = {key:?}\n"),
|
||||
format!("[grpc]\nca = {ca:?}\n[grpc.vector]\nallowed_commonNames = \"s3\"\n"),
|
||||
] {
|
||||
assert!(
|
||||
security(&broken, &[])
|
||||
.grpc_server_tls("grpc.vector")
|
||||
.is_err(),
|
||||
"{broken}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_searched_where_weed_looks() {
|
||||
let found = candidates(
|
||||
Some(Path::new("/etc/weed")),
|
||||
Some(Path::new("/cwd")),
|
||||
Some(Path::new("/home/u")),
|
||||
);
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
"/etc/weed/security.toml",
|
||||
"/cwd/security.toml",
|
||||
"/home/u/.seaweedfs/security.toml",
|
||||
"/usr/local/etc/seaweedfs/security.toml",
|
||||
"/etc/seaweedfs/security.toml"
|
||||
]
|
||||
.map(PathBuf::from)
|
||||
);
|
||||
let home = Some(Path::new("/home/u"));
|
||||
for (dir, want) in [
|
||||
("~", "/home/u/security.toml"),
|
||||
("~/cluster", "/home/u/cluster/security.toml"),
|
||||
("~other/cluster", "~other/cluster/security.toml"),
|
||||
("/srv/~/cluster", "/srv/~/cluster/security.toml"),
|
||||
] {
|
||||
assert_eq!(
|
||||
candidates(Some(Path::new(dir)), None, home)[0],
|
||||
PathBuf::from(want),
|
||||
"{dir}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_takes_the_config_dir_before_the_usual_places() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let in_config_dir = dir.path().join(FILE_NAME);
|
||||
std::fs::write(&in_config_dir, "").unwrap();
|
||||
let loaded = Security::load(None, Some(dir.path())).unwrap();
|
||||
assert_eq!(loaded.path(), Some(in_config_dir.as_path()));
|
||||
// An explicit file still wins.
|
||||
let explicit = dir.path().join("other.toml");
|
||||
std::fs::write(&explicit, "").unwrap();
|
||||
let loaded = Security::load(Some(&explicit), Some(dir.path())).unwrap();
|
||||
assert_eq!(loaded.path(), Some(explicit.as_path()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
//! Decodes what the filer and the S3 gateway encrypt, for reads that bypass
|
||||
//! the gateway, and encodes the same for writes that do. The filer's volume
|
||||
//! encryption (`cipher_key`) is AES-256-GCM over the chunk, compressed first
|
||||
//! when `is_compressed`. The gateway's SSE-S3 is AES-256-CTR per chunk under a
|
||||
//! per-object key, which the chunk's and the object's metadata carry wrapped
|
||||
//! (AES-256-GCM) by the cluster's KEK; the KEK comes from `s3.sse.kek`,
|
||||
//! `s3.sse.key` or the filer's `/etc/s3/sse_kek`, as for the gateway.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use aes_gcm::aead::rand_core::RngCore;
|
||||
use aes_gcm::aead::{Aead, OsRng};
|
||||
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::{BASE64_STANDARD, Engine};
|
||||
use ctr::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
|
||||
use hkdf::Hkdf;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use sw_client::ChunkDecoder;
|
||||
use sw_client::filer_pb::{Entry, FileChunk};
|
||||
|
||||
type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>;
|
||||
|
||||
const KEY_SIZE: usize = 32;
|
||||
const IV_SIZE: usize = 16;
|
||||
const GCM_NONCE_SIZE: usize = 12;
|
||||
const SSE_S3_KEY_ATTRIBUTE: &str = "x-seaweedfs-sse-s3-key";
|
||||
const SSE_HEADER_ATTRIBUTE: &str = "X-Amz-Server-Side-Encryption";
|
||||
const AES256: &str = "AES256";
|
||||
/// `filer_pb.SSEType`.
|
||||
const SSE_C: i32 = 1;
|
||||
const SSE_KMS: i32 = 2;
|
||||
const SSE_S3: i32 = 3;
|
||||
pub const KEK_PATH: (&str, &str) = ("/etc/s3", "sse_kek");
|
||||
const KEK_WRAPPED_V2_MAGIC: &[u8] = b"SWv2";
|
||||
const KEK_SALT_SIZE: usize = 32;
|
||||
const LEGACY_KEK_SALT: &[u8] = b"seaweedfs-sse-s3-kek-wrapping-v1";
|
||||
|
||||
/// How the gateway's KEK is configured: `security.toml` `s3.sse.kek`,
|
||||
/// `s3.sse.key` and `s3.sse.kek.passphrase`, or their `WEED_` environment
|
||||
/// variables.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct SseConfig {
|
||||
/// Hex-encoded 256-bit KEK.
|
||||
pub kek_hex: Option<String>,
|
||||
/// Any secret; the KEK is derived from it.
|
||||
pub key: Option<String>,
|
||||
/// Unwraps a KEK stored encrypted on the filer.
|
||||
pub passphrase: Option<String>,
|
||||
/// Refuse objects whose metadata carries no key commitment.
|
||||
pub require_commitment: bool,
|
||||
}
|
||||
|
||||
/// The KEK that unwraps SSE-S3 object keys.
|
||||
pub struct SseS3Keys {
|
||||
kek: Option<[u8; KEY_SIZE]>,
|
||||
require_commitment: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SseS3Keys {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SseS3Keys")
|
||||
.field("configured", &self.kek.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SseS3Keys {
|
||||
/// Resolves the KEK the gateway's way: `kek_hex` (which must match the
|
||||
/// filer's file when both exist), else `key` (refused while the filer's
|
||||
/// file exists), else the filer's file, else none. `filer_file` is the
|
||||
/// content of `/etc/s3/sse_kek` when it exists.
|
||||
pub fn load(config: &SseConfig, filer_file: Option<&[u8]>) -> Result<Self> {
|
||||
let filer_kek = filer_file
|
||||
.map(|content| kek_from_filer(content, config.passphrase.as_deref()))
|
||||
.transpose()?;
|
||||
let kek = match (&config.kek_hex, &config.key) {
|
||||
(Some(_), Some(_)) => bail!("only one of s3.sse.kek and s3.sse.key may be set"),
|
||||
(Some(hex), None) => {
|
||||
let kek = key_from_hex(hex).context("s3.sse.kek")?;
|
||||
if filer_kek.is_some_and(|f| f != kek) {
|
||||
bail!("s3.sse.kek does not match the filer's /etc/s3/sse_kek");
|
||||
}
|
||||
Some(kek)
|
||||
}
|
||||
(None, Some(secret)) => {
|
||||
if filer_kek.is_some() {
|
||||
bail!("s3.sse.key cannot be used while /etc/s3/sse_kek exists on the filer");
|
||||
}
|
||||
Some(derive_key(secret.as_bytes(), None, b"seaweedfs-sse-s3-kek"))
|
||||
}
|
||||
(None, None) => filer_kek,
|
||||
};
|
||||
Ok(Self {
|
||||
kek,
|
||||
require_commitment: config.require_commitment,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn configured(&self) -> bool {
|
||||
self.kek.is_some()
|
||||
}
|
||||
|
||||
/// Wraps an object key under the KEK, as the gateway's key manager does:
|
||||
/// AES-256-GCM under a fresh nonce.
|
||||
fn wrap_dek(&self, dek: &[u8; KEY_SIZE]) -> Result<(Vec<u8>, [u8; GCM_NONCE_SIZE])> {
|
||||
let Some(kek) = &self.kek else {
|
||||
bail!(
|
||||
"SSE-S3 is not configured: set s3.sse.kek or s3.sse.key for the engine as for the S3 gateway"
|
||||
);
|
||||
};
|
||||
let mut nonce = [0u8; GCM_NONCE_SIZE];
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let wrapped = Aes256Gcm::new(kek.into())
|
||||
.encrypt(&Nonce::from(nonce), dek.as_slice())
|
||||
.map_err(|_| anyhow::anyhow!("wrapping the object key"))?;
|
||||
Ok((wrapped, nonce))
|
||||
}
|
||||
|
||||
fn unwrap_dek(&self, wrapped: &[u8], nonce: &[u8]) -> Result<[u8; KEY_SIZE]> {
|
||||
let Some(kek) = &self.kek else {
|
||||
bail!(
|
||||
"SSE-S3 is not configured: set s3.sse.kek or s3.sse.key for the worker as for the S3 gateway"
|
||||
);
|
||||
};
|
||||
gcm_open(kek, nonce, wrapped)
|
||||
.context("unwrapping the object key")?
|
||||
.try_into()
|
||||
.ok()
|
||||
.context("the object key is not 256 bits")
|
||||
}
|
||||
}
|
||||
|
||||
fn key_from_hex(hex: &str) -> Result<[u8; KEY_SIZE]> {
|
||||
hex::decode(hex.trim())
|
||||
.context("not hex")?
|
||||
.try_into()
|
||||
.ok()
|
||||
.context("not 32 bytes")
|
||||
}
|
||||
|
||||
fn derive_key(secret: &[u8], salt: Option<&[u8]>, info: &[u8]) -> [u8; KEY_SIZE] {
|
||||
let mut key = [0u8; KEY_SIZE];
|
||||
Hkdf::<Sha256>::new(salt, secret)
|
||||
.expand(info, &mut key)
|
||||
.expect("32 bytes fit in one HKDF block");
|
||||
key
|
||||
}
|
||||
|
||||
/// The filer's `/etc/s3/sse_kek`: hex, or wrapped under the passphrase as
|
||||
/// `magic || salt || nonce || ciphertext` (v2) or `nonce || ciphertext` with
|
||||
/// a fixed salt (v1).
|
||||
fn kek_from_filer(content: &[u8], passphrase: Option<&str>) -> Result<[u8; KEY_SIZE]> {
|
||||
if content.is_empty() {
|
||||
bail!("the filer's /etc/s3/sse_kek is empty");
|
||||
}
|
||||
let text = std::str::from_utf8(content).context("/etc/s3/sse_kek is not text")?;
|
||||
let Some(passphrase) = passphrase else {
|
||||
return key_from_hex(text).context("/etc/s3/sse_kek");
|
||||
};
|
||||
let unwrapped = (|| {
|
||||
let raw = BASE64_STANDARD.decode(text.trim())?;
|
||||
let (salt, payload) = match raw.strip_prefix(KEK_WRAPPED_V2_MAGIC) {
|
||||
Some(rest) if rest.len() > KEK_SALT_SIZE => rest.split_at(KEK_SALT_SIZE),
|
||||
_ => (LEGACY_KEK_SALT, &raw[..]),
|
||||
};
|
||||
let wrapping = derive_key(passphrase.as_bytes(), Some(salt), b"kek-wrapping");
|
||||
if payload.len() < GCM_NONCE_SIZE {
|
||||
bail!("wrapped KEK too short");
|
||||
}
|
||||
let (nonce, sealed) = payload.split_at(GCM_NONCE_SIZE);
|
||||
gcm_open(&wrapping, nonce, sealed)
|
||||
})();
|
||||
match unwrapped {
|
||||
Ok(kek) => kek
|
||||
.try_into()
|
||||
.ok()
|
||||
.context("the unwrapped KEK is not 256 bits"),
|
||||
// A KEK written before the passphrase was set is still plain hex.
|
||||
Err(err) => key_from_hex(text).map_err(|_| err.context("unwrapping /etc/s3/sse_kek")),
|
||||
}
|
||||
}
|
||||
|
||||
fn gcm_open(key: &[u8; KEY_SIZE], nonce: &[u8], sealed: &[u8]) -> Result<Vec<u8>> {
|
||||
let nonce: [u8; GCM_NONCE_SIZE] = nonce
|
||||
.try_into()
|
||||
.ok()
|
||||
.with_context(|| format!("nonce is {} bytes, not {GCM_NONCE_SIZE}", nonce.len()))?;
|
||||
Aes256Gcm::new(key.into())
|
||||
.decrypt(&Nonce::from(nonce), sealed)
|
||||
.map_err(|_| anyhow::anyhow!("AES-GCM authentication failed"))
|
||||
}
|
||||
|
||||
/// The filer's volume encryption on the way in: `nonce || ciphertext` under a
|
||||
/// fresh chunk key, which the caller records as the chunk's `cipher_key`.
|
||||
fn encrypt_chunk(data: &[u8]) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut key = [0u8; KEY_SIZE];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
let mut nonce = [0u8; GCM_NONCE_SIZE];
|
||||
OsRng.fill_bytes(&mut nonce);
|
||||
let mut out = nonce.to_vec();
|
||||
out.extend(
|
||||
Aes256Gcm::new((&key).into())
|
||||
.encrypt(&Nonce::from(nonce), data)
|
||||
.expect("AES-GCM encryption of a chunk"),
|
||||
);
|
||||
(out, key.to_vec())
|
||||
}
|
||||
|
||||
/// The filer's volume encryption: `nonce || ciphertext` under the chunk's key.
|
||||
fn decrypt_chunk(cipher_key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
|
||||
let key: &[u8; KEY_SIZE] = cipher_key
|
||||
.try_into()
|
||||
.ok()
|
||||
.context("the chunk's cipher key is not 256 bits")?;
|
||||
if data.len() < GCM_NONCE_SIZE {
|
||||
bail!("encrypted chunk too short");
|
||||
}
|
||||
let (nonce, sealed) = data.split_at(GCM_NONCE_SIZE);
|
||||
gcm_open(key, nonce, sealed).context("decrypting the chunk")
|
||||
}
|
||||
|
||||
/// Undoes the filer's compression by the data's magic bytes; other data is
|
||||
/// returned as it is, as the filer does.
|
||||
fn decompress(data: Vec<u8>) -> Result<Vec<u8>> {
|
||||
match data.as_slice() {
|
||||
[0x1f, 0x8b, ..] => {
|
||||
let mut out = Vec::new();
|
||||
flate2::read::GzDecoder::new(data.as_slice())
|
||||
.read_to_end(&mut out)
|
||||
.context("gunzip")?;
|
||||
Ok(out)
|
||||
}
|
||||
[0x28, 0xb5, 0x2f, 0xfd, ..] => zstd::decode_all(data.as_slice()).context("unzstd"),
|
||||
_ => Ok(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// An SSE-S3 key as the gateway serializes it: the object key wrapped by the
|
||||
/// KEK, with the IV and the commitment binding the two.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SerializedKey {
|
||||
algorithm: Option<String>,
|
||||
#[serde(rename = "encryptedDEK")]
|
||||
encrypted_dek: String,
|
||||
nonce: String,
|
||||
iv: Option<String>,
|
||||
#[serde(rename = "keyCommitment")]
|
||||
key_commitment: Option<String>,
|
||||
}
|
||||
|
||||
struct ObjectKey {
|
||||
key: [u8; KEY_SIZE],
|
||||
iv: Option<[u8; IV_SIZE]>,
|
||||
}
|
||||
|
||||
impl ObjectKey {
|
||||
fn generate() -> Self {
|
||||
let mut key = [0u8; KEY_SIZE];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
let mut iv = [0u8; IV_SIZE];
|
||||
OsRng.fill_bytes(&mut iv);
|
||||
Self { key, iv: Some(iv) }
|
||||
}
|
||||
|
||||
/// The key as the gateway serializes it, with `iv` as its IV.
|
||||
fn serialize(&self, keys: &SseS3Keys, key_id: &str, iv: [u8; IV_SIZE]) -> Result<Vec<u8>> {
|
||||
let (wrapped, nonce) = keys.wrap_dek(&self.key)?;
|
||||
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&self.key).expect("any key length");
|
||||
mac.update(&iv);
|
||||
mac.update(AES256.as_bytes());
|
||||
let commitment = mac.finalize().into_bytes();
|
||||
Ok(serde_json::to_vec(&serde_json::json!({
|
||||
"algorithm": AES256,
|
||||
"keyId": key_id,
|
||||
"encryptedDEK": BASE64_STANDARD.encode(&wrapped),
|
||||
"nonce": BASE64_STANDARD.encode(nonce),
|
||||
"iv": BASE64_STANDARD.encode(iv),
|
||||
"keyCommitment": BASE64_STANDARD.encode(commitment),
|
||||
}))?)
|
||||
}
|
||||
|
||||
fn parse(keys: &SseS3Keys, data: &[u8]) -> Result<Self> {
|
||||
let meta: SerializedKey = serde_json::from_slice(data).context("SSE-S3 metadata")?;
|
||||
let b64 = |field: &str| {
|
||||
BASE64_STANDARD
|
||||
.decode(field)
|
||||
.context("SSE-S3 metadata base64")
|
||||
};
|
||||
let key = keys.unwrap_dek(&b64(&meta.encrypted_dek)?, &b64(&meta.nonce)?)?;
|
||||
let iv: Option<[u8; IV_SIZE]> = match &meta.iv {
|
||||
Some(iv) => Some(
|
||||
<[u8; IV_SIZE]>::try_from(b64(iv)?.as_slice())
|
||||
.ok()
|
||||
.context("the SSE-S3 IV is not 16 bytes")?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let algorithm = meta.algorithm.as_deref().unwrap_or(AES256);
|
||||
match (&meta.key_commitment, iv) {
|
||||
(Some(commitment), Some(iv)) => {
|
||||
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&key).expect("any key length");
|
||||
mac.update(&iv);
|
||||
mac.update(algorithm.as_bytes());
|
||||
mac.verify_slice(&b64(commitment)?)
|
||||
.map_err(|_| anyhow::anyhow!("the SSE-S3 key commitment does not match"))?;
|
||||
}
|
||||
(None, Some(_)) if keys.require_commitment => {
|
||||
bail!("the SSE-S3 metadata carries no key commitment")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(Self { key, iv })
|
||||
}
|
||||
|
||||
/// Decrypts `data`, the ciphertext from `position` bytes into the CTR
|
||||
/// stream that starts at this key's IV.
|
||||
fn decrypt(&self, position: u64, data: &mut [u8]) -> Result<()> {
|
||||
let iv = self.iv.context("the SSE-S3 key has no IV")?;
|
||||
let mut ctr = Aes256Ctr::new(&self.key.into(), &iv.into());
|
||||
ctr.try_seek(position)
|
||||
.map_err(|e| anyhow::anyhow!("CTR position {position}: {e}"))?;
|
||||
ctr.apply_keystream(data);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One chunk's bytes as the volume stores them, with what its `FileChunk`
|
||||
/// records about them.
|
||||
pub struct EncodedChunk {
|
||||
pub data: Vec<u8>,
|
||||
pub cipher_key: Vec<u8>,
|
||||
pub sse_type: i32,
|
||||
pub sse_metadata: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Encodes an object's chunks as the gateway would store them: SSE-S3 when the
|
||||
/// bucket encrypts, then the filer's volume encryption when the cluster asks
|
||||
/// for it. The first chunk is under the object's key and IV, which is how the
|
||||
/// gateway reads an object of one chunk; every other chunk is under a key and
|
||||
/// IV of its own, as the gateway's multipart parts are and as it reads an
|
||||
/// object of several, so no two chunks share a keystream whatever their
|
||||
/// boundaries.
|
||||
pub struct EntryEncoder {
|
||||
keys: Arc<SseS3Keys>,
|
||||
object: Option<(ObjectKey, String)>,
|
||||
cipher: bool,
|
||||
}
|
||||
|
||||
fn key_id() -> String {
|
||||
format!("sse-s3-key-{}", OsRng.next_u64() >> 1)
|
||||
}
|
||||
|
||||
impl EntryEncoder {
|
||||
pub fn new(keys: Arc<SseS3Keys>, sse_s3: bool, cipher: bool) -> Result<Self> {
|
||||
let object = if sse_s3 {
|
||||
if !keys.configured() {
|
||||
bail!(
|
||||
"the bucket encrypts with SSE-S3, which needs s3.sse.kek or s3.sse.key for the engine as for the S3 gateway"
|
||||
);
|
||||
}
|
||||
Some((ObjectKey::generate(), key_id()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self {
|
||||
keys,
|
||||
object,
|
||||
cipher,
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes of the chunk at `offset` in the object, as they go to the
|
||||
/// volume server, with the SSE-S3 metadata that reads them back.
|
||||
pub fn encode(&self, offset: u64, mut data: Vec<u8>) -> Result<EncodedChunk> {
|
||||
let (sse_type, sse_metadata) = match &self.object {
|
||||
Some((object, key_id)) if offset == 0 => {
|
||||
let iv = object.iv.expect("a generated key has an IV");
|
||||
object.decrypt(0, &mut data)?;
|
||||
(SSE_S3, object.serialize(&self.keys, key_id, iv)?)
|
||||
}
|
||||
Some(_) => {
|
||||
let chunk_key = ObjectKey::generate();
|
||||
let iv = chunk_key.iv.expect("a generated key has an IV");
|
||||
chunk_key.decrypt(0, &mut data)?;
|
||||
(SSE_S3, chunk_key.serialize(&self.keys, &key_id(), iv)?)
|
||||
}
|
||||
None => (0, Vec::new()),
|
||||
};
|
||||
let (data, cipher_key) = if self.cipher {
|
||||
encrypt_chunk(&data)
|
||||
} else {
|
||||
(data, Vec::new())
|
||||
};
|
||||
Ok(EncodedChunk {
|
||||
data,
|
||||
cipher_key,
|
||||
sse_type,
|
||||
sse_metadata,
|
||||
})
|
||||
}
|
||||
|
||||
/// The attributes the entry carries for its chunks to be decodable: the
|
||||
/// SSE-S3 header and the object key.
|
||||
pub fn attributes(&self) -> Result<Vec<(String, Vec<u8>)>> {
|
||||
let Some((object, key_id)) = &self.object else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let iv = object.iv.expect("a generated key has an IV");
|
||||
Ok(vec![
|
||||
(SSE_HEADER_ATTRIBUTE.to_string(), AES256.as_bytes().to_vec()),
|
||||
(
|
||||
SSE_S3_KEY_ATTRIBUTE.to_string(),
|
||||
object.serialize(&self.keys, key_id, iv)?,
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute<'a>(entry: &'a Entry, name: &str) -> Option<&'a [u8]> {
|
||||
entry
|
||||
.extended
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case(name))
|
||||
.map(|(_, v)| v.as_slice())
|
||||
}
|
||||
|
||||
/// Decodes one entry's chunks: the filer's encryption first, then SSE-S3 with
|
||||
/// the chunk's own key, or the object's key for chunks written without one.
|
||||
pub struct EntryDecoder {
|
||||
keys: Arc<SseS3Keys>,
|
||||
object: Option<ObjectKey>,
|
||||
chunk_keys: Mutex<HashMap<String, Arc<ObjectKey>>>,
|
||||
}
|
||||
|
||||
impl EntryDecoder {
|
||||
pub fn new(keys: Arc<SseS3Keys>, entry: &Entry) -> Result<Self> {
|
||||
// As the gateway, an object is SSE-S3 only with both the header and
|
||||
// the key; a header left over from a decrypting copy means nothing.
|
||||
let object = match (
|
||||
attribute(entry, SSE_HEADER_ATTRIBUTE),
|
||||
attribute(entry, SSE_S3_KEY_ATTRIBUTE),
|
||||
) {
|
||||
(Some(algorithm), Some(key)) if algorithm == AES256.as_bytes() => {
|
||||
Some(ObjectKey::parse(&keys, key).context("the object's SSE-S3 key")?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok(Self {
|
||||
keys,
|
||||
object,
|
||||
chunk_keys: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether anything about this entry needs decoding.
|
||||
pub fn is_plain(&self, entry: &Entry) -> bool {
|
||||
self.object.is_none()
|
||||
&& entry
|
||||
.chunks
|
||||
.iter()
|
||||
.all(|c| c.cipher_key.is_empty() && c.sse_type == 0)
|
||||
}
|
||||
|
||||
fn chunk_key(&self, chunk: &FileChunk) -> Result<Arc<ObjectKey>> {
|
||||
// A chunk out of a manifest carries its id as `fid`, not `file_id`.
|
||||
let id = sw_client::read::file_id_string(chunk).unwrap_or_default();
|
||||
if let Some(key) = self.chunk_keys.lock().unwrap().get(&id) {
|
||||
return Ok(key.clone());
|
||||
}
|
||||
let key = Arc::new(
|
||||
ObjectKey::parse(&self.keys, &chunk.sse_metadata)
|
||||
.with_context(|| format!("chunk {id}'s SSE-S3 key"))?,
|
||||
);
|
||||
self.chunk_keys.lock().unwrap().insert(id, key.clone());
|
||||
Ok(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkDecoder for EntryDecoder {
|
||||
fn needs_whole_chunk(&self, chunk: &FileChunk) -> bool {
|
||||
!chunk.cipher_key.is_empty()
|
||||
}
|
||||
|
||||
fn decode(&self, chunk: &FileChunk, offset: u64, data: Vec<u8>) -> Result<Vec<u8>> {
|
||||
let mut data = if chunk.cipher_key.is_empty() {
|
||||
data
|
||||
} else {
|
||||
let plain = decrypt_chunk(&chunk.cipher_key, &data)?;
|
||||
if chunk.is_compressed {
|
||||
decompress(plain)?
|
||||
} else {
|
||||
plain
|
||||
}
|
||||
};
|
||||
// Manifests list chunks; the gateway encrypts only the bytes.
|
||||
if chunk.is_chunk_manifest {
|
||||
return Ok(data);
|
||||
}
|
||||
match chunk.sse_type {
|
||||
0 => {
|
||||
if let Some(object) = &self.object {
|
||||
object.decrypt(chunk.offset as u64 + offset, &mut data)?;
|
||||
}
|
||||
}
|
||||
SSE_S3 if chunk.sse_metadata.is_empty() => {
|
||||
let object = self
|
||||
.object
|
||||
.as_ref()
|
||||
.context("an SSE-S3 chunk without a key in an object without one")?;
|
||||
object.decrypt(chunk.offset as u64 + offset, &mut data)?;
|
||||
}
|
||||
SSE_S3 => self.chunk_key(chunk)?.decrypt(offset, &mut data)?,
|
||||
SSE_C => bail!("SSE-C objects need the customer's key, which direct reads do not have"),
|
||||
SSE_KMS => bail!("SSE-KMS objects are not supported by direct reads"),
|
||||
other => bail!("unknown SSE type {other}"),
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sw_client::filer_pb::FuseAttributes;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct FixtureChunk {
|
||||
offset: i64,
|
||||
ciphertext: String,
|
||||
sse_metadata: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Fixture {
|
||||
kek_secret: String,
|
||||
kek_hex: String,
|
||||
kek_passphrase: String,
|
||||
kek_wrapped_v1: String,
|
||||
kek_wrapped_v2: String,
|
||||
plaintext: String,
|
||||
object_metadata: String,
|
||||
chunks: Vec<FixtureChunk>,
|
||||
whole_ciphertext: String,
|
||||
cipher_key: String,
|
||||
cipher_plain: String,
|
||||
cipher_gzip: String,
|
||||
}
|
||||
|
||||
/// Written by the gateway's own code: `TestGenerateDirectReadFixture` in
|
||||
/// weed/s3api.
|
||||
fn fixture() -> Fixture {
|
||||
serde_json::from_str(include_str!("../tests/direct_read_fixture.json")).unwrap()
|
||||
}
|
||||
|
||||
fn un(hex: &str) -> Vec<u8> {
|
||||
hex::decode(hex).unwrap()
|
||||
}
|
||||
|
||||
fn keys(config: SseConfig, filer_file: Option<&[u8]>) -> Arc<SseS3Keys> {
|
||||
Arc::new(SseS3Keys::load(&config, filer_file).unwrap())
|
||||
}
|
||||
|
||||
fn from_secret(f: &Fixture) -> Arc<SseS3Keys> {
|
||||
keys(
|
||||
SseConfig {
|
||||
key: Some(f.kek_secret.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn sse_entry(f: &Fixture, with_object_key: bool) -> Entry {
|
||||
let mut entry = Entry {
|
||||
name: "a.lance".into(),
|
||||
attributes: Some(FuseAttributes {
|
||||
file_size: f.plaintext.len() as u64 / 2,
|
||||
..Default::default()
|
||||
}),
|
||||
chunks: f
|
||||
.chunks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| FileChunk {
|
||||
file_id: format!("3,{i:02x}"),
|
||||
offset: c.offset,
|
||||
size: c.ciphertext.len() as u64 / 2,
|
||||
sse_type: SSE_S3,
|
||||
sse_metadata: c.sse_metadata.clone().into_bytes(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
if with_object_key {
|
||||
entry
|
||||
.extended
|
||||
.insert(SSE_HEADER_ATTRIBUTE.into(), AES256.into());
|
||||
entry.extended.insert(
|
||||
SSE_S3_KEY_ATTRIBUTE.into(),
|
||||
f.object_metadata.clone().into_bytes(),
|
||||
);
|
||||
}
|
||||
entry
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_s3_chunks_decrypt_from_any_offset() {
|
||||
let f = fixture();
|
||||
let plain = un(&f.plaintext);
|
||||
let entry = sse_entry(&f, false);
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
assert!(!decoder.is_plain(&entry));
|
||||
for (i, chunk) in entry.chunks.iter().enumerate() {
|
||||
let ciphertext = un(&f.chunks[i].ciphertext);
|
||||
assert!(!decoder.needs_whole_chunk(chunk));
|
||||
for offset in [0usize, 1, 7, 16, 17, 100, 2047] {
|
||||
let want = &plain
|
||||
[chunk.offset as usize + offset..chunk.offset as usize + chunk.size as usize];
|
||||
let got = decoder
|
||||
.decode(chunk, offset as u64, ciphertext[offset..].to_vec())
|
||||
.unwrap();
|
||||
assert_eq!(got, want, "chunk {i} from {offset}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Chunks expanded from a manifest name themselves by `fid`; keyed by the
|
||||
/// empty `file_id` they would all share one key and IV.
|
||||
#[test]
|
||||
fn chunks_out_of_a_manifest_keep_their_own_keys() {
|
||||
let f = fixture();
|
||||
let plain = un(&f.plaintext);
|
||||
let mut entry = sse_entry(&f, false);
|
||||
for (i, chunk) in entry.chunks.iter_mut().enumerate() {
|
||||
chunk.file_id.clear();
|
||||
chunk.fid = Some(sw_client::filer_pb::FileId {
|
||||
volume_id: 3,
|
||||
file_key: i as u64 + 1,
|
||||
cookie: 7,
|
||||
});
|
||||
}
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
for (i, chunk) in entry.chunks.iter().enumerate() {
|
||||
let got = decoder
|
||||
.decode(chunk, 0, un(&f.chunks[i].ciphertext))
|
||||
.unwrap();
|
||||
let want = &plain[chunk.offset as usize..chunk.offset as usize + chunk.size as usize];
|
||||
assert_eq!(got, want, "chunk {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_without_their_own_key_use_the_objects() {
|
||||
let f = fixture();
|
||||
let plain = un(&f.plaintext);
|
||||
let whole = un(&f.whole_ciphertext);
|
||||
let mut entry = sse_entry(&f, true);
|
||||
for chunk in &mut entry.chunks {
|
||||
chunk.sse_type = 0;
|
||||
chunk.sse_metadata.clear();
|
||||
}
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
let chunk = &entry.chunks[1];
|
||||
let start = chunk.offset as usize;
|
||||
let got = decoder
|
||||
.decode(chunk, 13, whole[start + 13..start + 500].to_vec())
|
||||
.unwrap();
|
||||
assert_eq!(got, &plain[start + 13..start + 500]);
|
||||
|
||||
// A header without a key is not encryption, as for the gateway.
|
||||
entry.extended.remove(SSE_S3_KEY_ATTRIBUTE);
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
assert!(decoder.is_plain(&entry));
|
||||
assert_eq!(
|
||||
decoder.decode(chunk, 0, b"as is".to_vec()).unwrap(),
|
||||
b"as is"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kek_comes_from_hex_a_secret_or_the_filer() {
|
||||
let f = fixture();
|
||||
let entry = sse_entry(&f, false);
|
||||
let plain = un(&f.plaintext);
|
||||
let ciphertext = un(&f.chunks[0].ciphertext);
|
||||
let v1 = f.kek_wrapped_v1.as_bytes();
|
||||
let v2 = f.kek_wrapped_v2.as_bytes();
|
||||
let hex_file = f.kek_hex.as_bytes();
|
||||
let passphrase = Some(f.kek_passphrase.clone());
|
||||
let hex = Some(f.kek_hex.clone());
|
||||
let secret = Some(f.kek_secret.clone());
|
||||
let cases: Vec<(&str, SseConfig, Option<&[u8]>)> = vec![
|
||||
(
|
||||
"hex",
|
||||
SseConfig {
|
||||
kek_hex: hex.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
),
|
||||
(
|
||||
"hex matching the filer",
|
||||
SseConfig {
|
||||
kek_hex: hex.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(hex_file),
|
||||
),
|
||||
(
|
||||
"secret",
|
||||
SseConfig {
|
||||
key: secret.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
),
|
||||
("filer hex", SseConfig::default(), Some(hex_file)),
|
||||
(
|
||||
"filer v2",
|
||||
SseConfig {
|
||||
passphrase: passphrase.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(v2),
|
||||
),
|
||||
(
|
||||
"filer v1",
|
||||
SseConfig {
|
||||
passphrase: passphrase.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(v1),
|
||||
),
|
||||
(
|
||||
"filer hex with a passphrase",
|
||||
SseConfig {
|
||||
passphrase: passphrase.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(hex_file),
|
||||
),
|
||||
];
|
||||
for (case, config, file) in cases {
|
||||
let decoder = EntryDecoder::new(keys(config, file), &entry).unwrap();
|
||||
let got = decoder
|
||||
.decode(&entry.chunks[0], 0, ciphertext.clone())
|
||||
.unwrap();
|
||||
assert_eq!(got, &plain[..ciphertext.len()], "{case}");
|
||||
}
|
||||
|
||||
let refused: Vec<(&str, SseConfig, Option<&[u8]>)> = vec![
|
||||
(
|
||||
"both",
|
||||
SseConfig {
|
||||
kek_hex: hex.clone(),
|
||||
key: secret.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
),
|
||||
(
|
||||
"secret beside a filer file",
|
||||
SseConfig {
|
||||
key: secret.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(hex_file),
|
||||
),
|
||||
(
|
||||
"hex differing from the filer",
|
||||
SseConfig {
|
||||
kek_hex: Some("00".repeat(32)),
|
||||
..Default::default()
|
||||
},
|
||||
Some(hex_file),
|
||||
),
|
||||
(
|
||||
"wrong passphrase",
|
||||
SseConfig {
|
||||
passphrase: Some("other".into()),
|
||||
..Default::default()
|
||||
},
|
||||
Some(v2),
|
||||
),
|
||||
(
|
||||
"wrapped without a passphrase",
|
||||
SseConfig::default(),
|
||||
Some(v2),
|
||||
),
|
||||
("empty file", SseConfig::default(), Some(b"")),
|
||||
];
|
||||
for (case, config, file) in refused {
|
||||
assert!(SseS3Keys::load(&config, file).is_err(), "{case}");
|
||||
}
|
||||
|
||||
let unconfigured = keys(SseConfig::default(), None);
|
||||
assert!(!unconfigured.configured());
|
||||
let err = EntryDecoder::new(unconfigured.clone(), &entry)
|
||||
.unwrap()
|
||||
.decode(&entry.chunks[0], 0, ciphertext)
|
||||
.unwrap_err();
|
||||
assert!(format!("{err:#}").contains("not configured"), "{err:#}");
|
||||
assert!(EntryDecoder::new(unconfigured, &sse_entry(&f, true)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tampered_iv_fails_the_commitment() {
|
||||
let f = fixture();
|
||||
let mut entry = sse_entry(&f, false);
|
||||
let meta = std::str::from_utf8(&entry.chunks[1].sse_metadata).unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_str(meta).unwrap();
|
||||
value["iv"] = serde_json::Value::String(BASE64_STANDARD.encode(b"fedcba9876543210"));
|
||||
entry.chunks[1].sse_metadata = value.to_string().into_bytes();
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
let err = decoder
|
||||
.decode(&entry.chunks[1], 0, un(&f.chunks[1].ciphertext))
|
||||
.unwrap_err();
|
||||
assert!(format!("{err:#}").contains("commitment"), "{err:#}");
|
||||
|
||||
let mut without = value.clone();
|
||||
without.as_object_mut().unwrap().remove("keyCommitment");
|
||||
entry.chunks[1].sse_metadata = without.to_string().into_bytes();
|
||||
let strict = keys(
|
||||
SseConfig {
|
||||
key: Some(f.kek_secret.clone()),
|
||||
require_commitment: true,
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
);
|
||||
assert!(
|
||||
EntryDecoder::new(strict, &entry)
|
||||
.unwrap()
|
||||
.decode(&entry.chunks[1], 0, un(&f.chunks[1].ciphertext))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filer_encrypted_chunks_are_decrypted_then_decompressed() {
|
||||
let f = fixture();
|
||||
let plain = un(&f.plaintext);
|
||||
let entry = Entry::default();
|
||||
let decoder = EntryDecoder::new(keys(SseConfig::default(), None), &entry).unwrap();
|
||||
// zstd is an Enterprise codec the fixture's generator cannot produce;
|
||||
// its sealed form is made here with the fixture's key.
|
||||
let zstd = zstd::encode_all(plain.as_slice(), 0).unwrap();
|
||||
let nonce = [7u8; GCM_NONCE_SIZE];
|
||||
let mut cipher_zstd = nonce.to_vec();
|
||||
cipher_zstd.extend(
|
||||
Aes256Gcm::new(un(&f.cipher_key).as_slice().into())
|
||||
.encrypt(&Nonce::from(nonce), zstd.as_slice())
|
||||
.unwrap(),
|
||||
);
|
||||
for (case, data, compressed) in [
|
||||
("plain", un(&f.cipher_plain), false),
|
||||
("gzip", un(&f.cipher_gzip), true),
|
||||
("zstd", cipher_zstd, true),
|
||||
] {
|
||||
let chunk = FileChunk {
|
||||
file_id: "3,01".into(),
|
||||
size: plain.len() as u64,
|
||||
cipher_key: un(&f.cipher_key),
|
||||
is_compressed: compressed,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(decoder.needs_whole_chunk(&chunk));
|
||||
assert_eq!(decoder.decode(&chunk, 0, data).unwrap(), plain, "{case}");
|
||||
}
|
||||
let wrong_key = FileChunk {
|
||||
cipher_key: vec![1; 32],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(decoder.decode(&wrong_key, 0, un(&f.cipher_plain)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_in_an_encrypted_object_only_undo_the_filers_encryption() {
|
||||
let f = fixture();
|
||||
let plain = un(&f.plaintext);
|
||||
let entry = sse_entry(&f, true);
|
||||
let decoder = EntryDecoder::new(from_secret(&f), &entry).unwrap();
|
||||
let manifest = FileChunk {
|
||||
file_id: "3,0m".into(),
|
||||
is_chunk_manifest: true,
|
||||
cipher_key: un(&f.cipher_key),
|
||||
is_compressed: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
decoder.decode(&manifest, 0, un(&f.cipher_gzip)).unwrap(),
|
||||
plain
|
||||
);
|
||||
let plain_manifest = FileChunk {
|
||||
is_chunk_manifest: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
decoder
|
||||
.decode(&plain_manifest, 0, b"proto".to_vec())
|
||||
.unwrap(),
|
||||
b"proto"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn customer_and_kms_keys_are_refused() {
|
||||
let decoder =
|
||||
EntryDecoder::new(keys(SseConfig::default(), None), &Entry::default()).unwrap();
|
||||
for sse_type in [SSE_C, SSE_KMS, 9] {
|
||||
let chunk = FileChunk {
|
||||
sse_type,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
decoder.decode(&chunk, 0, vec![0; 16]).is_err(),
|
||||
"{sse_type}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The vector index an S3 Vectors table searches through: how it is named,
|
||||
//! sized and built. The query engine and the maintenance worker share this.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use lance::Dataset;
|
||||
use lance::index::DatasetIndexExt;
|
||||
use lance::index::vector::VectorIndexParams;
|
||||
use lance_index::IndexType;
|
||||
use lance_index::optimize::OptimizeOptions;
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use roaring::RoaringBitmap;
|
||||
|
||||
/// The name every S3 Vectors index build uses, so a table has one logical index.
|
||||
pub const INDEX_NAME: &str = "vector_idx";
|
||||
pub const MAX_PARTITIONS: usize = 4096;
|
||||
/// Delta segments one index name may pile up before they are merged into one:
|
||||
/// each is a separate search per query.
|
||||
pub const MAX_DELTAS: usize = 8;
|
||||
|
||||
/// IVF partitions for a table of `rows`: about one per sqrt(rows), at least one.
|
||||
pub fn partitions_for(rows: usize) -> usize {
|
||||
((rows as f64).sqrt().round() as usize).clamp(1, MAX_PARTITIONS)
|
||||
}
|
||||
|
||||
/// The metric the table was created with, from the vector field's
|
||||
/// `distance_metric` metadata as the S3 Vectors gateway writes it; L2 when
|
||||
/// absent.
|
||||
pub fn distance_metric(dataset: &Dataset, vector_column: &str) -> DistanceType {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Names of the indices built on `vector_column`, each once.
|
||||
pub async fn index_names(dataset: &Dataset, vector_column: &str) -> Result<Vec<String>> {
|
||||
let Some(field) = dataset.schema().field(vector_column) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut names: Vec<String> = dataset
|
||||
.load_indices()
|
||||
.await?
|
||||
.iter()
|
||||
.filter(|i| i.fields == [field.id])
|
||||
.map(|i| i.name.clone())
|
||||
.collect();
|
||||
names.sort();
|
||||
names.dedup();
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// What the indices on a vector column cover, taken together. Sharded builds
|
||||
/// give one name per shard and each name misses the others' fragments, so
|
||||
/// coverage is the union over names, never a single name's statistics.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Coverage {
|
||||
pub indexed_rows: u64,
|
||||
pub unindexed_rows: u64,
|
||||
/// Delta segments per index name.
|
||||
pub deltas: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
/// Coverage of `vector_column` by every index built on it, or `None` when it
|
||||
/// has no index. An index that does not record its fragments is an error:
|
||||
/// counting its rows as uncovered would have them indexed a second time.
|
||||
pub async fn coverage(dataset: &Dataset, vector_column: &str) -> Result<Option<Coverage>> {
|
||||
let Some(field) = dataset.schema().field(vector_column) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut deltas: BTreeMap<String, usize> = BTreeMap::new();
|
||||
let mut covered = RoaringBitmap::new();
|
||||
for index in dataset.load_indices().await?.iter() {
|
||||
if index.fields != [field.id] {
|
||||
continue;
|
||||
}
|
||||
let Some(bitmap) = &index.fragment_bitmap else {
|
||||
anyhow::bail!(
|
||||
"index {} does not record the fragments it covers",
|
||||
index.name
|
||||
);
|
||||
};
|
||||
*deltas.entry(index.name.clone()).or_default() += 1;
|
||||
covered |= bitmap;
|
||||
}
|
||||
if deltas.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let (mut indexed_rows, mut unindexed_rows) = (0, 0);
|
||||
for fragment in dataset.get_fragments() {
|
||||
let rows = fragment.count_rows(None).await? as u64;
|
||||
if covered.contains(fragment.id() as u32) {
|
||||
indexed_rows += rows;
|
||||
} else {
|
||||
unindexed_rows += rows;
|
||||
}
|
||||
}
|
||||
Ok(Some(Coverage {
|
||||
indexed_rows,
|
||||
unindexed_rows,
|
||||
deltas,
|
||||
}))
|
||||
}
|
||||
|
||||
/// How to extend an index name that already has `deltas` segments: another
|
||||
/// delta while there is room, and once the limit is reached every delta
|
||||
/// merged with the new rows into one. Lance's default options promise no
|
||||
/// merge, so the count is explicit.
|
||||
pub fn optimize_policy(deltas: usize) -> OptimizeOptions {
|
||||
if deltas >= MAX_DELTAS {
|
||||
OptimizeOptions::merge(deltas)
|
||||
} else {
|
||||
OptimizeOptions::append()
|
||||
}
|
||||
}
|
||||
|
||||
/// What an index was built as, from Lance's statistics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct IndexSettings {
|
||||
/// The most partitions any of its deltas has.
|
||||
pub partitions: usize,
|
||||
/// Lance's name for the type, such as `IVF_FLAT`.
|
||||
pub index_type: String,
|
||||
pub metric: Option<DistanceType>,
|
||||
}
|
||||
|
||||
pub async fn index_settings(dataset: &Dataset, name: &str) -> Result<IndexSettings> {
|
||||
let stats: serde_json::Value = serde_json::from_str(&dataset.index_statistics(name).await?)
|
||||
.with_context(|| format!("parse index statistics for {name}"))?;
|
||||
let deltas: Vec<&serde_json::Value> =
|
||||
stats["indices"].as_array().into_iter().flatten().collect();
|
||||
Ok(IndexSettings {
|
||||
partitions: deltas
|
||||
.iter()
|
||||
.filter_map(|i| i["num_partitions"].as_u64())
|
||||
.max()
|
||||
.unwrap_or(0) as usize,
|
||||
index_type: deltas
|
||||
.first()
|
||||
.and_then(|i| i["index_type"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
metric: deltas
|
||||
.first()
|
||||
.and_then(|i| i["metric_type"].as_str())
|
||||
.and_then(|m| DistanceType::try_from(m).ok()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an index built with `partitions` should be trained again for a
|
||||
/// table of `rows`: once the table has grown to twice the partitions it was
|
||||
/// sized for, the centroids no longer fit it.
|
||||
pub fn needs_retrain(partitions: usize, rows: usize) -> bool {
|
||||
partitions_for(rows) >= 2 * partitions.max(1)
|
||||
}
|
||||
|
||||
/// Whether the index on `vector_column` is due for [`optimize`] with
|
||||
/// `retrain`: a single IVF_FLAT name the table has outgrown. A sharded build
|
||||
/// sizes each name for its shard, and other index types keep the settings
|
||||
/// they were built with.
|
||||
pub async fn retrain_due(dataset: &Dataset, vector_column: &str) -> Result<bool> {
|
||||
let Some(cover) = coverage(dataset, vector_column).await? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let [name] = Vec::from_iter(cover.deltas.keys())[..] else {
|
||||
return Ok(false);
|
||||
};
|
||||
let settings = index_settings(dataset, name).await?;
|
||||
Ok(settings.index_type == "IVF_FLAT"
|
||||
&& needs_retrain(settings.partitions, dataset.count_rows(None).await?))
|
||||
}
|
||||
|
||||
/// Build an IVF_FLAT index named `name` over `vector_column` in the metric the
|
||||
/// table was created with. `replace` rebuilds an index of that name; the
|
||||
/// dataset is left at the new version.
|
||||
pub async fn build(
|
||||
dataset: &mut Dataset,
|
||||
vector_column: &str,
|
||||
name: &str,
|
||||
partitions: usize,
|
||||
replace: bool,
|
||||
) -> Result<()> {
|
||||
let metric = distance_metric(dataset, vector_column);
|
||||
build_with(dataset, vector_column, name, partitions, replace, metric).await
|
||||
}
|
||||
|
||||
async fn build_with(
|
||||
dataset: &mut Dataset,
|
||||
vector_column: &str,
|
||||
name: &str,
|
||||
partitions: usize,
|
||||
replace: bool,
|
||||
metric: DistanceType,
|
||||
) -> Result<()> {
|
||||
let params = VectorIndexParams::ivf_flat(partitions, metric);
|
||||
dataset
|
||||
.create_index(
|
||||
&[vector_column],
|
||||
IndexType::Vector,
|
||||
Some(name.to_string()),
|
||||
¶ms,
|
||||
replace,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("build index {name} with {partitions} partitions"))?;
|
||||
dataset.checkout_latest().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cover the rows written since the indices on `vector_column` were built.
|
||||
/// One name takes them, the one with the fewest deltas, under
|
||||
/// [`optimize_policy`]; the other names keep the fragments they have, so
|
||||
/// shards stay disjoint. With `retrain` the index is built again over the
|
||||
/// whole table with partitions for the current row count, in the metric it
|
||||
/// has; only a single IVF_FLAT name is rebuilt this way. Lance's own retrain
|
||||
/// does not size the partitions, so the rebuild goes through [`build`].
|
||||
/// Indices on other columns are left alone.
|
||||
pub async fn optimize(dataset: &mut Dataset, vector_column: &str, retrain: bool) -> Result<()> {
|
||||
let Some(cover) = coverage(dataset, vector_column).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if retrain {
|
||||
if cover.deltas.len() > 1 {
|
||||
anyhow::bail!(
|
||||
"the vector index is sharded over {} names; each would be rebuilt over the whole table",
|
||||
cover.deltas.len()
|
||||
);
|
||||
}
|
||||
let partitions = partitions_for(dataset.count_rows(None).await?);
|
||||
for name in cover.deltas.keys() {
|
||||
let settings = index_settings(dataset, name).await?;
|
||||
if settings.index_type != "IVF_FLAT" {
|
||||
anyhow::bail!(
|
||||
"index {name} is {}; only an IVF_FLAT index is retrained here",
|
||||
settings.index_type
|
||||
);
|
||||
}
|
||||
let metric = settings
|
||||
.metric
|
||||
.unwrap_or_else(|| distance_metric(dataset, vector_column));
|
||||
build_with(dataset, vector_column, name, partitions, true, metric).await?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let (name, deltas) = cover
|
||||
.deltas
|
||||
.iter()
|
||||
.min_by_key(|(name, deltas)| (**deltas, (*name).clone()))
|
||||
.map(|(name, deltas)| (name.clone(), *deltas))
|
||||
.context("no index to extend")?;
|
||||
let mut options = optimize_policy(deltas);
|
||||
options.index_names = Some(vec![name]);
|
||||
dataset.optimize_indices(&options).await?;
|
||||
dataset.checkout_latest().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retrain_once_the_table_quadruples() {
|
||||
assert!(!needs_retrain(224, 50_000));
|
||||
assert!(!needs_retrain(224, 150_000));
|
||||
assert!(needs_retrain(224, 200_704));
|
||||
assert!(needs_retrain(0, 4));
|
||||
assert!(!needs_retrain(4096, 100_000_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deltas_append_until_the_limit_then_merge() {
|
||||
assert_eq!(optimize_policy(1).num_indices_to_merge, Some(0));
|
||||
assert_eq!(optimize_policy(7).num_indices_to_merge, Some(0));
|
||||
assert_eq!(optimize_policy(8).num_indices_to_merge, Some(8));
|
||||
assert_eq!(optimize_policy(11).num_indices_to_merge, Some(11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partitions_follow_the_square_root() {
|
||||
assert_eq!(partitions_for(0), 1);
|
||||
assert_eq!(partitions_for(64), 8);
|
||||
assert_eq!(partitions_for(50_000), 224);
|
||||
assert_eq!(partitions_for(1_000_000), 1000);
|
||||
assert_eq!(partitions_for(100_000_000), MAX_PARTITIONS);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use seaweed_worker_core::pb::{
|
||||
JobProgressUpdate, JobProposal, ObjectObservation, WorkerObservations, config_value::Kind,
|
||||
};
|
||||
use seaweed_worker_core::{DetectionSender, ExecutionSender};
|
||||
use weed_lance_worker::catalog::{NamespaceClient, SigningKey};
|
||||
|
||||
/// Keeps everything a handler reports, so a test can assert on it afterwards.
|
||||
#[derive(Default)]
|
||||
@@ -57,6 +58,14 @@ impl ExecutionSender for Recorder {
|
||||
/// these handlers rewrite real files, and there is nothing to learn from them
|
||||
/// against a fake.
|
||||
pub fn namespace_url() -> Option<String> {
|
||||
// The handlers say why they skip a table only in their logs.
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.with_test_writer()
|
||||
.try_init();
|
||||
std::env::var("WEED_LANCE_NAMESPACE")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
@@ -73,25 +82,32 @@ pub fn int_config(name: &str, value: i64) -> HashMap<String, ConfigValue> {
|
||||
values
|
||||
}
|
||||
|
||||
/// What to reach the data with where the namespace vends nothing of its own -
|
||||
/// a gateway without STS vends no credentials, and one bound to a wildcard
|
||||
/// address vends no endpoint either. Taken from the environment so a harness
|
||||
/// can point these tests at a gateway that does check what it is given.
|
||||
pub fn fallback() -> weed_lance_worker::dataset::FallbackOptions {
|
||||
let mut options = weed_lance_worker::dataset::FallbackOptions::new();
|
||||
let from_env =
|
||||
|name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.to_string());
|
||||
options.insert(
|
||||
"aws_access_key_id".to_string(),
|
||||
from_env("AWS_ACCESS_KEY_ID", "any"),
|
||||
);
|
||||
options.insert(
|
||||
"aws_secret_access_key".to_string(),
|
||||
from_env("AWS_SECRET_ACCESS_KEY", "any"),
|
||||
);
|
||||
if let Ok(endpoint) = std::env::var("AWS_ENDPOINT_URL") {
|
||||
options.insert("aws_endpoint".to_string(), endpoint);
|
||||
options.insert("allow_http".to_string(), "true".to_string());
|
||||
}
|
||||
options
|
||||
/// The cluster's storage, from the masters WEED_MASTERS names. A live
|
||||
/// namespace without them would have the tests seed tables through lance's
|
||||
/// own S3 store, which reaches nothing, so the pair is required together.
|
||||
pub async fn storage() -> weed_lance_worker::dataset::Storage {
|
||||
let masters = std::env::var("WEED_MASTERS")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.expect("WEED_LANCE_NAMESPACE names a live namespace; WEED_MASTERS must name its masters");
|
||||
let security = security();
|
||||
let cluster =
|
||||
weed_lance_worker::cluster::Cluster::new(&masters, "", &security).expect("masters");
|
||||
weed_lance_worker::dataset::Storage(Some(cluster.storage(&security).await.expect("storage")))
|
||||
}
|
||||
|
||||
fn security() -> weed_lance_worker::security::Security {
|
||||
weed_lance_worker::security::Security::load(None, None).expect("security.toml")
|
||||
}
|
||||
|
||||
/// The cluster token the namespace authenticates its processes by, from
|
||||
/// `jwt.filer_signing.key` (WEED_JWT_FILER_SIGNING_KEY or security.toml),
|
||||
/// as the worker reads it.
|
||||
pub fn signing_key() -> Option<SigningKey> {
|
||||
SigningKey::new(security().get("jwt.filer_signing.key"))
|
||||
}
|
||||
|
||||
/// The namespace client the handlers would use.
|
||||
pub fn client(url: &str) -> NamespaceClient {
|
||||
NamespaceClient::new(url.to_string()).with_signing_key(signing_key().as_ref())
|
||||
}
|
||||
@@ -4,21 +4,18 @@
|
||||
//! tests skip without Docker: compaction rewrites real files, and there is
|
||||
//! nothing to learn from it against a fake.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::Result;
|
||||
use seaweed_worker_core::pb::{
|
||||
ExecuteJobRequest, JobSpec, RunDetectionRequest, config_value::Kind,
|
||||
};
|
||||
use seaweed_worker_core::{JobHandler, PreviewProvider};
|
||||
use weed_lance_worker::catalog::NamespaceClient;
|
||||
use weed_lance_worker::jobs::cleanup::CleanupVersionsHandler;
|
||||
use weed_lance_worker::jobs::compact::{CompactHandler, JOB_TYPE};
|
||||
use weed_lance_worker::jobs::indices::OptimizeIndicesHandler;
|
||||
use weed_lance_worker::preview::LancePreview;
|
||||
|
||||
mod common;
|
||||
use common::{Recorder, fallback, int_config, namespace_url};
|
||||
use common::{Recorder, client, int_config, namespace_url, signing_key, storage};
|
||||
|
||||
/// These tests drive one live gateway and one shared catalog: `list_all_tables`
|
||||
/// sweeps everything, so a table another test is writing shows up in this test's
|
||||
@@ -47,7 +44,6 @@ async fn seed_table(
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use lance::dataset::{Dataset, WriteMode, WriteParams};
|
||||
use lance::io::{ObjectStoreParams, StorageOptionsAccessor};
|
||||
use std::sync::Arc;
|
||||
|
||||
// Declaring is the namespace's job, not the worker's, so the test asks for
|
||||
@@ -69,12 +65,11 @@ async fn seed_table(
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
let client = NamespaceClient::new(url.to_string());
|
||||
let client = client(url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), name.to_string()];
|
||||
let description = client.describe_table(&id).await?;
|
||||
|
||||
let mut options = description.storage_options.clone();
|
||||
options.extend(fallback());
|
||||
let wrapper = storage().await.wrapper(&description.location).await?;
|
||||
const DIM: i32 = 16;
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
@@ -108,12 +103,7 @@ async fn seed_table(
|
||||
} else {
|
||||
WriteMode::Append
|
||||
},
|
||||
store_params: Some(ObjectStoreParams {
|
||||
storage_options_accessor: Some(std::sync::Arc::new(
|
||||
StorageOptionsAccessor::with_static_options(options.clone()),
|
||||
)),
|
||||
..Default::default()
|
||||
}),
|
||||
store_params: Some(weed_lance_worker::dataset::store_params(wrapper.clone())),
|
||||
..Default::default()
|
||||
};
|
||||
let dataset = Dataset::write(reader, description.location.as_str(), Some(params)).await?;
|
||||
@@ -154,7 +144,9 @@ async fn compacts_a_fragmented_table() {
|
||||
let encoded = seed_fragmented_table(&url, "compactme", 12)
|
||||
.await
|
||||
.expect("seed a fragmented table");
|
||||
let handler = CompactHandler::new(url).with_fallback(fallback());
|
||||
let handler = CompactHandler::new(url)
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
|
||||
let request = RunDetectionRequest {
|
||||
@@ -242,7 +234,9 @@ async fn cleans_up_old_versions() {
|
||||
.await
|
||||
.expect("seed a table with versions to clean");
|
||||
|
||||
let handler = CleanupVersionsHandler::new(url).with_fallback(fallback());
|
||||
let handler = CleanupVersionsHandler::new(url)
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
|
||||
let request = RunDetectionRequest {
|
||||
@@ -306,7 +300,9 @@ async fn skips_tables_without_indices() {
|
||||
.await
|
||||
.expect("seed a table without an index");
|
||||
|
||||
let handler = OptimizeIndicesHandler::new(url).with_fallback(fallback());
|
||||
let handler = OptimizeIndicesHandler::new(url)
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
|
||||
let request = RunDetectionRequest {
|
||||
@@ -345,7 +341,9 @@ async fn reindexes_rows_an_index_does_not_cover() {
|
||||
let encoded = seed_table(&url, "reindexme", 2, 512, true)
|
||||
.await
|
||||
.expect("seed an indexed table with uncovered rows");
|
||||
let handler = OptimizeIndicesHandler::new(url).with_fallback(fallback());
|
||||
let handler = OptimizeIndicesHandler::new(url)
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
|
||||
let request = RunDetectionRequest {
|
||||
@@ -418,7 +416,7 @@ async fn previews_rows_of_a_table() {
|
||||
.await
|
||||
.expect("seed a table to preview");
|
||||
|
||||
let provider = LancePreview::new(url, fallback());
|
||||
let provider = LancePreview::new(url, storage().await);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), "previewme".to_string()];
|
||||
let preview = provider.preview(&id, 4).await.expect("preview the table");
|
||||
|
||||
@@ -450,27 +448,32 @@ async fn concurrent_writers_keep_every_commit() {
|
||||
.await
|
||||
.expect("seed the table the writers will append to");
|
||||
|
||||
let client = NamespaceClient::new(url.clone());
|
||||
let client = client(&url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), "racers".to_string()];
|
||||
let description = client.describe_table(&id).await.expect("describe");
|
||||
let mut options = description.storage_options.clone();
|
||||
options.extend(fallback());
|
||||
let wrapper = storage()
|
||||
.await
|
||||
.wrapper(&description.location)
|
||||
.await
|
||||
.expect("storage for the table");
|
||||
|
||||
let writes = (0..WRITERS).map(|writer| {
|
||||
let location = description.location.clone();
|
||||
let options = options.clone();
|
||||
tokio::spawn(
|
||||
async move { append_rows(&location, &options, writer * 1000, ROWS_EACH).await },
|
||||
)
|
||||
});
|
||||
for (writer, handle) in writes.enumerate() {
|
||||
let writes: Vec<_> = (0..WRITERS)
|
||||
.map(|writer| {
|
||||
let location = description.location.clone();
|
||||
let wrapper = wrapper.clone();
|
||||
tokio::spawn(
|
||||
async move { append_rows(&location, wrapper, writer * 1000, ROWS_EACH).await },
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for (writer, handle) in writes.into_iter().enumerate() {
|
||||
handle
|
||||
.await
|
||||
.expect("writer panicked")
|
||||
.unwrap_or_else(|err| panic!("writer {writer} failed to commit: {err:#}"));
|
||||
}
|
||||
|
||||
let table = weed_lance_worker::dataset::open(&client, &id, &fallback())
|
||||
let table = weed_lance_worker::dataset::open(&client, &id, &storage().await)
|
||||
.await
|
||||
.expect("reopen the table");
|
||||
let rows = table.dataset.count_rows(None).await.expect("count rows");
|
||||
@@ -484,7 +487,7 @@ async fn concurrent_writers_keep_every_commit() {
|
||||
/// Appends one batch to an existing dataset, the way an independent writer would.
|
||||
async fn append_rows(
|
||||
location: &str,
|
||||
options: &HashMap<String, String>,
|
||||
wrapper: Option<std::sync::Arc<dyn lance::io::WrappingObjectStore>>,
|
||||
first_id: i64,
|
||||
rows: i64,
|
||||
) -> Result<()> {
|
||||
@@ -493,7 +496,6 @@ async fn append_rows(
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use lance::dataset::{Dataset, WriteMode, WriteParams};
|
||||
use lance::io::{ObjectStoreParams, StorageOptionsAccessor};
|
||||
use std::sync::Arc;
|
||||
|
||||
const DIM: i32 = 16;
|
||||
@@ -522,12 +524,7 @@ async fn append_rows(
|
||||
)?;
|
||||
let params = WriteParams {
|
||||
mode: WriteMode::Append,
|
||||
store_params: Some(ObjectStoreParams {
|
||||
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
|
||||
options.clone(),
|
||||
))),
|
||||
..Default::default()
|
||||
}),
|
||||
store_params: Some(weed_lance_worker::dataset::store_params(wrapper)),
|
||||
..Default::default()
|
||||
};
|
||||
Dataset::write(
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"chunks": [
|
||||
{
|
||||
"offset": 0,
|
||||
"ciphertext": "2a0ec302f289637828dab37afdfbad45e49589cf8aacbb52c77565813987ebe842cc61d48e26f986ab033bbb051e3ce3cf21a98c8b45780ab2dedb84875eb71d788c6631f5336245ffd3e6da192795968546189447d9ab9a5bdeaf8dabdf7bdb32a2ab6432722ed9b9be3e95343a7f37dfc83a7f958a10a3302c97e9882271e7dd4796dd3c28a0696690e324c5e6010d28cc7d01f9bad6627e0622e37cdd267f92faafc9f78866e0a33b37fdc7b67ff7de4db58247c933854f1eea1dff683594499773bceb425dbe892a6273901c6fe3d5bc98e6e54e8dbe8397dcfef280cfee55c5bf340c81ccf4d4fd47cd40c2cfefb6b9e47d30909a247b3d56d5150c290b5bec299a45371a77b569a4faf1a5971f2e49fcb82e9dbb28fc9d35d95cbcb865c88ca03bec82d943d517751bb3ef583a98c21acd66b59aa0e924a1fa319cc27456fb804cc1fd592c2b8e815be5ceebcfccdf3e3baa4fe730be985bcef0bada6fa654c56477be177a1b486b36bd90a81c6d88106278559ed7d8777163e8e9b179354826ac07a430e2f1f865c01c9c2610d20ebf5bad986fa5d7fc29fef56b2b4ec2de81cf72e8399ad234c88e2a62bda73b0bc3c94181942f03a2b6a433b5554252b510dd3f81ac69868d163433fa7326e5da4e2b1342a18f0948cad8b361b6fefbc8ac426261b3e9d043eeaed46b4ea41ad62282797d5e505cf3f7351470ceb8bf52568f49910570c7b16f32a37b52efa0f97326b9ad2f30a02c84f567514cb004d4782d31eb387a1c3c1d7f3ff184ad6e87f15ed8d93e7693a78b806b818673c229fc9a8d9ab2967903ceea324646bbd0c99412e3217c2f56a116f2d1b6031674bd3d33d197ad702a4812d4f4c4a17fafc7cdce1d4f7b491d0064999ef49f952a8d998baf77a65210ecec2381d8e13695318ca59b4602598fe0f58a2ee1bbd945dcbc0d571bc478d8401fffc1bd47218ffab2a966b247bdb93100ddd4612b18b82267eb3a8af6f8eeb668cbab3f31086dfc93815ade90d458234e88263535927d6c1400443a81cf72f31beddc0625d959de17f9cd8e9e719f430357e71684f59bbb2454b02533e7d15b8d28ccf54f55398c5dd193d12a14adff66cd9f46b2c3a80519cbc5d89c2abec0e80df70d2df4d9934287ec0640d1889c6f4f9f5b639f669753dbce78b72360440bb7821d9bfaef38bfc68dde2eb14f95637d2343537262bd3a677a2cde0031b286f76669e6d6fb62fca09eecc587d29292f0e09cc45e09b0f29672bf96d29b5620e1df94524c92c9b0b69eb16a8991117d00e977e92ff6c2dfae550e9049a88cb1d730318d8ee9b174c79b16bed6e5e1e2a8d21d179a84f2927fdd0e1feb35bbc796b15577e3586bea6276c42f0d34df34e667ef18c1f50bf5bc1a6db86f85b83b67d9162e0d64be141a36c19d9a13da8930f6faac38a000cf3623fa44ae2fb3ddad6345dabd9fad64248343580b92746794e8b30f91a5acba6f641155d7be863c6db494664895c23eb17988b1f6922181d9aa4ac2d06f07250c0e2e3cd1bd660b2dc3827def39f6113fcf6397f806f4d199f51e5f065d577ec20c009c52866b1b98dd2a4d68ad794978e24728986d1205f21c6ee2e32671646fbb49be468ee8b9bb9ca3e0defb483d54c114cc44f4e41240c8c68c357915c878e902e829329efbaf233f787c1b0cc65f9515b2e9565c892e1414d6e8d7bdb39af1f8e16f571f08936df36278a2afcbb44f852c2e1b6979e7c35abc486a610bbe97d5097a032b75a7996ad2b1e0e4dc102ad3f3be6254e9c0c3c9b5f706be25d742c710370568cbe5e54c346f5d65d49142e87d838f0f86a966d47ceb9bdfe0d893704bf70a6d95f5b221bd622d6145ae1875da4c0d53b7b43bd7b2d5804c243d5ac98b901bd949a1d91d2039e1f8865da69a54e349815fe92013104d8d3608c2cf378c9df81543760f646feba0b2e2e2bfbd869f9e19bc75b733efa15eb67b1cd53c2008bf3d1b6fc084497cba21a3f9741904353bbcab2bf8e1e4e86e1054c87bb0f7dca4b4bc52bf0120be8ec638d734712bab7776283c3a5c8fe621092a5ac4fac0d7a1bb754f7e02e9483bcbdc831335ebc96c36fef8f81333bc9986cf6bbe1c598c8c3e53b0f44968999f8eada87e646265dfcec8d31ae82ab611f390e1f7b1b72afb5576e8e682798714ab9172a0b96f0d739c7f21d25742040bfc129002d230fdc2d9f58c8ec9f8bfcadde8dd3d7259a5f263d94b79040ef9fca48c71991e4f4fbfd8c27be71707f632206e2f57eed446963fce6fbd1ee5591eec393512e46ec1a8a27b2aa3d5324f222d03db18df716b4166ef31f2a1d225a6a99d726919d3ac861ec3314a45988abcb21ac876ea1abb8848dafbaccbc1201f318c5911505c24d9edbae57bf58bb3c83a2ffee30cd35e8847e59c93f75b1e2247f4c12115bca558bd9b04f4c273b1001a301703cf749ed859de903c8c1c02f9e83f75c070287cff6112622f8a8847da1351e53f37728edfb0d85c0625aa8ea9265c97b02b89d1c3b74032e16bad92d3aaa3a37648f68bf1aaff61ec6841fc02d72af86aa7a10a280be213096f3fa73a958896a4c99be4e7c8e60b8c6e592bff01348c179643d29122eb773497c1e775837d2cfc7e1e34937e136f029a2a3ee852bcf37baae626e180e74b700c859b56b54251b48ffff05658488d90491815a16f8c5e8ca561a9344de7b9499771a528b1664663e5f29bf0cd6b909da922bc286b3b26ba621b5fa67ec387f974fb4bb9b9a28d450370dd1ebf419bd6c02b0a790e6b3fc44050c16d3e4007c81061079695095973870c1533f910e075bcd7d9776d0199aac5ceac2bdb6bc48e6a6dc24ecc7fa3480ec87880f628980786319e",
|
||||
"sse_metadata": "{\"algorithm\":\"AES256\",\"encryptedDEK\":\"jJuAjPFVQNo8MbyNEIISVlLhpnxIBKwmr+zUxVk+LRmlBVb+xM0sabyuoISSsjZD\",\"iv\":\"MDEyMzQ1Njc4OWFiY2RlZg==\",\"keyCommitment\":\"oUtzqchnKPjfujBwQUO1cdzeqvgxoM9i8u7AphUIEyY=\",\"keyId\":\"sse-s3-key-1674606777407842260\",\"nonce\":\"qYpP//qAGOxs1hNq\"}"
|
||||
},
|
||||
{
|
||||
"offset": 2048,
|
||||
"ciphertext": "f91999d6f6443d817d68210d4ad178ed83d7ad0ef1d48544fac78ca8eb39beef1864cddab3ae099a6d5f908bb454370d78254c832684667e1f080e122b1b18dae91534428d5721c2fb58986b065375077edbba0977aa07083520c807b2402653e189be2b9c8916685040b4e66949675bbb026f50971522723a265077eea1c54772b189b5b271a7f2dd79cb392dbf70148cf944380a4bbe19fbd88919a92eef3377eed498f3bcf5d7f21037ac2ebcb0a3d91886bc1870d195727e344594439fb3f83982e1466efab1073db45b92120a49e70bc0e7a828a21d788fb2e6050102e90cf29e49dd4b1e78edf22e31c6dc33909e2d9d0a3582385760d417fdeaca8e0d31a51a9e1dc1c4300478210e5f5862da7f47263d8b018bf74f45f6fe326df42f78a1f468da714ddadd197266f4bdc3c3b69e6e060392a58eadbacf6bf93820aa13fadcc7c3122ba9370f536d6814e00bbc0a398f5ded3573b9fa0ed799c84b2c18d1dc098b524883a1d109deffe9a1b30e6d0717b10847db8859a647c89952fac8dda24acd57d1197ceb05c897213803b28b8f89158a9fc6dee50761319c19ad41bcd334ad3cbe2323c3ffc3626afadcc9a60dbd1e6749758ecf87745deaee02469843bbd7a7566d9f7e23f4c6519d1daff250efe83044492a55736e37551c805b8a83c0e7f337b670e3d84d8af22ab859cadeccc4d55cf6a9eed13aa3ac1bca813afbcacdbecdfe9553d14596df69f3da3134e43e9c090f8f7e204c6ee8bf3b1ad669513d548feb6c44bc2621346cedd01523b840e823c682579e2d0562a23f3de0641d7e0ea1a768484fb0a6ba8d850f9c4cf50ab92192bc74e21c70fe8049fd15a60169f47b6558f9e2de3aa26e18ee4d5922aa93159b2e4b2971f7a016cf1c680dbfee5bef0c8883bb78093272a86c117961b8472665568601320b5ebd02269d34eeb9b2f6854703dcba6ee791131d9ce674fef8b973afc0fcc6f25e37892a94353ef6940a71c1317aa10deb533f098e2527006c77522330e56fef913da5ae65c2b7d8c7f3be1307e0d5502edee9bacb42b58283555bc039bdf84a0f52ddba4ca742863786ec70e0973f03eece191e3eaa8c09a26b249c42087665380a1bf2cc2834193d407b26ad70d0ae2e9a43f0b3dea7b6326f70fca9070b3f3aa4be1b6433eb32437bd63b357e1f4148ad79ac47418cf3505343b1369d8e742db1f64701f1a75df58189b9667fdcacb1d261fe055be57b521f7798f570ccdb70938046956058cbb720f8a00a2a73fd61481ba9da6f7df7ddb9d33e2c58b679630163dddfd92729c95e60766966f1ef0a07c7b809c0c0a34ac8bcdfab513885dfe74db74d508d8fd391f6e986dae82af6d794ddc33ede0bb5c99271c8673cf6616691fbd9df298c93e79d210a1a4c2adf7e9c731c959efaab691dc89b704e175f2cfda88c0c2f38ff6352ee380f6a7713760c998eb2a66ccd81d142ae4509340879f4be282a643f9da2098cc95ee6ac661fd066f1a1b502834f5825db5744eeddb0f439659086ee7345e6d71215c16feec198907e48a19b42760b47dc7a1b7dae77724b2f7ca8e93008cddea794669e0b5d7b7e959af321e2f04916c3b12107c596a0856fb62a96ffb9b95c8c7697f79af3be336dfddf0fe90407bbfb35d850698cd180df2d09e5acf1d9f687c996e875d7a3f10aa29d89cbcbc03b7c95951b93ba959a175d1ce9b2edada2b715e503efc0da29e9154fe98c91ecf241f8bd6d5f3f2e4300d70cbf516a52d15d287a3721dd16d57ca29a92b2e09c937a22204ffb3f0ebc66584bfd70b4194b63997a4a90d8ba62c616dc19c794b625cb6ee5b1f890bc92d756c00c9caa105337e832991888b4cb0ee1f445dadae212c7ecf0e43c80aa3da6abdbf9ce101deb510dca8cb691f5c6f94648b9ed19d8feaf9fe26641dfc8be145d2ac0a84bfa5b3a4806b829d4c8fd88796093199cb08e2cec722faad44aef87819d69e999a6e0ff4f8e78dd7cdaeb03641cd5eebb210b2eef12d043db40b50246ad7a441574024acd3ff711acdfd8f85abf2f313c716dbb40c154da6958452fef6540a7c64e71647ce146e8120cfc98bd74a4162006d585ef289c2f4750920d9fe0cea926983553a3956d2c451da99d23f15c355a71f066f88f346e5ef6b83d029b61765ad3290a7b504fe1b8513164410b1ff8b073d4487393c0c7b3c1cbf3369fb718f41685c54f0ec483e5aa1e73ab92d948e543329c59e89ff4f4b255b9688cd597c53beb280fe0c0529e4b147401cc3a6da4d8728927fc71aeedc2aaa107d99ada4f489188d85bcb288e669f52c83fbfdd673627253278d69925b88b54343a4c4fa93aeb4b58cf76597d598df2373c2b96ccfde9c905dd03bc48130da42e877b9b6af8cd1d528a29a91576d3d2c20d1ae65c4f2f7492aea7895ef9908e9909d598f650d4bd3d4bf1dfdfe902806abb9f6661648bace8f119102b66366d261610de4463b2a324f8c7007d192c5fd829bd58fd268344ef05ec6c29db85aee26992e10f05a96c93b243373508e4cd9650182b24b615f803713a183d51191f708e9179b7ca7db8220917594f5547083f208f8f854623ca36963c48fee7c7f1776525871afb62a7488d4582538d028c18eec8bc0e7b01679131a05ad267802a102b9b9b99d96b5b8f53fa0f8cb19d43814a132d574c4907df0fe7076f91bf61dda818a746ac4425e0aecea670797faf821a70c040c9044d766144c021b0b9a8942041e12d6876e6aa4568566f3eaea607a06b5d770073b12a09a90bf6f9cffbbe74dbe2a0b60fb62a76ed1cc7e1a48f0b6a1b4e8879be59eeda03b46947afb3e30b84075b429752a5a4207169f500acb7b48a4125d5a21de431d00a338578198be20b08a59c3d6d3d723d9d266eb5dba5ebf94f450fb7a3869c58029cdd6218d4fd0807f9770eea155b88931b85c5b021fed8e6dd250e740cc4fa06d58d1adaaff1301bd5b390c6a59f0c0eb5cd65247e7c145ebb5e65fe8f7d49677d12d37ddc1199f21f68508db95983ee37d4f46cf2d28f575952038fb2e156134e6a935b7e7652594e97692cdc200164da6e2f339a6a5a06997bd25bdabc60d76f0fd32d09357559119c857522af1011598ad9ab63f8c0ceea527a59be0f0951b3b8a69f37a06078f6df825f94e6ad07b92856b33483eca5e4e356e574c728aa219cbc790cc34eb367e2883e09467fb50a8a590861a14add11416e5c27a51e00e3a2dab7b50d3b60f3b83d9e161932b94311c0d600a8689a8d9728855e569fc737b8eee40b427fd55011e099a63d7770460e9e9c413c1310590cc6f9a23e66c592f9c5fa72aaa74477ffb95cb2374917db0414c0cea2833343402696deeb08555f8e78c917ad53c67d4fa5dccd7dd927cdecf598ff0c096b77b4a61d607e9d3eaf48e06a5935d6d7946d716c60d07d2a4024548322da1a5250e788bb1240bc2bc67e594c893ccb594d1efdcb123de0290edd9f56c013e9201ceaef5faLine truncated
|
||||
"sse_metadata": "{\"algorithm\":\"AES256\",\"encryptedDEK\":\"IROFhJs/+elQcq7q+pfDM3GIDd5s0G/jMLHJLwV+nToI0ecet+tmfiFEqETSFZQ8\",\"iv\":\"MDEyMzQ1Njc4OWFiY2Rl5g==\",\"keyCommitment\":\"6POJ4Oy2Pd/hcoQUEtIsd3JCxPZrZPwUsvLzWkXX79A=\",\"keyId\":\"sse-s3-key-1674606777407842260\",\"nonce\":\"tjKML4uA8mje1JIU\"}"
|
||||
}
|
||||
],
|
||||
"cipher_gzip": "43ac83534bef5b644a22350fb1c6e04fc5965493d40cd0f1d8e8bbefee2ff90260eaf5ca9d8e764df62f6d79539a49393c5a91edce5ee6b21cc96e1bbd9fe518e4e6e4fa47a924216eb6bc5e3422db8d39f78c7bfc784626f36673af5d0d76e25759e0d20d85ad3f96648ba7d20442bc415bbd66f2c18ce2ae8a2da134e23fa6054616cc346391dac2dc454b97f69b596218dc4d09caa13ab439afcdb68de1cd9379ad755e16c8b68cf5125c535b4bebfa07dce945fd94345e932a0cab360f0b7dd8f53807abad456b134f55a0754709f7266f85aeb5cb23e50b0b31367f8056a0d9887a97e0797a4dace2fb8d1f96c82018908aa8fa06480c031cc994ba97e57483ee274f6ecde8dc72fb44794dd7be50d68c920b01e81e72f349b154d27940c25e0a1c6df10d9d3d2ae767c4c6b385d9f8eb5aa8402cb7490723d4fc57e94ae6191b422ed6e1954160d6db465e5b17afabdbb27b120d7102ae7edc48b83b536aba096d93fd1876ce88189fc8780068418e7cb43d9cbf5b9070db98445fe33672892977fd089dc1634ef81b98e27da1228231eadc893583dc7d7f1d09af09f1833b0802fbfc704557035738d9e19a6429557e3e2bfc245e5b1e3565e6cbf6bea890f59977c03bf348dcac05da24341dd786c9d87dea0a6fdfd136f724469f294f3a2a2f3897cd54b54e8e63390288450dc42a71ca562dcd4edba55c22493a02df6bade2ba8c2fc696ede9bef14578a07110e85921d8f00d8252f57d82046d1ccb8d12e4115d7a1fd192812e705849e1cdba540ff0305b9ef1e59d870473270689fd6458b1cde41f9ce178529c5c0d3a0f3d67580ab741630abc9c4e33765c9872c261b4a7585e0f9f45b25792d172606e7299951bac1ecc73cb614a9bc0b6b50da66e89af3bed32550a8fb348186086e6805751a5a88ceb6a116300ca7720a0b70516aeadba40c25f54304739cf7a03598c3b0c2d3e190538cf00e7c8594a1f0a3872657dcc1ea7c086fd1e060da4d6d78272b9b9d613fca64a2071d8f755eb1e4d18741884ee13a6fca503495e62510d7f9f36ed14340011fcd7a626db9c96f106986c67a10e9672b5b91b5c86e0f5106dfb1b27d2e4322c6efc187ff141e1ee4dbbb2a46653169a88b7b360ad74ecb3f8a0ef07ba7cbe28c339c62fd1f18fb5568eef",
|
||||
"cipher_key": "b34344a5441ecd890cfba0b88d6b80e5ce441e4c08ce3026400db5af4301c0dd",
|
||||
"cipher_plain": "a362d682485d2683a939bae63362f9e5cf7a0066c40e38369622af5975c09ee572b7b35b6a1a65ba756d7847c69d222e5310c5002a0a70debc33c6668e05a89a87c1286c0af1f45334073672f93222e0a087f30547307dc26973031bad8a85118533cec5a9ce2e128f202ab89262de6de33896aff8afc68f34cb15420b24226a53e1d29431200319b761d0f3bbf4aa5370812184ea65cddd2d16509586ddb76a4fc043c9ddf56e57f50d1b053b6ede45d1caa6b9a739d761599befcfc40bc6074b01aade404ca37e1fdbd6e2b07fb015d3332e901ce9a0f3b4d3ddd95824cf1434be3b35b7ca57131b8e36d6a2afd7bbe623159f49d627ede46b6bc166544f42349e7c07fa5659113b1ede695655fd5dfb8c9e8ecbe5a812c2e8524e67eebc678382a063294947d5e40961ebbfb966594b3a3f5af5af62978bbc5359b5eb99d7db55a785e2440934bbe9b80396fe8f5868172fbe4f4143cfcf11039d11e331d11ac7dc0d3c4f93f4852113dd9917d4ca1b70c7c6b0ede65d754a1ce12fa763aa4c8672e627f30fb1d888509ddcf44cbdc38344fffdd514589cdaaf550d79492fa7d3b55d204ec7807794b271c97c04ac2136b1a095f025f8080321533f5c96cbf27e1b2a1d3016b05615840839b409e0d55cd89e2f08714838a98023c0e3935154225e5e234969de1365af6469a40399a11332ca885e228eab3620c71241526d5b3fcb1a8cce2e081f26b5a1abd698145edd0eec69faacee2ddfa941d739cc4fdce5b6c39e163c031c220a0bb906576b0ff6d86b12736a6d7c86c89e5dd028f9c05e4e64fed3737f082a82707c1275d4e01c0da9baf63281a28fb2032e1ea24f4c89e091ac99bba56efde9cedfd6b56c8db5777220e86892828a15e6aafa03cad9139c34eccd5a4f61e6bc8fed368f7699bb65d2fe0c4a15e13ba6f3f1339b218b13759b36974c8c3bea6b69e8d5d76129995366471773db96c241294bc4e7392e06c05d1441aa8758a52fafe9d779b130627485a8716985a6979e15060cba84adf51cbc3bee8f3356f40481b413b0140187a48829d7c6df6cac11c75f6cb6e6df456b44bf28ea192613486d546cf812ded6a03f66297a94d6183b455feddee795d982a493bef8fdd12ba8a7cafb23e6e00248b84c343e9c9039e137134f31944aa0a3a7783526d020aac747acfc53314f2bc1e35b728f3d1692f7b421e61160a3044d309123143cc6694d2e7007d9172b2a578bc31808975c26fdce368517cb3fd34c1be9c8b832a74eec495823752fcf9de97ffded1fe4f280abb2da658a0d6ed59b3980b1644e47b7af8d14a8a1cd65dc7900f18d358f42141d5444964062f8a1519308efe47255a6968bea410a75c5d92b93b8a9247a6714c33aa27c253601079433dc22e78f4f252f3cc99f4fec9859e84a06d2a7b2d88ee2bfdfcf5d19706ddec9db1171d25e4632da84d4a1f084609f3309a0acb9751d1bbf85fcbf3f576765b9d54ed37246526596b2c692afb7518beef48a79a2a5bf976d1488a2d5834459035b6000c43b518ee802b39af9dd8c2ad499437b547e834950145a40aab50cbe15ec32a59b0ebb8d7442a4a1cc4cd2c2e5f813db3b1b12b67d219d65c72ed395d1a67577280ab72d99c28a20180351bc87db6e18f16359731ac733becdbd0ad8d9759a2f2d8e19f49d0c175c7b6598d7dd47badded855f2c1226de86ac473af25d1b7a36d1f100b522d6ae057d3067ab195fd7f6ceade0393ebc7283182d18711bf41a5065987bdc50696ed9e0d2d89f48f326b53c905e85c0922aff03b8e61cf0ee5d7d62af376ac98ec7322e8f96982fd32a471436ba930cb14c4e02b178121c4d9ea694f4b81d4adb62f44f7e5fd4599c04a6ff4723486fe1c5ad0bd9e000b19d566730af0cfdca7b6826899c18fa2b5c64271bf74e4cc653d23eca86d55b8caacf33fd09a6e0cf9f8ad1ac3956f477b9fd2eff4f63790bd4ed557912ccf78d19748eb2f6dd1dc4b1c828e61a87cf1f9b0ce94030d82e676678b271d8cc44da9783b19a2478f9bd813869d18f44398ef1585b924e69ab6687b953c83d6e03ecb74893ce75e42f0f5c903cdac22b74eb5d01d767710798aaf3120e5973891d1e6734a69a141fd2299739dcd8e3059c6da38fb8fe7eb367bba849d648c24f7aecc7e9e9fdb17eda1bb495d409c6f1cc6323fbbefd4364ddd4bf6a11547d3826a1ab46e10de481ecc9a08b6a28d096527ddb411530ff4148cbe52bff77c29afa5719321d1d3a23463e746748741e24522d0f5d33c5028902318ac7207df6151fa8fa58631e7a99e4a8e21f5fbe9ad48e248ce5ce76c7007a0afa8a6753f0d7c9500f91c58dcf4aa2601571e7400e83e4a4a6767cf5f56caf429e0af846429b7a16df723b57baf09c330893b432de98f86da6b20e73a4123302c99cee383d2bbeb9563613b736c4e420601fc8e839b80d8cde664ffcc460228c1e1e5a838c730882616666f49b414a783dc2c5ae45f98e77ddacf45b3d640f3208204e913cecb0eb9337c0b8577b732ccc8458f0fc34045c5de25495b8253761256eb81b857994249c3bca61b9aa5f8298837a92d64dab6efcb59af9dea295358daadc6a8930e87cf88fb64a70fccc6b7c1ebfdfc19f7a52c00a88916f95fc19d8e5cbe5d6e8d16ad4781cafb69db63251630ce1880d93365d8849f999c3b0aa4474d6678dbf7fddfa906c376355ccc6f5f2109d02a2d5c95b9b9ad4a8ea91267357d72be08a5a7b0cb136d3fddba7eeb2f86d5712613bb8ab91459a9c6c44762821cadbb2a200b83eac6a0bdf65cdf30d75d07b47c14b96bda6152289e4505fc0d1b8b0e3aa2220466cd3153c1e79e426aa9289ef0a7d12820bdf18e3f258a97bb37c0630295ca317931433c3577e4ce84b906bfa368aca52d6452bfd9ecfe4f015aa9e8e301661a738b7b1913aaccb356f5d161fa31a695a49821b2f9dbb0d10acac5299fddfd4ddec40f69af60a29b333462e19298c2f7ac12d3f137184e228e68d0845a33bcf53537e6a1a5b296533ebff6b237ad54e676659fdbde00a1c34a4e7fb7196163b99c03404dc171109da0988662ac0d834d01f2d505392b185bd21fd4b13f87066fad216ffd30b595b3b23308f58f27b288d320ffbb420eec02776ec9e08bb895a6223456c1aca9c6113f50d8eb8ca686401f1c88ede5d8018a1d4260c918ecbb4c7ef0b8ae8fade079fc5be58e400a8549e4f875cfb8a3a6b5c4366df5c46a57b30c2cbbd859a8bc090cde741b54d7997118c7da5e180c1b49d8fd16c3b8795f3ffec8526f4202aa58f84028bb5c9d4876ad7fdbe2cb5ac7e10a1e00b33c9fc4ed54de8eab0974eceb18a1636ddc8f1b811e4c755af94af3237073362eecb97bc6c1ad2489f00caba0ee9aafd8431dce4c9e6fcfe1819d78b4b0da5f0f25df405f96bdee1dac86c955af4619fc41c6239449342e362c9210164a3f264f7c7ef8aaf93e6cd7a8e5ca6500c22cfa96a0a7a94f553f96e758Line truncated
|
||||
"commitment_sample": "a14b73a9c86728f8dfba30704143b571dcdeaaf831a0cf62f2eec0a615081326",
|
||||
"kek_hex": "814e33b95dd38da733a0f98aa4045e350107136d568257228ac27e5689c70308",
|
||||
"kek_passphrase": "pass-phrase",
|
||||
"kek_secret": "s3vectors-test",
|
||||
"kek_wrapped_v1": "yH4CEgYyWUYSGNgAnXAQPm7LC4TkmBcTqQGOOoF3B7aKEVyL41Xoya7fsVXGne2cBoYSPRwlVP6x6KZw",
|
||||
"kek_wrapped_v2": "U1d2MgrNBSvQd7lXUkHwq8CoZw6dBJOH3AAh1HXexumBnCzU3IhF3goZCKjxSmgpeWU10psw5J5tTolPNZoRKdLsJ08wSPMygpGFzH5FFAGmc7cYada6g4TGnvsKWF7y",
|
||||
"object_metadata": "{\"algorithm\":\"AES256\",\"encryptedDEK\":\"/BQZt87OjM4PBQ1xMgp1BLGzLeF/azzYEIJElIsA5E9Tr5Jb/Y/cwLz/tSfHiJhj\",\"iv\":\"MDEyMzQ1Njc4OWFiY2RlZg==\",\"keyCommitment\":\"oUtzqchnKPjfujBwQUO1cdzeqvgxoM9i8u7AphUIEyY=\",\"keyId\":\"sse-s3-key-1674606777407842260\",\"nonce\":\"2KY1nIo6MR6c1dwy\"}",
|
||||
"plaintext": "00070e151c232a31383f464d545c636a71787f868d949ba2a9b0b8bfc6cdd4dbe2e9f0f7fe050c141b222930373e454c535a616870777e858c939aa1a8afb6bdc4ccd3dae1e8eff6fd040b121920282f363d444b525960676e757c848b9299a0a7aeb5bcc3cad1d8e0e7eef5fc030a11181f262d343c434a51585f666d747b828990989fa6adb4bbc2c9d0d7dee5ecf4fb020910171e252c333a414850575e656c737a81888f969da4acb3bac1c8cfd6dde4ebf2f900080f161d242b323940474e555c646b727980878e959ca3aab1b8c0c7ced5dce3eaf1f8ff060d141c232a31383f464d545b626970787f868d949ba2a9b0b7bec5ccd4dbe2e9f0f7fe050c131a212830373e454c535a61686f767d848c939aa1a8afb6bdc4cbd2d9e0e8eff6fd040b121920272e353c444b525960676e757c838a9198a0a7aeb5bcc3cad1d8dfe6edf4fc030a11181f262d343b424950585f666d747b828990979ea5acb4bbc2c9d0d7dee5ecf3fa010810171e252c333a41484f565d646c737a81888f969da4abb2b9c0c8cfd6dde4ebf2f900070e151c242b323940474e555c636a717880878e959ca3aab1b8bfc6cdd4dce3eaf1f8ff060d141b222930383f464d545b626970777e858c949ba2a9b0b7bec5ccd3dae1e8f0f7fe050c131a21282f363d444c535a61686f767d848b9299a0a8afb6bdc4cbd2d9e0e7eef5fc040b121920272e353c434a515860676e757c838a91989fa6adb4bcc3cad1d8dfe6edf4fb020910181f262d343b424950575e656c747b828990979ea5acb3bac1c8d0d7dee5ecf3fa01080f161d242c333a41484f565d646b727980888f969da4abb2b9c0c7ced5dce4ebf2f900070e151c232a313840474e555c636a71787f868d949ca3aab1b8bfc6cdd4dbe2e9f0f8ff060d141b222930373e454c545b626970777e858c939aa1a8b0b7bec5ccd3dae1e8eff6fd040c131a21282f363d444b525960686f767d848b9299a0a7aeb5bcc4cbd2d9e0e7eef5fc030a111820272e353c434a51585f666d747c838a91989fa6adb4bbc2c9d0d8dfe6edf4fb020910171e252c343b424950575e656c737a818890979ea5acb3bac1c8cfd6dde4ecf3fa01080f161d242b323940484f565d646b727980878e959ca4abb2b9c0c7ced5dce3eaf1f800070e151c232a31383f464d545c636a71787f868d949ba2a9b0b8bfc6cdd4dbe2e9f0f7fe050c141b222930373e454c535a616870777e858c939aa1a8afb6bdc4ccd3dae1e8eff6fd040b121920282f363d444b525960676e757c848b9299a0a7aeb5bcc3cad1d8e0e7eef5fc030a11181f262d343c434a51585f666d747b828990989fa6adb4bbc2c9d0d7dee5ecf4fb020910171e252c333a414850575e656c737a81888f969da4acb3bac1c8cfd6dde4ebf2f900080f161d242b323940474e555c646b727980878e959ca3aab1b8c0c7ced5dce3eaf1f8ff060d141c232a31383f464d545b626970787f868d949ba2a9b0b7bec5ccd4dbe2e9f0f7fe050c131a212830373e454c535a61686f767d848c939aa1a8afb6bdc4cbd2d9e0e8eff6fd040b121920272e353c444b525960676e757c838a9198a0a7aeb5bcc3cad1d8dfe6edf4fc030a11181f262d343b424950585f666d747b828990979ea5acb4bbc2c9d0d7dee5ecf3fa010810171e252c333a41484f565d646c737a81888f969da4abb2b9c0c8cfd6dde4ebf2f900070e151c242b323940474e555c636a717880878e959ca3aab1b8bfc6cdd4dce3eaf1f8ff060d141b222930383f464d545b626970777e858c949ba2a9b0b7bec5ccd3dae1e8f0f7fe050c131a21282f363d444c535a61686f767d848b9299a0a8afb6bdc4cbd2d9e0e7eef5fc040b121920272e353c434a515860676e757c838a91989fa6adb4bcc3cad1d8dfe6edf4fb020910181f262d343b424950575e656c747b828990979ea5acb3bac1c8d0d7dee5ecf3fa01080f161d242c333a41484f565d646b727980888f969da4abb2b9c0c7ced5dce4ebf2f900070e151c232a313840474e555c636a71787f868d949ca3aab1b8bfc6cdd4dbe2e9f0f8ff060d141b222930373e454c545b626970777e858c939aa1a8b0b7bec5ccd3dae1e8eff6fd040c131a21282f363d444b525960686f767d848b9299a0a7aeb5bcc4cbd2d9e0e7eef5fc030a111820272e353c434a51585f666d747c838a91989fa6adb4bbc2c9d0d8dfe6edf4fb020910171e252c343b424950575e656c737a818890979ea5acb3bac1c8cfd6dde4ecf3fa01080f161d242b323940484f565d646b727980878e959ca4abb2b9c0c7ced5dce3eaf1f800070e151c232a31383f464d545c636a71787f868d949ba2a9b0b8bfc6cdd4dbe2e9f0f7fe050c141b222930373e454c535a616870777e858c939aa1a8afb6bdc4ccd3dae1e8eff6fd040b121920282f363d444b525960676e757c848b9299a0a7aeb5bcc3cad1d8e0e7eef5fc030a11181f262d343c434a51585f666d747b828990989fa6adb4bbc2c9d0d7dee5ecf4fb020910171e252c333a414850575e656c737a81888f969da4acb3bac1c8cfd6dde4ebf2f900080f161d242b323940474e555c646b727980878e959ca3aab1b8c0c7ced5dce3eaf1f8ff060d141c232a31383f464d545b626970787f868d949ba2a9b0b7bec5ccd4dbe2e9f0f7fe050c131a212830373e454c535a61686f767d848c939aa1a8afb6bdc4cbd2d9e0e8eff6fd040b121920272e353c444b525960676e757c838a9198a0a7aeb5bcc3cad1d8dfe6edf4fc030a11181f262d343b424950585f666d747b828990979ea5acb4bbc2c9d0d7dee5ecf3fa010810171e252c333a41484f565d646c737a81888f969da4abb2b9c0c8cfd6dde4ebf2f900070e151c242b323940474e555c636a717880878e959ca3aab1b8bfc6cdd4dce3eaf1f8ff060d141b222930383f464d545b626970777e858c949ba2a9b0b7bec5ccd3dae1e8f0f7fe050c131a21282f363d444c535a61686f767d848b9299a0a8afb6bdc4cbd2d9e0e7eef5fc040b121920272e353c434a515860676e757c838a91989fa6adb4bcc3cad1d8dfe6edf4fb020910181f262d343b424950575e656c747b828990979ea5acb3bac1c8d0d7dee5ecf3fa01080f161d242c333a41484f565d646b727980888f969da4abb2b9c0c7ced5dce4ebf2f900070e151c232a313840474e555c636a71787f868d949ca3aab1b8bfc6cdd4dbe2e9f0f8ff060d141b222930373e454c545b626970777e858c939aa1a8b0b7bec5ccd3dae1e8eff6fd040c131a21282f363d444b525960686f767d848b9299a0a7aeb5bcc4cbd2d9e0e7eef5fc030a111820272e353c434a51585f666d747c838a91989fa6adb4bbc2c9d0d8dfe6edf4fb020910171e252c343b424950575e656c737a818890979ea5acb3bac1c8cfd6dde4ecf3fa01080f161d242b323940484f565d646b727980878e959ca4abb2b9c0c7ced5dcLine truncated
|
||||
"whole_ciphertext": "2a0ec302f289637828dab37afdfbad45e49589cf8aacbb52c77565813987ebe842cc61d48e26f986ab033bbb051e3ce3cf21a98c8b45780ab2dedb84875eb71d788c6631f5336245ffd3e6da192795968546189447d9ab9a5bdeaf8dabdf7bdb32a2ab6432722ed9b9be3e95343a7f37dfc83a7f958a10a3302c97e9882271e7dd4796dd3c28a0696690e324c5e6010d28cc7d01f9bad6627e0622e37cdd267f92faafc9f78866e0a33b37fdc7b67ff7de4db58247c933854f1eea1dff683594499773bceb425dbe892a6273901c6fe3d5bc98e6e54e8dbe8397dcfef280cfee55c5bf340c81ccf4d4fd47cd40c2cfefb6b9e47d30909a247b3d56d5150c290b5bec299a45371a77b569a4faf1a5971f2e49fcb82e9dbb28fc9d35d95cbcb865c88ca03bec82d943d517751bb3ef583a98c21acd66b59aa0e924a1fa319cc27456fb804cc1fd592c2b8e815be5ceebcfccdf3e3baa4fe730be985bcef0bada6fa654c56477be177a1b486b36bd90a81c6d88106278559ed7d8777163e8e9b179354826ac07a430e2f1f865c01c9c2610d20ebf5bad986fa5d7fc29fef56b2b4ec2de81cf72e8399ad234c88e2a62bda73b0bc3c94181942f03a2b6a433b5554252b510dd3f81ac69868d163433fa7326e5da4e2b1342a18f0948cad8b361b6fefbc8ac426261b3e9d043eeaed46b4ea41ad62282797d5e505cf3f7351470ceb8bf52568f49910570c7b16f32a37b52efa0f97326b9ad2f30a02c84f567514cb004d4782d31eb387a1c3c1d7f3ff184ad6e87f15ed8d93e7693a78b806b818673c229fc9a8d9ab2967903ceea324646bbd0c99412e3217c2f56a116f2d1b6031674bd3d33d197ad702a4812d4f4c4a17fafc7cdce1d4f7b491d0064999ef49f952a8d998baf77a65210ecec2381d8e13695318ca59b4602598fe0f58a2ee1bbd945dcbc0d571bc478d8401fffc1bd47218ffab2a966b247bdb93100ddd4612b18b82267eb3a8af6f8eeb668cbab3f31086dfc93815ade90d458234e88263535927d6c1400443a81cf72f31beddc0625d959de17f9cd8e9e719f430357e71684f59bbb2454b02533e7d15b8d28ccf54f55398c5dd193d12a14adff66cd9f46b2c3a80519cbc5d89c2abec0e80df70d2df4d9934287ec0640d1889c6f4f9f5b639f669753dbce78b72360440bb7821d9bfaef38bfc68dde2eb14f95637d2343537262bd3a677a2cde0031b286f76669e6d6fb62fca09eecc587d29292f0e09cc45e09b0f29672bf96d29b5620e1df94524c92c9b0b69eb16a8991117d00e977e92ff6c2dfae550e9049a88cb1d730318d8ee9b174c79b16bed6e5e1e2a8d21d179a84f2927fdd0e1feb35bbc796b15577e3586bea6276c42f0d34df34e667ef18c1f50bf5bc1a6db86f85b83b67d9162e0d64be141a36c19d9a13da8930f6faac38a000cf3623fa44ae2fb3ddad6345dabd9fad64248343580b92746794e8b30f91a5acba6f641155d7be863c6db494664895c23eb17988b1f6922181d9aa4ac2d06f07250c0e2e3cd1bd660b2dc3827def39f6113fcf6397f806f4d199f51e5f065d577ec20c009c52866b1b98dd2a4d68ad794978e24728986d1205f21c6ee2e32671646fbb49be468ee8b9bb9ca3e0defb483d54c114cc44f4e41240c8c68c357915c878e902e829329efbaf233f787c1b0cc65f9515b2e9565c892e1414d6e8d7bdb39af1f8e16f571f08936df36278a2afcbb44f852c2e1b6979e7c35abc486a610bbe97d5097a032b75a7996ad2b1e0e4dc102ad3f3be6254e9c0c3c9b5f706be25d742c710370568cbe5e54c346f5d65d49142e87d838f0f86a966d47ceb9bdfe0d893704bf70a6d95f5b221bd622d6145ae1875da4c0d53b7b43bd7b2d5804c243d5ac98b901bd949a1d91d2039e1f8865da69a54e349815fe92013104d8d3608c2cf378c9df81543760f646feba0b2e2e2bfbd869f9e19bc75b733efa15eb67b1cd53c2008bf3d1b6fc084497cba21a3f9741904353bbcab2bf8e1e4e86e1054c87bb0f7dca4b4bc52bf0120be8ec638d734712bab7776283c3a5c8fe621092a5ac4fac0d7a1bb754f7e02e9483bcbdc831335ebc96c36fef8f81333bc9986cf6bbe1c598c8c3e53b0f44968999f8eada87e646265dfcec8d31ae82ab611f390e1f7b1b72afb5576e8e682798714ab9172a0b96f0d739c7f21d25742040bfc129002d230fdc2d9f58c8ec9f8bfcadde8dd3d7259a5f263d94b79040ef9fca48c71991e4f4fbfd8c27be71707f632206e2f57eed446963fce6fbd1ee5591eec393512e46ec1a8a27b2aa3d5324f222d03db18df716b4166ef31f2a1d225a6a99d726919d3ac861ec3314a45988abcb21ac876ea1abb8848dafbaccbc1201f318c5911505c24d9edbae57bf58bb3c83a2ffee30cd35e8847e59c93f75b1e2247f4c12115bca558bd9b04f4c273b1001a301703cf749ed859de903c8c1c02f9e83f75c070287cff6112622f8a8847da1351e53f37728edfb0d85c0625aa8ea9265c97b02b89d1c3b74032e16bad92d3aaa3a37648f68bf1aaff61ec6841fc02d72af86aa7a10a280be213096f3fa73a958896a4c99be4e7c8e60b8c6e592bff01348c179643d29122eb773497c1e775837d2cfc7e1e34937e136f029a2a3ee852bcf37baae626e180e74b700c859b56b54251b48ffff05658488d90491815a16f8c5e8ca561a9344de7b9499771a528b1664663e5f29bf0cd6b909da922bc286b3b26ba621b5fa67ec387f974fb4bb9b9a28d450370dd1ebf419bd6c02b0a790e6b3fc44050c16d3e4007c81061079695095973870c1533f910e075bcd7d9776d0199aac5ceac2bdb6bc48e6a6dc24ecc7fa3480ec87880f628980786319ef91999d6f6443d817d68210d4ad178ed83d7ad0ef1d48544fac78ca8eb39beef1864cddab3ae099a6d5f908bb454370d78254c832684667e1f080e122b1b18dae91534428d5721c2fb58986b065375077edbba0977aa07083520c807b2402653e189be2b9c8916685040b4e66949675bbb026f50971522723a265077eea1c54772b189b5b271a7f2dd79cb392dbf70148cf944380a4bbe19fbd88919a92eef3377eed498f3bcf5d7f21037ac2ebcb0a3d91886bc1870d195727e344594439fb3f83982e1466efab1073db45b92120a49e70bc0e7a828a21d788fb2e6050102e90cf29e49dd4b1e78edf22e31c6dc33909e2d9d0a3582385760d417fdeaca8e0d31a51a9e1dc1c4300478210e5f5862da7f47263d8b018bf74f45f6fe326df42f78a1f468da714ddadd197266f4bdc3c3b69e6e060392a58eadbacf6bf93820aa13fadcc7c3122ba9370f536d6814e00bbc0a398f5ded3573b9fa0ed799c84b2c18d1dc098b524883a1d109deffe9a1b30e6d0717b10847db8859a647c89952fac8dda24acd57d1197ceb05c897213803b28b8f89158a9fc6dee50761319c19ad41bcd334ad3cbe2323c3ffc3626afadcc9a60dbd1e6749758Line truncated
|
||||
}
|
||||
@@ -18,7 +18,7 @@ use weed_lance_worker::jobs::cleanup::{self, CleanupVersionsHandler};
|
||||
use weed_lance_worker::jobs::compact::{CompactHandler, JOB_TYPE as COMPACT_JOB_TYPE};
|
||||
|
||||
mod common;
|
||||
use common::{Recorder, fallback, int_config, namespace_url};
|
||||
use common::{Recorder, int_config, namespace_url, signing_key, storage};
|
||||
|
||||
fn table() -> Option<String> {
|
||||
std::env::var("WEED_LANCE_TABLE")
|
||||
@@ -40,14 +40,18 @@ async fn maintains_the_named_table() {
|
||||
// anything above one fragment is worth merging here.
|
||||
let mut config = int_config("min_fragments", 2);
|
||||
config.extend(int_config("target_rows_per_fragment", 1_048_576));
|
||||
let compact = CompactHandler::new(url.clone()).with_fallback(fallback());
|
||||
let compact = CompactHandler::new(url.clone())
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
run(&compact, COMPACT_JOB_TYPE, &name, config, true).await;
|
||||
|
||||
// Keep the current version and retain nothing else, so the versions
|
||||
// compaction superseded are actually removed rather than counted.
|
||||
let mut config = int_config("min_versions_to_keep", 1);
|
||||
config.extend(int_config("retain_hours", 0));
|
||||
let cleanup = CleanupVersionsHandler::new(url).with_fallback(fallback());
|
||||
let cleanup = CleanupVersionsHandler::new(url)
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
run(&cleanup, cleanup::JOB_TYPE, &name, config, true).await;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,10 @@ use seaweed_worker_core::JobHandler;
|
||||
use seaweed_worker_core::pb::{
|
||||
ConfigValue, ExecuteJobRequest, JobSpec, RunDetectionRequest, config_value::Kind,
|
||||
};
|
||||
use weed_lance_worker::catalog::NamespaceClient;
|
||||
use weed_lance_worker::jobs::sort::{JOB_TYPE, SortHandler};
|
||||
|
||||
mod common;
|
||||
use common::{Recorder, fallback, namespace_url};
|
||||
use common::{Recorder, client, namespace_url, signing_key, storage};
|
||||
|
||||
/// One live gateway and one shared catalog, and `list_all_tables` sweeps
|
||||
/// everything, so these tests take a lock the way the compaction ones do.
|
||||
@@ -52,7 +51,6 @@ async fn seed_unsorted_table(
|
||||
use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use lance::dataset::{Dataset, WriteMode, WriteParams};
|
||||
use lance::io::{ObjectStoreParams, StorageOptionsAccessor};
|
||||
use std::sync::Arc;
|
||||
|
||||
let http = reqwest::Client::new();
|
||||
@@ -70,11 +68,10 @@ async fn seed_unsorted_table(
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
let client = NamespaceClient::new(url.to_string());
|
||||
let client = client(url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), name.to_string()];
|
||||
let description = client.describe_table(&id).await?;
|
||||
let mut options = description.storage_options.clone();
|
||||
options.extend(fallback());
|
||||
let wrapper = storage().await.wrapper(&description.location).await?;
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
|
||||
let total = batches * rows_each;
|
||||
@@ -92,12 +89,7 @@ async fn seed_unsorted_table(
|
||||
} else {
|
||||
WriteMode::Append
|
||||
},
|
||||
store_params: Some(ObjectStoreParams {
|
||||
storage_options_accessor: Some(Arc::new(
|
||||
StorageOptionsAccessor::with_static_options(options.clone()),
|
||||
)),
|
||||
..Default::default()
|
||||
}),
|
||||
store_params: Some(weed_lance_worker::dataset::store_params(wrapper.clone())),
|
||||
..Default::default()
|
||||
};
|
||||
dataset = Some(
|
||||
@@ -125,9 +117,9 @@ async fn stored_ids(url: &str, name: &str) -> Result<Vec<i64>> {
|
||||
use arrow_array::Int64Array;
|
||||
use futures::TryStreamExt;
|
||||
|
||||
let client = NamespaceClient::new(url.to_string());
|
||||
let client = client(url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), name.to_string()];
|
||||
let table = weed_lance_worker::dataset::open(&client, &id, &fallback()).await?;
|
||||
let table = weed_lance_worker::dataset::open(&client, &id, &storage().await).await?;
|
||||
let stream = table.dataset.scan().try_into_stream().await?;
|
||||
let batches: Vec<_> = stream.try_collect().await?;
|
||||
let mut ids = Vec::new();
|
||||
@@ -164,7 +156,9 @@ async fn sorts_a_table_and_stops_proposing_it() {
|
||||
"the seeded table was already sorted, so the test proves nothing"
|
||||
);
|
||||
|
||||
let handler = SortHandler::new(url.clone()).with_fallback(fallback());
|
||||
let handler = SortHandler::new(url.clone())
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
let detection = RunDetectionRequest {
|
||||
request_id: "detect-sort".to_string(),
|
||||
@@ -259,7 +253,9 @@ async fn leaves_a_table_that_declares_no_order_alone() {
|
||||
.await
|
||||
.expect("seed a table with no declared order");
|
||||
|
||||
let handler = SortHandler::new(url.clone()).with_fallback(fallback());
|
||||
let handler = SortHandler::new(url.clone())
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let recorder = Recorder::default();
|
||||
handler
|
||||
.detect(
|
||||
@@ -302,7 +298,9 @@ async fn proposes_a_replacement_that_barely_changes_the_row_count() {
|
||||
.await
|
||||
.expect("seed an unsorted table");
|
||||
|
||||
let handler = SortHandler::new(url.clone()).with_fallback(fallback());
|
||||
let handler = SortHandler::new(url.clone())
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
// A threshold no realistic append would cross, so nothing but the identity
|
||||
// of the data can be what proposes this table.
|
||||
let detection = RunDetectionRequest {
|
||||
@@ -395,7 +393,9 @@ async fn deletions_do_not_hide_appended_rows() {
|
||||
.await
|
||||
.expect("seed an unsorted table");
|
||||
|
||||
let handler = SortHandler::new(url.clone()).with_fallback(fallback());
|
||||
let handler = SortHandler::new(url.clone())
|
||||
.with_storage(storage().await)
|
||||
.with_signing_key(signing_key());
|
||||
let detection = RunDetectionRequest {
|
||||
request_id: "detect-delete".to_string(),
|
||||
job_type: JOB_TYPE.to_string(),
|
||||
@@ -436,9 +436,9 @@ async fn deletions_do_not_hide_appended_rows() {
|
||||
|
||||
// Delete 900 of the 1000 sorted rows, then append 200 unsorted ones. The
|
||||
// table is smaller than when it was sorted, so net growth reads as zero.
|
||||
let client = NamespaceClient::new(url.clone());
|
||||
let client = client(&url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), "deleteme".to_string()];
|
||||
let mut table = weed_lance_worker::dataset::open(&client, &id, &fallback())
|
||||
let mut table = weed_lance_worker::dataset::open(&client, &id, &storage().await)
|
||||
.await
|
||||
.expect("reopen the sorted table");
|
||||
table
|
||||
@@ -472,26 +472,19 @@ async fn append_ids(url: &str, name: &str, first_id: i64, rows: i64) -> Result<(
|
||||
use arrow_array::{Int64Array, RecordBatch, RecordBatchIterator};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use lance::dataset::{Dataset, WriteMode, WriteParams};
|
||||
use lance::io::{ObjectStoreParams, StorageOptionsAccessor};
|
||||
use std::sync::Arc;
|
||||
|
||||
let client = NamespaceClient::new(url.to_string());
|
||||
let client = client(url);
|
||||
let id = vec!["vec".to_string(), "ml".to_string(), name.to_string()];
|
||||
let description = client.describe_table(&id).await?;
|
||||
let mut options = description.storage_options.clone();
|
||||
options.extend(fallback());
|
||||
let wrapper = storage().await.wrapper(&description.location).await?;
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
|
||||
let ids: Vec<i64> = (0..rows).map(|row| first_id + row).collect();
|
||||
let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int64Array::from(ids))])?;
|
||||
let params = WriteParams {
|
||||
mode: WriteMode::Append,
|
||||
store_params: Some(ObjectStoreParams {
|
||||
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
|
||||
options,
|
||||
))),
|
||||
..Default::default()
|
||||
}),
|
||||
store_params: Some(weed_lance_worker::dataset::store_params(wrapper)),
|
||||
..Default::default()
|
||||
};
|
||||
Dataset::write(
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MC4CAQAwBQYDK2VwBCIEIIe8UCQQm2tMev77AnUJM5AQHPGBJ06euM8nGjDkILso
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBfTCCAS+gAwIBAgIUTqmeCb9ijj6cVkoZU6tXADadFnEwBQYDK2VwMB4xHDAa
|
||||
BgNVBAMME3dlZWQtdmVjdG9yIHRlc3QgQ0EwHhcNMjYxMTAzMTgwNjI5WhcNMzYx
|
||||
MDMxMTgwNjI5WjATMREwDwYDVQQDDAhlbmdpbmUtYTAqMAUGAytlcAMhACDaGO8F
|
||||
ITSUkCId23gLzafauk7Z6bzZOpD732Zq5p/Uo4GJMIGGMBoGA1UdEQQTMBGCCWxv
|
||||
Y2FsaG9zdIcEfwAAATAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwCQYD
|
||||
VR0TBAIwADAdBgNVHQ4EFgQUr386MhXMqJ19631S4E70aTmtJ7wwHwYDVR0jBBgw
|
||||
FoAUY0IfV1/n+b5dGE81HUcczB3Z5e4wBQYDK2VwA0EAalLd1JyRIForesFYzdVZ
|
||||
x4xMjUqXmZHjIZfrnwli6jLwXHhOBD57Kg8diozVVWFviTqaw58q/615qikJn6hO
|
||||
AA==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MC4CAQAwBQYDK2VwBCIEIE/JTETGtdVKPupXUWAvw6QMjiKZQvXvClUSyOt3etEt
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBfTCCAS+gAwIBAgIUTqmeCb9ijj6cVkoZU6tXADadFnIwBQYDK2VwMB4xHDAa
|
||||
BgNVBAMME3dlZWQtdmVjdG9yIHRlc3QgQ0EwHhcNMjYxMTAzMTgwNjI5WhcNMzYx
|
||||
MDMxMTgwNjI5WjATMREwDwYDVQQDDAhlbmdpbmUtYjAqMAUGAytlcAMhAJ+akJpq
|
||||
yTvnOqNrXU9gAVTZ6UZksVQ8dLrYKruicLy4o4GJMIGGMBoGA1UdEQQTMBGCCWxv
|
||||
Y2FsaG9zdIcEfwAAATAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwCQYD
|
||||
VR0TBAIwADAdBgNVHQ4EFgQUq90KSsHhZ+BFewHdX/j8D7/Ow0kwHwYDVR0jBBgw
|
||||
FoAUY0IfV1/n+b5dGE81HUcczB3Z5e4wBQYDK2VwA0EAJUIkaJjItZ15e+ais3NQ
|
||||
nMa4r/Xk+goY48Kw+GXapcT6goxMqiMOcbg3i1Ct3Guywew5VPTLlw12g8rFbYiU
|
||||
CQ==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,10 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBYTCCAROgAwIBAgIUTmlwPR0OgCN9BqG8FpVZDesTFz0wBQYDK2VwMB4xHDAa
|
||||
BgNVBAMME3dlZWQtdmVjdG9yIHRlc3QgQ0EwHhcNMjYxMTAzMTgwNjI5WhcNMzYx
|
||||
MDMxMTgwNjI5WjAeMRwwGgYDVQQDDBN3ZWVkLXZlY3RvciB0ZXN0IENBMCowBQYD
|
||||
K2VwAyEAYHNDiIBy6Y4b3hBO71kc80611yE53/ZCCfszFpsV06ijYzBhMB0GA1Ud
|
||||
DgQWBBRjQh9XX+f5vl0YTzUdRxzMHdnl7jAfBgNVHSMEGDAWgBRjQh9XX+f5vl0Y
|
||||
TzUdRxzMHdnl7jAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAFBgMr
|
||||
ZXADQQAdFveXGKtqg1whYn7dKVnHyJp8+pbSDHhOzjkj5zMXssT6I9l/ydb00jpA
|
||||
0d9mGnOB2cgywGgeAOpqypbCnxIG
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "sw-client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "SeaweedFS client library: filer gRPC metadata plane + volume HTTP data plane"
|
||||
|
||||
[lib]
|
||||
name = "sw_client"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
async-trait.workspace = true
|
||||
bytes = "1"
|
||||
log = "0.4"
|
||||
prost.workspace = true
|
||||
# System roots for volume servers behind public CAs, as Go's http client.
|
||||
reqwest = { version = "0.12", default-features = false, features = ["multipart", "rustls-tls-native-roots"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
thiserror = "2"
|
||||
tokio.workspace = true
|
||||
tonic.workspace = true
|
||||
tonic-prost.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
rustls-pemfile = "2"
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] }
|
||||
|
||||
[build-dependencies]
|
||||
tonic-prost-build.workspace = true
|
||||
protoc-bin-vendored = "3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,24 @@
|
||||
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()?);
|
||||
}
|
||||
}
|
||||
|
||||
// Compiled straight out of the Go tree, the way seaweed-volume already reads
|
||||
// filer.proto, so the contract cannot drift from a vendored copy.
|
||||
tonic_prost_build::configure()
|
||||
.build_server(true)
|
||||
.build_client(true)
|
||||
.protoc_arg("--experimental_allow_proto3_optional")
|
||||
.compile_protos(&["../../../weed/pb/filer.proto"], &["../../../weed/pb/"])?;
|
||||
println!("cargo:rerun-if-changed=../../../weed/pb/filer.proto");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! A small fileId-keyed whole-chunk cache for read prefetch.
|
||||
//!
|
||||
//! SeaweedFS needles are immutable for a given fileId (`<vid>,<key><cookie>`),
|
||||
//! so caching a chunk's bytes by fileId is coherence-safe — no invalidation is
|
||||
//! ever needed, only capacity-bounded LRU eviction. This lets the read path
|
||||
//! prefetch upcoming chunks in parallel (independent of the kernel's small,
|
||||
//! single-chunk read upcalls) so sequential reads hit already-fetched bytes.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Bounded LRU of fileId -> whole-chunk bytes. Not thread-safe on its own; wrap
|
||||
/// in a `Mutex`. All ops are O(cache size) at worst (the LRU order is a deque),
|
||||
/// which is fine for the few-hundred-entry caches used here.
|
||||
pub struct ChunkCache {
|
||||
map: HashMap<String, Arc<Vec<u8>>>,
|
||||
order: VecDeque<String>, // front = least-recently-used
|
||||
bytes: usize,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
impl ChunkCache {
|
||||
pub fn new(cap_bytes: usize) -> Self {
|
||||
Self {
|
||||
map: HashMap::new(),
|
||||
order: VecDeque::new(),
|
||||
bytes: 0,
|
||||
cap: cap_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch a cached chunk, marking it most-recently-used.
|
||||
pub fn get(&mut self, file_id: &str) -> Option<Arc<Vec<u8>>> {
|
||||
let v = self.map.get(file_id)?.clone();
|
||||
if let Some(pos) = self.order.iter().position(|x| x == file_id) {
|
||||
let f = self.order.remove(pos).unwrap();
|
||||
self.order.push_back(f);
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
pub fn contains(&self, file_id: &str) -> bool {
|
||||
self.map.contains_key(file_id)
|
||||
}
|
||||
|
||||
/// Insert a chunk (no-op if empty, already present or larger than the whole
|
||||
/// cap). Evicts least-recently-used entries until within capacity.
|
||||
pub fn put(&mut self, file_id: String, data: Arc<Vec<u8>>) {
|
||||
if self.map.contains_key(&file_id) {
|
||||
return;
|
||||
}
|
||||
let len = data.len();
|
||||
if len == 0 || len > self.cap {
|
||||
return; // a single chunk bigger than the whole cache: don't churn
|
||||
}
|
||||
self.map.insert(file_id.clone(), data);
|
||||
self.order.push_back(file_id);
|
||||
self.bytes += len;
|
||||
while self.bytes > self.cap {
|
||||
let Some(old) = self.order.pop_front() else {
|
||||
break;
|
||||
};
|
||||
if let Some(o) = self.map.remove(&old) {
|
||||
self.bytes -= o.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn len_bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn chunk(n: usize) -> Arc<Vec<u8>> {
|
||||
Arc::new(vec![0u8; n])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_miss_then_hit() {
|
||||
let mut c = ChunkCache::new(1024);
|
||||
assert!(c.get("a").is_none());
|
||||
c.put("a".into(), chunk(100));
|
||||
assert_eq!(c.get("a").unwrap().len(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_is_idempotent_on_bytes() {
|
||||
let mut c = ChunkCache::new(1024);
|
||||
c.put("a".into(), chunk(100));
|
||||
c.put("a".into(), chunk(100)); // duplicate ignored
|
||||
assert_eq!(c.len_bytes(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lru_evicts_oldest_first() {
|
||||
let mut c = ChunkCache::new(250);
|
||||
c.put("a".into(), chunk(100));
|
||||
c.put("b".into(), chunk(100));
|
||||
// touch a so b is now least-recently-used
|
||||
assert!(c.get("a").is_some());
|
||||
c.put("c".into(), chunk(100)); // bytes would be 300 > 250 -> evict LRU (b)
|
||||
assert!(c.contains("a"));
|
||||
assert!(!c.contains("b"));
|
||||
assert!(c.contains("c"));
|
||||
assert_eq!(c.len_bytes(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_chunks_are_not_cached() {
|
||||
let mut c = ChunkCache::new(0);
|
||||
for i in 0..10 {
|
||||
c.put(i.to_string(), chunk(0));
|
||||
}
|
||||
assert!(c.map.is_empty() && c.order.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_chunk_not_cached() {
|
||||
let mut c = ChunkCache::new(100);
|
||||
c.put("big".into(), chunk(200));
|
||||
assert!(!c.contains("big"));
|
||||
assert_eq!(c.len_bytes(), 0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
//! SeaweedFS client library.
|
||||
//!
|
||||
//! Speaks the filer gRPC metadata plane and the volume-server HTTP data plane,
|
||||
//! and resolves files (lists of immutable chunks) into byte ranges. The vector
|
||||
//! engine, the Lance maintenance worker and its CLI reach the cluster's
|
||||
//! storage through it; the Enterprise repository's VFS client shares its API.
|
||||
|
||||
/// Generated protobuf + gRPC client stubs for the SeaweedFS filer
|
||||
/// (`package filer_pb;` in `weed/pb/filer.proto`).
|
||||
pub mod filer_pb {
|
||||
#![allow(clippy::all)]
|
||||
#![allow(rustdoc::all)]
|
||||
tonic::include_proto!("filer_pb");
|
||||
}
|
||||
|
||||
mod cache;
|
||||
pub mod filer;
|
||||
pub mod location_cache;
|
||||
pub mod read;
|
||||
pub mod transport;
|
||||
pub mod wbuf;
|
||||
pub mod write;
|
||||
|
||||
/// Upper bound on a single read's up-front allocation. `read_file` allocates the
|
||||
/// requested span, so a malformed request with an absurd size could otherwise
|
||||
/// trigger a huge allocation (OOM/DoS); a read span over this is rejected. This
|
||||
/// is purely a per-read guard — file *size* is unbounded, since writes stream
|
||||
/// chunk-by-chunk via [`wbuf::StreamingWriteBuffer`].
|
||||
pub const MAX_READ_BYTES: u64 = 1 << 30; /* 1 GiB */
|
||||
|
||||
pub use filer::{
|
||||
AssignVolumeOptions, Assignment, EntryExists, EntryPage, FilerClient, FilerConfig, GrpcTls,
|
||||
LogPos, Seek, VolumeLocation, is_entry_exists, is_unavailable, seek_page,
|
||||
};
|
||||
pub use location_cache::{DEFAULT_RETAIN_GENERATIONS, LocationCache};
|
||||
pub use read::{
|
||||
ChunkDecoder, ReadOptions, ResolvedChunks, VolumeReader, compact_shadowed, read_file,
|
||||
read_file_with, read_resolved, resolve_chunks,
|
||||
};
|
||||
pub use transport::{
|
||||
CommitAmbiguous, HttpTransport, HttpsTls, NotWritten, VolumeTransport, VolumeWriteReceipt,
|
||||
install_crypto_provider, is_not_written,
|
||||
};
|
||||
pub use wbuf::{SealPiece, StreamingWriteBuffer};
|
||||
pub use write::{Writer, flush_file, now_ns, now_unix, upload_pieces, upload_pieces_with_options};
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Volume id -> volume server locations, cached for reads.
|
||||
//!
|
||||
//! Mirrors the Go client's vid map (`weed/wdclient/vid_map.go`): one flat map
|
||||
//! whose entries remember the generation they were learned in. [`reset`] starts
|
||||
//! a new generation when the metadata source has to be relearned, entries stay
|
||||
//! readable while that happens, and any not relearned within
|
||||
//! `retain_generations` resets are dropped. Nothing is chained, so there is no
|
||||
//! history to walk and none to sever underneath a reader.
|
||||
//!
|
||||
//! [`reset`]: LocationCache::reset
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// How many resets a location survives without being relearned. Matches the Go
|
||||
/// client's `DefaultVidMapCacheSize`.
|
||||
pub const DEFAULT_RETAIN_GENERATIONS: u64 = 5;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Entry {
|
||||
urls: Vec<String>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Inner {
|
||||
entries: HashMap<u32, Entry>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LocationCache {
|
||||
inner: Mutex<Inner>,
|
||||
retain_generations: u64,
|
||||
}
|
||||
|
||||
impl Default for LocationCache {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl LocationCache {
|
||||
pub fn new() -> Self {
|
||||
Self::with_retain_generations(DEFAULT_RETAIN_GENERATIONS)
|
||||
}
|
||||
|
||||
/// Keep locations for `retain_generations` resets after they were last
|
||||
/// learned. Zero is raised to one: an entry always survives the reset that
|
||||
/// immediately follows it, which is what keeps in-flight reads resolving.
|
||||
pub fn with_retain_generations(retain_generations: u64) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(Inner::default()),
|
||||
retain_generations: retain_generations.max(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Locations for `vid`, or `None` when it is unknown or has none. There is
|
||||
/// nothing older to fall back to: a volume's history lives in its own entry.
|
||||
pub fn locations(&self, vid: u32) -> Option<Vec<String>> {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
inner.entries.get(&vid).map(|entry| entry.urls.clone())
|
||||
}
|
||||
|
||||
/// Record what the lookup returned for `vid`, replacing whatever an earlier
|
||||
/// generation held. A volume that moved must not keep answering with the
|
||||
/// server it moved off, and one with no locations left is dropped rather
|
||||
/// than kept as an empty entry.
|
||||
pub fn learn(&self, vid: u32, urls: Vec<String>) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
if urls.is_empty() {
|
||||
inner.entries.remove(&vid);
|
||||
return;
|
||||
}
|
||||
let generation = inner.generation;
|
||||
inner.entries.insert(vid, Entry { urls, generation });
|
||||
}
|
||||
|
||||
/// Forget `vid` so the next read looks it up again.
|
||||
pub fn invalidate(&self, vid: u32) {
|
||||
self.inner.lock().unwrap().entries.remove(&vid);
|
||||
}
|
||||
|
||||
/// Forget `vid` only while it still holds exactly `urls`, and report
|
||||
/// whether it did. The counterpart of a read that failed against the
|
||||
/// servers we had cached: a slow read failing against servers that a newer
|
||||
/// lookup has already replaced must not throw the fresh entry away.
|
||||
pub fn invalidate_stale(&self, vid: u32, urls: &[String]) -> bool {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
let stale = inner
|
||||
.entries
|
||||
.get(&vid)
|
||||
.is_some_and(|entry| entry.urls == urls);
|
||||
if stale {
|
||||
inner.entries.remove(&vid);
|
||||
}
|
||||
stale
|
||||
}
|
||||
|
||||
/// Start a new generation, as when the metadata subscription reconnects and
|
||||
/// what we were told may no longer hold. Entries stay readable until they
|
||||
/// are relearned or fall out of the retained window.
|
||||
pub fn reset(&self) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
inner.generation += 1;
|
||||
if inner.generation <= self.retain_generations {
|
||||
return;
|
||||
}
|
||||
let oldest = inner.generation - self.retain_generations;
|
||||
inner.entries.retain(|_, entry| entry.generation >= oldest);
|
||||
}
|
||||
|
||||
/// Number of volumes currently held, retained generations included.
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.lock().unwrap().entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn urls(urls: &[&str]) -> Vec<String> {
|
||||
urls.iter().map(|u| u.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_volume_is_a_miss() {
|
||||
let cache = LocationCache::new();
|
||||
assert_eq!(cache.locations(1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn learned_locations_are_served() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["h1:8080", "h2:8080"]));
|
||||
assert_eq!(cache.locations(1), Some(urls(&["h1:8080", "h2:8080"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_learn_is_a_definitive_miss() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.learn(1, Vec::new());
|
||||
assert_eq!(
|
||||
cache.locations(1),
|
||||
None,
|
||||
"a volume known to have no locations must not serve what it had before"
|
||||
);
|
||||
assert!(cache.is_empty(), "an emptied volume is dropped, not kept");
|
||||
}
|
||||
|
||||
// The Go side's addLocation rule: the first write of a generation replaces
|
||||
// the entry rather than merging into it.
|
||||
#[test]
|
||||
fn learn_replaces_earlier_generation() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["moved-from:8080"]));
|
||||
cache.reset();
|
||||
cache.learn(1, urls(&["moved-to:8080"]));
|
||||
assert_eq!(cache.locations(1), Some(urls(&["moved-to:8080"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locations_survive_a_reset() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.reset();
|
||||
assert_eq!(
|
||||
cache.locations(1),
|
||||
Some(urls(&["h1:8080"])),
|
||||
"a reset must not strand reads that are already in flight"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_expire_after_the_retained_window() {
|
||||
let retain = 2;
|
||||
let cache = LocationCache::with_retain_generations(retain);
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
|
||||
for i in 0..retain {
|
||||
cache.reset();
|
||||
assert!(
|
||||
cache.locations(1).is_some(),
|
||||
"location should still be retained after {} reset(s)",
|
||||
i + 1
|
||||
);
|
||||
}
|
||||
|
||||
cache.reset();
|
||||
assert_eq!(cache.locations(1), None);
|
||||
assert!(
|
||||
cache.is_empty(),
|
||||
"expired entries must be dropped, not kept"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relearning_restarts_the_window() {
|
||||
let cache = LocationCache::with_retain_generations(2);
|
||||
for _ in 0..5 {
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.reset();
|
||||
}
|
||||
assert!(cache.locations(1).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_retention_still_survives_one_reset() {
|
||||
let cache = LocationCache::with_retain_generations(0);
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.reset();
|
||||
assert!(cache.locations(1).is_some());
|
||||
cache.reset();
|
||||
assert_eq!(cache.locations(1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidate_drops_a_retained_entry() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.reset();
|
||||
cache.invalidate(1);
|
||||
assert_eq!(cache.locations(1), None);
|
||||
assert_eq!(cache.locations(2), None, "unrelated volumes are untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidate_stale_only_drops_what_the_caller_used() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["stale:8080"]));
|
||||
|
||||
assert!(cache.invalidate_stale(1, &urls(&["stale:8080"])));
|
||||
assert_eq!(cache.locations(1), None);
|
||||
|
||||
// A newer lookup has already replaced the entry the failed read used.
|
||||
cache.learn(1, urls(&["fresh:8080"]));
|
||||
assert!(!cache.invalidate_stale(1, &urls(&["stale:8080"])));
|
||||
assert_eq!(
|
||||
cache.locations(1),
|
||||
Some(urls(&["fresh:8080"])),
|
||||
"a read failing against replaced servers must not drop the fresh entry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidate_stale_on_an_unknown_volume_is_a_no_op() {
|
||||
let cache = LocationCache::new();
|
||||
assert!(!cache.invalidate_stale(1, &urls(&["h1:8080"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidate_only_touches_its_own_volume() {
|
||||
let cache = LocationCache::new();
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
cache.learn(2, urls(&["h2:8080"]));
|
||||
cache.invalidate(1);
|
||||
assert_eq!(cache.locations(2), Some(urls(&["h2:8080"])));
|
||||
assert_eq!(cache.len(), 1);
|
||||
}
|
||||
|
||||
// A volume relearned every generation must always resolve, however many
|
||||
// resets run concurrently with the readers.
|
||||
#[test]
|
||||
fn concurrent_resets_never_strand_a_live_volume() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let cache = Arc::new(LocationCache::with_retain_generations(2));
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let readers: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let cache = Arc::clone(&cache);
|
||||
let stop = Arc::clone(&stop);
|
||||
std::thread::spawn(move || {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
assert!(
|
||||
cache.locations(1).is_some(),
|
||||
"live volume went missing during a reset"
|
||||
);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
for _ in 0..2_000 {
|
||||
cache.reset();
|
||||
cache.learn(1, urls(&["h1:8080"]));
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
for reader in readers {
|
||||
reader.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,653 @@
|
||||
//! Volume data-plane transport: moves needle bytes to/from volume servers.
|
||||
//!
|
||||
//! Everything *above* this — resolving a file's chunks, looking up a volume's
|
||||
//! locations, assigning a volume for a write — stays in the filer client. A
|
||||
//! transport only transfers bytes for an already-resolved `fileId` at an
|
||||
//! already-known location, so it is the single seam where the wire technology
|
||||
//! lives: HTTP today ([`HttpTransport`]), RDMA (SoftRoCE / real NICs) next.
|
||||
//!
|
||||
//! The trait is deliberately narrow (read a range, write a needle) so an RDMA
|
||||
//! implementation — registered memory regions, queue pairs, one-sided READ —
|
||||
//! drops in without touching `read.rs` / `write.rs` or the kernel daemon.
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use reqwest::header::{AUTHORIZATION, RANGE};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct VolumeWriteReceipt {
|
||||
/// SHA-256 computed by the volume over the bytes it committed. `None`
|
||||
/// means the transport/server pair does not advertise that proof.
|
||||
pub committed_sha256: Option<String>,
|
||||
/// Exact volume endpoint that accepted this commit. Fenced capacity writes
|
||||
/// persist it with their ownership receipt so GC can retire the original
|
||||
/// writer even after the volume topology changes.
|
||||
pub committed_location: Option<String>,
|
||||
}
|
||||
|
||||
/// Transfers needle bytes for a resolved `fileId` + location. Implementations
|
||||
/// must be cheap to clone/share (wrapped in `Arc`) and safe for concurrent use.
|
||||
#[async_trait]
|
||||
pub trait VolumeTransport: Send + Sync {
|
||||
/// Read `file_id` from any one of `locations` (`host:port`), optionally the
|
||||
/// logical byte range `(offset, len)`. Returns the (server-decompressed)
|
||||
/// needle bytes. Implementations should try locations in order until one
|
||||
/// succeeds.
|
||||
async fn read(
|
||||
&self,
|
||||
locations: &[String],
|
||||
file_id: &str,
|
||||
range: Option<(u64, u64)>,
|
||||
) -> Result<Vec<u8>>;
|
||||
|
||||
/// Read with a short-lived exact-FID capability. Transports which cannot
|
||||
/// carry read authorization fail closed instead of silently dropping it.
|
||||
async fn read_with_auth(
|
||||
&self,
|
||||
locations: &[String],
|
||||
file_id: &str,
|
||||
range: Option<(u64, u64)>,
|
||||
auth: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
if !auth.is_empty() {
|
||||
bail!(
|
||||
"{} transport cannot carry an exact-FID read capability",
|
||||
self.name()
|
||||
);
|
||||
}
|
||||
self.read(locations, file_id, range).await
|
||||
}
|
||||
|
||||
/// Upload `data` as needle `file_id` to `location` (`host:port`). `filename`
|
||||
/// names the needle (volume servers use it for content-type/compression
|
||||
/// heuristics); `auth` is the per-fileId write JWT (`""` if none).
|
||||
async fn write(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
) -> Result<()>;
|
||||
|
||||
/// Upload and return any proof produced by the volume commit. The default
|
||||
/// keeps existing transports source-compatible without claiming a digest.
|
||||
async fn write_with_receipt(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
) -> Result<VolumeWriteReceipt> {
|
||||
self.write(location, file_id, auth, filename, data).await?;
|
||||
Ok(VolumeWriteReceipt::default())
|
||||
}
|
||||
|
||||
/// [`Self::write_with_receipt`] with the volume told to sync the needle to
|
||||
/// disk before it answers, when `fsync` is set. A transport that cannot ask
|
||||
/// for that fails closed rather than acknowledge a write still in memory.
|
||||
async fn write_synced(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
fsync: bool,
|
||||
) -> Result<VolumeWriteReceipt> {
|
||||
if fsync {
|
||||
bail!("{} transport cannot request fsync", self.name());
|
||||
}
|
||||
self.write_with_receipt(location, file_id, auth, filename, data)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Delete needle `file_id` at `location`; `auth` is the write JWT its
|
||||
/// assignment came with (`""` if none). A needle already gone is no error.
|
||||
async fn delete(&self, location: &str, file_id: &str, auth: &str) -> Result<()> {
|
||||
let _ = (location, file_id, auth);
|
||||
bail!("{} transport cannot delete needles", self.name())
|
||||
}
|
||||
|
||||
/// Short label for logs/diagnostics (e.g. `"http"`, `"rdma"`).
|
||||
fn name(&self) -> &'static str;
|
||||
}
|
||||
|
||||
/// Marker a [`VolumeTransport::write`] attaches when the write may have already
|
||||
/// been committed but its outcome is unknown, so retrying or falling back could
|
||||
/// duplicate data. Callers should fence the write instead of retrying; detect it
|
||||
/// with `err.chain().any(|c| c.is::<CommitAmbiguous>())`.
|
||||
#[derive(Debug)]
|
||||
pub struct CommitAmbiguous;
|
||||
|
||||
impl std::fmt::Display for CommitAmbiguous {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "write commit status unknown; no safe fallback")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CommitAmbiguous {}
|
||||
|
||||
/// Marker a [`VolumeTransport::write`] attaches when the Volume refused the
|
||||
/// write before any of it was committed, for example a required RDMA write to
|
||||
/// a Volume that was sealed after the assignment. The needle does not exist,
|
||||
/// so the caller may write it again under a fresh assignment; detect it with
|
||||
/// [`is_not_written`].
|
||||
#[derive(Debug)]
|
||||
pub struct NotWritten;
|
||||
|
||||
impl std::fmt::Display for NotWritten {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "write refused before commit; nothing was written")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for NotWritten {}
|
||||
|
||||
/// Whether `error` carries [`NotWritten`] anywhere in its context chain.
|
||||
pub fn is_not_written(error: &anyhow::Error) -> bool {
|
||||
error.downcast_ref::<NotWritten>().is_some()
|
||||
}
|
||||
|
||||
/// Connect bound for every volume request: a server that never answers a SYN
|
||||
/// (silently partitioned) must not hold a read or a write.
|
||||
pub const VOLUME_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Bound on one GET from one location, connect to end of body. Two locations
|
||||
/// fit inside a caller's 30 s op budget, so a silent first location fails
|
||||
/// over to the next instead of holding the read (chaos C3).
|
||||
pub const VOLUME_READ_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// Bound on one upload. Longer than the volume server's own 10 s bound on its
|
||||
/// replica forwards, so a dead replica comes back as the server's error
|
||||
/// first; still inside a caller's 30 s op budget.
|
||||
pub const VOLUME_WRITE_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// TLS for volume servers, as `https.client` in security.toml configures it
|
||||
/// for weed processes: enabled, volume servers are dialed over HTTPS, their
|
||||
/// certificates checked against `ca` (the system roots without one), and
|
||||
/// this client presents `cert`/`key` when set.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct HttpsTls {
|
||||
pub ca_pem: Option<Vec<u8>>,
|
||||
pub cert_pem: Option<Vec<u8>>,
|
||||
pub key_pem: Option<Vec<u8>>,
|
||||
/// `https.client.insecure_skip_verify`
|
||||
pub insecure_skip_verify: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for HttpsTls {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("HttpsTls")
|
||||
.field("ca", &self.ca_pem.is_some())
|
||||
.field("identity", &self.cert_pem.is_some())
|
||||
.field("insecure_skip_verify", &self.insecure_skip_verify)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Both tonic and reqwest link rustls; with more than one crypto provider
|
||||
/// compiled in, rustls needs one picked before TLS is configured.
|
||||
pub fn install_crypto_provider() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
|
||||
/// Default transport: the SeaweedFS volume HTTP API — `GET /<fileId>` with an
|
||||
/// optional `Range` header, and a multipart `POST` to upload a needle.
|
||||
pub struct HttpTransport {
|
||||
http: reqwest::Client,
|
||||
scheme: &'static str,
|
||||
read_timeout: Duration,
|
||||
write_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for HttpTransport {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport {
|
||||
pub fn new() -> Self {
|
||||
Self::with_timeouts(VOLUME_READ_TIMEOUT, VOLUME_WRITE_TIMEOUT)
|
||||
}
|
||||
|
||||
fn with_timeouts(read_timeout: Duration, write_timeout: Duration) -> Self {
|
||||
Self {
|
||||
http: reqwest::Client::builder()
|
||||
.connect_timeout(VOLUME_CONNECT_TIMEOUT)
|
||||
.build()
|
||||
.expect("volume HTTP client"),
|
||||
scheme: "http",
|
||||
read_timeout,
|
||||
write_timeout,
|
||||
}
|
||||
}
|
||||
|
||||
/// A transport dialing volume servers over HTTPS.
|
||||
pub fn with_tls(tls: &HttpsTls) -> Result<Self> {
|
||||
install_crypto_provider();
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.connect_timeout(VOLUME_CONNECT_TIMEOUT)
|
||||
.use_rustls_tls()
|
||||
.danger_accept_invalid_certs(tls.insecure_skip_verify);
|
||||
if let Some(ca) = &tls.ca_pem {
|
||||
builder = builder.tls_built_in_root_certs(false).add_root_certificate(
|
||||
reqwest::Certificate::from_pem(ca).context("https.client.ca")?,
|
||||
);
|
||||
}
|
||||
match (&tls.cert_pem, &tls.key_pem) {
|
||||
(Some(cert), Some(key)) => {
|
||||
let mut pem = cert.clone();
|
||||
if !pem.ends_with(b"\n") {
|
||||
pem.push(b'\n');
|
||||
}
|
||||
pem.extend_from_slice(key);
|
||||
builder = builder.identity(
|
||||
reqwest::Identity::from_pem(&pem).context("https.client cert and key")?,
|
||||
);
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => bail!("https.client needs both cert and key, or neither"),
|
||||
}
|
||||
Ok(Self {
|
||||
http: builder.build().context("volume HTTPS client")?,
|
||||
scheme: "https",
|
||||
read_timeout: VOLUME_READ_TIMEOUT,
|
||||
write_timeout: VOLUME_WRITE_TIMEOUT,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VolumeTransport for HttpTransport {
|
||||
async fn read(
|
||||
&self,
|
||||
locations: &[String],
|
||||
file_id: &str,
|
||||
range: Option<(u64, u64)>,
|
||||
) -> Result<Vec<u8>> {
|
||||
self.read_with_auth(locations, file_id, range, "").await
|
||||
}
|
||||
|
||||
async fn read_with_auth(
|
||||
&self,
|
||||
locations: &[String],
|
||||
file_id: &str,
|
||||
range: Option<(u64, u64)>,
|
||||
auth: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
let range_header = match range {
|
||||
Some((_, 0)) => return Ok(Vec::new()),
|
||||
Some((start, len)) => {
|
||||
let end = start
|
||||
.checked_add(len - 1)
|
||||
.with_context(|| format!("range {start}+{len} of {file_id}"))?;
|
||||
Some(format!("bytes={start}-{end}"))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut last_err = None;
|
||||
for url in locations {
|
||||
let full = format!("{}://{url}/{file_id}", self.scheme);
|
||||
let mut req = self.http.get(&full).timeout(self.read_timeout);
|
||||
if let Some(range) = &range_header {
|
||||
req = req.header(RANGE, range);
|
||||
}
|
||||
if !auth.is_empty() {
|
||||
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
|
||||
}
|
||||
match req.send().await {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
// A 200 to a ranged GET is the whole needle.
|
||||
let whole = resp.status() != reqwest::StatusCode::PARTIAL_CONTENT;
|
||||
match resp.bytes().await {
|
||||
Ok(b) => {
|
||||
return Ok(match range {
|
||||
Some((start, len)) if whole => {
|
||||
let start = start.min(b.len() as u64) as usize;
|
||||
let end = start + (len.min((b.len() - start) as u64) as usize);
|
||||
b[start..end].to_vec()
|
||||
}
|
||||
_ => b.to_vec(),
|
||||
});
|
||||
}
|
||||
Err(e) => last_err = Some(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(resp) => last_err = Some(anyhow!("GET {full} -> HTTP {}", resp.status())),
|
||||
Err(e) => last_err = Some(e.into()),
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or_else(|| anyhow!("no volume URL for {file_id}")))
|
||||
}
|
||||
|
||||
async fn write(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
) -> Result<()> {
|
||||
self.upload(location, file_id, auth, filename, data, false)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn write_synced(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
fsync: bool,
|
||||
) -> Result<VolumeWriteReceipt> {
|
||||
self.upload(location, file_id, auth, filename, data, fsync)
|
||||
.await?;
|
||||
Ok(VolumeWriteReceipt::default())
|
||||
}
|
||||
|
||||
async fn delete(&self, location: &str, file_id: &str, auth: &str) -> Result<()> {
|
||||
let url = format!("{}://{location}/{file_id}", self.scheme);
|
||||
let mut req = self.http.delete(&url).timeout(self.write_timeout);
|
||||
if !auth.is_empty() {
|
||||
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
|
||||
}
|
||||
let resp = req.send().await.with_context(|| format!("delete {url}"))?;
|
||||
if resp.status().is_success() || resp.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(());
|
||||
}
|
||||
bail!("delete {url} -> HTTP {}", resp.status())
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"http"
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport {
|
||||
async fn upload(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
fsync: bool,
|
||||
) -> Result<()> {
|
||||
let mut url = format!("{}://{location}/{file_id}", self.scheme);
|
||||
if fsync {
|
||||
url.push_str("?fsync=true");
|
||||
}
|
||||
let size = data.len() as u64;
|
||||
let part = reqwest::multipart::Part::stream_with_length(data, size)
|
||||
.file_name(filename.to_string());
|
||||
let form = reqwest::multipart::Form::new().part("file", part);
|
||||
let mut req = self
|
||||
.http
|
||||
.post(&url)
|
||||
.timeout(self.write_timeout)
|
||||
.multipart(form);
|
||||
if !auth.is_empty() {
|
||||
req = req.header(AUTHORIZATION, format!("BEARER {auth}"));
|
||||
}
|
||||
let resp = match req.send().await {
|
||||
Ok(resp) => resp,
|
||||
// Timed out after the request went out: the volume may have
|
||||
// committed it, so callers must fence instead of retrying.
|
||||
Err(e) if e.is_timeout() && !e.is_connect() => {
|
||||
return Err(e)
|
||||
.with_context(|| format!("upload to {url}"))
|
||||
.context(CommitAmbiguous);
|
||||
}
|
||||
Err(e) => return Err(e).with_context(|| format!("upload to {url}")),
|
||||
};
|
||||
if !resp.status().is_success() {
|
||||
let error = anyhow!("upload {url} -> HTTP {}", resp.status());
|
||||
// Only an explicit pre-append refusal permits reassignment.
|
||||
if resp.status() == reqwest::StatusCode::CONFLICT
|
||||
&& resp
|
||||
.headers()
|
||||
.get("x-seaweed-write-outcome")
|
||||
.is_some_and(|value| value == "refused-before-append")
|
||||
{
|
||||
return Err(error.context(NotWritten));
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[test]
|
||||
fn not_written_is_found_under_later_contexts_and_only_there() {
|
||||
use anyhow::Context;
|
||||
let refused: anyhow::Result<()> = Err(anyhow::anyhow!("prepare rejected"))
|
||||
.context(NotWritten)
|
||||
.context("required RDMA write failed in PrepareRejected");
|
||||
let wrapped = refused
|
||||
.context("upload 38,03e1 to 10.0.2.3:19601")
|
||||
.context("loader write /lmcache/k")
|
||||
.unwrap_err();
|
||||
assert!(is_not_written(&wrapped));
|
||||
|
||||
let ambiguous: anyhow::Result<()> =
|
||||
Err(anyhow::anyhow!("commit rpc timed out")).context(CommitAmbiguous);
|
||||
assert!(!is_not_written(&ambiguous.context("upload").unwrap_err()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticated_read_sends_exact_fid_bearer_token() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = vec![0; 4096];
|
||||
let length = socket.read(&mut request).await.unwrap();
|
||||
let request = String::from_utf8_lossy(&request[..length]).to_ascii_lowercase();
|
||||
assert!(request.starts_with("get /7,abc http/1.1\r\n"));
|
||||
assert!(request.contains("\r\nauthorization: bearer signed-token\r\n"));
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc")
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let bytes = HttpTransport::new()
|
||||
.read_with_auth(&[address.to_string()], "7,abc", None, "signed-token")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bytes, b"abc");
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
/// A server that ignores Range and answers 200 with the whole needle
|
||||
/// yields only the bytes asked for.
|
||||
#[tokio::test]
|
||||
async fn a_whole_needle_answer_to_a_ranged_read_is_sliced() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let server = tokio::spawn(async move {
|
||||
for _ in 0..3 {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = vec![0; 4096];
|
||||
let _ = socket.read(&mut request).await.unwrap();
|
||||
socket
|
||||
.write_all(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\n0123456789",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let http = HttpTransport::new();
|
||||
let at = std::slice::from_ref(&address);
|
||||
assert_eq!(http.read(at, "7,abc", Some((3, 4))).await.unwrap(), b"3456");
|
||||
assert_eq!(http.read(at, "7,abc", Some((8, 4))).await.unwrap(), b"89");
|
||||
assert!(
|
||||
http.read(at, "7,abc", Some((12, 4)))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
/// An empty range needs no request, and one past the end of the address
|
||||
/// space sends none.
|
||||
#[tokio::test]
|
||||
async fn empty_and_overflowing_ranges_send_no_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed = listener.local_addr().unwrap().to_string();
|
||||
drop(listener);
|
||||
let http = HttpTransport::new();
|
||||
let read = http
|
||||
.read(std::slice::from_ref(&closed), "7,abc", Some((5, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(read.is_empty());
|
||||
let error = http
|
||||
.read(&[closed], "7,abc", Some((u64::MAX, 2)))
|
||||
.await
|
||||
.expect_err("the range cannot be expressed");
|
||||
assert!(format!("{error:#}").contains("range"), "{error:#}");
|
||||
}
|
||||
|
||||
/// A server that accepts the connection and never answers: a silently
|
||||
/// partitioned volume server after the connect (chaos C3).
|
||||
async fn silent_server() -> (String, tokio::task::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let held = tokio::spawn(async move {
|
||||
let mut sockets = Vec::new();
|
||||
while let Ok((socket, _)) = listener.accept().await {
|
||||
sockets.push(socket);
|
||||
}
|
||||
});
|
||||
(address, held)
|
||||
}
|
||||
|
||||
/// Chaos C3: a GET with the silent copy listed first must reach the
|
||||
/// healthy copy within its per-location bound, not wait on the first.
|
||||
#[tokio::test]
|
||||
async fn read_fails_over_from_a_silent_location() {
|
||||
let (silent, held) = silent_server().await;
|
||||
let healthy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let healthy_address = healthy.local_addr().unwrap().to_string();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = healthy.accept().await.unwrap();
|
||||
let mut request = vec![0; 4096];
|
||||
let _ = socket.read(&mut request).await.unwrap();
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc")
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let bound = Duration::from_millis(300);
|
||||
let started = std::time::Instant::now();
|
||||
let bytes = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
HttpTransport::with_timeouts(bound, bound).read(
|
||||
&[silent, healthy_address],
|
||||
"7,abc",
|
||||
None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a silent first location must not hold the read")
|
||||
.unwrap();
|
||||
assert_eq!(bytes, b"abc");
|
||||
assert!(started.elapsed() >= bound && started.elapsed() < bound * 10);
|
||||
server.await.unwrap();
|
||||
held.abort();
|
||||
}
|
||||
|
||||
/// A write to a silent server fails at its bound instead of waiting.
|
||||
#[tokio::test]
|
||||
async fn write_to_a_silent_server_fails_at_its_bound() {
|
||||
let (silent, held) = silent_server().await;
|
||||
let bound = Duration::from_millis(300);
|
||||
let started = std::time::Instant::now();
|
||||
let written = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
HttpTransport::with_timeouts(bound, bound).write(
|
||||
&silent,
|
||||
"7,abc",
|
||||
"",
|
||||
"k",
|
||||
Bytes::from(vec![0u8; 1 << 20]),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a silent server must not hold the write");
|
||||
// The request went out, so the commit is unknown: fence, never
|
||||
// reassign. Detected through the context, as sw-kd does (#918).
|
||||
let error = written.expect_err("a silent server cannot ack the write");
|
||||
assert!(
|
||||
error.downcast_ref::<CommitAmbiguous>().is_some(),
|
||||
"{error:#}"
|
||||
);
|
||||
assert!(!is_not_written(&error));
|
||||
assert!(started.elapsed() >= bound && started.elapsed() < bound * 10);
|
||||
held.abort();
|
||||
}
|
||||
|
||||
/// An assignment that wants the needle on disk asks the volume for it.
|
||||
#[tokio::test]
|
||||
async fn synced_write_asks_the_volume_to_fsync() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap().to_string();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut lines = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = vec![0; 4096];
|
||||
let length = socket.read(&mut request).await.unwrap();
|
||||
let request = String::from_utf8_lossy(&request[..length]).to_string();
|
||||
lines.push(request.lines().next().unwrap_or_default().to_string());
|
||||
socket
|
||||
.write_all(
|
||||
b"HTTP/1.1 201 Created\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
lines
|
||||
});
|
||||
let http = HttpTransport::new();
|
||||
for fsync in [true, false] {
|
||||
http.write_synced(&address, "7,abc", "", "k", Bytes::from_static(b"kv"), fsync)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
server.await.unwrap(),
|
||||
["POST /7,abc?fsync=true HTTP/1.1", "POST /7,abc HTTP/1.1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A write that never reached the server (connection refused) is a plain
|
||||
/// error, not an ambiguous commit.
|
||||
#[tokio::test]
|
||||
async fn write_that_never_connected_is_not_ambiguous() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed = listener.local_addr().unwrap().to_string();
|
||||
drop(listener);
|
||||
let error = HttpTransport::new()
|
||||
.write(&closed, "7,abc", "", "k", Bytes::from_static(b"kv"))
|
||||
.await
|
||||
.expect_err("nothing listens there");
|
||||
assert!(
|
||||
error.downcast_ref::<CommitAmbiguous>().is_none(),
|
||||
"{error:#}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Streaming write buffer: stages dirty file bytes per chunk so a flush can
|
||||
//! upload completed chunks incrementally and free them, keeping resident memory
|
||||
//! bounded (a few chunks) regardless of file size — instead of holding the whole
|
||||
//! file in RAM.
|
||||
//!
|
||||
//! Modelled on the SeaweedFS Go mount page writer (`weed/mount/page_writer`):
|
||||
//! dirty bytes are keyed by chunk index, a fully-written chunk is "sealed" and
|
||||
//! uploaded as an overlay `FileChunk` (newest wins by `modified_ts_ns` at read
|
||||
//! time, see [`crate::read::resolve_visibles`]), and reads merge committed
|
||||
//! chunks with the still-staged bytes.
|
||||
//!
|
||||
//! This type is pure (no I/O): the daemon drives the actual uploads. It tracks
|
||||
//! *which* bytes are dirty (per-chunk written intervals) so that a partially
|
||||
//! written chunk only ever uploads the bytes the caller actually wrote — never
|
||||
//! zero-filling a gap, which would clobber underlying committed data.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Dirty bytes for one chunk index. `data` is dense from offset 0; only the
|
||||
/// ranges listed in `intervals` (chunk-relative, merged, sorted, non-adjacent)
|
||||
/// hold caller-written bytes.
|
||||
struct StagedChunk {
|
||||
data: Vec<u8>,
|
||||
intervals: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl StagedChunk {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
data: Vec::new(),
|
||||
intervals: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `[lo, hi)` written, coalescing with touching/overlapping intervals.
|
||||
fn mark(&mut self, lo: usize, hi: usize) {
|
||||
let mut merged = (lo, hi);
|
||||
let mut out: Vec<(usize, usize)> = Vec::with_capacity(self.intervals.len() + 1);
|
||||
for &(s, e) in &self.intervals {
|
||||
if e < merged.0 || s > merged.1 {
|
||||
out.push((s, e)); // disjoint (note: adjacent merges, hence >/<)
|
||||
} else {
|
||||
merged.0 = merged.0.min(s);
|
||||
merged.1 = merged.1.max(e);
|
||||
}
|
||||
}
|
||||
out.push(merged);
|
||||
out.sort_unstable();
|
||||
self.intervals = out;
|
||||
}
|
||||
|
||||
/// True if `[0, n)` is covered by a single interval.
|
||||
fn covers(&self, n: usize) -> bool {
|
||||
matches!(self.intervals.first(), Some(&(0, e)) if e >= n) && self.intervals.len() == 1
|
||||
}
|
||||
}
|
||||
|
||||
/// A contiguous run of staged bytes ready to upload as one overlay chunk.
|
||||
pub struct SealPiece {
|
||||
/// Chunk index this run belongs to (for [`StreamingWriteBuffer::drop_chunk`]).
|
||||
pub chunk_index: u64,
|
||||
/// Absolute file offset of the run.
|
||||
pub offset: u64,
|
||||
/// The written bytes.
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Per-file streaming write buffer. Stages dirty bytes by chunk index and tracks
|
||||
/// the logical file size; the daemon seals chunks (uploads + [`drop_chunk`]s) to
|
||||
/// keep resident memory bounded.
|
||||
///
|
||||
/// [`drop_chunk`]: StreamingWriteBuffer::drop_chunk
|
||||
pub struct StreamingWriteBuffer {
|
||||
chunk_size: usize,
|
||||
staged: BTreeMap<u64, StagedChunk>,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl StreamingWriteBuffer {
|
||||
pub fn new(chunk_size: usize) -> Self {
|
||||
Self::with_size(chunk_size, 0)
|
||||
}
|
||||
|
||||
/// Construct with an initial logical size — the existing size of a file being
|
||||
/// modified, so getattr/read report it before any write grows the buffer.
|
||||
pub fn with_size(chunk_size: usize, size: u64) -> Self {
|
||||
assert!(chunk_size > 0);
|
||||
Self {
|
||||
chunk_size,
|
||||
staged: BTreeMap::new(),
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Logical file size (max of all writes / truncates).
|
||||
pub fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
|
||||
/// Total bytes currently staged in memory (the resident-memory pressure).
|
||||
pub fn staged_len(&self) -> usize {
|
||||
self.staged.values().map(|c| c.data.len()).sum()
|
||||
}
|
||||
|
||||
/// No staged bytes remain (everything sealed/uploaded).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.staged.is_empty()
|
||||
}
|
||||
|
||||
/// Stage `data` written at absolute `offset`, splitting across chunk
|
||||
/// boundaries. Grows the logical size to cover the write.
|
||||
pub fn write(&mut self, offset: u64, data: &[u8]) {
|
||||
if data.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut off = offset;
|
||||
let mut rest = data;
|
||||
let cs = self.chunk_size as u64;
|
||||
while !rest.is_empty() {
|
||||
let idx = off / cs;
|
||||
let chunk_start = idx * cs;
|
||||
let in_chunk = (off - chunk_start) as usize;
|
||||
let take = rest.len().min(self.chunk_size - in_chunk);
|
||||
let chunk = self.staged.entry(idx).or_insert_with(StagedChunk::new);
|
||||
let end = in_chunk + take;
|
||||
if chunk.data.len() < end {
|
||||
chunk.data.resize(end, 0);
|
||||
}
|
||||
chunk.data[in_chunk..end].copy_from_slice(&rest[..take]);
|
||||
chunk.mark(in_chunk, end);
|
||||
off += take as u64;
|
||||
rest = &rest[take..];
|
||||
}
|
||||
self.size = self.size.max(offset.saturating_add(data.len() as u64));
|
||||
}
|
||||
|
||||
/// Resize the logical file to `new_size`. Shrinking drops staged bytes beyond
|
||||
/// the new end; growing leaves a hole (reads return zeros there).
|
||||
pub fn truncate(&mut self, new_size: u64) {
|
||||
if new_size < self.size {
|
||||
let cs = self.chunk_size as u64;
|
||||
self.staged.retain(|&idx, _| idx * cs < new_size);
|
||||
if let Some((&idx, chunk)) = self.staged.range_mut(..).next_back() {
|
||||
let chunk_start = idx * cs;
|
||||
if chunk_start < new_size && new_size < chunk_start + cs {
|
||||
let keep = (new_size - chunk_start) as usize;
|
||||
if chunk.data.len() > keep {
|
||||
chunk.data.truncate(keep);
|
||||
}
|
||||
chunk.intervals.retain_mut(|iv| {
|
||||
iv.1 = iv.1.min(keep);
|
||||
iv.0 < iv.1
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
self.size = new_size;
|
||||
}
|
||||
|
||||
/// Overlay still-staged bytes onto `out` (which the caller pre-filled with
|
||||
/// committed data) for the read window starting at absolute `offset`.
|
||||
pub fn overlay_read(&self, offset: u64, out: &mut [u8]) {
|
||||
let want_start = offset;
|
||||
let want_end = offset + out.len() as u64;
|
||||
let cs = self.chunk_size as u64;
|
||||
for (&idx, chunk) in &self.staged {
|
||||
let chunk_start = idx * cs;
|
||||
if chunk_start >= want_end || chunk_start + cs <= want_start {
|
||||
continue;
|
||||
}
|
||||
for &(lo, hi) in &chunk.intervals {
|
||||
let abs_lo = chunk_start + lo as u64;
|
||||
let abs_hi = chunk_start + hi as u64;
|
||||
let s = abs_lo.max(want_start);
|
||||
let e = abs_hi.min(want_end);
|
||||
if s < e {
|
||||
let dst = (s - want_start) as usize..(e - want_start) as usize;
|
||||
let src = (s - chunk_start) as usize..(e - chunk_start) as usize;
|
||||
out[dst].copy_from_slice(&chunk.data[src]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Indices of chunks fully covering `[0, chunk_size)` — safe to seal eagerly
|
||||
/// while writing so memory stays bounded. The final short chunk is excluded
|
||||
/// (it only seals at flush via [`drain_all`]).
|
||||
///
|
||||
/// [`drain_all`]: StreamingWriteBuffer::drain_all
|
||||
pub fn full_chunk_indices(&self) -> Vec<u64> {
|
||||
self.staged
|
||||
.iter()
|
||||
.filter(|(_, c)| c.covers(self.chunk_size))
|
||||
.map(|(&idx, _)| idx)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The lowest staged chunk index (for pressure-sealing a partial chunk).
|
||||
pub fn lowest_index(&self) -> Option<u64> {
|
||||
self.staged.keys().next().copied()
|
||||
}
|
||||
|
||||
/// Every staged chunk index (used on flush to seal all that remain).
|
||||
pub fn staged_indices(&self) -> Vec<u64> {
|
||||
self.staged.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Upload pieces for one chunk: one [`SealPiece`] per contiguous written
|
||||
/// interval (so gaps are never zero-filled). Does NOT remove the chunk —
|
||||
/// call [`drop_chunk`] once the uploads are confirmed, so a concurrent read
|
||||
/// still sees the bytes while they are in flight.
|
||||
///
|
||||
/// [`drop_chunk`]: StreamingWriteBuffer::drop_chunk
|
||||
pub fn pieces_for(&self, idx: u64) -> Vec<SealPiece> {
|
||||
let cs = self.chunk_size as u64;
|
||||
let chunk_start = idx * cs;
|
||||
match self.staged.get(&idx) {
|
||||
Some(chunk) => chunk
|
||||
.intervals
|
||||
.iter()
|
||||
.map(|&(lo, hi)| SealPiece {
|
||||
chunk_index: idx,
|
||||
offset: chunk_start + lo as u64,
|
||||
data: chunk.data[lo..hi].to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces for every staged chunk (used on flush to seal the partial tail).
|
||||
pub fn drain_all(&self) -> Vec<SealPiece> {
|
||||
self.staged
|
||||
.keys()
|
||||
.flat_map(|&idx| self.pieces_for(idx))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Forget a chunk's staged bytes once its pieces have been uploaded.
|
||||
pub fn drop_chunk(&mut self, idx: u64) {
|
||||
self.staged.remove(&idx);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CS: usize = 4 * 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn sequential_fills_seal_eagerly() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
// Three full chunks written in 1 MiB pieces, then a short tail.
|
||||
for i in 0..(3 * 4) {
|
||||
b.write(i as u64 * (1 << 20), &vec![1u8; 1 << 20]);
|
||||
}
|
||||
b.write(3 * CS as u64, &vec![2u8; 1000]);
|
||||
assert_eq!(b.size(), 3 * CS as u64 + 1000);
|
||||
// Chunks 0,1,2 are full; the tail (chunk 3) is not.
|
||||
assert_eq!(b.full_chunk_indices(), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_chunk_pieces_are_single_run() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(0, &vec![7u8; CS]);
|
||||
let pieces = b.pieces_for(0);
|
||||
assert_eq!(pieces.len(), 1);
|
||||
assert_eq!(pieces[0].offset, 0);
|
||||
assert_eq!(pieces[0].data.len(), CS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_chunk_uploads_only_written_intervals() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
// Two disjoint runs in chunk 0, with a gap between them.
|
||||
b.write(0, &[0xaa; 100]);
|
||||
b.write(1_000_000, &[0xbb; 50]);
|
||||
assert!(b.full_chunk_indices().is_empty()); // not fully covered
|
||||
let pieces = b.pieces_for(0);
|
||||
assert_eq!(pieces.len(), 2);
|
||||
assert_eq!((pieces[0].offset, pieces[0].data.len()), (0, 100));
|
||||
assert_eq!((pieces[1].offset, pieces[1].data.len()), (1_000_000, 50));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_write_past_the_end_keeps_the_size() {
|
||||
let mut b = StreamingWriteBuffer::with_size(CS, 10);
|
||||
b.write(1000, &[]);
|
||||
assert_eq!(b.size(), 10);
|
||||
assert!(b.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touching_writes_coalesce() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(0, &[1u8; 100]);
|
||||
b.write(100, &[1u8; 100]); // adjacent -> one interval
|
||||
assert_eq!(b.pieces_for(0).len(), 1);
|
||||
assert_eq!(b.pieces_for(0)[0].data.len(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_read_overwrites_committed() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(10, &[0xfe; 4]);
|
||||
let mut out = vec![0u8; 20]; // pretend committed data is all zeros
|
||||
b.overlay_read(0, &mut out);
|
||||
let mut want = vec![0u8; 20];
|
||||
want[10..14].fill(0xfe);
|
||||
assert_eq!(out, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_read_partial_window() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(CS as u64 - 2, &[9u8; 4]); // straddles chunk boundary
|
||||
let mut out = vec![0u8; 4];
|
||||
b.overlay_read(CS as u64 - 2, &mut out);
|
||||
assert_eq!(out, vec![9u8; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_shrinks_and_drops() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(0, &vec![1u8; CS + 100]); // chunk 0 full + 100 into chunk 1
|
||||
b.truncate(CS as u64 + 10);
|
||||
assert_eq!(b.size(), CS as u64 + 10);
|
||||
let p = b.pieces_for(1);
|
||||
assert_eq!(p.len(), 1);
|
||||
assert_eq!(p[0].data.len(), 10);
|
||||
b.truncate(5);
|
||||
assert!(b.pieces_for(1).is_empty());
|
||||
assert_eq!(b.pieces_for(0)[0].data.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_chunk_frees_memory() {
|
||||
let mut b = StreamingWriteBuffer::new(CS);
|
||||
b.write(0, &vec![1u8; CS]);
|
||||
b.write(CS as u64, &vec![1u8; 1000]);
|
||||
assert_eq!(b.staged_len(), CS + 1000);
|
||||
b.drop_chunk(0);
|
||||
assert_eq!(b.staged_len(), 1000);
|
||||
assert_eq!(b.lowest_index(), Some(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
//! Data plane (write): upload file content as immutable chunks and persist the
|
||||
//! chunk list on the filer.
|
||||
//!
|
||||
//! Phase B2 uses a simple whole-file model: the daemon buffers a file's content
|
||||
//! and, on flush, re-uploads it as `chunk_size`-sized chunks and replaces the
|
||||
//! entry's chunk list. Correct for sequential writes and full overwrites; an
|
||||
//! incremental/append-merge pipeline is a later optimisation.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use bytes::Bytes;
|
||||
|
||||
use crate::filer::{AssignVolumeOptions, Assignment, FilerClient};
|
||||
use crate::filer_pb::{Entry, FileChunk};
|
||||
use crate::transport::{HttpTransport, VolumeTransport};
|
||||
use crate::wbuf::SealPiece;
|
||||
|
||||
/// Current Unix time as (seconds, nanoseconds).
|
||||
pub fn now_unix() -> (i64, i32) {
|
||||
let d = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
(d.as_secs() as i64, d.subsec_nanos() as i32)
|
||||
}
|
||||
|
||||
/// Current Unix time in nanoseconds.
|
||||
pub fn now_ns() -> i64 {
|
||||
let d = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
d.as_nanos() as i64
|
||||
}
|
||||
|
||||
/// Max chunk uploads in flight per flush (bounds load on the filer/volumes).
|
||||
const MAX_PARALLEL_UPLOADS: usize = 8;
|
||||
|
||||
/// Uploads chunk data to volume servers via a pluggable [`VolumeTransport`]
|
||||
/// (HTTP by default; RDMA later). Volume assignment stays on the filer.
|
||||
/// Cheap to clone (shares the transport) so a flush can upload chunks in parallel.
|
||||
#[derive(Clone)]
|
||||
pub struct Writer {
|
||||
transport: Arc<dyn VolumeTransport>,
|
||||
}
|
||||
|
||||
impl Default for Writer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub fn new() -> Self {
|
||||
Self::with_transport(Arc::new(HttpTransport::new()))
|
||||
}
|
||||
|
||||
/// Construct with a specific data-plane transport (e.g. an RDMA transport).
|
||||
pub fn with_transport(transport: Arc<dyn VolumeTransport>) -> Self {
|
||||
Self { transport }
|
||||
}
|
||||
|
||||
/// Assign a volume, upload `data` as one needle, and return the resulting
|
||||
/// `FileChunk` positioned at `offset` in the file.
|
||||
pub async fn upload_chunk(
|
||||
&self,
|
||||
client: &mut FilerClient,
|
||||
file_path: &str,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: &[u8],
|
||||
) -> Result<FileChunk> {
|
||||
self.upload_chunk_with_options(
|
||||
client,
|
||||
file_path,
|
||||
filename,
|
||||
offset,
|
||||
data,
|
||||
&AssignVolumeOptions::default(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_chunk_with_options(
|
||||
&self,
|
||||
client: &mut FilerClient,
|
||||
file_path: &str,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: &[u8],
|
||||
options: &AssignVolumeOptions,
|
||||
) -> Result<FileChunk> {
|
||||
self.upload_chunk_with_options_bytes(
|
||||
client,
|
||||
file_path,
|
||||
filename,
|
||||
offset,
|
||||
Bytes::copy_from_slice(data),
|
||||
options,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_chunk_with_options_bytes(
|
||||
&self,
|
||||
client: &mut FilerClient,
|
||||
file_path: &str,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: Bytes,
|
||||
options: &AssignVolumeOptions,
|
||||
) -> Result<FileChunk> {
|
||||
let size = data.len() as u64;
|
||||
let first = client
|
||||
.assign_volume_with_options(file_path, size, options)
|
||||
.await?;
|
||||
upload_reassigning_once(
|
||||
first,
|
||||
data,
|
||||
|assign, data| async move {
|
||||
self.upload_assigned_chunk_bytes(&assign, filename, offset, data)
|
||||
.await
|
||||
},
|
||||
|| client.assign_volume_with_options(file_path, size, options),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Upload to a volume assignment that has already been resolved by the
|
||||
/// filer. This is the data-plane seam: HTTP/RDMA details live only in the
|
||||
/// transport implementation, while assignment and filer metadata stay above.
|
||||
pub async fn upload_assigned_chunk(
|
||||
&self,
|
||||
assign: &Assignment,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: &[u8],
|
||||
) -> Result<FileChunk> {
|
||||
self.upload_assigned_chunk_bytes(assign, filename, offset, Bytes::copy_from_slice(data))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_assigned_chunk_bytes(
|
||||
&self,
|
||||
assign: &Assignment,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: Bytes,
|
||||
) -> Result<FileChunk> {
|
||||
self.upload_assigned_chunk_bytes_with_receipt(assign, filename, offset, data)
|
||||
.await
|
||||
.map(|(chunk, _)| chunk)
|
||||
}
|
||||
|
||||
pub async fn upload_assigned_chunk_bytes_with_receipt(
|
||||
&self,
|
||||
assign: &Assignment,
|
||||
filename: &str,
|
||||
offset: i64,
|
||||
data: Bytes,
|
||||
) -> Result<(FileChunk, crate::VolumeWriteReceipt)> {
|
||||
let size = data.len() as u64;
|
||||
let receipt = self
|
||||
.transport
|
||||
.write_synced(
|
||||
&assign.url,
|
||||
&assign.file_id,
|
||||
&assign.auth,
|
||||
filename,
|
||||
data,
|
||||
assign.fsync,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("upload {} to {}", assign.file_id, assign.url))?;
|
||||
|
||||
Ok((
|
||||
FileChunk {
|
||||
file_id: assign.file_id.clone(),
|
||||
offset,
|
||||
size,
|
||||
modified_ts_ns: now_ns(),
|
||||
..Default::default()
|
||||
},
|
||||
receipt,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads under `first`; if the Volume refused before committing anything
|
||||
/// (e.g. it was sealed for rotation after the assignment), asks `reassign` for
|
||||
/// one fresh assignment and uploads once more. Any other result, a commit with
|
||||
/// an unknown outcome included, returns as is, so nothing is written twice.
|
||||
async fn upload_reassigning_once<U, UF, A, AF>(
|
||||
first: Assignment,
|
||||
data: Bytes,
|
||||
upload: U,
|
||||
reassign: A,
|
||||
) -> Result<FileChunk>
|
||||
where
|
||||
U: Fn(Assignment, Bytes) -> UF,
|
||||
UF: std::future::Future<Output = Result<FileChunk>>,
|
||||
A: FnOnce() -> AF,
|
||||
AF: std::future::Future<Output = Result<Assignment>>,
|
||||
{
|
||||
match upload(first, data.clone()).await {
|
||||
Err(error) if crate::is_not_written(&error) => upload(reassign().await?, data).await,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Upload a batch of staged write pieces concurrently (bounded), each as one
|
||||
/// overlay needle at its file offset. Returns the resulting `FileChunk`s sorted
|
||||
/// by file offset. Used
|
||||
/// by the streaming write path to seal chunks incrementally without holding the
|
||||
/// whole file in memory.
|
||||
pub async fn upload_pieces(
|
||||
client: &FilerClient,
|
||||
writer: &Writer,
|
||||
file_path: &str,
|
||||
filename: &str,
|
||||
pieces: Vec<SealPiece>,
|
||||
) -> Result<Vec<FileChunk>> {
|
||||
upload_pieces_with_options(
|
||||
client,
|
||||
writer,
|
||||
file_path,
|
||||
filename,
|
||||
pieces,
|
||||
&AssignVolumeOptions::default(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_pieces_with_options(
|
||||
client: &FilerClient,
|
||||
writer: &Writer,
|
||||
file_path: &str,
|
||||
filename: &str,
|
||||
pieces: Vec<SealPiece>,
|
||||
options: &AssignVolumeOptions,
|
||||
) -> Result<Vec<FileChunk>> {
|
||||
let sem = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_UPLOADS));
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for p in pieces {
|
||||
let permit = sem.clone().acquire_owned().await.expect("semaphore open");
|
||||
let mut c = client.clone();
|
||||
let w = writer.clone();
|
||||
let fp = file_path.to_string();
|
||||
let name = filename.to_string();
|
||||
let opts = options.clone();
|
||||
set.spawn(async move {
|
||||
let _permit = permit;
|
||||
w.upload_chunk_with_options_bytes(
|
||||
&mut c,
|
||||
&fp,
|
||||
&name,
|
||||
p.offset as i64,
|
||||
Bytes::from(p.data),
|
||||
&opts,
|
||||
)
|
||||
.await
|
||||
});
|
||||
}
|
||||
let mut out = Vec::with_capacity(set.len());
|
||||
while let Some(joined) = set.join_next().await {
|
||||
out.push(joined.context("piece upload task")??);
|
||||
}
|
||||
out.sort_by(|a, b| {
|
||||
(a.offset, a.modified_ts_ns)
|
||||
.cmp(&(b.offset, b.modified_ts_ns))
|
||||
.then_with(|| a.file_id.cmp(&b.file_id))
|
||||
});
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Flush a full-file buffer: upload it as `chunk_size` chunks and `UpdateEntry`
|
||||
/// with the new chunk list and size/mtime. The entry is mutated in place.
|
||||
///
|
||||
/// `data` is taken as a shared `Arc` (not a slice) so the caller's in-memory
|
||||
/// write buffer is uploaded in place — no extra full-file copy. With a large
|
||||
/// file this is the difference between ~1x and ~3x its size in resident memory.
|
||||
pub async fn flush_file(
|
||||
client: &mut FilerClient,
|
||||
writer: &Writer,
|
||||
directory: &str,
|
||||
entry: &mut Entry,
|
||||
data: Arc<Vec<u8>>,
|
||||
chunk_size: usize,
|
||||
signature: i32,
|
||||
) -> Result<()> {
|
||||
let file_path = if directory == "/" {
|
||||
format!("/{}", entry.name)
|
||||
} else {
|
||||
format!("{directory}/{}", entry.name)
|
||||
};
|
||||
|
||||
// Upload chunks concurrently (bounded), preserving order in the chunk list.
|
||||
// FilerClient/Writer are cheap clones (h2 multiplexes), so parallel uploads
|
||||
// overlap their AssignVolume + needle-POST round-trips.
|
||||
anyhow::ensure!(chunk_size > 0, "flushing {file_path}: chunk size is zero");
|
||||
let n = data.len().div_ceil(chunk_size);
|
||||
let shared = data;
|
||||
let sem = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_UPLOADS));
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for i in 0..n {
|
||||
let start = i * chunk_size;
|
||||
let end = (start + chunk_size).min(shared.len());
|
||||
let permit = sem.clone().acquire_owned().await.expect("semaphore open");
|
||||
let mut c = client.clone();
|
||||
let w = writer.clone();
|
||||
let d = shared.clone();
|
||||
let fp = file_path.clone();
|
||||
let name = entry.name.clone();
|
||||
set.spawn(async move {
|
||||
let _permit = permit;
|
||||
let r = w
|
||||
.upload_chunk(&mut c, &fp, &name, start as i64, &d[start..end])
|
||||
.await;
|
||||
(i, r)
|
||||
});
|
||||
}
|
||||
let mut slots: Vec<Option<FileChunk>> = (0..n).map(|_| None).collect();
|
||||
while let Some(joined) = set.join_next().await {
|
||||
let (i, r) = joined.context("chunk upload task")?;
|
||||
slots[i] = Some(r?);
|
||||
}
|
||||
|
||||
entry.chunks = slots
|
||||
.into_iter()
|
||||
.map(|c| c.expect("all chunks uploaded"))
|
||||
.collect();
|
||||
// Small-file inline content from a previous version no longer applies.
|
||||
entry.content = Vec::new();
|
||||
if let Some(a) = entry.attributes.as_mut() {
|
||||
a.file_size = shared.len() as u64;
|
||||
let (sec, nsec) = now_unix();
|
||||
a.mtime = sec;
|
||||
a.mtime_ns = nsec;
|
||||
}
|
||||
|
||||
client
|
||||
.update_entry(directory, entry.clone(), signature)
|
||||
.await
|
||||
.context("persisting chunk list")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn assignment(fid: &str) -> Assignment {
|
||||
Assignment {
|
||||
file_id: fid.to_string(),
|
||||
url: "10.0.2.3:19601".to_string(),
|
||||
auth: String::new(),
|
||||
fsync: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn chunk(fid: &str, data: &Bytes) -> FileChunk {
|
||||
FileChunk {
|
||||
file_id: fid.to_string(),
|
||||
size: data.len() as u64,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the helper with an upload that answers from `answers` in order
|
||||
/// and a reassign that returns `fresh`; reports the chunk and the calls.
|
||||
async fn reassign_run(
|
||||
answers: Vec<&'static str>,
|
||||
fresh: Result<Assignment>,
|
||||
) -> (Result<FileChunk>, Vec<(String, Vec<u8>)>, bool) {
|
||||
let answers = Mutex::new(answers.into_iter());
|
||||
let uploads = Mutex::new(Vec::new());
|
||||
let reassigned = Mutex::new(false);
|
||||
let result = upload_reassigning_once(
|
||||
assignment("38,a1"),
|
||||
Bytes::from_static(b"kv-bytes"),
|
||||
|assign, data| {
|
||||
uploads
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((assign.file_id.clone(), data.to_vec()));
|
||||
let answer = answers.lock().unwrap().next().unwrap();
|
||||
async move {
|
||||
match answer {
|
||||
"ok" => Ok(chunk(&assign.file_id, &data)),
|
||||
"refused" => Err(anyhow::anyhow!("prepare rejected")
|
||||
.context(crate::NotWritten)
|
||||
.context("upload")),
|
||||
_ => {
|
||||
Err(anyhow::anyhow!("commit timed out").context(crate::CommitAmbiguous))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|| {
|
||||
*reassigned.lock().unwrap() = true;
|
||||
async move { fresh }
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let uploads = uploads.into_inner().unwrap();
|
||||
(result, uploads, reassigned.into_inner().unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_write_is_uploaded_once_more_under_a_fresh_assignment() {
|
||||
let (result, uploads, reassigned) =
|
||||
reassign_run(vec!["refused", "ok"], Ok(assignment("41,b2"))).await;
|
||||
assert!(reassigned);
|
||||
assert_eq!(result.unwrap().file_id, "41,b2");
|
||||
assert_eq!(
|
||||
uploads,
|
||||
vec![
|
||||
("38,a1".to_string(), b"kv-bytes".to_vec()),
|
||||
("41,b2".to_string(), b"kv-bytes".to_vec()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_zero_chunk_size_is_an_error() {
|
||||
let mut client = FilerClient::connect_lazy("127.0.0.1:1").unwrap();
|
||||
let mut entry = Entry {
|
||||
name: "f".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let err = flush_file(
|
||||
&mut client,
|
||||
&Writer::new(),
|
||||
"/d",
|
||||
&mut entry,
|
||||
Arc::new(vec![1; 8]),
|
||||
0,
|
||||
0,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{err:#}").contains("chunk size is zero"), "{err:#}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_retry_happens_at_most_once() {
|
||||
let (result, uploads, _) =
|
||||
reassign_run(vec!["refused", "refused"], Ok(assignment("41,b2"))).await;
|
||||
assert!(crate::is_not_written(&result.unwrap_err()));
|
||||
assert_eq!(uploads.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ambiguous_commit_is_never_retried() {
|
||||
let (result, uploads, reassigned) =
|
||||
reassign_run(vec!["ambiguous"], Ok(assignment("41,b2"))).await;
|
||||
assert!(result.is_err());
|
||||
assert!(!reassigned);
|
||||
assert_eq!(uploads.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_reassignment_returns_its_error_without_a_second_upload() {
|
||||
let (result, uploads, reassigned) =
|
||||
reassign_run(vec!["refused"], Err(anyhow::anyhow!("no writable volumes"))).await;
|
||||
assert!(reassigned);
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("no writable volumes")
|
||||
);
|
||||
assert_eq!(uploads.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_success_is_not_retried() {
|
||||
let (result, uploads, reassigned) = reassign_run(vec!["ok"], Ok(assignment("41,b2"))).await;
|
||||
assert_eq!(result.unwrap().file_id, "38,a1");
|
||||
assert!(!reassigned);
|
||||
assert_eq!(uploads.len(), 1);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct WriteCall {
|
||||
location: String,
|
||||
file_id: String,
|
||||
auth: String,
|
||||
filename: String,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockTransport {
|
||||
writes: Mutex<Vec<WriteCall>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VolumeTransport for MockTransport {
|
||||
async fn read(
|
||||
&self,
|
||||
_locations: &[String],
|
||||
_file_id: &str,
|
||||
_range: Option<(u64, u64)>,
|
||||
) -> Result<Vec<u8>> {
|
||||
anyhow::bail!("read is not used by write tests")
|
||||
}
|
||||
|
||||
async fn write(
|
||||
&self,
|
||||
location: &str,
|
||||
file_id: &str,
|
||||
auth: &str,
|
||||
filename: &str,
|
||||
data: Bytes,
|
||||
) -> Result<()> {
|
||||
self.writes.lock().unwrap().push(WriteCall {
|
||||
location: location.to_string(),
|
||||
file_id: file_id.to_string(),
|
||||
auth: auth.to_string(),
|
||||
filename: filename.to_string(),
|
||||
data: data.to_vec(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"mock"
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assigned_chunk_upload_uses_volume_transport_only() {
|
||||
let transport = Arc::new(MockTransport::default());
|
||||
let writer = Writer::with_transport(transport.clone());
|
||||
let assign = Assignment {
|
||||
file_id: "7,abc".to_string(),
|
||||
url: "10.0.0.2:8080".to_string(),
|
||||
auth: "write-token".to_string(),
|
||||
fsync: false,
|
||||
};
|
||||
|
||||
let chunk = writer
|
||||
.upload_assigned_chunk(&assign, "part-0", 4096, b"needle-bytes")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(chunk.file_id, "7,abc");
|
||||
assert_eq!(chunk.offset, 4096);
|
||||
assert_eq!(chunk.size, 12);
|
||||
|
||||
let writes = transport.writes.lock().unwrap();
|
||||
assert_eq!(
|
||||
writes.as_slice(),
|
||||
[WriteCall {
|
||||
location: "10.0.0.2:8080".to_string(),
|
||||
file_id: "7,abc".to_string(),
|
||||
auth: "write-token".to_string(),
|
||||
filename: "part-0".to_string(),
|
||||
data: b"needle-bytes".to_vec(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -14,20 +14,10 @@ import (
|
||||
)
|
||||
|
||||
// TestDuckDBDeterministicLocationRead validates that DuckDB's iceberg
|
||||
// extension can resolve and scan a table that lives at the deterministic
|
||||
// <bucket>/<namespace>/<tableName> path produced when no client-side UUID
|
||||
// is appended to the table location. This is the layout produced by:
|
||||
//
|
||||
// - iceberg-spark (no concept of UUID-suffixed locations)
|
||||
// - pyiceberg (no concept of UUID-suffixed locations)
|
||||
// - Trino with iceberg.unique-table-location=false
|
||||
//
|
||||
// Post-#9246, REST clients can resolve table locations under a namespace
|
||||
// because GetNamespace advertises a default `location` property. This
|
||||
// test creates a namespace + table via the REST API directly (so no
|
||||
// client-side UUID is added), then asks DuckDB to ATTACH the catalog and
|
||||
// describe the table — verifying DuckDB walks the catalog → metadata →
|
||||
// schema chain successfully against a deterministic on-disk path.
|
||||
// extension can resolve and scan a table created through the REST API with no
|
||||
// location. The catalog gives such a table the directory
|
||||
// <bucket>/<namespace>/<tableName>-<uuid>, and DuckDB has to reach its
|
||||
// metadata and schema through the catalog rather than by the table's name.
|
||||
//
|
||||
// The test does not insert data files — DuckDB scanning an empty table
|
||||
// is sufficient to validate the catalog/metadata resolution path. If
|
||||
@@ -55,14 +45,11 @@ func TestDuckDBDeterministicLocationRead(t *testing.T) {
|
||||
createNamespaceWithToken(t, env, token, bucketName, namespace)
|
||||
createIcebergTableWithToken(t, env, token, bucketName, namespace, tableName)
|
||||
|
||||
// Sanity-check the catalog row exposes a deterministic location.
|
||||
// The table gets a directory of its own, named after it and its UUID.
|
||||
tableLoc := getTableLocation(t, env, token, bucketName, namespace, tableName)
|
||||
wantPrefix := fmt.Sprintf("s3://%s/%s/%s", bucketName, namespace, tableName)
|
||||
if !strings.HasPrefix(tableLoc, wantPrefix) {
|
||||
t.Fatalf("table location %q should start with %q (deterministic, no UUID suffix)", tableLoc, wantPrefix)
|
||||
}
|
||||
if strings.Contains(strings.TrimPrefix(tableLoc, wantPrefix), "-") {
|
||||
t.Fatalf("table location %q should not have a -<uuid> suffix after %q", tableLoc, wantPrefix)
|
||||
wantPrefix := fmt.Sprintf("s3://%s/%s/%s-", bucketName, namespace, tableName)
|
||||
if !strings.HasPrefix(tableLoc, wantPrefix) || strings.Contains(strings.TrimPrefix(tableLoc, wantPrefix), "/") {
|
||||
t.Fatalf("table location %q should be a directory %s<uuid>", tableLoc, wantPrefix)
|
||||
}
|
||||
|
||||
sqlContent := fmt.Sprintf(`
|
||||
|
||||
@@ -476,12 +476,24 @@ func (env *TestEnvironment) readTable(t *testing.T, mode string) string {
|
||||
|
||||
// listTableMetadata lists the table's metadata directory through the filer so
|
||||
// the repair assertion looks at real objects rather than at what the catalog
|
||||
// reports about itself.
|
||||
// reports about itself. A table created without a location sits in a
|
||||
// <table>-<uuid> directory, so every directory of the table's name is read.
|
||||
func (env *TestEnvironment) listTableMetadata(t *testing.T) []string {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/buckets/%s/%s/%s/metadata/?limit=200",
|
||||
env.bindIP, env.filerPort, tableBucketName, expectedNamespace, expectedTable)
|
||||
var names []string
|
||||
for _, dir := range env.listFilerDir(t, fmt.Sprintf("/buckets/%s/%s/", tableBucketName, expectedNamespace)) {
|
||||
if dir == expectedTable || strings.HasPrefix(dir, expectedTable+"-") {
|
||||
names = append(names, env.listFilerDir(t, fmt.Sprintf("/buckets/%s/%s/%s/metadata/", tableBucketName, expectedNamespace, dir))...)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func (env *TestEnvironment) listFilerDir(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d%s?limit=200", env.bindIP, env.filerPort, dir)
|
||||
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to build filer request: %v", err)
|
||||
@@ -494,6 +506,9 @@ func (env *TestEnvironment) listTableMetadata(t *testing.T) []string {
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
return nil
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("filer listing returned %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
@@ -13,11 +13,9 @@ import (
|
||||
|
||||
// TestSparkDeterministicLocationCTAS exercises Spark's iceberg-spark
|
||||
// connector against the SeaweedFS REST catalog with no explicit `LOCATION`
|
||||
// clause and no UUID-suffixing. iceberg-spark does not implement Trino's
|
||||
// unique-table-location feature, so every CREATE TABLE here produces a
|
||||
// deterministic <namespace-location>/<tableName> path. The test asserts
|
||||
// the fresh-CTAS pattern works AND the resulting on-disk layout has no
|
||||
// UUID-suffixed sibling — i.e. one directory per table.
|
||||
// clause. The catalog picks the location, <namespace>/<tableName>-<uuid>, and
|
||||
// the test asserts the fresh-CTAS pattern works and each table's files sit in
|
||||
// that one directory, none under the bare table name.
|
||||
//
|
||||
// The fix in #9246 (advertise a default `location` namespace property)
|
||||
// is what allows iceberg-spark to resolve the table location at all when
|
||||
@@ -82,13 +80,11 @@ print(f"ctas row count: {count}")
|
||||
}
|
||||
}
|
||||
|
||||
// Layout assertion: each table's data must land at the deterministic
|
||||
// <namespace>/<tableName>/ path, with no UUID-suffixed sibling.
|
||||
// Layout assertion: each table's files land in one <tableName>-<uuid>
|
||||
// directory, and nothing sits under the bare table name.
|
||||
keys := listSparkBucketKeysUnder(t, env, tableBucket, namespace+"/")
|
||||
expectKeyAtSparkLocation(t, keys, namespace, srcTable)
|
||||
expectKeyAtSparkLocation(t, keys, namespace, ctasTable)
|
||||
rejectUUIDSuffixedSparkSibling(t, keys, namespace, srcTable)
|
||||
rejectUUIDSuffixedSparkSibling(t, keys, namespace, ctasTable)
|
||||
expectKeysInOneSparkLocation(t, keys, namespace, srcTable)
|
||||
expectKeysInOneSparkLocation(t, keys, namespace, ctasTable)
|
||||
}
|
||||
|
||||
func listSparkBucketKeysUnder(t *testing.T, env *TestEnvironment, bucket, prefix string) []string {
|
||||
@@ -113,23 +109,18 @@ func listSparkBucketKeysUnder(t *testing.T, env *TestEnvironment, bucket, prefix
|
||||
return keys
|
||||
}
|
||||
|
||||
func expectKeyAtSparkLocation(t *testing.T, keys []string, namespace, table string) {
|
||||
func expectKeysInOneSparkLocation(t *testing.T, keys []string, namespace, table string) {
|
||||
t.Helper()
|
||||
want := namespace + "/" + table + "/"
|
||||
dirs := map[string]bool{}
|
||||
for _, k := range keys {
|
||||
if strings.HasPrefix(k, want) {
|
||||
return
|
||||
if strings.HasPrefix(k, namespace+"/"+table+"/") {
|
||||
t.Fatalf("found key %q under the bare table name %q", k, table)
|
||||
}
|
||||
if rest, ok := strings.CutPrefix(k, namespace+"/"+table+"-"); ok {
|
||||
dirs[strings.SplitN(rest, "/", 2)[0]] = true
|
||||
}
|
||||
}
|
||||
t.Fatalf("expected at least one object under %q; got keys: %v", want, keys)
|
||||
}
|
||||
|
||||
func rejectUUIDSuffixedSparkSibling(t *testing.T, keys []string, namespace, table string) {
|
||||
t.Helper()
|
||||
prefix := namespace + "/" + table + "-"
|
||||
for _, k := range keys {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
t.Fatalf("found UUID-suffixed sibling key %q for table %q (Spark should produce no -<uuid> suffix)", k, table)
|
||||
}
|
||||
if len(dirs) != 1 {
|
||||
t.Fatalf("want the files of %q in one %s-<uuid> directory, found %d; keys: %v", table, table, len(dirs), keys)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package catalog_spark
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
@@ -16,13 +17,14 @@ import (
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
)
|
||||
|
||||
// TestSparkRegisterTableServesItsData registers a table under a new name from
|
||||
// the current metadata file of another and checks that Spark reads the
|
||||
// registered rows and can write on top of them. One file is the one the
|
||||
// catalog wrote; the other is a copy uploaded through the S3 gateway, the way
|
||||
// the metadata of a table migrated in arrives, which the filer stores in
|
||||
// chunks rather than inline. A registered table used to load as an empty
|
||||
// placeholder: SELECT found no rows and INSERT failed its table UUID check.
|
||||
// TestSparkRegisterTableServesItsData registers a table from a copy of another
|
||||
// table's current metadata, uploaded through the S3 gateway into the new
|
||||
// table's own directory the way the metadata of a table migrated in arrives,
|
||||
// which the filer stores in chunks rather than inline, and checks that Spark
|
||||
// reads the registered rows and can write on top of them. A registered table
|
||||
// used to load as an empty placeholder: SELECT found no rows and INSERT failed
|
||||
// its table UUID check. The source's own file is refused under another name,
|
||||
// since both tables would then own the source's files.
|
||||
func TestSparkRegisterTableServesItsData(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
@@ -30,56 +32,63 @@ func TestSparkRegisterTableServesItsData(t *testing.T) {
|
||||
|
||||
env, _, tableBucket := setupSparkTestEnv(t)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
upload bool
|
||||
}{
|
||||
{"metadata file written by the catalog", false},
|
||||
{"metadata file uploaded through S3", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
namespace := "register_" + randomString(6)
|
||||
source := fmt.Sprintf("iceberg.%s.src_%s", namespace, randomString(6))
|
||||
table := "reg_" + randomString(6)
|
||||
ident := fmt.Sprintf("iceberg.%s.%s", namespace, table)
|
||||
|
||||
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
|
||||
namespace := "register_" + randomString(6)
|
||||
source := fmt.Sprintf("iceberg.%s.src_%s", namespace, randomString(6))
|
||||
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
|
||||
spark.sql("CREATE NAMESPACE iceberg.%[1]s")
|
||||
spark.sql("CREATE TABLE %[2]s (id INT, name STRING) USING iceberg")
|
||||
spark.sql("INSERT INTO %[2]s VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma')")
|
||||
meta = spark.sql("SELECT file FROM %[2]s.metadata_log_entries ORDER BY timestamp DESC LIMIT 1").collect()[0]['file']
|
||||
print(f"metadata file: {meta}")
|
||||
`, namespace, source), env.icebergRestPort, env.s3Port)
|
||||
match := regexp.MustCompile(`metadata file: (\S+)`).FindStringSubmatch(output)
|
||||
if match == nil {
|
||||
t.Fatalf("create/insert of %s failed, output:\n%s", source, output)
|
||||
}
|
||||
metadataFile := match[1]
|
||||
if tc.upload {
|
||||
metadataFile = uploadMetadataCopy(t, env, tableBucket, metadataFile)
|
||||
}
|
||||
match := regexp.MustCompile(`metadata file: (\S+)`).FindStringSubmatch(output)
|
||||
if match == nil {
|
||||
t.Fatalf("create/insert of %s failed, output:\n%s", source, output)
|
||||
}
|
||||
metadataFile := match[1]
|
||||
|
||||
output = runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
|
||||
t.Run("the source's own metadata file is refused", func(t *testing.T) {
|
||||
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
|
||||
try:
|
||||
spark.sql("CALL iceberg.system.register_table('%[1]s.alias_%[2]s', '%[3]s')")
|
||||
print("register accepted")
|
||||
except Exception as e:
|
||||
print(f"register refused: {e}")
|
||||
count = spark.sql("SELECT COUNT(*) AS c FROM %[4]s").collect()[0]['c']
|
||||
print(f"source row count: {count}")
|
||||
`, namespace, randomString(6), metadataFile, source), env.icebergRestPort, env.s3Port)
|
||||
if !strings.Contains(output, "register refused") || !strings.Contains(output, "location is in use") {
|
||||
t.Fatalf("registering %s under another name was not refused, output:\n%s", metadataFile, output)
|
||||
}
|
||||
if !strings.Contains(output, "source row count: 3") {
|
||||
t.Fatalf("the source lost its rows, output:\n%s", output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a copy uploaded under the new table's location", func(t *testing.T) {
|
||||
table := "reg_" + randomString(6)
|
||||
ident := fmt.Sprintf("iceberg.%s.%s", namespace, table)
|
||||
copied := uploadMetadataCopy(t, env, tableBucket, metadataFile, path.Join(namespace, table))
|
||||
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
|
||||
spark.sql("CALL iceberg.system.register_table('%[1]s.%[2]s', '%[3]s')")
|
||||
registered = spark.sql("SELECT COUNT(*) AS c FROM %[4]s").collect()[0]['c']
|
||||
print(f"registered row count: {registered}")
|
||||
spark.sql("INSERT INTO %[4]s VALUES (4, 'delta')")
|
||||
inserted = spark.sql("SELECT COUNT(*) AS c FROM %[4]s").collect()[0]['c']
|
||||
print(f"row count after insert: {inserted}")
|
||||
`, namespace, table, metadataFile, ident), env.icebergRestPort, env.s3Port)
|
||||
if !strings.Contains(output, "registered row count: 3") {
|
||||
t.Fatalf("the table registered from %s does not serve its rows, output:\n%s", metadataFile, output)
|
||||
}
|
||||
if !strings.Contains(output, "row count after insert: 4") {
|
||||
t.Fatalf("INSERT into the table registered from %s failed, output:\n%s", metadataFile, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
`, namespace, table, copied, ident), env.icebergRestPort, env.s3Port)
|
||||
if !strings.Contains(output, "registered row count: 3") {
|
||||
t.Fatalf("the table registered from %s does not serve its rows, output:\n%s", copied, output)
|
||||
}
|
||||
if !strings.Contains(output, "row count after insert: 4") {
|
||||
t.Fatalf("INSERT into the table registered from %s failed, output:\n%s", copied, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// uploadMetadataCopy puts a copy of metadataFile next to it through the S3
|
||||
// gateway and returns the copy's location.
|
||||
func uploadMetadataCopy(t *testing.T, env *TestEnvironment, bucket, metadataFile string) string {
|
||||
// uploadMetadataCopy puts a copy of metadataFile whose location is tableDir
|
||||
// under tableDir through the S3 gateway and returns the copy's location.
|
||||
func uploadMetadataCopy(t *testing.T, env *TestEnvironment, bucket, metadataFile, tableDir string) string {
|
||||
t.Helper()
|
||||
key, ok := strings.CutPrefix(metadataFile, "s3://"+bucket+"/")
|
||||
if !ok {
|
||||
@@ -104,8 +113,16 @@ func uploadMetadataCopy(t *testing.T, env *TestEnvironment, bucket, metadataFile
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", key, err)
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(content, &fields); err != nil {
|
||||
t.Fatalf("parse %s: %v", key, err)
|
||||
}
|
||||
fields["location"], _ = json.Marshal("s3://" + bucket + "/" + tableDir)
|
||||
if content, err = json.Marshal(fields); err != nil {
|
||||
t.Fatalf("encode %s: %v", key, err)
|
||||
}
|
||||
|
||||
copyKey := path.Join(path.Dir(key), "00003-uploaded.metadata.json")
|
||||
copyKey := path.Join(tableDir, "metadata", "00003-uploaded.metadata.json")
|
||||
if _, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(copyKey),
|
||||
|
||||
@@ -384,7 +384,15 @@ func runLakekeeperTableBucketRepro(t *testing.T, env *TestEnvironment) {
|
||||
t.Fatalf("Create S3 client failed: %v", err)
|
||||
}
|
||||
|
||||
objectKey := fmt.Sprintf("%s/%s/data/part-%d.parquet", namespaceName, tableName, time.Now().UnixNano())
|
||||
table, err := client.GetTable(ctx, bucketARN, namespaceName, tableName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTable failed: %v", err)
|
||||
}
|
||||
tableDir := strings.TrimPrefix(table.WarehouseLocation, "s3://"+bucketName+"/")
|
||||
if tableDir == "" || tableDir == table.WarehouseLocation {
|
||||
t.Fatalf("unexpected warehouse location %q", table.WarehouseLocation)
|
||||
}
|
||||
objectKey := fmt.Sprintf("%s/data/part-%d.parquet", tableDir, time.Now().UnixNano())
|
||||
createResp, err := s3Client.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
@@ -556,6 +564,18 @@ func (c *s3TablesClient) CreateTable(ctx context.Context, bucketARN, namespace,
|
||||
return c.doRequest(ctx, "CreateTable", http.MethodPut, path, req, nil)
|
||||
}
|
||||
|
||||
func (c *s3TablesClient) GetTable(ctx context.Context, bucketARN, namespace, name string) (*s3tables.GetTableResponse, error) {
|
||||
query := url.Values{}
|
||||
query.Set("tableBucketARN", bucketARN)
|
||||
query.Set("namespace", namespace)
|
||||
query.Set("name", name)
|
||||
var resp s3tables.GetTableResponse
|
||||
if err := c.doRequest(ctx, "GetTable", http.MethodGet, "/get-table?"+query.Encode(), nil, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (c *s3TablesClient) DeleteTable(ctx context.Context, bucketARN, namespace, name string) error {
|
||||
path := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(namespace) + "/" + url.PathEscape(name)
|
||||
return c.doRequest(ctx, "DeleteTable", http.MethodDelete, path, nil, nil)
|
||||
|
||||
@@ -101,6 +101,10 @@ type environment struct {
|
||||
lancePort int
|
||||
adminPort int
|
||||
|
||||
// The cluster's jwt.filer_signing.key, which the Lance namespace
|
||||
// authenticates the Rust worker by.
|
||||
clusterKey string
|
||||
|
||||
weedCancel context.CancelFunc
|
||||
weedCmd *exec.Cmd
|
||||
}
|
||||
@@ -159,6 +163,7 @@ func newEnvironment() (*environment, error) {
|
||||
icebergPort: ports[8],
|
||||
lancePort: ports[9],
|
||||
adminPort: adminPorts[0],
|
||||
clusterKey: randomSuffix() + randomSuffix(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -197,6 +202,7 @@ func (env *environment) start() error {
|
||||
cmd.Env = append(os.Environ(),
|
||||
"AWS_ACCESS_KEY_ID="+accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+secretKey,
|
||||
"WEED_JWT_FILER_SIGNING_KEY="+env.clusterKey,
|
||||
)
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
|
||||
@@ -83,13 +83,14 @@ func (env *environment) maintainLanceTable(t *testing.T, bucket, namespace, tabl
|
||||
cmd := exec.CommandContext(ctx, "cargo", "test",
|
||||
"-p", "weed-lance-worker", "--test", "lifecycle", "--", "--nocapture")
|
||||
cmd.Dir = filepath.Join(env.rootDir, "seaweed-worker")
|
||||
// The worker keeps the table through the filers and volume servers the
|
||||
// masters name, and the namespace knows it by the cluster key; it holds
|
||||
// no S3 credentials.
|
||||
cmd.Env = append(cmd.Environ(),
|
||||
fmt.Sprintf("WEED_LANCE_NAMESPACE=http://127.0.0.1:%d", env.lancePort),
|
||||
fmt.Sprintf("WEED_LANCE_TABLE=%s$%s$%s", bucket, namespace, table),
|
||||
"AWS_ACCESS_KEY_ID="+accessKey,
|
||||
"AWS_SECRET_ACCESS_KEY="+secretKey,
|
||||
"AWS_REGION=us-east-1",
|
||||
fmt.Sprintf("AWS_ENDPOINT_URL=http://127.0.0.1:%d", env.s3Port),
|
||||
fmt.Sprintf("WEED_MASTERS=127.0.0.1:%d.%d", env.masterPort, env.masterGrpcPort),
|
||||
"WEED_JWT_FILER_SIGNING_KEY="+env.clusterKey,
|
||||
)
|
||||
out, err := cmd.CombinedOutput()
|
||||
t.Logf("lance worker:\n%s", out)
|
||||
|
||||
@@ -336,6 +336,44 @@ func (c *S3TablesClient) DeleteTable(bucketARN string, namespace []string, name
|
||||
return c.doRestRequestAndDecode("DeleteTable", http.MethodDelete, path, nil, nil)
|
||||
}
|
||||
|
||||
// RenameTable renames a table through the AWS REST shape: the path names the
|
||||
// source and the body the destination, where an empty newNamespace or newName
|
||||
// keeps the source's. Any 2xx is success, as for the SDK (AWS answers 204).
|
||||
func (c *S3TablesClient) RenameTable(bucketARN string, namespace []string, name, newNamespace, newName, versionToken string) error {
|
||||
nameSpace, err := getFirstNamespace(namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("RenameTable requires namespace: %w", err)
|
||||
}
|
||||
body := map[string]string{}
|
||||
if newNamespace != "" {
|
||||
body["newNamespaceName"] = newNamespace
|
||||
}
|
||||
if newName != "" {
|
||||
body["newName"] = newName
|
||||
}
|
||||
if versionToken != "" {
|
||||
body["versionToken"] = versionToken
|
||||
}
|
||||
path := "/tables/" + url.PathEscape(bucketARN) + "/" + url.PathEscape(nameSpace) + "/" + url.PathEscape(name) + "/rename"
|
||||
resp, err := c.doRestRequest(http.MethodPut, path, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
bodyBytes, readErr := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
return nil
|
||||
}
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("RenameTable failed with status %d and could not read error response body: %v", resp.StatusCode, readErr)
|
||||
}
|
||||
var errResp s3tables.S3TablesError
|
||||
if err := json.Unmarshal(bodyBytes, &errResp); err != nil {
|
||||
return fmt.Errorf("RenameTable failed with status %d, could not decode error response: %v. Body: %s", resp.StatusCode, err, string(bodyBytes))
|
||||
}
|
||||
return fmt.Errorf("RenameTable failed: %s - %s", errResp.Type, errResp.Message)
|
||||
}
|
||||
|
||||
// Policy operations
|
||||
|
||||
func (c *S3TablesClient) PutTableBucketPolicy(bucketARN, policy string) error {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package s3tables
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
|
||||
// emptyObjectBucket deletes every object in bucket.
|
||||
func emptyObjectBucket(t *testing.T, ctx context.Context, client *s3.Client, bucket string) {
|
||||
t.Helper()
|
||||
pages := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{Bucket: aws.String(bucket)})
|
||||
for pages.HasMorePages() {
|
||||
page, err := pages.NextPage(ctx)
|
||||
require.NoError(t, err)
|
||||
for _, o := range page.Contents {
|
||||
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: o.Key})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The AWS SDK sends RenameTable as PUT /tables/<arn>/<ns>/<name>/rename. With
|
||||
// no route for it the gateway ran it as a PutObject into an S3 bucket named
|
||||
// "tables" and answered 2xx, so the rename reported success while the table
|
||||
// kept its old name. The bucket is created up front so that failure shows as
|
||||
// an object landing in it.
|
||||
func TestRenameTableREST(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
ctx := context.Background()
|
||||
tables := NewS3TablesClient(sharedCluster.s3Endpoint, testRegion, testAccessKey, testSecretKey)
|
||||
objects := newObjectClient(t)
|
||||
|
||||
const decoyBucket = "tables"
|
||||
if _, err := objects.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(decoyBucket)}); err != nil {
|
||||
require.Equal(t, "BucketAlreadyOwnedByYou", apiErrorCode(err), "create the %q bucket: %v", decoyBucket, err)
|
||||
}
|
||||
emptyObjectBucket(t, ctx, objects, decoyBucket)
|
||||
defer func() {
|
||||
emptyObjectBucket(t, ctx, objects, decoyBucket)
|
||||
_, _ = objects.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(decoyBucket)})
|
||||
}()
|
||||
|
||||
created, err := tables.CreateTableBucket("rename-rest-"+randomString(8), nil)
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteTableBucket(created.ARN)
|
||||
bucketARN := created.ARN
|
||||
|
||||
const namespace, otherNamespace = "rename_ns", "rename_other"
|
||||
for _, ns := range []string{namespace, otherNamespace} {
|
||||
_, err := tables.CreateNamespace(bucketARN, []string{ns})
|
||||
require.NoError(t, err)
|
||||
defer tables.DeleteNamespace(bucketARN, []string{ns})
|
||||
}
|
||||
|
||||
// Each subtest owns its source table, so any one of them runs alone.
|
||||
createSource := func(t *testing.T, name string) string {
|
||||
resp, err := tables.CreateTable(bucketARN, []string{namespace}, name, "ICEBERG", nil, nil)
|
||||
require.NoError(t, err)
|
||||
return resp.VersionToken
|
||||
}
|
||||
|
||||
t.Run("newName only", func(t *testing.T) {
|
||||
createSource(t, "src")
|
||||
defer tables.DeleteTable(bucketARN, []string{namespace}, "src")
|
||||
defer tables.DeleteTable(bucketARN, []string{namespace}, "dst")
|
||||
require.NoError(t, tables.RenameTable(bucketARN, []string{namespace}, "src", "", "dst", ""))
|
||||
|
||||
got, err := tables.GetTable(bucketARN, []string{namespace}, "dst")
|
||||
require.NoError(t, err, "the renamed table must resolve under its new name")
|
||||
assert.Equal(t, "dst", got.Name)
|
||||
|
||||
_, err = tables.GetTable(bucketARN, []string{namespace}, "src")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), s3tables.ErrCodeNoSuchTable)
|
||||
|
||||
list, err := objects.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(decoyBucket)})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, list.Contents, "the rename must not store anything in the %q bucket", decoyBucket)
|
||||
})
|
||||
|
||||
t.Run("stale versionToken", func(t *testing.T) {
|
||||
token := createSource(t, "stale_src")
|
||||
defer tables.DeleteTable(bucketARN, []string{namespace}, "stale_src")
|
||||
defer tables.DeleteTable(bucketARN, []string{otherNamespace}, "stale_moved")
|
||||
err := tables.RenameTable(bucketARN, []string{namespace}, "stale_src", otherNamespace, "stale_moved", token+"-stale")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), s3tables.ErrCodeConflict)
|
||||
|
||||
_, err = tables.GetTable(bucketARN, []string{namespace}, "stale_src")
|
||||
require.NoError(t, err, "a refused rename must leave the source in place")
|
||||
})
|
||||
|
||||
t.Run("newNamespaceName and newName with the current versionToken", func(t *testing.T) {
|
||||
token := createSource(t, "tok_src")
|
||||
defer tables.DeleteTable(bucketARN, []string{namespace}, "tok_src")
|
||||
defer tables.DeleteTable(bucketARN, []string{otherNamespace}, "moved")
|
||||
require.NoError(t, tables.RenameTable(bucketARN, []string{namespace}, "tok_src", otherNamespace, "moved", token))
|
||||
|
||||
got, err := tables.GetTable(bucketARN, []string{otherNamespace}, "moved")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "moved", got.Name)
|
||||
|
||||
_, err = tables.GetTable(bucketARN, []string{namespace}, "tok_src")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), s3tables.ErrCodeNoSuchTable)
|
||||
})
|
||||
}
|
||||
Loaded 100 of 440 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user