mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25896cf051 | ||
|
|
8cf8abf9f6 | ||
|
|
b62bbb99fc | ||
|
|
a816c6202c | ||
|
|
3fd8d0cf09 | ||
|
|
18691e7b5b | ||
|
|
9059cc2a07 | ||
|
|
b3d0caabe2 | ||
|
|
c2863d9a4f | ||
|
|
7a25983266 | ||
|
|
d5433ae745 | ||
|
|
9b3f09d0a5 | ||
|
|
afb8472c5e | ||
|
|
7d823265e5 | ||
|
|
2b7c65048d | ||
|
|
237db29dca | ||
|
|
190ab32cfb | ||
|
|
81879fba7b | ||
|
|
a2863bf83b | ||
|
|
67ce9a5f6d | ||
|
|
10ba1b782f | ||
|
|
b6851e561f | ||
|
|
3b65169d6c | ||
|
|
bb5375d2b9 | ||
|
|
89cc910a86 | ||
|
|
3a0af308ce | ||
|
|
1e9cc44697 | ||
|
|
f16f234c53 | ||
|
|
7b0e57eada | ||
|
|
a1f6621553 | ||
|
|
ef16b4ed02 | ||
|
|
5f26ef6ad1 | ||
|
|
6536fac9bd | ||
|
|
4c9e62177d | ||
|
|
660a826eab | ||
|
|
7a47c63d54 | ||
|
|
c46a42694b | ||
|
|
af77406cf9 | ||
|
|
a5036f568f | ||
|
|
5c14e566bc | ||
|
|
8557771fc2 | ||
|
|
80f3cc0613 | ||
|
|
d182be6a9e | ||
|
|
0ea818a44f | ||
|
|
b747e0d3b1 | ||
|
|
ee315527cb | ||
|
|
8379ee9251 | ||
|
|
bfb6e40fb4 | ||
|
|
67240f538d | ||
|
|
0f1e73cc3a | ||
|
|
e2d899ac25 |
No files matched your search
@@ -560,7 +560,7 @@ jobs:
|
||||
print("cluster alias: hook waits on the renamed names and the chart's addresses")
|
||||
|
||||
# Keys kept in a Secret are referenced, not inlined, so the hook
|
||||
# must render valueFrom for non-string extraEnvironmentVars.
|
||||
# must render valueFrom for map-valued extraEnvironmentVars.
|
||||
out = render(dict(jwt, **{
|
||||
"global.seaweedfs.extraEnvironmentVars.WEED_JWT_FILER_SIGNING_KEY.secretKeyRef.name": "signing-keys",
|
||||
"global.seaweedfs.extraEnvironmentVars.WEED_JWT_FILER_SIGNING_KEY.secretKeyRef.key": "filerWrite",
|
||||
@@ -636,12 +636,47 @@ jobs:
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.name=db \
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_PASSWORD.secretKeyRef.key=password > /tmp/filer-mysql-on-secret.yaml
|
||||
grep -A 4 -- "- name: WEED_MYSQL_PASSWORD$" /tmp/filer-mysql-on-secret.yaml | grep -q "name: db"
|
||||
# It replaces the db secret's entry rather than adding a second one, which
|
||||
# Helm 4's server-side apply rejects as a duplicate.
|
||||
test "$(grep -c -- "- name: WEED_MYSQL_PASSWORD$" /tmp/filer-mysql-on-secret.yaml)" -eq 1
|
||||
test "$(grep -c -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-on-secret.yaml)" -eq 1
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_USERNAME=app > /tmp/filer-mysql-on-plain.yaml
|
||||
test "$(grep -c -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-on-plain.yaml)" -eq 1
|
||||
grep -A 1 -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-on-plain.yaml | grep -q 'value: "app"'
|
||||
# Credentials render ahead of the merged vars so a $(...) reference resolves.
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_USERNAME=app \
|
||||
--set-string 'filer.extraEnvironmentVars.WEED_MYSQL_DSN=$(WEED_MYSQL_USERNAME)@tcp(h)/db' > /tmp/filer-mysql-dsn.yaml
|
||||
test "$(grep -n -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-dsn.yaml | cut -d: -f1)" -lt "$(grep -n -- "- name: WEED_MYSQL_DSN$" /tmp/filer-mysql-dsn.yaml | cut -d: -f1)"
|
||||
# Vars a credential's own $(...) references point at render before it.
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set-string filer.extraEnvironmentVars.DB_USER=app \
|
||||
--set-string 'filer.extraEnvironmentVars.WEED_MYSQL_USERNAME=$(DB_USER)' > /tmp/filer-mysql-ref.yaml
|
||||
test "$(grep -n -- "- name: DB_USER$" /tmp/filer-mysql-ref.yaml | cut -d: -f1)" -lt "$(grep -n -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-ref.yaml | cut -d: -f1)"
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set filer.secretExtraEnvironmentVars.DB_USER.secretKeyRef.name=db \
|
||||
--set filer.secretExtraEnvironmentVars.DB_USER.secretKeyRef.key=user \
|
||||
--set-string 'filer.extraEnvironmentVars.WEED_MYSQL_USERNAME=$(DB_USER)' > /tmp/filer-mysql-ref-secret.yaml
|
||||
test "$(grep -c -- "- name: DB_USER$" /tmp/filer-mysql-ref-secret.yaml)" -eq 1
|
||||
test "$(grep -n -- "- name: DB_USER$" /tmp/filer-mysql-ref-secret.yaml | cut -d: -f1)" -lt "$(grep -n -- "- name: WEED_MYSQL_USERNAME$" /tmp/filer-mysql-ref-secret.yaml | cut -d: -f1)"
|
||||
# A flag the chart cannot read counts as selected, not as off.
|
||||
helm template test $CHART_DIR \
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_ENABLED.secretKeyRef.name=store \
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_ENABLED.secretKeyRef.key=enabled > /tmp/filer-mysql-secret.yaml
|
||||
grep -q "name: test-seaweedfs-db-secret" /tmp/filer-mysql-secret.yaml
|
||||
grep -q "name: WEED_MYSQL_HOSTNAME" /tmp/filer-mysql-secret.yaml
|
||||
# A secret-backed key also replaces the matching plain entry, not adds one.
|
||||
test "$(grep -c -- "- name: WEED_MYSQL_ENABLED$" /tmp/filer-mysql-secret.yaml)" -eq 1
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_HOSTNAME.secretKeyRef.name=db \
|
||||
--set filer.secretExtraEnvironmentVars.WEED_MYSQL_HOSTNAME.secretKeyRef.key=host > /tmp/filer-mysql-hostname-secret.yaml
|
||||
test "$(grep -c -- "- name: WEED_MYSQL_HOSTNAME$" /tmp/filer-mysql-hostname-secret.yaml)" -eq 1
|
||||
helm template test $CHART_DIR \
|
||||
--set-string filer.extraEnvironmentVars.WEED_MYSQL2_HOSTNAME=other > /tmp/filer-mysql2.yaml
|
||||
grep -q "name: WEED_MYSQL2_HOSTNAME" /tmp/filer-mysql2.yaml
|
||||
@@ -1224,6 +1259,43 @@ jobs:
|
||||
print("all-in-one env: shared key renders once, component value wins")
|
||||
PYEOF
|
||||
|
||||
echo "=== Testing extraEnvironmentVars: numbers and booleans render as values ==="
|
||||
# Only a string rendered as value; anything else went to valueFrom, so an
|
||||
# unquoted 3306 or true in a values file (or --set) became "valueFrom: 3306"
|
||||
# and the API server rejected the workload. A map still renders valueFrom,
|
||||
# and a null still renders an empty variable. --set-json decodes numbers as
|
||||
# float64, as values files do, which quote would print as 1e+06.
|
||||
helm template test $CHART_DIR \
|
||||
--set-json global.seaweedfs.extraEnvironmentVars.WEED_GLOBAL_INT=1000000 \
|
||||
--set master.extraEnvironmentVars.WEED_MASTER_VOLUME_GROWTH_COPY_1=7 \
|
||||
--set master.extraEnvironmentVars.WEED_EMPTY=null \
|
||||
--set filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true \
|
||||
--set filer.extraEnvironmentVars.WEED_MYSQL_PORT=3306 \
|
||||
--set filer.extraEnvironmentVars.WEED_REF.secretKeyRef.name=s \
|
||||
--set filer.extraEnvironmentVars.WEED_REF.secretKeyRef.key=k > /tmp/env-scalars.yaml
|
||||
python3 - /tmp/env-scalars.yaml <<'PYEOF'
|
||||
import sys, yaml
|
||||
docs = [d for d in yaml.safe_load_all(open(sys.argv[1])) if d]
|
||||
def env(suffix):
|
||||
sts = next(d for d in docs if d.get("kind") == "StatefulSet"
|
||||
and d["metadata"]["name"].endswith(suffix))
|
||||
return {e["name"]: e for e in sts["spec"]["template"]["spec"]["containers"][0]["env"]}
|
||||
master, filer = env("-master"), env("-filer")
|
||||
want = [(master, "WEED_MASTER_VOLUME_GROWTH_COPY_1", "7"), (master, "WEED_GLOBAL_INT", "1000000"),
|
||||
(filer, "WEED_MYSQL_ENABLED", "true"), (filer, "WEED_MYSQL_PORT", "3306"),
|
||||
(filer, "WEED_GLOBAL_INT", "1000000")]
|
||||
failed = [f"{name}: {e.get(name)}" for e, name, value in want
|
||||
if e.get(name) != {"name": name, "value": value}]
|
||||
if master.get("WEED_EMPTY") != {"name": "WEED_EMPTY"}:
|
||||
failed.append(f"WEED_EMPTY: {master.get('WEED_EMPTY')}")
|
||||
if filer.get("WEED_REF", {}).get("valueFrom") != {"secretKeyRef": {"name": "s", "key": "k"}}:
|
||||
failed.append(f"WEED_REF: {filer.get('WEED_REF')}")
|
||||
if failed:
|
||||
print("FAIL: extraEnvironmentVars rendered wrong:", *failed, sep="\n ", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print("extraEnvironmentVars: numbers and booleans render as values, a map as valueFrom, a null as empty")
|
||||
PYEOF
|
||||
|
||||
echo "=== Testing bucket versioning: YAML bool false suspends like string \"false\" ==="
|
||||
# bool false used to be a silent no-op while string "false" suspended.
|
||||
BOOL_FALSE=$(helm template test $CHART_DIR \
|
||||
@@ -1997,6 +2069,38 @@ jobs:
|
||||
kubectl delete namespace "$NS"
|
||||
echo "SFTP host key lifecycle tests passed"
|
||||
|
||||
- name: Verify the filer db secret survives uninstall and install
|
||||
run: |
|
||||
set -e
|
||||
CHART_DIR="k8s/charts/seaweedfs"
|
||||
NS="filer-db-secret"
|
||||
SECRET="db-seaweedfs-db-secret"
|
||||
DB_ARGS="--set image.tag=$IMAGE_TAG --set-string filer.extraEnvironmentVars.WEED_MYSQL_ENABLED=true --set master.enabled=false --set volume.enabled=false"
|
||||
kubectl create namespace "$NS"
|
||||
|
||||
echo "=== install generates the db credentials ==="
|
||||
helm install db $CHART_DIR -n "$NS" $DB_ARGS
|
||||
[ "$(kubectl get secret "$SECRET" -n "$NS" -o jsonpath='{.data.user}' | base64 -d)" = YourSWUser ] \
|
||||
|| { echo "FAIL: install did not create the default user"; exit 1; }
|
||||
[ "$(kubectl get secret "$SECRET" -n "$NS" -o jsonpath='{.data.password}' | base64 -d | wc -c)" -eq 32 ] \
|
||||
|| { echo "FAIL: install did not generate a 32-character password"; exit 1; }
|
||||
|
||||
echo "=== credentials in the kept Secret survive uninstall and install ==="
|
||||
PASSWORD='p"a\ss: #x {{ .Values }}'
|
||||
kubectl patch secret "$SECRET" -n "$NS" --type merge \
|
||||
-p "$(jq -n --arg p "$PASSWORD" '{stringData: {user: "seaweed_app", password: $p}}')"
|
||||
helm uninstall db -n "$NS"
|
||||
kubectl get secret "$SECRET" -n "$NS" >/dev/null || { echo "FAIL: uninstall removed the db secret"; exit 1; }
|
||||
helm install db $CHART_DIR -n "$NS" $DB_ARGS
|
||||
[ "$(kubectl get secret "$SECRET" -n "$NS" -o jsonpath='{.data.user}' | base64 -d)" = seaweed_app ] \
|
||||
|| { echo "FAIL: reinstall reset the db user"; exit 1; }
|
||||
[ "$(kubectl get secret "$SECRET" -n "$NS" -o jsonpath='{.data.password}' | base64 -d)" = "$PASSWORD" ] \
|
||||
|| { echo "FAIL: reinstall replaced the db password"; exit 1; }
|
||||
|
||||
helm uninstall db -n "$NS"
|
||||
kubectl delete namespace "$NS"
|
||||
echo "Filer db secret reinstall test passed"
|
||||
|
||||
- name: Verify JWT signing key persistence across upgrades
|
||||
run: |
|
||||
# chart-testing puts its pip-less venv first on PATH; use setup-python.
|
||||
|
||||
@@ -120,5 +120,5 @@ jobs:
|
||||
- name: Run the s3vectors conformance subset
|
||||
working-directory: test/vectors
|
||||
run: |
|
||||
cp ../../seaweed-vector/target/release/weed-vector-server weed-vector-server
|
||||
cp ../../seaweed-vector/target/release/weed-vector weed-vector
|
||||
./run_test.sh
|
||||
@@ -101,7 +101,7 @@ require (
|
||||
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/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7
|
||||
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
|
||||
modernc.org/b v1.0.0 // indirect
|
||||
@@ -290,7 +290,7 @@ 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/compute/metadata v0.9.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/monitoring v1.30.0 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
@@ -302,7 +302,7 @@ require (
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.194 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.37.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0 // indirect
|
||||
github.com/IBM/go-sdk-core/v5 v5.23.1 // indirect
|
||||
@@ -355,7 +355,7 @@ require (
|
||||
github.com/elastic/gosigar v0.14.3 // indirect
|
||||
github.com/emersion/go-message v0.18.2 // indirect
|
||||
github.com/emersion/go-vcard v0.0.0-20260618161152-d854b7e0e2d3 // indirect
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be // indirect
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.40.1-0.20261014170222-9c4befd3c419 // indirect
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
@@ -364,7 +364,7 @@ require (
|
||||
github.com/geoffgarside/ber v1.2.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.4.0 // indirect
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.5 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
@@ -455,7 +455,7 @@ require (
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/t3rm1n4l/go-mega v0.0.0-20260717075258-c6acd6a5bd04 // indirect
|
||||
github.com/tarantool/go-iproto v1.1.0 // indirect
|
||||
@@ -493,8 +493,8 @@ require (
|
||||
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-20260904194346-d0f1323225a4 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/validator.v2 v2.0.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
|
||||
@@ -8,8 +8,8 @@ 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/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
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=
|
||||
@@ -75,8 +75,8 @@ github.com/FilenCloudDienste/filen-sdk-go v0.0.39 h1:tgV5jYL6dsXop9TpDTIQU6UwJjw
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.39/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.194 h1:dtOFxSTWWRpkmvXa6ycNiw8dVDu1wkgzcXyVV1VafNc=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.194/go.mod h1:rl0WumSN9gSo775DgvQv+wMQ8rlb0ES/1hU5jkMtLXg=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.37.0 h1:edOuLWehuDlQ68roBF900Y09jvBoJP5W5d/wusz9nWY=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.37.0/go.mod h1:iIyrdhveU5Ow84ipRlxtjCOQnIM0DiqSMxuxm50xwZY=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0 h1:rmzbFS2CkHq0y2L5LkMVWm+QXjjNEXxjmhrJqga/QGk=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0/go.mod h1:iIyrdhveU5Ow84ipRlxtjCOQnIM0DiqSMxuxm50xwZY=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0 h1:BeC1Bub7Ttk33TF8v3ZeQ2L8acvz4ZLqtQuLyJAZquc=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0/go.mod h1:UgG/Xn9+NXb1/ueSczIFxyuya3hs3srFDiZG2JrpJwY=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.61.0 h1:eSgSuKdcpY7RTN1oXSzC6S39rPBImn03ubLMsWK4RRg=
|
||||
@@ -428,8 +428,8 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.m
|
||||
github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be h1:SWe0x6yfglnxuvOiYgTTnNq7QD/yvqthOh1RBI8Bj8w=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be/go.mod h1:PYEOlng9XcrulfyWpm49jECTPV0LT4q8cO7fLW/xwgk=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.40.1-0.20261014170222-9c4befd3c419 h1:DybMDTfb3z9UZasQ2vRKnt7VmhjR7HDaOdflhJt7SDI=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.40.1-0.20261014170222-9c4befd3c419/go.mod h1:UZVGjwWu2QV8PkGSlXmqWiSgqCGZe16TgIu4jDl3T5w=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
@@ -491,8 +491,8 @@ github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8b
|
||||
github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-git/go-billy/v5 v5.9.0 h1:jItGXszUDRtR/AlferWPTMN4j38BQ88XnXKbilmmBPA=
|
||||
github.com/go-git/go-billy/v5 v5.9.0/go.mod h1:jCnQMLj9eUgGU7+ludSTYoZL/GGmii14RxKFj7ROgHw=
|
||||
github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
@@ -1155,8 +1155,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2 h1:jUEsvCMD6fH25J8K/w3q/XnIx8W1lb8+YLaEEHIjHmc=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2/go.mod h1:w2CLWKLMTX/PPYUEUPv3ltH0RXsw5S8suwNF46w9/Aw=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
@@ -1633,10 +1633,10 @@ google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEY
|
||||
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-20260904194346-d0f1323225a4 h1:NCe/UiklGd/9xjT+ROBVhJ1kf6TRQaFedsR+z7u1gvo=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4/go.mod h1:fJ2lYaWjqNknJyQBOCd0fA3HnEElJqGplH71a2txi+g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 h1:5t+ZydAFj5kGVLrgCvLmpmCf9ylGRd64hpEronfRaws=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
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/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=
|
||||
@@ -1647,8 +1647,8 @@ google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv
|
||||
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
|
||||
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
|
||||
google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk=
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7 h1:5+EEM1fC0yjOZID0NUZVrE2+8M/+1TclNrSz/l1xMYs=
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7/go.mod h1:Ovl0ECo4xx5r4kn/6d4BPSNB7OIFuu6EAjOzjtVAKaM=
|
||||
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089 h1:8300TIaXaOq+IoVmVzsZKUP3z4PpTsxu0ArPkPV/4Ts=
|
||||
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089/go.mod h1:Zr6uoNHvZlKOMmDEULT/cdZrN8qcSkXRXPkw4ybjoxI=
|
||||
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6 h1:ExN12ndbJ608cboPYflpTny6mXSzPrDLh0iTaVrRrds=
|
||||
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8=
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0 h1:/KQ7VP/1bs53/aopk9QhuPyFAp9Dm9Ejix3lzYkCrDA=
|
||||
|
||||
@@ -23,7 +23,7 @@ helm install --values=values.yaml seaweedfs seaweedfs/seaweedfs
|
||||
* master/filer/volume are stateful sets with anti-affinity on the hostname,
|
||||
so your deployment will be spread/HA.
|
||||
* leveldb2 is the default filer backend; a mysql-compatible database (memsql, ...) enables HA (multiple filer instances) and the backup/HA it can provide.
|
||||
* with `filer.extraEnvironmentVars.WEED_MYSQL_ENABLED` set to `"true"`, mysql user/password are created in a k8s secret (default: `<release>-seaweedfs-db-secret`) and injected to the filer with ENV. On any other store neither the secret nor the `WEED_MYSQL_*` env, plain or secret-backed, is rendered.
|
||||
* with `filer.extraEnvironmentVars.WEED_MYSQL_ENABLED` set to `"true"`, mysql user/password are created in a k8s secret (default: `<release>-seaweedfs-db-secret`) and injected to the filer with ENV. The secret is kept on `helm uninstall`, and a later install reuses the user and password in it, including ones you edited in. On any other store neither the secret nor the `WEED_MYSQL_*` env, plain or secret-backed, is rendered.
|
||||
* cert config exists and can be enabled, but not been tested, requires cert-manager to be installed.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -138,9 +138,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
{{- $secretExtraEnvironmentVars := .Values.admin.secretExtraEnvironmentVars }}
|
||||
|
||||
@@ -118,9 +118,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
@@ -107,9 +107,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
volumeMounts:
|
||||
|
||||
@@ -101,27 +101,77 @@ spec:
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
{{- if $mysqlEnabled }}
|
||||
- name: WEED_MYSQL_USERNAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "seaweedfs.fullname" . }}-db-secret
|
||||
key: user
|
||||
optional: true
|
||||
- name: WEED_MYSQL_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "seaweedfs.fullname" . }}-db-secret
|
||||
key: password
|
||||
optional: true
|
||||
{{- end }}
|
||||
{{- $mergedExtraEnvironmentVars := dict }}
|
||||
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.filer "target" $mergedExtraEnvironmentVars) }}
|
||||
{{- $secretExtraEnvironmentVars := .Values.filer.secretExtraEnvironmentVars | default dict }}
|
||||
{{- $emittedEarly := dict }}
|
||||
- name: SEAWEEDFS_FULLNAME
|
||||
value: "{{ include "seaweedfs.fullname" . }}"
|
||||
{{- if and .Values.filer.s3.enabled .Values.filer.s3.enableAuth }}
|
||||
{{- include "seaweedfs.s3.credentialEnv" . | nindent 12 }}
|
||||
{{- end }}
|
||||
{{- $mergedExtraEnvironmentVars := dict }}
|
||||
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.filer "target" $mergedExtraEnvironmentVars) }}
|
||||
{{- if $mysqlEnabled }}
|
||||
{{- /* Emit the mysql credentials and every var they reach through $(...)
|
||||
in dependency order, after the chart's own vars so references to
|
||||
them resolve too: Kubernetes only resolves a reference to a var
|
||||
declared earlier. A credential the user sets wins over the db
|
||||
secret's, secret-backed over plain. */}}
|
||||
{{- $early := dict "WEED_MYSQL_USERNAME" true "WEED_MYSQL_PASSWORD" true }}
|
||||
{{- $maxDiscover := int (add (len $mergedExtraEnvironmentVars) (len $secretExtraEnvironmentVars)) }}
|
||||
{{- range $round := until $maxDiscover }}
|
||||
{{- range $key := keys $early }}
|
||||
{{- $v := index $mergedExtraEnvironmentVars $key }}
|
||||
{{- if and (not (hasKey $secretExtraEnvironmentVars $key)) (kindIs "string" $v) }}
|
||||
{{- range $ref := regexFindAll `\$\([A-Za-z_][A-Za-z0-9_]*\)` (tpl $v $) -1 }}
|
||||
{{- $name := $ref | trimPrefix "$(" | trimSuffix ")" }}
|
||||
{{- if and (or (hasKey $mergedExtraEnvironmentVars $name) (hasKey $secretExtraEnvironmentVars $name)) (not (hasKey $early $name)) }}
|
||||
{{- $_ := set $early $name true }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- $ordered := list "WEED_MYSQL_USERNAME" "WEED_MYSQL_PASSWORD" }}
|
||||
{{- range $key := keys $early | sortAlpha }}
|
||||
{{- if not (has $key $ordered) }}{{ $ordered = append $ordered $key }}{{ end }}
|
||||
{{- end }}
|
||||
{{- $maxRounds := int (len $ordered) }}
|
||||
{{- range $round := until $maxRounds }}
|
||||
{{- range $key := $ordered }}
|
||||
{{- if not (hasKey $emittedEarly $key) }}
|
||||
{{- $ready := true }}
|
||||
{{- $v := index $mergedExtraEnvironmentVars $key }}
|
||||
{{- if and (not (hasKey $secretExtraEnvironmentVars $key)) (kindIs "string" $v) }}
|
||||
{{- range $ref := regexFindAll `\$\([A-Za-z_][A-Za-z0-9_]*\)` (tpl $v $) -1 }}
|
||||
{{- $name := $ref | trimPrefix "$(" | trimSuffix ")" }}
|
||||
{{- if and (hasKey $early $name) (not (hasKey $emittedEarly $name)) }}{{- $ready = false }}{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if or $ready (eq $round (sub $maxRounds 1)) }}
|
||||
- name: {{ $key }}
|
||||
{{- if hasKey $secretExtraEnvironmentVars $key }}
|
||||
valueFrom: {{ toYaml (index $secretExtraEnvironmentVars $key) | nindent 16 }}
|
||||
{{- else if hasKey $mergedExtraEnvironmentVars $key }}
|
||||
{{- if kindIs "string" $v }}
|
||||
value: {{ tpl $v $ | quote }}
|
||||
{{- else }}
|
||||
valueFrom:
|
||||
{{ toYaml $v | nindent 16 | trim }}
|
||||
{{- end }}
|
||||
{{- else }}
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "seaweedfs.fullname" $ }}-db-secret
|
||||
key: {{ ternary "password" "user" (eq $key "WEED_MYSQL_PASSWORD") }}
|
||||
optional: true
|
||||
{{- end }}
|
||||
{{- $_ := set $emittedEarly $key true }}
|
||||
{{- $_ := unset $mergedExtraEnvironmentVars $key }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if not $mysqlEnabled }}
|
||||
{{- range $key := keys $mergedExtraEnvironmentVars }}
|
||||
{{- if hasPrefix "WEED_MYSQL_" $key }}
|
||||
@@ -130,18 +180,25 @@ spec:
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
|
||||
{{- if hasKey $secretExtraEnvironmentVars $key }}
|
||||
- name: {{ $key }}
|
||||
valueFrom: {{ toYaml (index $secretExtraEnvironmentVars $key) | nindent 16 }}
|
||||
{{- else }}
|
||||
{{- $value := index $mergedExtraEnvironmentVars $key }}
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.secretExtraEnvironmentVars }}
|
||||
{{- range $key, $value := .Values.filer.secretExtraEnvironmentVars }}
|
||||
{{- if or $mysqlEnabled (not (hasPrefix "WEED_MYSQL_" $key)) }}
|
||||
{{- if and (or $mysqlEnabled (not (hasPrefix "WEED_MYSQL_" $key))) (not (hasKey $emittedEarly $key)) (not (hasKey $mergedExtraEnvironmentVars $key)) }}
|
||||
- name: {{ $key }}
|
||||
valueFrom: {{ toYaml $value | nindent 16 }}
|
||||
{{- end }}
|
||||
|
||||
@@ -105,9 +105,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
command:
|
||||
|
||||
@@ -110,9 +110,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
command:
|
||||
|
||||
@@ -101,9 +101,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
command:
|
||||
|
||||
@@ -124,9 +124,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 14 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{{- if and .Values.filer.enabled (include "seaweedfs.filer.mysqlEnabled" .) }}
|
||||
{{- /* Kept on uninstall, but the pre-install hook recreates it on the next install:
|
||||
reuse the stored user and password so the filer can still log in. */}}
|
||||
{{- $existing := lookup "v1" "Secret" .Release.Namespace (printf "%s-db-secret" (include "seaweedfs.fullname" .)) }}
|
||||
{{- $data := ($existing | default dict).data | default dict }}
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
type: Opaque
|
||||
@@ -8,13 +12,14 @@ metadata:
|
||||
annotations:
|
||||
"helm.sh/resource-policy": keep
|
||||
"helm.sh/hook": "pre-install"
|
||||
"helm.sh/hook-delete-policy": "before-hook-creation"
|
||||
labels:
|
||||
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
|
||||
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
stringData:
|
||||
user: "YourSWUser"
|
||||
# auto-generated password
|
||||
password: {{ randAlphaNum 10 | sha256sum | b64enc | trunc 32 }}
|
||||
user: {{ if $data.user }}{{ b64dec $data.user | quote }}{{ else }}"YourSWUser"{{ end }}
|
||||
# generated on first install, reused afterwards
|
||||
password: {{ if $data.password }}{{ b64dec $data.password | quote }}{{ else }}{{ randAlphaNum 10 | sha256sum | b64enc | trunc 32 }}{{ end }}
|
||||
{{- end }}
|
||||
@@ -152,9 +152,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
command:
|
||||
|
||||
@@ -104,9 +104,11 @@ spec:
|
||||
- name: {{ $key }}
|
||||
{{- if kindIs "string" $value }}
|
||||
value: {{ tpl $value $ | quote }}
|
||||
{{- else }}
|
||||
{{- else if kindIs "map" $value }}
|
||||
valueFrom:
|
||||
{{ toYaml $value | nindent 16 | trim }}
|
||||
{{- else if not (kindIs "invalid" $value) }}
|
||||
value: {{ toJson $value | quote }}
|
||||
{{- end -}}
|
||||
{{- end }}
|
||||
command:
|
||||
|
||||
+1003
-1037
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
@@ -34,7 +34,7 @@
|
||||
<protobuf.version>3.25.5</protobuf.version>
|
||||
<!-- follow https://github.com/grpc/grpc-java -->
|
||||
<grpc.version>1.77.0</grpc.version>
|
||||
<guava.version>32.0.0-jre</guava.version>
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -527,6 +527,11 @@ message DeleteEntryRequest {
|
||||
int64 if_not_modified_after = 9; // unix time in seconds
|
||||
bool keep_remote_object = 10;
|
||||
int64 if_not_modified_after_ns = 11; // unix time in nanoseconds; overrides if_not_modified_after when set
|
||||
// Optional precondition evaluated against the entry atomically with the
|
||||
// delete, under the filer's per-path lock. The request is routed to the
|
||||
// entry's owner filer for the check to be authoritative.
|
||||
map<string, bytes> expected_extended = 12;
|
||||
bool is_moved = 13; // set on a forwarded request so the owner applies it locally
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
@@ -867,6 +872,7 @@ message Lock {
|
||||
int64 generation = 5;
|
||||
bool is_backup = 6;
|
||||
int64 seq = 7;
|
||||
string prev_renew_token = 8;
|
||||
}
|
||||
message TransferLocksRequest {
|
||||
repeated Lock locks = 1;
|
||||
@@ -881,6 +887,7 @@ message ReplicateLockRequest {
|
||||
int64 generation = 5;
|
||||
bool is_unlock = 6;
|
||||
int64 seq = 7;
|
||||
string prev_renew_token = 8;
|
||||
}
|
||||
message ReplicateLockResponse {
|
||||
}
|
||||
|
||||
Generated
+4
@@ -6465,6 +6465,7 @@ dependencies = [
|
||||
"lance-index",
|
||||
"lance-linalg",
|
||||
"lance-table",
|
||||
"object_store",
|
||||
"roaring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6472,6 +6473,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"weed-lance-worker",
|
||||
]
|
||||
|
||||
@@ -6486,6 +6488,7 @@ dependencies = [
|
||||
"clap",
|
||||
"futures",
|
||||
"lance",
|
||||
"lance-arrow",
|
||||
"lance-linalg",
|
||||
"prost",
|
||||
"prost-types",
|
||||
@@ -6494,6 +6497,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
"tonic-prost-build",
|
||||
|
||||
@@ -24,5 +24,6 @@ undocumented_unsafe_blocks = "warn"
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-stream = "0.1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
@@ -9,7 +9,7 @@ description = "Vector query engine over SeaweedFS Lance table buckets"
|
||||
name = "weed_vector_core"
|
||||
|
||||
[[bin]]
|
||||
name = "weed-vector"
|
||||
name = "weed-vector-cli"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
@@ -18,6 +18,7 @@ path = "src/main.rs"
|
||||
# no common root manifest.
|
||||
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
|
||||
lance = { version = "10", default-features = false, features = ["aws"] }
|
||||
object_store = "0.13"
|
||||
lance-index = "10"
|
||||
lance-linalg = "10"
|
||||
lance-table = "10"
|
||||
@@ -32,6 +33,7 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -130,6 +130,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -156,6 +158,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let filtered = ann(&dataset, &table, &query).await.unwrap();
|
||||
let exact = flat(&dataset, &table, &query).await.unwrap();
|
||||
@@ -191,6 +195,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//! it does not, always covering the fragments no index has reached yet.
|
||||
|
||||
pub mod coverage;
|
||||
pub mod maintenance;
|
||||
pub mod query;
|
||||
pub mod segments;
|
||||
pub mod table;
|
||||
#[cfg(test)]
|
||||
mod testing;
|
||||
|
||||
@@ -233,6 +233,8 @@ async fn main() -> Result<()> {
|
||||
postfilter,
|
||||
distance,
|
||||
nprobes,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let hits = if flat {
|
||||
query::flat(&dataset, &vector_table, &query).await?
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! Snapshot discipline under Lance maintenance: queries pin a dataset version,
|
||||
//! and version tags act as the lease maintenance must respect.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::Result;
|
||||
use lance::Dataset;
|
||||
use lance::dataset::refs::Ref;
|
||||
use uuid::Uuid;
|
||||
|
||||
const QUERY_TAG_PREFIX: &str = "weed-vector-query-";
|
||||
/// A lease outliving this is treated as abandoned by a dead or cancelled
|
||||
/// request and reaped by the next [`pin`].
|
||||
const LEASE_TTL: Duration = Duration::from_secs(3600);
|
||||
/// Foreign leases — another server's live queries or a dead process's
|
||||
/// leftovers — get this much longer backstop; a live query on a different
|
||||
/// server keeps its pin.
|
||||
const FOREIGN_TTL: Duration = Duration::from_secs(24 * 3600);
|
||||
/// Expired-lease scans run at most once per interval per dataset, not per
|
||||
/// request.
|
||||
const REAP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
/// A process-unique owner id embedded in lease tags so a reaper only applies
|
||||
/// the short TTL to its own leases.
|
||||
static INSTANCE: LazyLock<String> = LazyLock::new(|| Uuid::new_v4().simple().to_string());
|
||||
/// Nanos since the Unix epoch when each dataset last had its tags scanned,
|
||||
/// keyed by dataset uri.
|
||||
static LAST_REAP: LazyLock<Mutex<HashMap<String, u128>>> = LazyLock::new(Mutex::default);
|
||||
/// Tags this process still holds. An expired tag is only reaped once no live
|
||||
/// lease here owns it, so a long-running query keeps its pin.
|
||||
static LIVE_TAGS: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
|
||||
|
||||
/// A pinned dataset version. The lease tag is removed on drop; call
|
||||
/// [`Lease::release`] to await removal and observe failures.
|
||||
pub struct Lease {
|
||||
dataset: Dataset,
|
||||
tag: String,
|
||||
}
|
||||
|
||||
impl Lease {
|
||||
/// Remove the lease tag now instead of on drop.
|
||||
pub async fn release(mut self) -> Result<()> {
|
||||
let tag = std::mem::take(&mut self.tag);
|
||||
untrack(&tag);
|
||||
release(&self.dataset, &tag).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
fn drop(&mut self) {
|
||||
if self.tag.is_empty() {
|
||||
return;
|
||||
}
|
||||
let tag = std::mem::take(&mut self.tag);
|
||||
untrack(&tag);
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
let dataset = self.dataset.clone();
|
||||
handle.spawn(async move {
|
||||
if let Err(err) = release(&dataset, &tag).await {
|
||||
tracing::warn!("releasing query lease {tag}: {err:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lease-pin `dataset`'s current version with a tag so cleanup skips it.
|
||||
pub async fn pin(dataset: &Dataset) -> Result<Lease> {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
|
||||
reap_expired(dataset, now).await;
|
||||
let tag = format!(
|
||||
"{QUERY_TAG_PREFIX}{instance}-{now}-{}",
|
||||
Uuid::new_v4().simple(),
|
||||
instance = &*INSTANCE,
|
||||
);
|
||||
let version = dataset.version().version;
|
||||
dataset
|
||||
.tags()
|
||||
.create(&tag, Ref::Version(None, Some(version)))
|
||||
.await?;
|
||||
// A cleanup that listed tags before this create can still reclaim the
|
||||
// version; fail the read now rather than mid-query.
|
||||
if dataset.checkout_version(version).await.is_err() {
|
||||
let _ = dataset.tags().delete(&tag).await;
|
||||
anyhow::bail!("dataset version {version} was removed before it could be leased");
|
||||
}
|
||||
if let Ok(mut live) = LIVE_TAGS.lock() {
|
||||
live.insert(tag.clone());
|
||||
}
|
||||
Ok(Lease {
|
||||
dataset: dataset.clone(),
|
||||
tag,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`pin`] that answers the query anyway when the storage identity may read
|
||||
/// but not write: a denied tag write degrades to an unleased query rather
|
||||
/// than an error.
|
||||
pub async fn try_pin(dataset: &Dataset) -> Result<Option<Lease>> {
|
||||
match pin(dataset).await {
|
||||
Ok(lease) => Ok(Some(lease)),
|
||||
Err(err) if denied(&err) => {
|
||||
tracing::warn!("query runs without a version lease: {err:#}");
|
||||
Ok(None)
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn denied(err: &anyhow::Error) -> bool {
|
||||
err.chain().any(|cause| {
|
||||
matches!(
|
||||
cause.downcast_ref::<object_store::Error>(),
|
||||
Some(object_store::Error::PermissionDenied { .. })
|
||||
| Some(object_store::Error::Unauthenticated { .. })
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn release(dataset: &Dataset, tag: &str) -> Result<()> {
|
||||
Ok(dataset.tags().delete(tag).await?)
|
||||
}
|
||||
|
||||
fn untrack(tag: &str) {
|
||||
if let Ok(mut live) = LIVE_TAGS.lock() {
|
||||
live.remove(tag);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop lease tags whose owner never released them, so an abandoned lease
|
||||
/// cannot keep a version out of cleanup forever.
|
||||
async fn reap_expired(dataset: &Dataset, now: u128) {
|
||||
{
|
||||
let Ok(mut scanned) = LAST_REAP.lock() else {
|
||||
return;
|
||||
};
|
||||
if now.saturating_sub(*scanned.get(dataset.uri()).unwrap_or(&0)) <= REAP_INTERVAL.as_nanos()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if scanned.len() >= 4096 {
|
||||
scanned.clear();
|
||||
}
|
||||
scanned.insert(dataset.uri().to_string(), now);
|
||||
}
|
||||
let Ok(tags) = dataset.tags().list().await else {
|
||||
return;
|
||||
};
|
||||
for name in tags.keys() {
|
||||
let held = LIVE_TAGS
|
||||
.lock()
|
||||
.map(|live| live.contains(name))
|
||||
.unwrap_or(false);
|
||||
// {instance}-{ts}-{uuid} is the owned format; {ts}-{uuid} is a
|
||||
// legacy foreign tag. Segment count picks the format — an all-digit
|
||||
// owner parses as a number too. Own leases use the short TTL;
|
||||
// foreign ones only the long backstop.
|
||||
let expired = name
|
||||
.strip_prefix(QUERY_TAG_PREFIX)
|
||||
.and_then(|rest| {
|
||||
let mut it = rest.splitn(3, '-');
|
||||
let a = it.next()?;
|
||||
let b = it.next()?;
|
||||
match it.next() {
|
||||
Some(_) => Some((a == *INSTANCE, b.parse::<u128>().ok()?)),
|
||||
None => Some((false, a.parse::<u128>().ok()?)),
|
||||
}
|
||||
})
|
||||
.is_some_and(|(own, stamp)| {
|
||||
now.saturating_sub(stamp)
|
||||
> if own { LEASE_TTL } else { FOREIGN_TTL }.as_nanos()
|
||||
});
|
||||
if expired && !held {
|
||||
let _ = dataset.tags().delete(name).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Query, VectorTable, query, testing};
|
||||
use lance::dataset::cleanup::{CleanupPolicy, cleanup_old_versions};
|
||||
use lance::dataset::optimize::{CompactionOptions, compact_files};
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use tempfile::TempDir;
|
||||
|
||||
async fn pinned_hits(dataset: &Dataset, version: u64, query_vector: &[f32]) -> Vec<u64> {
|
||||
let pinned = dataset.checkout_version(version).await.unwrap();
|
||||
let resolved = VectorTable::resolve(&pinned, None, None).unwrap();
|
||||
let q = Query {
|
||||
vector: query_vector.to_vec(),
|
||||
k: 3,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let mut ids: Vec<u64> = query::flat(&pinned, &resolved, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| h.row_id)
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
/// Compaction commits a new version and rewrites fragments; a query pinned
|
||||
/// at the old version still reads it.
|
||||
#[tokio::test]
|
||||
async fn pinned_query_survives_compaction() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["e", "f", "g", "h"]).await;
|
||||
let v1 = dataset.version().version;
|
||||
let before = pinned_hits(&dataset, v1, &[0.0, 0.0, 0.0, 1.0]).await;
|
||||
|
||||
compact_files(
|
||||
&mut dataset,
|
||||
CompactionOptions {
|
||||
target_rows_per_fragment: 64,
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(dataset.version().version > v1);
|
||||
assert_eq!(
|
||||
pinned_hits(&dataset, v1, &[0.0, 0.0, 0.0, 1.0]).await,
|
||||
before
|
||||
);
|
||||
}
|
||||
|
||||
/// A pinned version carrying a query tag is skipped by cleanup; removing
|
||||
/// the lease first lets cleanup delete it.
|
||||
#[tokio::test]
|
||||
async fn tagged_version_survives_cleanup() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let v1 = dataset.version().version;
|
||||
let before = pinned_hits(&dataset, v1, &[0.0, 0.0, 0.0, 1.0]).await;
|
||||
let lease = pin(&dataset).await.unwrap();
|
||||
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["e", "f", "g", "h"]).await;
|
||||
let v2 = dataset.version().version;
|
||||
|
||||
// Tagged old versions refuse to clean by default.
|
||||
let policy = CleanupPolicy {
|
||||
before_version: Some(v2),
|
||||
delete_unverified: true,
|
||||
error_if_tagged_old_versions: true,
|
||||
clean_referenced_branches: false,
|
||||
delete_rate_limit: None,
|
||||
..Default::default()
|
||||
};
|
||||
cleanup_old_versions(&dataset, policy.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
let policy = CleanupPolicy {
|
||||
error_if_tagged_old_versions: false,
|
||||
..policy
|
||||
};
|
||||
cleanup_old_versions(&dataset, policy).await.unwrap();
|
||||
assert_eq!(
|
||||
pinned_hits(&dataset, v1, &[0.0, 0.0, 0.0, 1.0]).await,
|
||||
before
|
||||
);
|
||||
|
||||
// Lease released: the old version is now fair game.
|
||||
lease.release().await.unwrap();
|
||||
assert!(
|
||||
dataset
|
||||
.tags()
|
||||
.list()
|
||||
.await
|
||||
.unwrap()
|
||||
.keys()
|
||||
.all(|t| !t.starts_with(QUERY_TAG_PREFIX))
|
||||
);
|
||||
cleanup_old_versions(
|
||||
&dataset,
|
||||
CleanupPolicy {
|
||||
before_version: Some(v2),
|
||||
delete_unverified: true,
|
||||
error_if_tagged_old_versions: true,
|
||||
clean_referenced_branches: false,
|
||||
delete_rate_limit: None,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(dataset.checkout_version(v1).await.is_err());
|
||||
}
|
||||
|
||||
/// Concurrent pins never collide on a tag name.
|
||||
#[tokio::test]
|
||||
async fn pins_get_distinct_tags() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let a = pin(&dataset).await.unwrap();
|
||||
let b = pin(&dataset).await.unwrap();
|
||||
assert_ne!(a.tag, b.tag);
|
||||
assert_eq!(dataset.tags().list().await.unwrap().len(), 2);
|
||||
a.release().await.unwrap();
|
||||
b.release().await.unwrap();
|
||||
}
|
||||
|
||||
/// A stale lease tag left behind is reaped by the next pin; a stale-named
|
||||
/// tag this process still holds is not.
|
||||
#[tokio::test]
|
||||
async fn pin_reaps_abandoned_leases() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let stale = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
- LEASE_TTL.as_nanos()
|
||||
- 1;
|
||||
dataset
|
||||
.tags()
|
||||
.create(
|
||||
&format!("{QUERY_TAG_PREFIX}{}-{stale}-deadbeef", &*INSTANCE),
|
||||
Ref::Version(None, Some(dataset.version().version)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let held = format!("{QUERY_TAG_PREFIX}{}-{stale}-livebeef", &*INSTANCE);
|
||||
dataset
|
||||
.tags()
|
||||
.create(&held, Ref::Version(None, Some(dataset.version().version)))
|
||||
.await
|
||||
.unwrap();
|
||||
LIVE_TAGS.lock().unwrap().insert(held.clone());
|
||||
|
||||
let lease = pin(&dataset).await.unwrap();
|
||||
let tags = dataset.tags().list().await.unwrap();
|
||||
assert_eq!(tags.len(), 2);
|
||||
assert!(tags.contains_key(&held));
|
||||
assert!(tags.contains_key(&lease.tag));
|
||||
LIVE_TAGS.lock().unwrap().remove(&held);
|
||||
lease.release().await.unwrap();
|
||||
}
|
||||
|
||||
/// A stale lease from another process is not reaped at the short TTL —
|
||||
/// only the long foreign backstop applies.
|
||||
#[tokio::test]
|
||||
async fn foreign_leases_survive_local_reap() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let stale = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
- LEASE_TTL.as_nanos()
|
||||
- 1;
|
||||
let foreign = format!("{QUERY_TAG_PREFIX}other-{stale}-foreign");
|
||||
dataset
|
||||
.tags()
|
||||
.create(&foreign, Ref::Version(None, Some(dataset.version().version)))
|
||||
.await
|
||||
.unwrap();
|
||||
let lease = pin(&dataset).await.unwrap();
|
||||
let tags = dataset.tags().list().await.unwrap();
|
||||
assert!(tags.contains_key(&foreign), "foreign lease was reaped");
|
||||
lease.release().await.unwrap();
|
||||
}
|
||||
|
||||
/// An all-digit foreign owner still gets the backstop TTL applied to its
|
||||
/// own timestamp rather than being read as a far-future legacy stamp.
|
||||
#[tokio::test]
|
||||
async fn all_digit_foreign_owner_still_expires() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let stale = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
- FOREIGN_TTL.as_nanos()
|
||||
- 1;
|
||||
let tag = format!("{QUERY_TAG_PREFIX}12345678901234567890123456789012-{stale}-deadbeef");
|
||||
dataset
|
||||
.tags()
|
||||
.create(&tag, Ref::Version(None, Some(dataset.version().version)))
|
||||
.await
|
||||
.unwrap();
|
||||
let lease = pin(&dataset).await.unwrap();
|
||||
let tags = dataset.tags().list().await.unwrap();
|
||||
assert!(!tags.contains_key(&tag), "all-digit foreign owner was kept");
|
||||
lease.release().await.unwrap();
|
||||
}
|
||||
|
||||
/// Pins within one reap interval do not rescan the dataset's tags.
|
||||
#[tokio::test]
|
||||
async fn pin_throttles_reap_scans() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let first = pin(&dataset).await.unwrap();
|
||||
let stale = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
- LEASE_TTL.as_nanos()
|
||||
- 1;
|
||||
let tag = format!("{QUERY_TAG_PREFIX}{}-{stale}-slowbeef", &*INSTANCE);
|
||||
dataset
|
||||
.tags()
|
||||
.create(&tag, Ref::Version(None, Some(dataset.version().version)))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let second = pin(&dataset).await.unwrap();
|
||||
assert!(dataset.tags().list().await.unwrap().contains_key(&tag));
|
||||
first.release().await.unwrap();
|
||||
second.release().await.unwrap();
|
||||
}
|
||||
|
||||
/// A version reclaimed before its lease lands fails the pin instead of
|
||||
/// dying mid-query, and leaves no lease tag behind.
|
||||
#[tokio::test]
|
||||
async fn pin_fails_when_version_already_reclaimed() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let v1 = dataset.version().version;
|
||||
let old = dataset.checkout_version(v1).await.unwrap();
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["e", "f", "g", "h"]).await;
|
||||
let v2 = dataset.version().version;
|
||||
cleanup_old_versions(
|
||||
&dataset,
|
||||
CleanupPolicy {
|
||||
before_version: Some(v2),
|
||||
delete_unverified: true,
|
||||
error_if_tagged_old_versions: false,
|
||||
clean_referenced_branches: false,
|
||||
delete_rate_limit: None,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(dataset.checkout_version(v1).await.is_err());
|
||||
|
||||
assert!(pin(&old).await.is_err());
|
||||
assert!(
|
||||
dataset
|
||||
.tags()
|
||||
.list()
|
||||
.await
|
||||
.unwrap()
|
||||
.keys()
|
||||
.all(|t| !t.starts_with(QUERY_TAG_PREFIX))
|
||||
);
|
||||
}
|
||||
|
||||
/// A data file deleted under a pinned query fails the request rather than
|
||||
/// returning a partial result set.
|
||||
#[tokio::test]
|
||||
async fn missing_data_file_errors_instead_of_partial() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let data_dir = dir.path().join("data");
|
||||
let file = std::fs::read_dir(&data_dir)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.find(|e| e.file_name().to_string_lossy().ends_with(".lance"))
|
||||
.unwrap();
|
||||
std::fs::remove_file(file.path()).unwrap();
|
||||
|
||||
let resolved = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let q = Query {
|
||||
vector: vec![0.0; 4],
|
||||
k: 2,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
assert!(query::flat(&dataset, &resolved, &q).await.is_err());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use futures::TryStreamExt;
|
||||
use lance::Dataset;
|
||||
use lance::dataset::scanner::Scanner;
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use lance_table::format::Fragment;
|
||||
|
||||
use crate::table::VectorTable;
|
||||
|
||||
@@ -27,6 +28,17 @@ pub struct Query {
|
||||
pub postfilter: bool,
|
||||
pub distance: DistanceType,
|
||||
pub nprobes: Option<usize>,
|
||||
/// Restrict the indexed scan to these physical index segments (the
|
||||
/// Enterprise planner fans a query out across them). Without `fragments`,
|
||||
/// unindexed fragments outside the segments are not searched — the caller
|
||||
/// owns disjoint coverage of them. When `fragments` is also set the scan
|
||||
/// covers both, so a worker can take its segment share plus an
|
||||
/// unindexed-fragment sweep in one request.
|
||||
pub index_segments: Option<Vec<uuid::Uuid>>,
|
||||
/// Restrict the scan to these fragment ids — used by the planner to give
|
||||
/// a worker the unindexed-fragment sweep. Listed ids that no longer exist
|
||||
/// scan nothing.
|
||||
pub fragments: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
/// One row of a top-K answer.
|
||||
@@ -41,14 +53,14 @@ pub struct Hit {
|
||||
|
||||
/// Exact top-K over every fragment, ignoring any index.
|
||||
pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
|
||||
run(scanner(dataset, table, query, false)?, table).await
|
||||
run(scanner(dataset, table, query, false).await?, table).await
|
||||
}
|
||||
|
||||
/// Top-K with the ANN index where it covers the fragment and a flat pass over
|
||||
/// the rest. Whether the index is used is Lance's decision per fragment, so
|
||||
/// rows written after the last index build are always candidates.
|
||||
pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
|
||||
run(scanner(dataset, table, query, true)?, table).await
|
||||
run(scanner(dataset, table, query, true).await?, table).await
|
||||
}
|
||||
|
||||
/// Fetch rows by key.
|
||||
@@ -80,7 +92,7 @@ pub async fn get(
|
||||
.context("scan by keys")
|
||||
}
|
||||
|
||||
fn scanner(
|
||||
async fn scanner(
|
||||
dataset: &Dataset,
|
||||
table: &VectorTable,
|
||||
query: &Query,
|
||||
@@ -107,6 +119,34 @@ fn scanner(
|
||||
if let Some(nprobes) = query.nprobes {
|
||||
scanner.nprobes(nprobes);
|
||||
}
|
||||
let segments = query.index_segments.as_deref().unwrap_or(&[]);
|
||||
if use_index && !segments.is_empty() {
|
||||
scanner.with_index_segments(segments.to_vec())?;
|
||||
}
|
||||
// Lance intersects the fragment list with the selected segments, so a
|
||||
// scoped scan must name the segment-covered fragments itself: the universe
|
||||
// is the listed ids plus the live coverage of the selected segments. An
|
||||
// empty universe (or an empty-segment, fragment-less assignment) scopes to
|
||||
// nothing — `with_fragments` with an empty list scans nothing.
|
||||
let mut wanted: Option<Vec<u64>> = query.fragments.clone();
|
||||
if let Some(ids) = &mut wanted {
|
||||
if use_index && !segments.is_empty() {
|
||||
ids.extend(
|
||||
crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?,
|
||||
);
|
||||
}
|
||||
} else if use_index && query.index_segments.as_ref().is_some_and(|s| s.is_empty()) {
|
||||
wanted = Some(Vec::new());
|
||||
}
|
||||
if let Some(ids) = wanted {
|
||||
let frags: Vec<Fragment> = dataset
|
||||
.fragments()
|
||||
.iter()
|
||||
.filter(|f| ids.contains(&f.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
scanner.with_fragments(frags);
|
||||
}
|
||||
let mut columns = Vec::new();
|
||||
if let Some(key) = &table.key_column {
|
||||
columns.push(key.clone());
|
||||
@@ -167,6 +207,9 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::table::VectorTable;
|
||||
use crate::testing::{DIM, write_dataset};
|
||||
use arrow_array::{FixedSizeListArray, RecordBatchIterator, types::Float32Type};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn l2(a: &[f32], b: &[f32]) -> f32 {
|
||||
@@ -192,6 +235,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let hits = flat(&dataset, &table, &query).await.unwrap();
|
||||
assert_eq!(hits.len(), 2);
|
||||
@@ -231,6 +276,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -240,6 +287,137 @@ mod tests {
|
||||
assert_eq!(hits[1].key, "k2");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn filter_matches_json_types_exactly() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let metas = vec![
|
||||
r#"{"k": 3}"#, // k0: number
|
||||
r#"{"k": "3"}"#, // k1: numeric string
|
||||
r#"{"k": true}"#, // k2: bool
|
||||
r#"{"k": "abc"}"#, // k3: non-numeric string
|
||||
r#"{"x": 1}"#, // k4: missing key
|
||||
r#"{"k": [1, 2]}"#, // k5: array
|
||||
r#"{"k": null}"#, // k6: null
|
||||
r#"{"k": 1}"#, // k7: serializes to '1', castable to boolean
|
||||
r#"{"k": 0}"#, // k8: serializes to '0', castable to boolean
|
||||
];
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("key", DataType::Utf8, false),
|
||||
Field::new(
|
||||
"vector",
|
||||
DataType::FixedSizeList(
|
||||
Arc::new(Field::new("item", DataType::Float32, true)),
|
||||
DIM as i32,
|
||||
),
|
||||
false,
|
||||
),
|
||||
Field::new("metadata", DataType::Utf8, true).with_metadata(
|
||||
[("ARROW:extension:name".to_string(), "arrow.json".to_string())]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
),
|
||||
]));
|
||||
let keys: Vec<String> = (0..metas.len()).map(|i| format!("k{i}")).collect();
|
||||
let batch = RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![
|
||||
Arc::new(StringArray::from(keys)),
|
||||
Arc::new(
|
||||
FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
|
||||
(0..metas.len())
|
||||
.map(|i| Some(vec![Some(i as f32); DIM]))
|
||||
.collect::<Vec<_>>(),
|
||||
DIM as i32,
|
||||
),
|
||||
),
|
||||
Arc::new(StringArray::from(
|
||||
metas
|
||||
.iter()
|
||||
.map(|m| Some(m.to_string()))
|
||||
.collect::<Vec<_>>(),
|
||||
)),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let reader = RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema);
|
||||
let dataset = Dataset::write(reader, dir.path().to_str().unwrap(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let table = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
async fn run(dataset: &Dataset, table: &VectorTable, filter: &str) -> Vec<Hit> {
|
||||
flat(
|
||||
dataset,
|
||||
table,
|
||||
&Query {
|
||||
vector: vec![1.0, 0.0, 0.0, 0.0],
|
||||
k: 10,
|
||||
filter: Some(filter.to_string()),
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
let keys_of = |hits: Vec<Hit>| {
|
||||
let mut keys: Vec<String> = hits.into_iter().map(|h| h.key).collect();
|
||||
keys.sort();
|
||||
keys
|
||||
};
|
||||
|
||||
// A stored string, boolean, array, or null must not satisfy a numeric
|
||||
// comparison — nor fail the query, the way the converting json_get_*
|
||||
// extractors do.
|
||||
let hits = run(
|
||||
&dataset,
|
||||
&table,
|
||||
"TRY_CAST(json_extract(`metadata`, '$[\"k\"]') AS DOUBLE) = 3",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(keys_of(hits), ["k0"]);
|
||||
let hits = run(
|
||||
&dataset,
|
||||
&table,
|
||||
"TRY_CAST(json_extract(`metadata`, '$[\"k\"]') AS DOUBLE) > 1",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(keys_of(hits), ["k0"]);
|
||||
|
||||
// Booleans compare the serialized form as well: '1' and '0' would
|
||||
// satisfy a cast but not the text match.
|
||||
let hits = run(
|
||||
&dataset,
|
||||
&table,
|
||||
"json_extract(`metadata`, '$[\"k\"]') = 'true'",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(keys_of(hits), ["k2"]);
|
||||
|
||||
// The serialized extract is exact for strings too: the numeric 3 is
|
||||
// not a match for '"3"', and comparing json_extract never trips on
|
||||
// the array or null rows.
|
||||
let hits = run(
|
||||
&dataset,
|
||||
&table,
|
||||
"json_extract(`metadata`, '$[\"k\"]') = '\"3\"'",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(keys_of(hits), ["k1"]);
|
||||
let hits = run(
|
||||
&dataset,
|
||||
&table,
|
||||
"NOT COALESCE(json_extract(`metadata`, '$[\"k\"]') = '\"3\"', false)",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
keys_of(hits),
|
||||
["k0", "k2", "k3", "k4", "k5", "k6", "k7", "k8"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_fetches_rows_by_key() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
@@ -267,6 +445,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
assert!(flat(&dataset, &table, &query).await.is_err());
|
||||
}
|
||||
@@ -288,6 +468,8 @@ mod tests {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let indexed = ann(&dataset, &table, &query).await.unwrap();
|
||||
let exact = flat(&dataset, &table, &query).await.unwrap();
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Physical index segments and the partition a fanout planner assigns to each
|
||||
//! worker. OSS runs the same restriction in-process; Enterprise ships the
|
||||
//! segment ids to remote workers — the engine does not change.
|
||||
|
||||
use anyhow::Result;
|
||||
use lance::Dataset;
|
||||
use lance::index::DatasetIndexExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// UUIDs of every physical index segment covering `field` at this version.
|
||||
pub async fn index_segments(dataset: &Dataset, field: &str) -> Result<Vec<Uuid>> {
|
||||
Ok(segment_fragments(dataset, field)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|(id, _)| *id)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Per index segment on `field`: its uuid and the live fragments it covers.
|
||||
/// Segments with unknown coverage (no bitmap) are skipped — callers needing
|
||||
/// strict coverage must treat that as a degenerate plan.
|
||||
pub async fn segment_fragments(
|
||||
dataset: &Dataset,
|
||||
field: &str,
|
||||
) -> Result<Vec<(Uuid, roaring::RoaringBitmap)>> {
|
||||
Ok(named_segment_fragments(dataset, field)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|(id, _, b)| (id, b))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Like `segment_fragments` but carries the logical index name — sharded
|
||||
/// builds create one named index per shard, and a `with_index_segments`
|
||||
/// scan must not mix names, so a fanout planner groups by name.
|
||||
pub async fn named_segment_fragments(
|
||||
dataset: &Dataset,
|
||||
field: &str,
|
||||
) -> Result<Vec<(Uuid, String, roaring::RoaringBitmap)>> {
|
||||
let field = dataset
|
||||
.schema()
|
||||
.field(field)
|
||||
.ok_or_else(|| anyhow::anyhow!("no such field {field}"))?;
|
||||
let live: roaring::RoaringBitmap = dataset.fragments().iter().map(|f| f.id as u32).collect();
|
||||
Ok(dataset
|
||||
.load_indices()
|
||||
.await?
|
||||
.iter()
|
||||
.filter(|i| i.fields == [field.id])
|
||||
.filter_map(|i| {
|
||||
i.fragment_bitmap
|
||||
.clone()
|
||||
.map(|b| (i.uuid, i.name.clone(), b & &live))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Live fragment ids covered by `segments` on `field` — the union a scoped
|
||||
/// fragment list needs so the selected segments are not filtered out of the
|
||||
/// scan.
|
||||
pub async fn covered_fragments(
|
||||
dataset: &Dataset,
|
||||
field: &str,
|
||||
segments: &[Uuid],
|
||||
) -> Result<Vec<u64>> {
|
||||
Ok(segment_fragments(dataset, field)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|(id, _)| segments.contains(id))
|
||||
.flat_map(|(_, b)| b.iter().map(u64::from).collect::<Vec<_>>())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Round-robin `segments` across `n` workers. Index order is unstable, so
|
||||
/// workers see disjoint, deterministic-in-name partitions rather than
|
||||
/// physically adjacent ones. Zero workers means zero partitions — nothing is
|
||||
/// silently assigned.
|
||||
pub fn partition(segments: &[Uuid], n: usize) -> Vec<Vec<Uuid>> {
|
||||
let mut out = vec![Vec::new(); n];
|
||||
if n == 0 {
|
||||
return out;
|
||||
}
|
||||
let mut ids = segments.to_vec();
|
||||
ids.sort();
|
||||
for (i, id) in ids.into_iter().enumerate() {
|
||||
out[i % n].push(id);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Query, VectorTable, query, testing};
|
||||
use lance::index::vector::VectorIndexParams;
|
||||
use lance_index::IndexType;
|
||||
use lance_index::optimize::OptimizeOptions;
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Two workers each scan their share of the index segments; merged, the
|
||||
/// hits equal a single full-dataset search.
|
||||
#[tokio::test]
|
||||
async fn partitioned_segments_merge_to_full_result() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset = testing::write_dataset(
|
||||
&dir,
|
||||
&testing::vectors(8, 4),
|
||||
&["a", "b", "c", "d", "e", "f", "g", "h"],
|
||||
)
|
||||
.await;
|
||||
let params = VectorIndexParams::ivf_flat(4, DistanceType::L2);
|
||||
dataset
|
||||
.create_index(
|
||||
&["vector"],
|
||||
IndexType::Vector,
|
||||
Some("idx".to_string()),
|
||||
¶ms,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Second fragment + delta segment so the index has two parts, then a
|
||||
// third fragment left unindexed for the sweep half of the plan.
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["i", "j", "k", "l"]).await;
|
||||
dataset
|
||||
.optimize_indices(&OptimizeOptions::append())
|
||||
.await
|
||||
.unwrap();
|
||||
testing::append_dataset(&mut dataset, &testing::vectors(2, 4), &["m", "n"]).await;
|
||||
|
||||
let resolved = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let base = Query {
|
||||
vector: vec![0.5; 4],
|
||||
k: 5,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let want: Vec<(u64, u32)> = query::ann(&dataset, &resolved, &base)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| (h.row_id, h.distance.to_bits()))
|
||||
.collect();
|
||||
|
||||
let segments_bitmap = segment_fragments(&dataset, "vector").await.unwrap();
|
||||
let segments: Vec<Uuid> = segments_bitmap.iter().map(|(id, _)| *id).collect();
|
||||
assert!(
|
||||
segments.len() >= 2,
|
||||
"expected >=2 segments, got {segments:?}"
|
||||
);
|
||||
// The unindexed fragment belongs to nobody's segment; worker 0 sweeps
|
||||
// it next to its own share — the same contract plan_search implements
|
||||
// on the enterprise side.
|
||||
let unindexed: Vec<u64> = {
|
||||
let all: std::collections::BTreeSet<u64> =
|
||||
dataset.fragments().iter().map(|f| f.id).collect();
|
||||
let mut indexed = std::collections::BTreeSet::new();
|
||||
for (_, b) in &segments_bitmap {
|
||||
indexed.extend(b.iter().map(|i| i as u64));
|
||||
}
|
||||
all.difference(&indexed).copied().collect()
|
||||
};
|
||||
assert!(!unindexed.is_empty(), "expected an unindexed fragment");
|
||||
let mut merged: Vec<(f32, u64)> = Vec::new();
|
||||
for (w, share) in partition(&segments, 2).into_iter().enumerate() {
|
||||
let mut worker_q = base.clone();
|
||||
worker_q.index_segments = Some(share);
|
||||
if w == 0 {
|
||||
worker_q.fragments = Some(unindexed.clone());
|
||||
}
|
||||
merged.extend(
|
||||
query::ann(&dataset, &resolved, &worker_q)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| (h.distance, h.row_id)),
|
||||
);
|
||||
}
|
||||
merged.sort_by(|a, b| {
|
||||
a.0.partial_cmp(&b.0)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then(a.1.cmp(&b.1))
|
||||
});
|
||||
let got: Vec<(u64, u32)> = merged
|
||||
.iter()
|
||||
.take(base.k)
|
||||
.map(|(d, id)| (*id, d.to_bits()))
|
||||
.collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// named_segment_fragments must carry the logical index name through —
|
||||
/// a fanout planner groups tasks by name.
|
||||
#[tokio::test]
|
||||
async fn named_segment_fragments_returns_index_names() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut dataset = testing::write_dataset(
|
||||
&dir,
|
||||
&testing::vectors(8, 4),
|
||||
&["a", "b", "c", "d", "e", "f", "g", "h"],
|
||||
)
|
||||
.await;
|
||||
let params = VectorIndexParams::ivf_flat(4, DistanceType::L2);
|
||||
dataset
|
||||
.create_index(
|
||||
&["vector"],
|
||||
IndexType::Vector,
|
||||
Some("shard-a".to_string()),
|
||||
¶ms,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let named = named_segment_fragments(&dataset, "vector").await.unwrap();
|
||||
assert!(!named.is_empty());
|
||||
assert!(named.iter().all(|(_, name, _)| name == "shard-a"));
|
||||
}
|
||||
|
||||
/// A scope of fragment ids that no longer exist, an empty list, or an
|
||||
/// empty-segment assignment must return no hits — never fall through to
|
||||
/// an unrestricted scan.
|
||||
#[tokio::test]
|
||||
async fn empty_scope_scans_nothing() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let dataset =
|
||||
testing::write_dataset(&dir, &testing::vectors(4, 4), &["a", "b", "c", "d"]).await;
|
||||
let resolved = VectorTable::resolve(&dataset, None, None).unwrap();
|
||||
let mut q = Query {
|
||||
vector: vec![0.5; 4],
|
||||
k: 4,
|
||||
filter: None,
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: Some(vec![u64::MAX]),
|
||||
};
|
||||
assert!(
|
||||
query::ann(&dataset, &resolved, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
query::flat(&dataset, &resolved, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
q.fragments = Some(Vec::new());
|
||||
assert!(
|
||||
query::ann(&dataset, &resolved, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
q.fragments = None;
|
||||
q.index_segments = Some(Vec::new());
|
||||
assert!(
|
||||
query::ann(&dataset, &resolved, &q)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(partition(&[Uuid::nil()], 0).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,8 @@ fn query_for(vector: Vec<f32>, k: usize) -> Query {
|
||||
postfilter: false,
|
||||
distance: DistanceType::L2,
|
||||
nprobes: Some(4),
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,9 +144,9 @@ async fn deletes_are_not_returned() {
|
||||
/// $WEED_VECTOR_SPIKE_DIR for exercising the `weed-vector` CLI:
|
||||
///
|
||||
/// WEED_VECTOR_SPIKE_DIR=/tmp/vds cargo test make_spike_dataset -- --ignored
|
||||
/// weed-vector describe /tmp/vds
|
||||
/// weed-vector coverage /tmp/vds
|
||||
/// weed-vector query /tmp/vds --vector 0,0,0,0 --k 5
|
||||
/// weed-vector-cli describe /tmp/vds
|
||||
/// weed-vector-cli coverage /tmp/vds
|
||||
/// weed-vector-cli query /tmp/vds --vector 0,0,0,0 --k 5
|
||||
#[tokio::test]
|
||||
#[ignore]
|
||||
async fn make_spike_dataset() {
|
||||
|
||||
@@ -9,13 +9,14 @@ description = "VectorService gRPC server over SeaweedFS Lance table buckets"
|
||||
name = "weed_vector_server"
|
||||
|
||||
[[bin]]
|
||||
name = "weed-vector-server"
|
||||
name = "weed-vector"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
weed-vector-core = { path = "../core" }
|
||||
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
|
||||
lance = { version = "10", default-features = false, features = ["aws"] }
|
||||
lance-arrow = "10"
|
||||
lance-linalg = "10"
|
||||
arrow-array = "58"
|
||||
arrow-cast = "58"
|
||||
@@ -31,6 +32,7 @@ futures = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
|
||||
@@ -10,7 +10,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tonic_prost_build::configure()
|
||||
.build_server(true)
|
||||
.build_client(true)
|
||||
.compile_protos(&["../../../weed/pb/vector.proto"], &["../../../weed/pb/"])?;
|
||||
.compile_protos(
|
||||
&[
|
||||
"../../../weed/pb/vector.proto",
|
||||
"../../../weed/pb/master.proto",
|
||||
"../../../weed/pb/volume_server.proto",
|
||||
"../../../weed/pb/remote.proto",
|
||||
],
|
||||
&["../../../weed/pb/"],
|
||||
)?;
|
||||
println!("cargo:rerun-if-changed=../../../weed/pb/vector.proto");
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
pub mod service;
|
||||
|
||||
pub mod remote_pb {
|
||||
tonic::include_proto!("remote_pb");
|
||||
}
|
||||
pub mod volume_server_pb {
|
||||
tonic::include_proto!("volume_server_pb");
|
||||
}
|
||||
pub mod master_pb {
|
||||
tonic::include_proto!("master_pb");
|
||||
}
|
||||
pub mod master_client;
|
||||
|
||||
pub mod pb {
|
||||
pub mod vector {
|
||||
tonic::include_proto!("vector_pb");
|
||||
|
||||
@@ -23,6 +23,10 @@ struct Args {
|
||||
/// key=value, repeatable.
|
||||
#[arg(long = "storage-option", value_parser = parse_option)]
|
||||
storage_options: Vec<(String, String)>,
|
||||
/// Comma-separated master addresses to register this server with; the
|
||||
/// gateway discovers it via ListClusterNodes(client_type=vector).
|
||||
#[arg(long, env = "WEED_VECTOR_MASTERS")]
|
||||
masters: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_option(s: &str) -> Result<(String, String), String> {
|
||||
@@ -31,16 +35,52 @@ fn parse_option(s: &str) -> Result<(String, String), String> {
|
||||
.ok_or_else(|| "expected key=value".to_string())
|
||||
}
|
||||
|
||||
/// A wildcard listen address is not reachable for peers; derive the outbound
|
||||
/// IP toward the first master instead — the address the master sees anyway.
|
||||
fn advertised_addr(listen: &str, masters: &[String]) -> String {
|
||||
let Some((host, _)) = listen.rsplit_once(':') else {
|
||||
return listen.to_string();
|
||||
};
|
||||
if !matches!(host, "0.0.0.0" | "::" | "" | "[::]") {
|
||||
return listen.to_string();
|
||||
}
|
||||
let port = listen.rsplit_once(':').map(|(_, p)| p).unwrap_or_default();
|
||||
if let Some(master) = masters.first() {
|
||||
if let Ok(sock) = std::net::UdpSocket::bind((host, 0u16)) {
|
||||
if sock.connect(master).is_ok() {
|
||||
if let Ok(local) = sock.local_addr() {
|
||||
return format!("{}:{}", local.ip(), port);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
listen.to_string()
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt::init();
|
||||
let args = Args::parse();
|
||||
if let Some(masters) = &args.masters {
|
||||
let masters: Vec<String> = masters.split(',').map(|s| s.trim().to_string()).collect();
|
||||
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 client = NamespaceClient::new(args.namespace.clone()).with_fallback(&fallback);
|
||||
let service = VectorServer::new(client, fallback);
|
||||
tracing::info!(namespace = %args.namespace, listen = %args.listen, "weed-vector-server");
|
||||
tracing::info!(namespace = %args.namespace, listen = %args.listen, "weed-vector");
|
||||
Server::builder()
|
||||
.add_service(VectorServiceServer::new(service))
|
||||
// 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(args.listen.parse()?)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Self-registration with the weed master, mirroring how filer/s3 keep
|
||||
//! connected: hold a KeepConnected stream open to the leader and the node
|
||||
//! shows up in ListClusterNodes(client_type="vector").
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::time::sleep;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
use crate::master_pb::{seaweed_client::SeaweedClient, KeepConnectedRequest};
|
||||
|
||||
fn registration(client_addr: &str) -> KeepConnectedRequest {
|
||||
KeepConnectedRequest {
|
||||
client_type: "vector".into(),
|
||||
client_address: client_addr.into(),
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
filer_group: String::new(),
|
||||
data_center: String::new(),
|
||||
rack: String::new(),
|
||||
leave_lock_ring: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Masters are configured by their HTTP address; gRPC lives +10000 like the
|
||||
/// weed conventions (server_address.ToGrpcAddress).
|
||||
// A master address may carry an explicit gRPC port as `host:http.grpc` —
|
||||
// use it directly; otherwise the gRPC port is http + 10000.
|
||||
fn grpc_addr(master: &str) -> 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 grpc.parse::<u16>().is_ok() {
|
||||
return format!("{scheme}://{host}:{grpc}");
|
||||
}
|
||||
}
|
||||
if let Ok(port) = port.parse::<u16>() {
|
||||
return format!("{scheme}://{host}:{}", port + 10000);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
let rest = master.rsplit_once("://").map(|(_, r)| r).unwrap_or(master);
|
||||
match rest.rsplit_once(':') {
|
||||
Some((host, port)) => {
|
||||
format!("{host}:{}", port.split('.').next().unwrap_or(port))
|
||||
}
|
||||
None => rest.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retry forever: try each master until a stream opens, hold it until it
|
||||
/// errors, then rediscover — same shape as wdclient.KeepConnectedToMaster.
|
||||
/// A follower response's leader hint takes priority on the next pass.
|
||||
pub async fn keep_connected(masters: Vec<String>, client_addr: String) {
|
||||
let mut leader: Option<String> = None;
|
||||
loop {
|
||||
let mut seeds: Vec<String> = Vec::new();
|
||||
if let Some(l) = &leader {
|
||||
seeds.push(l.clone());
|
||||
}
|
||||
seeds.extend(masters.iter().cloned());
|
||||
for master in &seeds {
|
||||
match stream_to(master, &client_addr).await {
|
||||
Ok(Some(l)) => {
|
||||
leader = Some(l);
|
||||
break;
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(e) => tracing::warn!("master {master}: {e:#}"),
|
||||
}
|
||||
}
|
||||
sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn stream_to(master: &str, client_addr: &str) -> Result<Option<String>> {
|
||||
let channel = Endpoint::new(grpc_addr(master))?.connect().await?;
|
||||
let mut client = SeaweedClient::new(channel);
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(8);
|
||||
tx.send(registration(client_addr)).await?;
|
||||
let mut stream = client
|
||||
.keep_connected(tokio_stream::wrappers::ReceiverStream::new(rx))
|
||||
.await?
|
||||
.into_inner();
|
||||
// The master keeps the node live while the stream is open; resend the
|
||||
// registration periodically so a reconnect never leaves a stale entry.
|
||||
loop {
|
||||
tokio::select! {
|
||||
msg = stream.message() => match msg? {
|
||||
Some(resp) => {
|
||||
// A volume_location appears on every response — only
|
||||
// follow it when the hint points at a different master,
|
||||
// otherwise the leader keeps identifying itself and we
|
||||
// would reconnect forever.
|
||||
if let Some(loc) = resp.volume_location {
|
||||
if !loc.leader.is_empty()
|
||||
&& http_addr(&loc.leader) != http_addr(master)
|
||||
{
|
||||
return Ok(Some(loc.leader));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => anyhow::bail!("master closed the keep-connected stream"),
|
||||
},
|
||||
_ = sleep(Duration::from_secs(5)) => {
|
||||
tx.send(registration(client_addr)).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use lance::io::ObjectStoreParams;
|
||||
use lance::io::StorageOptionsAccessor;
|
||||
use lance_linalg::distance::DistanceType;
|
||||
use prost_types::{ListValue, Struct, Value, value::Kind};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
use tonic::{Request, Response, Status};
|
||||
use weed_lance_worker::catalog::NamespaceClient;
|
||||
@@ -74,17 +74,18 @@ fn schema_for(
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
let mut metadata_field = Field::new(METADATA_COLUMN, DataType::Utf8, true);
|
||||
// The arrow.json extension marks the Utf8 column as JSON: lance stores it
|
||||
// as jsonb, which is what the json_get_* filter functions take.
|
||||
let mut metadata_meta =
|
||||
HashMap::from_iter([("ARROW:extension:name".to_string(), "arrow.json".to_string())]);
|
||||
if !non_filterable.is_empty() {
|
||||
metadata_field = metadata_field.with_metadata(
|
||||
[(
|
||||
"non_filterable_metadata_keys".to_string(),
|
||||
serde_json::to_string(non_filterable).unwrap_or_default(),
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
metadata_meta.insert(
|
||||
"non_filterable_metadata_keys".to_string(),
|
||||
serde_json::to_string(non_filterable).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
let metadata_field =
|
||||
Field::new(METADATA_COLUMN, DataType::Utf8, true).with_metadata(metadata_meta);
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new(KEY_COLUMN, DataType::Utf8, false),
|
||||
vector_field,
|
||||
@@ -110,12 +111,18 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
|
||||
.flat_map(|v| v.data.iter().copied())
|
||||
.collect::<Vec<_>>();
|
||||
let values: ArrayRef = Arc::new(Float32Array::from(flat));
|
||||
let vectors_array = FixedSizeListArray::try_new(
|
||||
Field::new("item", DataType::Float32, false).into(),
|
||||
dimension as i32,
|
||||
values,
|
||||
None,
|
||||
)?;
|
||||
// Lance stores the list item as nullable even when the write schema
|
||||
// declared it non-null, so the child field must come from the batch's
|
||||
// schema rather than a fixed declaration.
|
||||
let DataType::FixedSizeList(item_field, _) = schema
|
||||
.field_with_name(VECTOR_COLUMN)
|
||||
.map_err(anyhow::Error::from)?
|
||||
.data_type()
|
||||
else {
|
||||
bail!("vector column is not a fixed-size list");
|
||||
};
|
||||
let vectors_array =
|
||||
FixedSizeListArray::try_new(item_field.clone(), dimension as i32, values, None)?;
|
||||
let metas = vectors
|
||||
.iter()
|
||||
.map(|v| {
|
||||
@@ -125,13 +132,20 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
|
||||
.transpose()
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The stored column is lance's jsonb (LargeBinary) once the field carries
|
||||
// the arrow.json extension; encode the strings, else keep the Utf8 batch.
|
||||
let metadata_array: ArrayRef = match schema
|
||||
.field_with_name(METADATA_COLUMN)
|
||||
.map(|f| f.data_type())
|
||||
{
|
||||
Ok(DataType::LargeBinary) => {
|
||||
Arc::new(lance_arrow::json::JsonArray::try_from_iter(metas)?.into_inner())
|
||||
}
|
||||
_ => Arc::new(StringArray::from(metas)),
|
||||
};
|
||||
RecordBatch::try_new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(keys),
|
||||
Arc::new(vectors_array),
|
||||
Arc::new(StringArray::from(metas)),
|
||||
],
|
||||
vec![Arc::new(keys), Arc::new(vectors_array), metadata_array],
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
@@ -368,6 +382,11 @@ impl VectorService for VectorServer {
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
// Lease the resolved version so maintenance cannot reclaim its files
|
||||
// while this query runs against it.
|
||||
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
|
||||
let batches = query::get(&dataset, &resolved, &req.keys)
|
||||
.await
|
||||
@@ -462,6 +481,11 @@ impl VectorService for VectorServer {
|
||||
.table
|
||||
.ok_or_else(|| Status::invalid_argument("missing table"))?;
|
||||
let dataset = self.open(&table).await.map_err(open_status)?;
|
||||
// Lease the resolved version so maintenance cannot reclaim its files
|
||||
// while this query runs against it.
|
||||
let _lease = weed_vector_core::maintenance::try_pin(&dataset)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
|
||||
if req.query_vector.len() != resolved.dimension {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
@@ -494,6 +518,8 @@ impl VectorService for VectorServer {
|
||||
postfilter: req.postfilter,
|
||||
distance,
|
||||
nprobes: None,
|
||||
index_segments: None,
|
||||
fragments: None,
|
||||
};
|
||||
let hits = query::ann(&dataset, &resolved, &query)
|
||||
.await
|
||||
|
||||
Generated
+10
-10
@@ -86,7 +86,7 @@ version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -97,7 +97,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1350,7 +1350,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2404,7 +2404,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3416,14 +3416,14 @@ dependencies = [
|
||||
"errno 0.3.14",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.45"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
@@ -3701,7 +3701,7 @@ version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno 0.2.8",
|
||||
"errno 0.3.14",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -3768,7 +3768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3902,7 +3902,7 @@ dependencies = [
|
||||
"getrandom 0.4.2",
|
||||
"once_cell",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -102,6 +102,22 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors Go's rejectHttpsDowngrade: a redirect must not downgrade a request
|
||||
/// carrying data and auth headers from https to plaintext.
|
||||
fn redirect_is_https_downgrade(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
|
||||
matches!(previous.first(), Some(url) if url.scheme() == "https") && next.scheme() != "https"
|
||||
}
|
||||
|
||||
fn reject_https_downgrade(attempt: reqwest::redirect::Attempt) -> reqwest::redirect::Action {
|
||||
if attempt.previous().len() >= 10 {
|
||||
attempt.error("redirect limit reached")
|
||||
} else if redirect_is_https_downgrade(attempt.previous(), attempt.url()) {
|
||||
attempt.error("redirect downgraded https to plaintext")
|
||||
} else {
|
||||
attempt.follow()
|
||||
}
|
||||
}
|
||||
|
||||
fn build_outgoing_http_client(
|
||||
config: &VolumeServerConfig,
|
||||
) -> Result<(reqwest::Client, String), Box<dyn std::error::Error>> {
|
||||
@@ -110,11 +126,17 @@ fn build_outgoing_http_client(
|
||||
} else {
|
||||
"http"
|
||||
};
|
||||
let redirect_policy = reqwest::redirect::Policy::custom(reject_https_downgrade);
|
||||
if !config.https_client_enabled {
|
||||
return Ok((reqwest::Client::new(), scheme.to_string()));
|
||||
return Ok((
|
||||
reqwest::Client::builder()
|
||||
.redirect(redirect_policy)
|
||||
.build()?,
|
||||
scheme.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut builder = reqwest::Client::builder();
|
||||
let mut builder = reqwest::Client::builder().redirect(redirect_policy);
|
||||
if !config.https_client_ca_file.is_empty() {
|
||||
let ca_pem = std::fs::read(&config.https_client_ca_file).map_err(|e| {
|
||||
format!(
|
||||
@@ -1152,4 +1174,19 @@ mod tests {
|
||||
cipher_suites: String::new(),
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_redirect_is_https_downgrade() {
|
||||
use super::redirect_is_https_downgrade;
|
||||
let https = reqwest::Url::parse("https://peer:8443/1?type=replicate").unwrap();
|
||||
let http = reqwest::Url::parse("http://other:8080/1?type=replicate").unwrap();
|
||||
assert!(redirect_is_https_downgrade(&[https.clone()], &http));
|
||||
assert!(!redirect_is_https_downgrade(&[http.clone()], &https));
|
||||
assert!(!redirect_is_https_downgrade(&[http.clone()], &http));
|
||||
assert!(!redirect_is_https_downgrade(&[https.clone()], &https));
|
||||
assert!(!redirect_is_https_downgrade(&[], &http));
|
||||
// Only the origin scheme counts (Go's via[0]): a chain that started
|
||||
// plaintext loses nothing by returning to plaintext.
|
||||
assert!(!redirect_is_https_downgrade(&[http.clone(), https.clone()], &http));
|
||||
}
|
||||
}
|
||||
@@ -5076,15 +5076,25 @@ impl VolumeServer for VolumeGrpcService {
|
||||
handles.push(tokio::spawn(async move {
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.part("file", reqwest::multipart::Part::bytes(data_clone));
|
||||
client_clone
|
||||
let resp = client_clone
|
||||
.post(&url)
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|e| {
|
||||
format!("remote write needle {} size {}: {}", needle_id, size, e)
|
||||
})
|
||||
})?;
|
||||
if resp.status().is_success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"remote write needle {} size {}: {} returned status {}",
|
||||
needle_id,
|
||||
size,
|
||||
url,
|
||||
resp.status()
|
||||
))
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,9 +55,19 @@ pub async fn run_heartbeat_with_state(
|
||||
config.master_addresses
|
||||
);
|
||||
|
||||
if config.master_addresses.is_empty() {
|
||||
warn!("Volume server has no master addresses to heartbeat to; heartbeats disabled");
|
||||
state.is_heartbeating.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
loop {
|
||||
for master_addr in &config.master_addresses {
|
||||
@@ -100,6 +110,7 @@ pub async fn run_heartbeat_with_state(
|
||||
&target_addr,
|
||||
pulse,
|
||||
&mut shutdown_rx,
|
||||
&mut confirmed_leader_once,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -159,7 +170,18 @@ pub async fn run_heartbeat_with_state(
|
||||
// adding to it.
|
||||
let retry_at = tokio::time::Instant::now() + pulse;
|
||||
refresh_leader_from_peers(&config, &state, pulse).await;
|
||||
tokio::time::sleep_until(retry_at).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)
|
||||
{
|
||||
// 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.
|
||||
wait = Duration::from_secs(1);
|
||||
}
|
||||
tokio::time::sleep(wait).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,19 +192,9 @@ pub async fn run_heartbeat_with_state(
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a leader redirect, skip the sleep and reconnect immediately
|
||||
if new_leader.is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(pulse) => {}
|
||||
_ = shutdown_rx.recv() => {
|
||||
state.is_heartbeating.store(false, Ordering::Relaxed);
|
||||
info!("Heartbeat shutting down");
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Pacing lives in the per-attempt error path, as in Go: a failed try
|
||||
// already slept its retry delay, so a round-losing pass over the seed
|
||||
// list restarts right away.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,6 +459,7 @@ async fn do_heartbeat(
|
||||
current_master: &str,
|
||||
pulse: Duration,
|
||||
shutdown_rx: &mut broadcast::Receiver<()>,
|
||||
confirmed_leader_once: &mut bool,
|
||||
) -> Result<Option<String>, Box<dyn std::error::Error>> {
|
||||
let channel = connect_channel(
|
||||
grpc_addr,
|
||||
@@ -516,6 +529,7 @@ async fn do_heartbeat(
|
||||
// naming a leader, so this peer is the one lookups
|
||||
// go to.
|
||||
confirmed_leader = true;
|
||||
*confirmed_leader_once = true;
|
||||
publish_current_master(state, current_master).await;
|
||||
}
|
||||
if !hb_resp.duplicated_uuids.is_empty() {
|
||||
|
||||
Generated
+2
-2
@@ -5189,9 +5189,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.45"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
|
||||
@@ -149,7 +149,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.1.3-jre</version>
|
||||
<version>33.7.2-jre</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SnakeYAML - Fix CVEs -->
|
||||
@@ -177,7 +177,7 @@
|
||||
<dependency>
|
||||
<groupId>org.xerial.snappy</groupId>
|
||||
<artifactId>snappy-java</artifactId>
|
||||
<version>1.1.10.4</version>
|
||||
<version>1.1.10.9</version>
|
||||
</dependency>
|
||||
|
||||
<!-- DNS Java - Fix CVEs -->
|
||||
|
||||
+13
-13
@@ -8,13 +8,13 @@ require (
|
||||
github.com/seaweedfs/seaweedfs v0.0.0-00010101000000-000000000000
|
||||
github.com/segmentio/kafka-go v0.4.49
|
||||
github.com/stretchr/testify v1.12.1
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7
|
||||
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089
|
||||
)
|
||||
|
||||
replace github.com/seaweedfs/seaweedfs => ../../
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.2.3 // indirect
|
||||
github.com/andybalholm/brotli v1.2.7 // indirect
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
@@ -25,8 +25,8 @@ require (
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
|
||||
github.com/eapache/queue v1.1.0 // indirect
|
||||
github.com/ebitengine/purego v0.10.2 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
@@ -42,11 +42,11 @@ require (
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
|
||||
github.com/jhump/protoreflect v1.18.0 // indirect
|
||||
github.com/jhump/protoreflect v1.18.1 // indirect
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/karlseguin/ccache/v2 v2.0.8 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/compress v1.20.3 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/reedsolomon v1.14.2 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260627054121-477a66015f15 // indirect
|
||||
@@ -76,7 +76,7 @@ require (
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/spf13/viper v1.21.0 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1 // indirect
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 // indirect
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
@@ -90,13 +90,13 @@ require (
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/crypto v0.58.0 // indirect
|
||||
golang.org/x/image v0.46.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect
|
||||
golang.org/x/net v0.61.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
)
|
||||
+28
-28
@@ -1,7 +1,7 @@
|
||||
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
|
||||
cloud.google.com/go/compute v1.20.1 h1:6aKEtlUiwEpJzM001l0yFkpXmUVXaN8W+fbkb2AZNbg=
|
||||
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
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=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/IBM/sarama v1.46.0 h1:+YTM1fNd6WKMchlnLKRUB5Z0qD4M8YbvwIIPLvJD53s=
|
||||
@@ -10,8 +10,8 @@ github.com/alecthomas/assert/v2 v2.10.0 h1:jjRCHsj6hBJhkmhznrCzoNpbA3zqy0fYiUcYZ
|
||||
github.com/alecthomas/assert/v2 v2.10.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
|
||||
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
|
||||
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/andybalholm/brotli v1.2.3 h1:8H1qwOkl2LPfjf3YezB90JnCliZb6SInJ/OJkEbA5NQ=
|
||||
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
|
||||
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
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/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -44,12 +44,12 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
|
||||
github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
@@ -103,8 +103,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||
github.com/jhump/protoreflect v1.18.0 h1:TOz0MSR/0JOZ5kECB/0ufGnC2jdsgZ123Rd/k4Z5/2w=
|
||||
github.com/jhump/protoreflect v1.18.0/go.mod h1:ezWcltJIVF4zYdIFM+D/sHV4Oh5LNU08ORzCGfwvTz8=
|
||||
github.com/jhump/protoreflect v1.18.1 h1:h4odAaLg9wyn7yHxMF7sSkJ7JfLwK1oy37/1Pi212GE=
|
||||
github.com/jhump/protoreflect v1.18.1/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:Dw1rslK/VotaUGYsv53XVWITr+5RCPXfvvlGrM/+B6w=
|
||||
github.com/jhump/protoreflect/v2 v2.0.0-beta.1/go.mod h1:D9LBEowZyv8/iSu97FU2zmXG3JxVTmNw21mu63niFzU=
|
||||
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
|
||||
@@ -115,8 +115,8 @@ github.com/karlseguin/ccache/v2 v2.0.8 h1:lT38cE//uyf6KcFok0rlgXtGFBWxkI6h/qg4tb
|
||||
github.com/karlseguin/ccache/v2 v2.0.8/go.mod h1:2BDThcfQMf/c0jnZowt16eW405XIqZPavt+HoYEtcxQ=
|
||||
github.com/karlseguin/expect v1.0.2-0.20190806010014-778a5f0c6003 h1:vJ0Snvo+SLMY72r5J4sEfkuE7AFbixEP2qRbEcum/wA=
|
||||
github.com/karlseguin/expect v1.0.2-0.20190806010014-778a5f0c6003/go.mod h1:zNBxMY8P21owkeogJELCLeHIt+voOSduHYTFUbwRAV8=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
|
||||
github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/reedsolomon v1.14.2 h1:SafJYwpBBQBI6amHUygcjxZjXeN2HpiENHQDwuPWCCQ=
|
||||
@@ -202,8 +202,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2 h1:jUEsvCMD6fH25J8K/w3q/XnIx8W1lb8+YLaEEHIjHmc=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.2/go.mod h1:w2CLWKLMTX/PPYUEUPv3ltH0RXsw5S8suwNF46w9/Aw=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -268,8 +268,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
@@ -284,16 +284,16 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
|
||||
golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -311,8 +311,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -320,8 +320,8 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
@@ -332,10 +332,10 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 h1:cYNAzI2sUwhmCcoj9TxvihSrqsxt6uIkj3rDRhSDmW4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7 h1:5+EEM1fC0yjOZID0NUZVrE2+8M/+1TclNrSz/l1xMYs=
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260915183914-4e49413dcab7/go.mod h1:Ovl0ECo4xx5r4kn/6d4BPSNB7OIFuu6EAjOzjtVAKaM=
|
||||
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/grpc v1.86.0-dev.0.20261027044109-d619b5d02089 h1:8300TIaXaOq+IoVmVzsZKUP3z4PpTsxu0ArPkPV/4Ts=
|
||||
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089/go.mod h1:Zr6uoNHvZlKOMmDEULT/cdZrN8qcSkXRXPkw4ybjoxI=
|
||||
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6 h1:ExN12ndbJ608cboPYflpTny6mXSzPrDLh0iTaVrRrds=
|
||||
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8=
|
||||
google.golang.org/grpc/security/advancedtls v1.0.0 h1:/KQ7VP/1bs53/aopk9QhuPyFAp9Dm9Ejix3lzYkCrDA=
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<guava.version>32.0.0-jre</guava.version>
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package catalog_spark
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"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.
|
||||
func TestSparkRegisterTableServesItsData(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
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(`
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
t.Helper()
|
||||
key, ok := strings.CutPrefix(metadataFile, "s3://"+bucket+"/")
|
||||
if !ok {
|
||||
t.Fatalf("metadata file %s is not in bucket %s", metadataFile, bucket)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cfg := aws.Config{
|
||||
Region: "us-east-1",
|
||||
Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(env.accessKey, env.secretKey, "")),
|
||||
BaseEndpoint: aws.String(fmt.Sprintf("http://localhost:%d", env.s3Port)),
|
||||
}
|
||||
client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true })
|
||||
|
||||
obj, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
if err != nil {
|
||||
t.Fatalf("GetObject %s: %v", key, err)
|
||||
}
|
||||
content, err := io.ReadAll(obj.Body)
|
||||
obj.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", key, err)
|
||||
}
|
||||
|
||||
copyKey := path.Join(path.Dir(key), "00003-uploaded.metadata.json")
|
||||
if _, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(copyKey),
|
||||
Body: bytes.NewReader(content),
|
||||
}); err != nil {
|
||||
t.Fatalf("PutObject %s: %v", copyKey, err)
|
||||
}
|
||||
return "s3://" + bucket + "/" + copyKey
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
# End-to-end S3 Vectors conformance run:
|
||||
# weed mini (cluster + lance catalog) + weed s3 (s3vectors port) +
|
||||
# weed-vector-server (VectorService gRPC), then boto3 s3vectors calls.
|
||||
# weed-vector (VectorService gRPC), then boto3 s3vectors calls.
|
||||
WEED := ./weed
|
||||
VEC := ./weed-vector-server
|
||||
VEC := ./weed-vector
|
||||
|
||||
.PHONY: all test build clean FORCE
|
||||
|
||||
@@ -14,7 +14,7 @@ $(WEED): FORCE
|
||||
|
||||
$(VEC): FORCE
|
||||
cargo build --release --manifest-path ../../seaweed-vector/Cargo.toml -p weed-vector-server
|
||||
cp ../../seaweed-vector/target/release/weed-vector-server $(VEC)
|
||||
cp ../../seaweed-vector/target/release/weed-vector $(VEC)
|
||||
|
||||
FORCE:
|
||||
|
||||
|
||||
@@ -19,16 +19,18 @@ PIDS+=($!)
|
||||
|
||||
./weed s3 \
|
||||
-filer 127.0.0.1:8888 \
|
||||
-config s3.json \
|
||||
-ip 127.0.0.1 \
|
||||
-ip.bind 127.0.0.1 \
|
||||
-port 8334 \
|
||||
-port.lance 9102 \
|
||||
-port.vectors 9201 \
|
||||
-vectors.grpc 127.0.0.1:9301 &
|
||||
-port.lance 9102 &
|
||||
PIDS+=($!)
|
||||
|
||||
./weed-vector-server \
|
||||
./weed-vector \
|
||||
--namespace http://127.0.0.1:9102 \
|
||||
--masters 127.0.0.1:9333 \
|
||||
--storage-option aws_access_key_id=test \
|
||||
--storage-option aws_secret_access_key=test \
|
||||
--listen 127.0.0.1:9301 &
|
||||
PIDS+=($!)
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"identities": [
|
||||
{
|
||||
"name": "admin",
|
||||
"credentials": [
|
||||
{
|
||||
"accessKey": "test",
|
||||
"secretKey": "test"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
"Admin",
|
||||
"Read",
|
||||
"List",
|
||||
"Tagging",
|
||||
"Write"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
"""Boto3 conformance subset for the S3 Vectors API gateway.
|
||||
|
||||
Run via `make test` — a mini cluster, an s3 gateway with -port.vectors, and a
|
||||
weed-vector-server are up by then.
|
||||
Run via `make test` — a mini cluster, an s3 gateway serving the vectors API on its main port, and a
|
||||
weed-vector are up by then.
|
||||
"""
|
||||
|
||||
import boto3
|
||||
import pytest
|
||||
|
||||
ENDPOINT = "http://127.0.0.1:9201"
|
||||
ENDPOINT = "http://127.0.0.1:8334"
|
||||
BUCKET = "vectors-bucket"
|
||||
INDEX = "idx"
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/parquet-go/parquet-go"
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/plugin"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
||||
)
|
||||
@@ -106,6 +107,7 @@ func (s *AdminServer) GetIcebergTableDataPreview(ctx context.Context, catalogNam
|
||||
s.applyWorkerPreview(ctx, &data, bucketArn, namespaceParts, tableName, rowLimit)
|
||||
return data, nil
|
||||
}
|
||||
s.fillTableMetadata(ctx, &resp, bucketArn, namespace, tableName)
|
||||
if resp.Metadata == nil || len(resp.Metadata.FullMetadata) == 0 {
|
||||
data.PreviewError = "Table has no Iceberg metadata."
|
||||
return data, nil
|
||||
@@ -271,6 +273,33 @@ func (s *AdminServer) listIcebergDataFiles(ctx context.Context, bucketName, name
|
||||
return files, hasDeletes, notes, nil
|
||||
}
|
||||
|
||||
// fillTableMetadata reads the metadata file a location-only record points to:
|
||||
// a commit that outgrew the request-size limit stores no inline copy, and
|
||||
// without the file the page reports a healthy table as having no metadata.
|
||||
func (s *AdminServer) fillTableMetadata(ctx context.Context, resp *s3tables.GetTableResponse, bucketArn, namespaceDir, tableName string) {
|
||||
if resp.MetadataLocation == "" || (resp.Metadata != nil && len(resp.Metadata.FullMetadata) > 0) {
|
||||
return
|
||||
}
|
||||
bucketName, err := s3tables.ParseBucketNameFromARN(bucketArn)
|
||||
if err != nil {
|
||||
bucketName = ""
|
||||
}
|
||||
filerPath, err := icebergLocationToFilerPath(resp.MetadataLocation, bucketName, namespaceDir, tableName)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("iceberg: cannot resolve metadata location %s: %v", resp.MetadataLocation, err)
|
||||
return
|
||||
}
|
||||
content, err := s.readFilerFileContent(ctx, filerPath)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("iceberg: cannot read metadata at %s: %v", resp.MetadataLocation, err)
|
||||
return
|
||||
}
|
||||
if resp.Metadata == nil {
|
||||
resp.Metadata = &s3tables.TableMetadata{}
|
||||
}
|
||||
resp.Metadata.FullMetadata = content
|
||||
}
|
||||
|
||||
// icebergLocationToFilerPath maps an Iceberg file location (s3://bucket/...,
|
||||
// an absolute filer path, or a table-relative path like data/x.parquet) to a
|
||||
// filer path, which must stay under the table-buckets root.
|
||||
|
||||
@@ -388,6 +388,7 @@ func (s *AdminServer) GetIcebergTableDetailsData(ctx context.Context, catalogNam
|
||||
MetadataLocation: resp.MetadataLocation,
|
||||
}
|
||||
|
||||
s.fillTableMetadata(ctx, &resp, bucketArn, strings.Join(namespaceParts, "/"), tableName)
|
||||
applyIcebergMetadata(resp.Metadata, &details)
|
||||
s.applyWorkerObservation(&details, bucketArn, namespaceParts, resp.Name)
|
||||
return details, nil
|
||||
|
||||
@@ -14,6 +14,7 @@ const (
|
||||
FilerType = "filer"
|
||||
BrokerType = "broker"
|
||||
S3Type = "s3"
|
||||
VectorType = "vector"
|
||||
)
|
||||
|
||||
type FilerGroupName string
|
||||
@@ -37,6 +38,7 @@ type Cluster struct {
|
||||
filerGroups *ClusterNodeGroups
|
||||
brokerGroups *ClusterNodeGroups
|
||||
s3Groups *ClusterNodeGroups
|
||||
vectorGroups *ClusterNodeGroups
|
||||
}
|
||||
|
||||
func newClusterNodeGroups() *ClusterNodeGroups {
|
||||
@@ -92,6 +94,7 @@ func NewCluster() *Cluster {
|
||||
filerGroups: newClusterNodeGroups(),
|
||||
brokerGroups: newClusterNodeGroups(),
|
||||
s3Groups: newClusterNodeGroups(),
|
||||
vectorGroups: newClusterNodeGroups(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +107,8 @@ func (cluster *Cluster) AddClusterNode(ns, nodeType string, dataCenter DataCente
|
||||
return cluster.brokerGroups.AddClusterNode(filerGroup, nodeType, dataCenter, rack, address, version)
|
||||
case S3Type:
|
||||
return cluster.s3Groups.AddClusterNode(filerGroup, nodeType, dataCenter, rack, address, version)
|
||||
case VectorType:
|
||||
return cluster.vectorGroups.AddClusterNode(filerGroup, nodeType, dataCenter, rack, address, version)
|
||||
case MasterType:
|
||||
return buildClusterNodeUpdateMessage(true, filerGroup, nodeType, address)
|
||||
}
|
||||
@@ -119,6 +124,8 @@ func (cluster *Cluster) RemoveClusterNode(ns string, nodeType string, address pb
|
||||
return cluster.brokerGroups.RemoveClusterNode(filerGroup, nodeType, address)
|
||||
case S3Type:
|
||||
return cluster.s3Groups.RemoveClusterNode(filerGroup, nodeType, address)
|
||||
case VectorType:
|
||||
return cluster.vectorGroups.RemoveClusterNode(filerGroup, nodeType, address)
|
||||
case MasterType:
|
||||
return buildClusterNodeUpdateMessage(false, filerGroup, nodeType, address)
|
||||
}
|
||||
@@ -133,6 +140,8 @@ func (cluster *Cluster) ListClusterNode(filerGroup FilerGroupName, nodeType stri
|
||||
return cluster.brokerGroups.ListClusterNode(filerGroup)
|
||||
case S3Type:
|
||||
return cluster.s3Groups.ListClusterNode(filerGroup)
|
||||
case VectorType:
|
||||
return cluster.vectorGroups.ListClusterNode(filerGroup)
|
||||
case MasterType:
|
||||
}
|
||||
return
|
||||
@@ -160,6 +169,8 @@ func (cluster *Cluster) IsKnownNode(nodeType string, address pb.ServerAddress) b
|
||||
groups = cluster.brokerGroups
|
||||
case S3Type:
|
||||
groups = cluster.s3Groups
|
||||
case VectorType:
|
||||
groups = cluster.vectorGroups
|
||||
default:
|
||||
return false
|
||||
}
|
||||
|
||||
+71
-29
@@ -311,21 +311,46 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
|
||||
// waiter must pick it up promptly, otherwise cross-mount write handoff stalls
|
||||
// long enough to time out clients.
|
||||
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
|
||||
// The retry window bounds acquisition as a whole: the clock starts
|
||||
// before the first attempt and each attempt gets what is left of it, so
|
||||
// a bounded attempt cannot burn the window inside one call.
|
||||
// The retry window bounds the attempts against one route: the clock
|
||||
// starts before the first attempt and each attempt gets what is left
|
||||
// of it. A spent window on a non-seed target falls back to the seed
|
||||
// filer — which can forward to the real owner — and that route gets
|
||||
// its own window, so a reachable fallback is always tried.
|
||||
unavailableSince := time.Now()
|
||||
for lock.renewToken == "" {
|
||||
// The seed route gets one fresh window per acquisition: the seed can
|
||||
// redirect back to a dead primary via LockHostMovedTo, and refilling the
|
||||
// window on every return to the seed would make that cycle unbounded.
|
||||
seedRetried := false
|
||||
var err error
|
||||
for {
|
||||
attemptTimeout := lock.lc.lockRpcTimeout
|
||||
if remaining := lock.lc.noLockServerRetryPeriod - time.Since(unavailableSince); remaining < attemptTimeout {
|
||||
if remaining <= 0 {
|
||||
return fmt.Errorf("no lock server within %s", lock.lc.noLockServerRetryPeriod)
|
||||
if lock.hostFiler.Equals(lock.lc.seedFiler) || seedRetried {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("lock %s: no lock server granted within %s", lock.key, lock.lc.noLockServerRetryPeriod)
|
||||
}
|
||||
return err
|
||||
}
|
||||
glog.V(0).Infof("LOCK: no response within %s for key=%s filer=%s, falling back to seed filer=%s",
|
||||
lock.lc.noLockServerRetryPeriod, lock.key, lock.hostFiler, lock.lc.seedFiler)
|
||||
lock.hostFiler = lock.lc.seedFiler
|
||||
seedRetried = true
|
||||
unavailableSince = time.Now()
|
||||
continue
|
||||
}
|
||||
attemptTimeout = remaining
|
||||
}
|
||||
err := lock.attemptToLockWithin(lockDuration, attemptTimeout)
|
||||
hostBefore := lock.hostFiler
|
||||
var granted bool
|
||||
granted, err = lock.attemptToLockWithin(lockDuration, attemptTimeout)
|
||||
if err == nil {
|
||||
unavailableSince = time.Now()
|
||||
if granted {
|
||||
return nil
|
||||
}
|
||||
// A clean LockHostMovedTo redirect returns no error and no
|
||||
// verdict; it must still count against the window, or a redirect
|
||||
// cycle between ring-disagreeing filers retries forever.
|
||||
continue
|
||||
}
|
||||
glog.V(1).Infof("create lock %s: %v", lock.key, err)
|
||||
@@ -336,26 +361,28 @@ func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
|
||||
continue
|
||||
}
|
||||
// Anything else — "no lock server found", a dead ring member refusing
|
||||
// connections — is a systemic fault waiting cannot fix; give up once
|
||||
// it persists past the retry period.
|
||||
if time.Since(unavailableSince) > lock.lc.noLockServerRetryPeriod {
|
||||
return err
|
||||
// connections — is a systemic fault waiting cannot fix. A failed
|
||||
// attempt that fell back to the seed route gets a fresh window for
|
||||
// it; a server redirect stays inside the current one.
|
||||
if !seedRetried && lock.hostFiler.Equals(lock.lc.seedFiler) && !hostBefore.Equals(lock.lc.seedFiler) {
|
||||
seedRetried = true
|
||||
unavailableSince = time.Now()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
|
||||
return lock.attemptToLockWithin(lockDuration, lock.lc.lockRpcTimeout)
|
||||
_, err := lock.attemptToLockWithin(lockDuration, lock.lc.lockRpcTimeout)
|
||||
return err
|
||||
}
|
||||
|
||||
func (lock *LiveLock) attemptToLockWithin(lockDuration, attemptTimeout time.Duration) error {
|
||||
func (lock *LiveLock) attemptToLockWithin(lockDuration, attemptTimeout time.Duration) (granted bool, err error) {
|
||||
glog.V(4).Infof("LOCK: AttemptToLock key=%s owner=%s", lock.key, lock.self)
|
||||
errorMessage, err := lock.doLock(lockDuration, attemptTimeout)
|
||||
errorMessage, granted, err := lock.doLock(lockDuration, attemptTimeout)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("LOCK: doLock failed for key=%s: %v", lock.key, err)
|
||||
time.Sleep(time.Second)
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if errorMessage != "" {
|
||||
if strings.Contains(errorMessage, "lock already owned") {
|
||||
@@ -364,14 +391,21 @@ func (lock *LiveLock) attemptToLockWithin(lockDuration, attemptTimeout time.Dura
|
||||
glog.V(2).Infof("LOCK: doLock returned error message for key=%s: %s", lock.key, errorMessage)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
return fmt.Errorf("%v", errorMessage)
|
||||
return false, fmt.Errorf("%v", errorMessage)
|
||||
}
|
||||
if !granted {
|
||||
// A bare LockHostMovedTo redirect carries no verdict: nothing was
|
||||
// acquired, so leave isLocked as it is and keep the same ~1s cadence
|
||||
// as other retries.
|
||||
time.Sleep(time.Second)
|
||||
return false, nil
|
||||
}
|
||||
if atomic.LoadInt32(&lock.isLocked) == 0 {
|
||||
// Only log when transitioning from unlocked to locked
|
||||
glog.V(1).Infof("LOCK: Successfully acquired key=%s owner=%s", lock.key, lock.self)
|
||||
}
|
||||
atomic.StoreInt32(&lock.isLocked, 1)
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (lock *LiveLock) StopShortLivedLock() error {
|
||||
@@ -382,7 +416,9 @@ func (lock *LiveLock) StopShortLivedLock() error {
|
||||
atomic.StoreInt32(&lock.isLocked, 0)
|
||||
}()
|
||||
return pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.DistributedUnlock(context.Background(), &filer_pb.UnlockRequest{
|
||||
ctx, cancel := context.WithTimeout(context.Background(), lock.lc.lockRpcTimeout)
|
||||
defer cancel()
|
||||
_, err := client.DistributedUnlock(ctx, &filer_pb.UnlockRequest{
|
||||
Name: lock.key,
|
||||
RenewToken: lock.renewToken,
|
||||
})
|
||||
@@ -428,19 +464,18 @@ func (lock *LiveLock) Stop() error {
|
||||
return lock.StopShortLivedLock()
|
||||
}
|
||||
|
||||
func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorMessage string, err error) {
|
||||
func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorMessage string, granted bool, err error) {
|
||||
glog.V(4).Infof("LOCK: doLock calling DistributedLock - key=%s filer=%s owner=%s",
|
||||
lock.key, lock.hostFiler, lock.self)
|
||||
|
||||
previousHostFiler := lock.hostFiler
|
||||
previousOwner := lock.owner
|
||||
|
||||
// Bound the whole attempt — connection acquisition included — so an
|
||||
// unreachable owner fails within the retry window.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
|
||||
defer cancel()
|
||||
err = pb.WithGrpcClient(ctx, false, 0, func(grpcConnection *grpc.ClientConn) error {
|
||||
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
|
||||
err = pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Bound each attempt: a ring member that is reachable from the masters
|
||||
// but not from this filer would otherwise block on the connect timeout.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
|
||||
defer cancel()
|
||||
resp, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
|
||||
Name: lock.key,
|
||||
SecondsToLock: int64(lockDuration.Seconds()),
|
||||
@@ -450,14 +485,21 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
})
|
||||
glog.V(4).Infof("LOCK: DistributedLock response - key=%s err=%v", lock.key, err)
|
||||
if err == nil && resp != nil {
|
||||
lock.renewToken = resp.RenewToken
|
||||
// Only a verdict replaces the token: a grant carries the new
|
||||
// token, a rejection carries an error. A bare LockHostMovedTo
|
||||
// redirect answers neither and must not drop a held token —
|
||||
// the next attempt can still renew with it on the new host.
|
||||
granted = resp.Error == "" && resp.RenewToken != ""
|
||||
if resp.RenewToken != "" || resp.Error != "" {
|
||||
lock.renewToken = resp.RenewToken
|
||||
}
|
||||
if resp.Generation > 0 {
|
||||
atomic.StoreInt64(&lock.generation, resp.Generation)
|
||||
}
|
||||
lock.consecutiveFailures = 0 // Reset failure counter on success
|
||||
glog.V(4).Infof("LOCK: Got renewToken for key=%s", lock.key)
|
||||
} else {
|
||||
// the request may have renewed the lease server-side before its
|
||||
// The request may have renewed the lease server-side before its
|
||||
// response was lost: the last token can still be valid, so the
|
||||
// next attempt retries with it. A definitive rejection clears it
|
||||
// through the response's empty RenewToken.
|
||||
@@ -485,7 +527,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
}
|
||||
}
|
||||
return err
|
||||
}, lock.hostFiler.ToGrpcAddress(), false, lock.grpcDialOption)
|
||||
})
|
||||
|
||||
if err != nil && !lock.hostFiler.Equals(lock.lc.seedFiler) {
|
||||
lock.consecutiveFailures++
|
||||
|
||||
@@ -291,11 +291,195 @@ type hangingLockFiler struct {
|
||||
}
|
||||
|
||||
func (s *hangingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
type grantingLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
}
|
||||
|
||||
func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
}
|
||||
|
||||
// A ring member that accepts connections but never answers must not swallow
|
||||
// the retry window: when its budget is spent the seed route still gets an
|
||||
// attempt before acquisition gives up.
|
||||
func TestNewShortLivedLockFallsBackToSeedOnHangingPrimary(t *testing.T) {
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
hangListener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
hangServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(hangServer, &hangingLockFiler{})
|
||||
go hangServer.Serve(hangListener)
|
||||
defer hangServer.Stop()
|
||||
|
||||
seedListener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
seedServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(seedServer, &grantingLockFiler{})
|
||||
go seedServer.Serve(seedListener)
|
||||
defer seedServer.Stop()
|
||||
|
||||
hangHost, hangPort, err := net.SplitHostPort(hangListener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
seedHost, seedPort, err := net.SplitHostPort(seedListener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
// ServerAddress.Equals compares the http port, so the two fake filers
|
||||
// need distinct ones even though only the grpc port is dialed.
|
||||
seedAddr := pb.ServerAddress(fmt.Sprintf("%s:1.%s", seedHost, seedPort))
|
||||
primaryAddr := pb.ServerAddress(fmt.Sprintf("%s:2.%s", hangHost, hangPort))
|
||||
|
||||
lc := NewLockClient(dialOption, seedAddr)
|
||||
lc.lockRpcTimeout = 50 * time.Millisecond
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
lc.SetRing([]pb.ServerAddress{primaryAddr}, 1)
|
||||
|
||||
start := time.Now()
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if lock == nil {
|
||||
t.Fatal("expected the seed fallback to acquire the lock")
|
||||
}
|
||||
if !lock.hostFiler.Equals(seedAddr) {
|
||||
t.Fatalf("expected acquisition through the seed %s, got %s", seedAddr, lock.hostFiler)
|
||||
}
|
||||
if elapsed > 5*time.Second {
|
||||
t.Fatalf("lock acquisition took %v, expected it bounded by the per-route window", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
type redirectingLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
movedTo string
|
||||
}
|
||||
|
||||
func (s *redirectingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{Error: "forward failed", LockHostMovedTo: s.movedTo}, nil
|
||||
}
|
||||
|
||||
// The seed can redirect back to a dead primary via LockHostMovedTo. The seed
|
||||
// fallback gets one fresh window per acquisition — letting every return to
|
||||
// the seed refill it would make the primary->seed->primary cycle unbounded.
|
||||
func TestNewShortLivedLockBoundsSeedRedirectCycle(t *testing.T) {
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
hangListener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
hangServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(hangServer, &hangingLockFiler{})
|
||||
go hangServer.Serve(hangListener)
|
||||
defer hangServer.Stop()
|
||||
|
||||
hangHost, hangPort, err := net.SplitHostPort(hangListener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
primaryAddr := pb.ServerAddress(fmt.Sprintf("%s:2.%s", hangHost, hangPort))
|
||||
|
||||
seedListener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
seedServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(seedServer, &redirectingLockFiler{movedTo: string(primaryAddr)})
|
||||
go seedServer.Serve(seedListener)
|
||||
defer seedServer.Stop()
|
||||
|
||||
seedHost, seedPort, err := net.SplitHostPort(seedListener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
seedAddr := pb.ServerAddress(fmt.Sprintf("%s:1.%s", seedHost, seedPort))
|
||||
|
||||
lc := NewLockClient(dialOption, seedAddr)
|
||||
lc.lockRpcTimeout = 50 * time.Millisecond
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
|
||||
start := time.Now()
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if lock != nil {
|
||||
t.Fatal("expected nil lock when the seed keeps redirecting to a dead primary")
|
||||
}
|
||||
if elapsed > 5*time.Second {
|
||||
t.Fatalf("lock acquisition took %v, expected a bounded redirect cycle", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
type cleanRedirectLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
movedTo string
|
||||
}
|
||||
|
||||
func (s *cleanRedirectLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{LockHostMovedTo: s.movedTo}, nil
|
||||
}
|
||||
|
||||
// A second hop whose ring disagrees answers with a bare LockHostMovedTo and
|
||||
// no error, so the first hop relays a clean redirect. Two filers pointing at
|
||||
// each other then bounce the client forever if every redirect refills the
|
||||
// window — tokenless redirects must count against it like failures do.
|
||||
func TestNewShortLivedLockBoundsCleanRedirectCycle(t *testing.T) {
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
listenerA, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
listenerB, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
hostA, portA, err := net.SplitHostPort(listenerA.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
hostB, portB, err := net.SplitHostPort(listenerB.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
addrA := pb.ServerAddress(fmt.Sprintf("%s:1.%s", hostA, portA))
|
||||
addrB := pb.ServerAddress(fmt.Sprintf("%s:2.%s", hostB, portB))
|
||||
|
||||
serverA := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(serverA, &cleanRedirectLockFiler{movedTo: string(addrB)})
|
||||
go serverA.Serve(listenerA)
|
||||
defer serverA.Stop()
|
||||
serverB := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(serverB, &cleanRedirectLockFiler{movedTo: string(addrA)})
|
||||
go serverB.Serve(listenerB)
|
||||
defer serverB.Stop()
|
||||
|
||||
lc := NewLockClient(dialOption, addrA)
|
||||
lc.lockRpcTimeout = 50 * time.Millisecond
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
|
||||
done := make(chan *LiveLock, 1)
|
||||
go func() {
|
||||
done <- lc.NewShortLivedLock("test-key", "test-owner")
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(30 * time.Second):
|
||||
return nil, fmt.Errorf("test: server never answered")
|
||||
case lock := <-done:
|
||||
if lock != nil {
|
||||
t.Fatal("expected nil lock when the ring keeps redirecting")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("clean redirect cycle was not bounded by the retry window")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,15 +499,16 @@ func TestDoLockKeepsRenewTokenOnError(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
filerAddr := pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))
|
||||
lc := NewLockClient(dialOption, filerAddr)
|
||||
lock := &LiveLock{
|
||||
key: "test-key",
|
||||
renewToken: "tok",
|
||||
hostFiler: pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)),
|
||||
hostFiler: filerAddr,
|
||||
grpcDialOption: dialOption,
|
||||
lc: lc,
|
||||
}
|
||||
if _, err := lock.doLock(time.Second, 50*time.Millisecond); err == nil {
|
||||
if _, _, err := lock.doLock(time.Second, 50*time.Millisecond); err == nil {
|
||||
t.Fatal("expected the attempt to fail against a dead member")
|
||||
}
|
||||
if lock.renewToken != "tok" {
|
||||
@@ -331,16 +516,15 @@ func TestDoLockKeepsRenewTokenOnError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A ring member that accepts connections but never answers stalls the caller
|
||||
// the same way a partially partitioned peer does: each attempt must fail
|
||||
// within the per-attempt bound so the retry window can give up.
|
||||
func TestNewShortLivedLockBoundsHangingAttempt(t *testing.T) {
|
||||
// A definitive rejection answers with an empty token, which clears the stale
|
||||
// one — only transport failures keep it.
|
||||
func TestDoLockClearsRenewTokenOnRejection(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &hangingLockFiler{})
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &contendedLockFiler{})
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
@@ -349,19 +533,57 @@ func TestNewShortLivedLockBoundsHangingAttempt(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.noLockServerRetryPeriod = 200 * time.Millisecond
|
||||
lc.lockRpcTimeout = 50 * time.Millisecond
|
||||
|
||||
start := time.Now()
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if lock != nil {
|
||||
t.Fatal("expected nil lock when the ring member never answers")
|
||||
filerAddr := pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))
|
||||
lc := NewLockClient(dialOption, filerAddr)
|
||||
lock := &LiveLock{
|
||||
key: "test-key",
|
||||
renewToken: "tok",
|
||||
hostFiler: filerAddr,
|
||||
grpcDialOption: dialOption,
|
||||
lc: lc,
|
||||
}
|
||||
if elapsed > 5*time.Second {
|
||||
t.Fatalf("lock acquisition took %v, expected it bounded by the per-attempt timeout", elapsed)
|
||||
errorMessage, _, err := lock.doLock(time.Second, time.Second)
|
||||
if err != nil || errorMessage == "" {
|
||||
t.Fatalf("expected a contended attempt to report an error message, got errorMessage=%q err=%v", errorMessage, err)
|
||||
}
|
||||
if lock.renewToken != "" {
|
||||
t.Errorf("renewToken = %q, want it cleared by the rejection", lock.renewToken)
|
||||
}
|
||||
}
|
||||
|
||||
// A bare LockHostMovedTo redirect is not a verdict on the token: the
|
||||
// request may have committed a renewal before the ring moved, so the held
|
||||
// token survives to renew against the new host.
|
||||
func TestDoLockKeepsRenewTokenOnCleanRedirect(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, &cleanRedirectLockFiler{movedTo: "127.0.0.1:1.1"})
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
filerAddr := pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port))
|
||||
lc := NewLockClient(dialOption, filerAddr)
|
||||
lock := &LiveLock{
|
||||
key: "test-key",
|
||||
renewToken: "tok",
|
||||
hostFiler: filerAddr,
|
||||
grpcDialOption: dialOption,
|
||||
lc: lc,
|
||||
}
|
||||
errorMessage, _, err := lock.doLock(time.Second, time.Second)
|
||||
if err != nil || errorMessage != "" {
|
||||
t.Fatalf("expected a clean redirect, got errorMessage=%q err=%v", errorMessage, err)
|
||||
}
|
||||
if lock.renewToken != "tok" {
|
||||
t.Errorf("renewToken = %q, want it kept across the redirect", lock.renewToken)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ var NoLockServerError = fmt.Errorf("no lock server found")
|
||||
// The caller (filer server) provides this to avoid a circular dependency.
|
||||
// seq is a per-lock monotonic sequence number for causal ordering — the backup
|
||||
// rejects mutations with seq <= its current seq for that key.
|
||||
type ReplicateFunc func(server pb.ServerAddress, key string, expiredAtNs int64, token string, owner string, generation int64, seq int64, isUnlock bool)
|
||||
type ReplicateFunc func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool)
|
||||
|
||||
type DistributedLockManager struct {
|
||||
lockManager *LockManager
|
||||
@@ -50,7 +50,7 @@ func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64
|
||||
var seq int64
|
||||
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
|
||||
if err == nil && renewToken != "" {
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, owner, generation, seq, false)
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64
|
||||
var seq int64
|
||||
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
|
||||
if err == nil && renewToken != "" {
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, owner, generation, seq, false)
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -101,7 +101,7 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
|
||||
var seq int64
|
||||
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
|
||||
if isUnlocked {
|
||||
dlm.replicateToBackup(key, 0, "", "", generation, seq, true)
|
||||
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
|
||||
var seq int64
|
||||
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
|
||||
if isUnlocked {
|
||||
dlm.replicateToBackup(key, 0, "", "", generation, seq, true)
|
||||
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -121,15 +121,15 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
|
||||
// InsertLock is used to insert a lock to a server unconditionally.
|
||||
// It is used when a server is down and the lock is moved to another server.
|
||||
// After inserting, it replicates to the backup for this key.
|
||||
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string, owner string, generation int64, seq int64) {
|
||||
if dlm.lockManager.InsertLock(key, expiredAtNs, token, owner, generation, seq) {
|
||||
dlm.replicateToBackup(key, expiredAtNs, token, owner, generation, seq, false)
|
||||
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
|
||||
if dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq) {
|
||||
dlm.replicateToBackup(key, expiredAtNs, token, prevToken, owner, generation, seq, false)
|
||||
}
|
||||
}
|
||||
|
||||
// InsertBackupLock inserts a lock as a backup copy, rejecting stale seq
|
||||
func (dlm *DistributedLockManager) InsertBackupLock(key string, expiredAtNs int64, token string, owner string, generation int64, seq int64) {
|
||||
dlm.lockManager.InsertBackupLock(key, expiredAtNs, token, owner, generation, seq)
|
||||
func (dlm *DistributedLockManager) InsertBackupLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
|
||||
dlm.lockManager.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
|
||||
}
|
||||
|
||||
// RemoveBackupLock removes a backup lock unconditionally
|
||||
@@ -181,12 +181,12 @@ func (dlm *DistributedLockManager) GetLock(key string) (*Lock, bool) {
|
||||
}
|
||||
|
||||
// replicateToBackup asynchronously replicates a lock operation to the backup server
|
||||
func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int64, token string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
_, backup := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if backup == "" {
|
||||
return // single-server deployment, no backup
|
||||
}
|
||||
if dlm.ReplicateFn != nil {
|
||||
go dlm.ReplicateFn(backup, key, expiredAtNs, token, owner, generation, seq, isUnlock)
|
||||
go dlm.ReplicateFn(backup, key, expiredAtNs, token, prevToken, owner, generation, seq, isUnlock)
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
|
||||
// Wire up replication: each node's ReplicateFn calls the backup's DLM directly
|
||||
for _, dlm := range c.nodes {
|
||||
d := dlm // capture
|
||||
d.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
d.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
c.mu.Lock()
|
||||
target, ok := c.nodes[server]
|
||||
c.mu.Unlock()
|
||||
@@ -43,7 +43,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
|
||||
if isUnlock {
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq)
|
||||
} else {
|
||||
target.InsertBackupLock(key, expiredAtNs, token, owner, generation, seq)
|
||||
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
|
||||
c.mu.Unlock()
|
||||
|
||||
// Wire up replication
|
||||
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
c.mu.Lock()
|
||||
target, ok := c.nodes[server]
|
||||
c.mu.Unlock()
|
||||
@@ -80,7 +80,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
|
||||
if isUnlock {
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq)
|
||||
} else {
|
||||
target.InsertBackupLock(key, expiredAtNs, token, owner, generation, seq)
|
||||
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,7 +311,7 @@ func TestDLM_RollingRestart(t *testing.T) {
|
||||
for _, lock := range dlm.AllLocks() {
|
||||
newPrimary, _ := dlm.LockRing.GetPrimaryAndBackup(lock.Key)
|
||||
if newPrimary == dlm.Host && !lock.IsBackup {
|
||||
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.Owner, lock.Generation, lock.Seq, false)
|
||||
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -370,7 +370,7 @@ func TestDLM_ReplicationFailure_PrimaryStillWorks(t *testing.T) {
|
||||
|
||||
// Break replication by setting a no-op ReplicateFn on all nodes
|
||||
for _, dlm := range cluster.getNodes() {
|
||||
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
// Simulate replication failure: do nothing
|
||||
}
|
||||
}
|
||||
@@ -539,7 +539,7 @@ func TestDLM_NodeDropAndJoin_OwnershipDisruption(t *testing.T) {
|
||||
for _, lock := range dlm.AllLocks() {
|
||||
p, _ := dlm.LockRing.GetPrimaryAndBackup(lock.Key)
|
||||
if p == dlm.Host && !lock.IsBackup {
|
||||
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.Owner, lock.Generation, lock.Seq, false)
|
||||
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -558,7 +558,7 @@ func TestDLM_NodeDropAndJoin_OwnershipDisruption(t *testing.T) {
|
||||
// This lock should move to the new primary
|
||||
target := cluster.get(p)
|
||||
if target != nil {
|
||||
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.Owner, lock.Generation, lock.Seq)
|
||||
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq)
|
||||
dlm.DemoteLock(lock.Key)
|
||||
}
|
||||
}
|
||||
@@ -671,26 +671,96 @@ func TestDLM_RenewalDuringTransferWindow(t *testing.T) {
|
||||
t.Logf("Key %s: primary changed from %s to %s, but renewal on old primary succeeded", key, primaryHost, newPrimary)
|
||||
}
|
||||
|
||||
func TestDLM_ReplayedRenewalExtendsBackupExpiry(t *testing.T) {
|
||||
hosts := []pb.ServerAddress{"filer1:8888", "filer2:8888", "filer3:8888"}
|
||||
cluster := newTestCluster(hosts...)
|
||||
|
||||
key := "replay-expiry-lock"
|
||||
token1, _, primaryHost, err := cluster.acquireLock(key, "owner1", 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, backup := cluster.get(primaryHost).LockRing.GetPrimaryAndBackup(key)
|
||||
require.NotEmpty(t, backup)
|
||||
backupDlm := cluster.get(backup)
|
||||
primary := cluster.get(primaryHost)
|
||||
|
||||
// Renewal rotates to token2, replicating seq=2 with expiry e1.
|
||||
e1 := time.Now().Add(30 * time.Second).UnixNano()
|
||||
_, token2, _, _, err := primary.LockWithTimeout(key, e1, token1, "owner1")
|
||||
require.NoError(t, err)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// The renewal response was lost; the client retries with the superseded
|
||||
// token and a later expiry e2.
|
||||
e2 := time.Now().Add(60 * time.Second).UnixNano()
|
||||
_, replayed, _, _, err := primary.LockWithTimeout(key, e2, token1, "owner1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, token2, replayed)
|
||||
|
||||
// The backup must accept the extended expiry instead of rejecting the
|
||||
// replayed mutation as stale.
|
||||
require.Eventually(t, func() bool {
|
||||
lock, found := backupDlm.GetLock(key)
|
||||
return found && lock.ExpiredAtNs == e2 && lock.Seq == 3
|
||||
}, time.Second, time.Millisecond)
|
||||
}
|
||||
|
||||
func TestDLM_BackupPromotionKeepsLostRenewalRecovery(t *testing.T) {
|
||||
hosts := []pb.ServerAddress{"filer1:8888", "filer2:8888", "filer3:8888"}
|
||||
cluster := newTestCluster(hosts...)
|
||||
|
||||
key := "lost-renewal-move-lock"
|
||||
token1, _, primaryHost, err := cluster.acquireLock(key, "owner1", 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The renewal rotated the token; the client never learned token2.
|
||||
token2, _, err := cluster.renewLock(key, "owner1", token1, 30*time.Second, primaryHost)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, token1, token2)
|
||||
|
||||
_, backup := cluster.get(primaryHost).LockRing.GetPrimaryAndBackup(key)
|
||||
require.NotEmpty(t, backup)
|
||||
|
||||
// The backup copy must carry the superseded token too, or a promoted
|
||||
// backup could not serve a retry of the lost renewal.
|
||||
backupDlm := cluster.get(backup)
|
||||
require.Eventually(t, func() bool {
|
||||
lock, found := backupDlm.GetLock(key)
|
||||
return found && lock.Token == token2 && lock.PrevToken == token1
|
||||
}, time.Second, time.Millisecond)
|
||||
|
||||
// Primary dies; backup is promoted to primary.
|
||||
cluster.removeNode(primaryHost)
|
||||
require.True(t, backupDlm.PromoteLock(key))
|
||||
assert.Equal(t, backup, backupDlm.LockRing.GetPrimary(key))
|
||||
|
||||
// A retry with the superseded token recovers the current one.
|
||||
_, replayed, _, movedTo, err := backupDlm.LockWithTimeout(key, time.Now().Add(30*time.Second).UnixNano(), token1, "owner1")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, movedTo)
|
||||
assert.Equal(t, token2, replayed)
|
||||
}
|
||||
|
||||
func TestDLM_StaleReplicationRejected(t *testing.T) {
|
||||
// Verify that a stale replication (lower seq) does not overwrite a newer one
|
||||
lm := NewLockManager()
|
||||
|
||||
// Insert backup with seq=3
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "owner1", 1, 3)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 1, 3)
|
||||
lock, found := lm.GetLock("key1")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, "token-new", lock.Token)
|
||||
assert.Equal(t, int64(3), lock.Seq)
|
||||
|
||||
// Try to overwrite with stale seq=2 — should be rejected
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "owner1", 1, 2)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 1, 2)
|
||||
lock, found = lm.GetLock("key1")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, "token-new", lock.Token, "stale replication should be rejected")
|
||||
assert.Equal(t, int64(3), lock.Seq)
|
||||
|
||||
// Update with higher seq=4 — should succeed
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-newer", "owner1", 1, 4)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-newer", "", "owner1", 1, 4)
|
||||
lock, found = lm.GetLock("key1")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, "token-newer", lock.Token, "newer replication should be accepted")
|
||||
|
||||
@@ -221,7 +221,7 @@ func (lm *LockManager) SelectLocks(selectFn func(key string) bool) (locks []*Loc
|
||||
}
|
||||
|
||||
// InsertLock inserts a lock from a transfer if it is newer than the current state.
|
||||
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, owner string, generation int64, seq int64) bool {
|
||||
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) bool {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
|
||||
@@ -231,7 +231,7 @@ func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string,
|
||||
return false
|
||||
}
|
||||
}
|
||||
lm.locks[path] = &Lock{Token: token, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
|
||||
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
|
||||
lm.advanceGenerationFloor(generation)
|
||||
return true
|
||||
}
|
||||
@@ -240,7 +240,7 @@ func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string,
|
||||
// It rejects stale mutations by comparing (generation, seq). If a current primary
|
||||
// already exists on this node, newer replicated state refreshes that primary copy
|
||||
// without demoting it back to a backup.
|
||||
func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token string, owner string, generation int64, seq int64) {
|
||||
func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
|
||||
@@ -251,6 +251,7 @@ func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token st
|
||||
}
|
||||
lm.locks[path] = &Lock{
|
||||
Token: token,
|
||||
PrevToken: prevToken,
|
||||
ExpiredAtNs: expiredAtNs,
|
||||
Owner: owner,
|
||||
IsBackup: existing.IsBackup,
|
||||
@@ -260,7 +261,7 @@ func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token st
|
||||
lm.advanceGenerationFloor(generation)
|
||||
return
|
||||
}
|
||||
lm.locks[path] = &Lock{Token: token, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: true, Generation: generation, Seq: seq}
|
||||
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: true, Generation: generation, Seq: seq}
|
||||
lm.advanceGenerationFloor(generation)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
func TestLockManager_GetLockOwnerIgnoresExpiredLock(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
lm.InsertLock("key1", time.Now().Add(-time.Second).UnixNano(), "token1", "owner1", 7, 3)
|
||||
lm.InsertLock("key1", time.Now().Add(-time.Second).UnixNano(), "token1", "", "owner1", 7, 3)
|
||||
|
||||
owner, err := lm.GetLockOwner("key1")
|
||||
assert.Empty(t, owner)
|
||||
@@ -20,8 +20,8 @@ func TestLockManager_GetLockOwnerIgnoresExpiredLock(t *testing.T) {
|
||||
func TestLockManager_InsertLockRejectsStaleTransfer(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "owner1", 8, 4)
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "owner1", 7, 3)
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 4)
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 7, 3)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
@@ -33,7 +33,7 @@ func TestLockManager_InsertLockRejectsStaleTransfer(t *testing.T) {
|
||||
func TestLockManager_InsertLockAdvancesGenerationCounter(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token1", "owner1", 12, 1)
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token1", "", "owner1", 12, 1)
|
||||
|
||||
_, renewToken, generation, _, err := lm.Lock("key2", time.Now().Add(30*time.Second).UnixNano(), "", "owner2")
|
||||
assert.NoError(t, err)
|
||||
@@ -44,8 +44,8 @@ func TestLockManager_InsertLockAdvancesGenerationCounter(t *testing.T) {
|
||||
func TestLockManager_InsertBackupLockRejectsOlderGeneration(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "owner1", 8, 1)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "owner1", 7, 9)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 1)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 7, 9)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
@@ -57,10 +57,10 @@ func TestLockManager_InsertBackupLockRejectsOlderGeneration(t *testing.T) {
|
||||
func TestLockManager_InsertBackupLockKeepsPrimaryRole(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
ok := lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "owner1", 8, 1)
|
||||
ok := lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 8, 1)
|
||||
assert.True(t, ok)
|
||||
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "owner1", 8, 2)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 2)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
@@ -73,7 +73,7 @@ func TestLockManager_InsertBackupLockKeepsPrimaryRole(t *testing.T) {
|
||||
func TestLockManager_RemoveBackupLockRejectsOlderGeneration(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "owner1", 8, 1)
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 1)
|
||||
|
||||
removed := lm.RemoveBackupLockIfSeq("key1", 7, 9)
|
||||
assert.False(t, removed)
|
||||
@@ -93,26 +93,16 @@ func TestLockManager_LostRenewalResponseReplaysToken(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
|
||||
// The renewal rotated token1 to token2; the client never learned it.
|
||||
_, token2, generation, seq2, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
_, token2, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, token1, token2)
|
||||
|
||||
// Retrying with the superseded token replays the current one instead of
|
||||
// conflicting with its own lease until it expires. The replayed mutation
|
||||
// still advances seq so backups accept the extended expiry as fresh.
|
||||
later := time.Now().Add(60 * time.Second).UnixNano()
|
||||
owner, replayed, _, seq3, err := lm.Lock("key1", later, token1, "owner1")
|
||||
// conflicting with its own lease until it expires.
|
||||
owner, replayed, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "owner1", owner)
|
||||
assert.Equal(t, token2, replayed)
|
||||
assert.Greater(t, seq3, seq2)
|
||||
|
||||
backup := NewLockManager()
|
||||
backup.InsertBackupLock("key1", expires, token2, "owner1", generation, seq2)
|
||||
backup.InsertBackupLock("key1", later, token2, "owner1", generation, seq3)
|
||||
backupLock, found := backup.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
assert.Equal(t, later, backupLock.ExpiredAtNs)
|
||||
|
||||
// A replay from a different owner still mismatches.
|
||||
_, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
|
||||
@@ -130,3 +120,54 @@ func TestLockManager_LostRenewalResponseReplaysToken(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, unlocked)
|
||||
}
|
||||
|
||||
func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
expires := time.Now().Add(30 * time.Second).UnixNano()
|
||||
later := time.Now().Add(60 * time.Second).UnixNano()
|
||||
|
||||
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, token2, _, seq2, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// A replay that extends the lease must advance seq, otherwise backups
|
||||
// reject the replicated expiry as a stale mutation and can grant the
|
||||
// lock when the old expiry passes after a promotion.
|
||||
_, replayed, _, seq3, err := lm.Lock("key1", later, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, token2, replayed)
|
||||
assert.Equal(t, seq2+1, seq3)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
assert.Equal(t, later, lock.ExpiredAtNs)
|
||||
assert.Equal(t, seq3, lock.Seq)
|
||||
|
||||
// Repeated retries keep advancing instead of colliding at one seq.
|
||||
_, _, _, seq4, err := lm.Lock("key1", later, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, seq3+1, seq4)
|
||||
}
|
||||
|
||||
func TestLockManager_InsertBackupLockKeepsPrevToken(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
expires := time.Now().Add(30 * time.Second).UnixNano()
|
||||
|
||||
// Backup copy of a renewed lock carries both the current token and the
|
||||
// superseded one a client may still present after a lost response.
|
||||
lm.InsertBackupLock("key1", expires, "token2", "token1", "owner1", 8, 2)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
assert.True(t, found)
|
||||
assert.Equal(t, "token2", lock.Token)
|
||||
assert.Equal(t, "token1", lock.PrevToken)
|
||||
|
||||
// Once promoted, the node still replays a retry of the superseded token.
|
||||
assert.True(t, lm.PromoteLock("key1"))
|
||||
owner, replayed, _, _, err := lm.Lock("key1", expires, "token1", "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "owner1", owner)
|
||||
assert.Equal(t, "token2", replayed)
|
||||
}
|
||||
+46
-28
@@ -68,6 +68,7 @@ type FilerOptions struct {
|
||||
port *int
|
||||
portGrpc *int
|
||||
publicPort *int
|
||||
idleTimeout *int
|
||||
filerGroup *string
|
||||
collection *string
|
||||
defaultReplicaPlacement *string
|
||||
@@ -107,6 +108,15 @@ type FilerOptions struct {
|
||||
// gracefulStopTimeout caps how long startFiler waits for gRPC graceful
|
||||
// stop before forcing the server to stop. Zero means the default of 15s.
|
||||
gracefulStopTimeout time.Duration
|
||||
// skipEmptyMembershipConfirm forwards to FilerOption: a single-master
|
||||
// weed mini's embedded filer announces on the startup scan instead of
|
||||
// holding registration for the confirm window.
|
||||
skipEmptyMembershipConfirm bool
|
||||
// clusterFreshHint, when non-nil, reports that the embedded master minted
|
||||
// a fresh TopologyId this boot — proof the peer scan's empty result is
|
||||
// final rather than a settling master, so the announce gate can end the
|
||||
// empty-membership confirm early. Used by weed server; nil elsewhere.
|
||||
clusterFreshHint func() bool
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -119,6 +129,7 @@ func init() {
|
||||
f.port = cmdFiler.Flag.Int("port", 8888, "filer server http listen port")
|
||||
f.portGrpc = cmdFiler.Flag.Int("port.grpc", 0, "filer server grpc listen port")
|
||||
f.publicPort = cmdFiler.Flag.Int("port.readonly", 0, "readonly port opened to public")
|
||||
f.idleTimeout = cmdFiler.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
f.defaultReplicaPlacement = cmdFiler.Flag.String("defaultReplicaPlacement", "", "default replication type. If not specified, use master setting.")
|
||||
f.disableDirListing = cmdFiler.Flag.Bool("disableDirListing", false, "turn off directory listing")
|
||||
f.maxMB = cmdFiler.Flag.Int("maxMB", 4, "split files larger than the limit")
|
||||
@@ -197,15 +208,18 @@ func init() {
|
||||
filerWebDavOptions.cacheSizeMB = cmdFiler.Flag.Int64("webdav.cacheCapacityMB", 0, "local cache capacity in MB")
|
||||
filerWebDavOptions.maxMB = cmdFiler.Flag.Int("webdav.maxMB", 4, "split files larger than the limit")
|
||||
filerWebDavOptions.filerRootPath = cmdFiler.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
|
||||
filerWebDavOptions.idleTimeout = cmdFiler.Flag.Int("webdav.idleTimeout", 10, "connection idle seconds")
|
||||
|
||||
// start iam on filer
|
||||
filerStartIam = cmdFiler.Flag.Bool("iam", false, "whether to start IAM service")
|
||||
filerIamOptions.ip = cmdFiler.Flag.String("iam.ip", *f.ip, "iam server http listen ip address")
|
||||
filerIamOptions.port = cmdFiler.Flag.Int("iam.port", 8111, "iam server http listen port")
|
||||
filerIamOptions.idleTimeout = cmdFiler.Flag.Int("iam.idleTimeout", 10, "connection idle seconds")
|
||||
filerIamOptions.selfServiceRequiresGrant = filerS3Options.iamSelfServiceRequiresGrant
|
||||
|
||||
filerStartSftp = cmdFiler.Flag.Bool("sftp", false, "whether to start the SFTP server")
|
||||
filerSftpOptions.port = cmdFiler.Flag.Int("sftp.port", 2022, "SFTP server listen port")
|
||||
filerSftpOptions.idleTimeout = cmdFiler.Flag.Int("sftp.idleTimeout", 10, "connection idle seconds")
|
||||
filerSftpOptions.sshPrivateKey = cmdFiler.Flag.String("sftp.sshPrivateKey", "", "path to the SSH private key file for host authentication")
|
||||
filerSftpOptions.hostKeysFolder = cmdFiler.Flag.String("sftp.hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
|
||||
filerSftpOptions.authMethods = cmdFiler.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
|
||||
@@ -371,6 +385,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
if fo.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *fo.listenOnLocalhost
|
||||
}
|
||||
idleTimeout := idleTimeoutSeconds(fo.idleTimeout)
|
||||
if *fo.bindIp == "" {
|
||||
*fo.bindIp = *fo.ip
|
||||
}
|
||||
@@ -404,32 +419,34 @@ func (fo *FilerOptions) startFiler() {
|
||||
|
||||
announce := make(chan struct{})
|
||||
fs, nfs_err := weed_server.NewFilerServer(defaultMux, publicVolumeMux, &weed_server.FilerOption{
|
||||
Masters: fo.masters,
|
||||
AnnounceCh: announce,
|
||||
FilerGroup: *fo.filerGroup,
|
||||
Collection: *fo.collection,
|
||||
DefaultReplication: *fo.defaultReplicaPlacement,
|
||||
DisableDirListing: *fo.disableDirListing,
|
||||
MaxMB: *fo.maxMB,
|
||||
DirListingLimit: *fo.dirListingLimit,
|
||||
DataCenter: *fo.dataCenter,
|
||||
Rack: *fo.rack,
|
||||
DefaultLevelDbDir: defaultLevelDbDirectory,
|
||||
DisableHttp: *fo.disableHttp,
|
||||
Host: filerAddress,
|
||||
Cipher: *fo.cipher,
|
||||
SaveToFilerLimit: int64(*fo.saveToFilerLimit),
|
||||
ConcurrentUploadLimit: int64(*fo.concurrentUploadLimitMB) * 1024 * 1024,
|
||||
ConcurrentFileUploadLimit: int64(*fo.concurrentFileUploadLimit),
|
||||
ShowUIDirectoryDelete: *fo.showUIDirectoryDelete,
|
||||
DownloadMaxBytesPs: int64(*fo.downloadMaxMBps) * 1024 * 1024,
|
||||
DiskType: *fo.diskType,
|
||||
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
|
||||
ExposeDirectoryData: *fo.exposeDirectoryData,
|
||||
TusBasePath: *fo.tusBasePath,
|
||||
TusMaxSize: int64(*fo.tusMaxSizeMB) * 1024 * 1024,
|
||||
TusSessionExpiry: *fo.tusSessionExpiry,
|
||||
CredentialManager: credentialManager,
|
||||
Masters: fo.masters,
|
||||
AnnounceCh: announce,
|
||||
SkipEmptyMembershipConfirm: fo.skipEmptyMembershipConfirm,
|
||||
ClusterFreshHint: fo.clusterFreshHint,
|
||||
FilerGroup: *fo.filerGroup,
|
||||
Collection: *fo.collection,
|
||||
DefaultReplication: *fo.defaultReplicaPlacement,
|
||||
DisableDirListing: *fo.disableDirListing,
|
||||
MaxMB: *fo.maxMB,
|
||||
DirListingLimit: *fo.dirListingLimit,
|
||||
DataCenter: *fo.dataCenter,
|
||||
Rack: *fo.rack,
|
||||
DefaultLevelDbDir: defaultLevelDbDirectory,
|
||||
DisableHttp: *fo.disableHttp,
|
||||
Host: filerAddress,
|
||||
Cipher: *fo.cipher,
|
||||
SaveToFilerLimit: int64(*fo.saveToFilerLimit),
|
||||
ConcurrentUploadLimit: int64(*fo.concurrentUploadLimitMB) * 1024 * 1024,
|
||||
ConcurrentFileUploadLimit: int64(*fo.concurrentFileUploadLimit),
|
||||
ShowUIDirectoryDelete: *fo.showUIDirectoryDelete,
|
||||
DownloadMaxBytesPs: int64(*fo.downloadMaxMBps) * 1024 * 1024,
|
||||
DiskType: *fo.diskType,
|
||||
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
|
||||
ExposeDirectoryData: *fo.exposeDirectoryData,
|
||||
TusBasePath: *fo.tusBasePath,
|
||||
TusMaxSize: int64(*fo.tusMaxSizeMB) * 1024 * 1024,
|
||||
TusSessionExpiry: *fo.tusSessionExpiry,
|
||||
CredentialManager: credentialManager,
|
||||
|
||||
AllowUntrustedRemoteEndpoints: *fo.allowUntrustedRemoteEndpoints,
|
||||
RemoteCacheEvictThreshold: *fo.remoteCacheEvictThreshold,
|
||||
@@ -448,7 +465,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
if *fo.publicPort != 0 {
|
||||
publicListeningAddress := util.JoinHostPort(*fo.bindIp, *fo.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed filer server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0, listenOnLocalhost)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, idleTimeout, listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer server public listener error on port %d:%v", *fo.publicPort, e)
|
||||
}
|
||||
@@ -474,7 +491,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
glog.V(0).Infof("Start Seaweed Filer %s at %s:%d", version.Version(), *fo.ip, *fo.port)
|
||||
filerListener, filerLocalListener, e := util.NewIpAndLocalListeners(
|
||||
*fo.bindIp, *fo.port,
|
||||
time.Duration(10)*time.Second, listenOnLocalhost,
|
||||
idleTimeout, listenOnLocalhost,
|
||||
)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer listener error: %v", e)
|
||||
@@ -543,6 +560,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
localSocket = fmt.Sprintf("/tmp/seaweedfs-filer-%d.sock", *fo.port)
|
||||
}
|
||||
if filerSocketListener := pb.ListenOnLocalSocket(localSocket); filerSocketListener != nil {
|
||||
filerSocketListener = &util.Listener{Listener: filerSocketListener, Timeout: idleTimeout}
|
||||
socketServer := newHttpServer(defaultHandler, nil)
|
||||
httpServers = append(httpServers, socketServer)
|
||||
go socketServer.Serve(filerSocketListener)
|
||||
|
||||
@@ -73,6 +73,10 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
return pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
}
|
||||
|
||||
// makeBucketedEventProcessor is the gateway half of the sync protocol
|
||||
// documented atop filer_remote_sync_dir.go: the same source-of-truth rules
|
||||
// applied per bucket, with each entry's object resolved through its own
|
||||
// bucket's mount. Guards added to processUpdateEvent belong here too.
|
||||
func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *source.FilerSource) (pb.ProcessMetadataFunc, error) {
|
||||
|
||||
handleCreateBucket := func(entry *filer_pb.Entry) error {
|
||||
@@ -360,16 +364,18 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
|
||||
oldBucket, oldRemoteStorageMountLocation, oldRemoteStorage, oldOk := option.detectBucketInfo(resp.Directory)
|
||||
newBucket, newRemoteStorageMountLocation, newRemoteStorage, newOk := option.detectBucketInfo(message.NewParentPath)
|
||||
if oldOk && newOk {
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping updating: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
|
||||
return nil
|
||||
}
|
||||
client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Directory == message.NewParentPath && message.OldEntry.Name == message.NewEntry.Name {
|
||||
// update the same entry
|
||||
// update the same entry; the sync-stamp check holds only
|
||||
// for updates in place: a rename keeps the mtime, so a
|
||||
// synced or pending-stamped rename must still run
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping updating: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
|
||||
return nil
|
||||
}
|
||||
if message.NewEntry.IsDirectory {
|
||||
// update directory property
|
||||
return nil
|
||||
@@ -393,41 +399,76 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
|
||||
remoteEntry = updated
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
} else {
|
||||
newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, newDest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
if isDroppedLocalCopy(message.NewEntry) {
|
||||
// remote.uncache, eviction, or remote.meta.sync dropped
|
||||
// the local copy: the object at this key is the entry's
|
||||
// content, and uploading the chunkless entry replaces
|
||||
// it with zero bytes
|
||||
glog.V(2).Infof("skipping update of remote-only entry: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
|
||||
return nil
|
||||
}
|
||||
newDest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, message.NewEntry.Name), newRemoteStorageMountLocation)
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, newDest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
|
||||
return nil
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
}
|
||||
}
|
||||
|
||||
// the following is entry rename
|
||||
var oldDest *remote_pb.RemoteStorageLocation
|
||||
if oldOk {
|
||||
oldDest = toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
|
||||
}
|
||||
if newOk && !message.NewEntry.IsDirectory {
|
||||
// A remote-only entry's content is the object its
|
||||
// renamed-from path maps to; copying it on the remote
|
||||
// completes the rename. Deleting the source and uploading
|
||||
// the chunkless entry would lose the only copy.
|
||||
current, err := currentEntry(filerSource, message.NewParentPath, message.NewEntry.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isRemoteOnly(current) {
|
||||
if err := gatewayRemoteOnlyRename(option, option, resp, current); err != nil {
|
||||
return err
|
||||
}
|
||||
// a pending entry the filer copied on this rename
|
||||
// leaves the source its marker named
|
||||
return releaseGatewayRenamedSource(filerSource, option, message)
|
||||
}
|
||||
if current == nil && len(message.NewEntry.Extended[filer.ExtRemoteRenameSourceKey]) > 0 {
|
||||
// the rename's copy was pending and the entry has moved
|
||||
// on: a later rename carries the source in its own
|
||||
// marker and finishes or releases it, so this leaves it
|
||||
glog.V(0).Infof("keep %s: the pending rename moved on", util.NewFullPath(resp.Directory, message.OldEntry.Name))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if oldOk {
|
||||
client, err := remote_storage.GetRemoteStorage(oldRemoteStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
oldDest := toRemoteStorageLocation(oldBucket, util.NewFullPath(resp.Directory, message.OldEntry.Name), oldRemoteStorageMountLocation)
|
||||
if message.OldEntry.IsDirectory {
|
||||
return client.RemoveDirectory(oldDest)
|
||||
}
|
||||
if !newOk && isRemoteOnly(message.OldEntry) {
|
||||
glog.V(0).Infof("keep %s: the renamed entry's only content", remote_storage.FormatLocation(oldDest))
|
||||
return nil
|
||||
}
|
||||
glog.V(0).Infof("delete %s", remote_storage.FormatLocation(oldDest))
|
||||
if err := client.DeleteFile(oldDest); err != nil {
|
||||
if err := deleteRemoteFileIfUnchanged(client, oldDest, message.OldEntry.GetRemoteEntry()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if newOk {
|
||||
if !shouldSendToRemote(message.NewEntry) {
|
||||
glog.V(2).Infof("skipping updating: %s/%s ts_ns=%d", filer_pb.MetadataEventTargetDirectory(resp), message.GetNewEntry().GetName(), resp.TsNs)
|
||||
return nil
|
||||
}
|
||||
client, err := remote_storage.GetRemoteStorage(newRemoteStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -439,12 +480,15 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
|
||||
remoteEntry, writeErr := retriedWriteFile(client, filerSource, message.NewParentPath, message.NewEntry, newDest)
|
||||
if errors.Is(writeErr, errSuperseded) {
|
||||
glog.Errorf("skipping %s: %v", remote_storage.FormatLocation(newDest), writeErr)
|
||||
return nil
|
||||
return releaseGatewayRenamedSource(filerSource, option, message)
|
||||
}
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
return updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry)
|
||||
if err := updateLocalEntry(option, message.NewParentPath, message.NewEntry, remoteEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
return releaseGatewayRenamedSource(filerSource, option, message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +497,128 @@ func (option *RemoteGatewayOptions) makeBucketedEventProcessor(filerSource *sour
|
||||
return eachEntryFunc, nil
|
||||
}
|
||||
|
||||
// gatewayRemoteOnlyRename completes a rename whose content exists only as
|
||||
// the object the renamed-from path maps to: the chunkless entry has nothing
|
||||
// to upload. When the destination already holds what the entry's stamp
|
||||
// describes (an earlier run copied it), only the stamp is refreshed.
|
||||
// Otherwise the source object is copied over, the entry is stamped with the
|
||||
// copy so reads stop resolving through the pending-source marker, and the
|
||||
// source goes only while it is still the object the stamp describes. A source
|
||||
// outside the gateway's coverage is never touched; the rename then completes
|
||||
// only out of what the destination already holds. With neither object present
|
||||
// the content is lost: the event fails and holds the offset for recovery.
|
||||
func gatewayRemoteOnlyRename(filerClient filer_pb.FilerClient, option *RemoteGatewayOptions, resp *filer_pb.SubscribeMetadataResponse, current *filer_pb.Entry) error {
|
||||
message := resp.EventNotification
|
||||
srcPath := util.FullPath(current.Extended[filer.ExtRemoteRenameSourceKey])
|
||||
if srcPath == "" {
|
||||
srcPath = util.NewFullPath(resp.Directory, message.OldEntry.Name)
|
||||
}
|
||||
newBucket, newMountLocation, newStorage, ok := option.detectBucketInfo(message.NewParentPath)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
client, err := remote_storage.GetRemoteStorage(newStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dest := toRemoteStorageLocation(newBucket, util.NewFullPath(message.NewParentPath, current.Name), newMountLocation)
|
||||
stamp := message.OldEntry.GetRemoteEntry()
|
||||
if stamp == nil {
|
||||
stamp = proto.Clone(current.RemoteEntry).(*filer_pb.RemoteEntry)
|
||||
}
|
||||
|
||||
// a source outside the gateway's coverage stays untouched; the rename
|
||||
// may only complete out of what the destination already holds
|
||||
srcDir, _ := srcPath.DirAndName()
|
||||
var srcClient remote_storage.RemoteStorageClient
|
||||
var source renameSource
|
||||
if srcBucket, srcMountLocation, srcStorage, ok := option.detectBucketInfo(srcDir); ok {
|
||||
if srcClient, err = remote_storage.GetRemoteStorage(srcStorage); err != nil {
|
||||
return err
|
||||
}
|
||||
source = renameSource{path: srcPath, loc: toRemoteStorageLocation(srcBucket, srcPath, srcMountLocation), stamp: stamp}
|
||||
}
|
||||
if existing, statErr := client.StatFile(dest); statErr == nil {
|
||||
if remote_storage.Describes(current.RemoteEntry, existing) {
|
||||
glog.V(0).Infof("%s already holds the renamed content", remote_storage.FormatLocation(dest))
|
||||
if len(current.Extended[filer.ExtRemoteRenameSourceKey]) > 0 {
|
||||
if err := updateLocalEntry(filerClient, message.NewParentPath, current, existing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if srcClient == nil {
|
||||
return nil
|
||||
}
|
||||
return deleteRenameSource(filerClient, srcClient, message.NewParentPath, current.Name, source, stamp)
|
||||
}
|
||||
glog.V(0).Infof("%s holds an object the entry does not describe (size %d, want %d); replacing it from %s", remote_storage.FormatLocation(dest), existing.RemoteSize, current.RemoteEntry.RemoteSize, srcPath)
|
||||
} else if !errors.Is(statErr, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return statErr
|
||||
}
|
||||
if srcClient == nil {
|
||||
return fmt.Errorf("rename source %s is not under a mounted bucket and %s does not hold the content", srcPath, remote_storage.FormatLocation(dest))
|
||||
}
|
||||
stat, err := srcClient.StatFile(source.loc)
|
||||
if errors.Is(err, remote_storage.ErrRemoteObjectNotFound) {
|
||||
return fmt.Errorf("%s: content is on neither %s nor %s", util.NewFullPath(message.NewParentPath, current.Name), remote_storage.FormatLocation(source.loc), remote_storage.FormatLocation(dest))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader, err := openRemoteObject(srcClient, source.loc, stat.RemoteSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
glog.V(0).Infof("copy %s -> %s", remote_storage.FormatLocation(source.loc), remote_storage.FormatLocation(dest))
|
||||
remoteEntry, err := client.WriteFile(dest, current, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateLocalEntry(filerClient, message.NewParentPath, current, remoteEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
return deleteRenameSource(filerClient, srcClient, message.NewParentPath, current.Name, source, stamp)
|
||||
}
|
||||
|
||||
// releaseGatewayRenamedSource releases the pending source a rename's old
|
||||
// entry read, once the renamed entry no longer reads through a marker: the
|
||||
// gateway-side releaseRenamedSource, with the source resolved through its
|
||||
// own bucket's mount.
|
||||
func releaseGatewayRenamedSource(filerSource filer_pb.FilerClient, option *RemoteGatewayOptions, message *filer_pb.EventNotification) error {
|
||||
srcPath := util.FullPath(message.OldEntry.GetExtended()[filer.ExtRemoteRenameSourceKey])
|
||||
if srcPath == "" {
|
||||
return nil
|
||||
}
|
||||
current, err := currentEntry(filerSource, message.NewParentPath, message.NewEntry.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current != nil && len(current.Extended[filer.ExtRemoteRenameSourceKey]) > 0 {
|
||||
return nil
|
||||
}
|
||||
srcDir, srcName := srcPath.DirAndName()
|
||||
srcBucket, srcMountLocation, srcStorage, ok := option.detectBucketInfo(srcDir)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
current, err = currentEntry(filerSource, srcDir, srcName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isRemoteOnly(current) {
|
||||
glog.V(0).Infof("keep %s: a remote-only entry holds the pending rename's source", srcPath)
|
||||
return nil
|
||||
}
|
||||
srcClient, err := remote_storage.GetRemoteStorage(srcStorage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srcLoc := toRemoteStorageLocation(srcBucket, srcPath, srcMountLocation)
|
||||
glog.V(0).Infof("delete %s, the source of a pending rename", remote_storage.FormatLocation(srcLoc))
|
||||
return deleteRemoteFileIfUnchanged(srcClient, srcLoc, message.OldEntry.GetRemoteEntry())
|
||||
}
|
||||
|
||||
func (option *RemoteGatewayOptions) findRemoteStorageClient(bucketName string) (client remote_storage.RemoteStorageClient, remoteStorageMountLocation *remote_pb.RemoteStorageLocation, err error) {
|
||||
bucket := util.FullPath(option.bucketsDir).Child(bucketName)
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
)
|
||||
|
||||
type recordingRemoteMaker struct{ client *recordingRemote }
|
||||
@@ -16,6 +18,293 @@ func (m recordingRemoteMaker) Make(*remote_pb.RemoteConf) (remote_storage.Remote
|
||||
}
|
||||
func (m recordingRemoteMaker) HasBucket() bool { return true }
|
||||
|
||||
func gatewayTestOption(storageType string) (*RemoteGatewayOptions, *recordingRemote) {
|
||||
remote := &recordingRemote{}
|
||||
remote_storage.RemoteStorageClientMakers[storageType] = recordingRemoteMaker{client: remote}
|
||||
filerAddress := "localhost:1"
|
||||
return &RemoteGatewayOptions{
|
||||
filerAddress: &filerAddress,
|
||||
bucketsDir: "/buckets",
|
||||
mappings: &remote_pb.RemoteStorageMapping{Mappings: map[string]*remote_pb.RemoteStorageLocation{
|
||||
"/buckets/gold": {Name: storageType, Bucket: "gold", Path: "/"},
|
||||
}},
|
||||
remoteConfs: map[string]*remote_pb.RemoteConf{storageType: {Name: storageType, Type: storageType}},
|
||||
}, remote
|
||||
}
|
||||
|
||||
// TestGatewayDroppedLocalCopyIsNotUploaded: remote.uncache drops a synced
|
||||
// entry's chunks and clears its sync stamp; shouldSendToRemote reads the
|
||||
// cleared stamp in the remote mtime's second as dirty, so the update reaches
|
||||
// the upload. The object at the key is the entry's only content and the
|
||||
// chunkless upload would replace it with zero bytes, so it is skipped.
|
||||
func TestGatewayDroppedLocalCopyIsNotUploaded(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-uncache")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-uncache") })
|
||||
process, err := option.makeBucketedEventProcessor(&source.FilerSource{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
resp := droppedCopyUpdate(
|
||||
droppedCopyEntry(droppedCopySynced, chunk("3,01", "e1")),
|
||||
droppedCopyEntry(droppedCopyStamp()),
|
||||
)
|
||||
if !shouldSendToRemote(resp.EventNotification.NewEntry) {
|
||||
t.Fatal("precondition: the cleared stamp reads the entry as dirty")
|
||||
}
|
||||
if err := process(resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: the remote object is the entry's content and an upload would zero it", remote.writes)
|
||||
}
|
||||
if len(remote.deletes) != 0 || len(remote.metadataUpdates) != 0 {
|
||||
t.Errorf("deletes = %+v, metadata updates = %+v, want the remote object left alone", remote.deletes, remote.metadataUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayUncachedRewriteIsStillUploaded: a rewrite of an uncached entry
|
||||
// holds local data, so the dropped-copy skip does not apply and the rewrite
|
||||
// uploads. The stamp cannot reach a filer in the test, so the call errors;
|
||||
// the upload is what is asserted.
|
||||
func TestGatewayUncachedRewriteIsStillUploaded(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-rewrite")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-rewrite") })
|
||||
process, err := option.makeBucketedEventProcessor(&source.FilerSource{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rewrite := entryWith(droppedCopyName, droppedCopyStamp(), chunk("4,02", "e2"))
|
||||
resp := droppedCopyUpdate(droppedCopyEntry(droppedCopyStamp()), rewrite)
|
||||
if err := process(resp); err != nil {
|
||||
t.Logf("stamp against the test filer fails as expected: %v", err)
|
||||
}
|
||||
if len(remote.writes) != 1 {
|
||||
t.Fatalf("writes = %+v, want the rewrite uploaded once", remote.writes)
|
||||
}
|
||||
if !slices.Equal(remote.writtenChunks[0], []string{"4,02"}) {
|
||||
t.Errorf("uploaded chunks %v, want the rewrite's [4,02]", remote.writtenChunks[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRemoteOnlyRenameCopiesTheObject: a remote-only entry holds its
|
||||
// content only as the object the renamed-from path maps to. The rename copies
|
||||
// that object to the destination key, stamps the entry so reads stop going
|
||||
// through the pending-source marker, and removes the source. Uploading the
|
||||
// chunkless entry would put a zero-byte object over it, and deleting the
|
||||
// source first would lose the only copy.
|
||||
func TestGatewayRemoteOnlyRenameCopiesTheObject(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-rename")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-rename") })
|
||||
|
||||
oldPath := "/buckets/gold/dir/old.txt"
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-rename", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
oldEntry := &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp}
|
||||
current := &filer_pb.Entry{
|
||||
Name: "new.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5},
|
||||
RemoteEntry: stamp,
|
||||
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte(oldPath)},
|
||||
}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/gold/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: oldEntry, NewParentPath: "/buckets/gold/dir", NewEntry: current,
|
||||
},
|
||||
}
|
||||
filerClient := &stubFilerClient{entries: map[string]*filer_pb.Entry{"/buckets/gold/dir/new.txt": current}}
|
||||
|
||||
remote.objects = map[string][]byte{"/dir/old.txt": []byte("hello")}
|
||||
remote.statETag = `"abc"`
|
||||
remote.statMtime = 100
|
||||
|
||||
if err := gatewayRemoteOnlyRename(filerClient, option, resp, current); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 1 || remote.writes[0].Path != "/dir/new.txt" {
|
||||
t.Fatalf("writes = %+v, want the source object copied to /dir/new.txt", remote.writes)
|
||||
}
|
||||
if string(remote.written[0]) != "hello" {
|
||||
t.Errorf("copied %q, want the source object's content", remote.written[0])
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped the entry %d times, want 1 to clear the pending-source marker", filerClient.updates)
|
||||
}
|
||||
if len(remote.deletes) != 1 || remote.deletes[0].Path != "/dir/old.txt" {
|
||||
t.Errorf("deletes = %+v, want the source object removed", remote.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRemoteOnlyRenameAlreadyComplete: when the destination already
|
||||
// holds what the stamp describes (an earlier run copied it), the rename only
|
||||
// refreshes the stamp and removes the source.
|
||||
func TestGatewayRemoteOnlyRenameAlreadyComplete(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-rename-complete")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-rename-complete") })
|
||||
|
||||
oldPath := "/buckets/gold/dir/old.txt"
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-rename-complete", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
oldEntry := &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp}
|
||||
current := &filer_pb.Entry{
|
||||
Name: "new.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5},
|
||||
RemoteEntry: stamp,
|
||||
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte(oldPath)},
|
||||
}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/gold/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: oldEntry, NewParentPath: "/buckets/gold/dir", NewEntry: current,
|
||||
},
|
||||
}
|
||||
filerClient := &stubFilerClient{entries: map[string]*filer_pb.Entry{"/buckets/gold/dir/new.txt": current}}
|
||||
|
||||
remote.objects = map[string][]byte{"/dir/old.txt": []byte("hello"), "/dir/new.txt": []byte("hello")}
|
||||
remote.statETag = `"abc"`
|
||||
remote.statMtime = 100
|
||||
|
||||
if err := gatewayRemoteOnlyRename(filerClient, option, resp, current); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.writes) != 0 {
|
||||
t.Errorf("writes = %+v, want none: the destination already holds the content", remote.writes)
|
||||
}
|
||||
if len(remote.deletes) != 1 || remote.deletes[0].Path != "/dir/old.txt" {
|
||||
t.Errorf("deletes = %+v, want the source object removed", remote.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRenameReleasesPendingSource: a rename whose old entry read a
|
||||
// pending source (an earlier rename's deferred copy had not finished) leaves
|
||||
// that source behind once the renamed entry no longer reads through a
|
||||
// marker. The gateway deletes it, guarded by the old entry's stamp.
|
||||
func TestGatewayRenameReleasesPendingSource(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-release")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-release") })
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-release", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
oldEntry := &filer_pb.Entry{
|
||||
Name: "mid.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5},
|
||||
RemoteEntry: stamp,
|
||||
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/gold/dir/orig.txt")},
|
||||
}
|
||||
newEntry := &filer_pb.Entry{Name: "new.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5}, RemoteEntry: stamp}
|
||||
message := &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: "/buckets/gold/dir", NewEntry: newEntry}
|
||||
filerClient := &stubFilerClient{entries: map[string]*filer_pb.Entry{
|
||||
"/buckets/gold/dir/new.txt": newEntry,
|
||||
}}
|
||||
remote.objects = map[string][]byte{"/dir/orig.txt": []byte("hello")}
|
||||
remote.statETag = `"abc"`
|
||||
remote.statMtime = 100
|
||||
|
||||
if err := releaseGatewayRenamedSource(filerClient, option, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.deletes) != 1 || remote.deletes[0].Path != "/dir/orig.txt" {
|
||||
t.Errorf("deletes = %+v, want the pending source released", remote.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRenameKeepsHeldPendingSource: the pending source stays while a
|
||||
// remote-only entry still holds its path.
|
||||
func TestGatewayRenameKeepsHeldPendingSource(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-release")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-release") })
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-release", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
oldEntry := &filer_pb.Entry{
|
||||
Name: "mid.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5},
|
||||
RemoteEntry: stamp,
|
||||
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/gold/dir/orig.txt")},
|
||||
}
|
||||
newEntry := &filer_pb.Entry{Name: "new.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5}, RemoteEntry: stamp}
|
||||
heldSource := &filer_pb.Entry{Name: "orig.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 300, FileSize: 5}, RemoteEntry: stamp}
|
||||
message := &filer_pb.EventNotification{OldEntry: oldEntry, NewParentPath: "/buckets/gold/dir", NewEntry: newEntry}
|
||||
filerClient := &stubFilerClient{entries: map[string]*filer_pb.Entry{
|
||||
"/buckets/gold/dir/new.txt": newEntry,
|
||||
"/buckets/gold/dir/orig.txt": heldSource,
|
||||
}}
|
||||
remote.objects = map[string][]byte{"/dir/orig.txt": []byte("hello")}
|
||||
remote.statETag = `"abc"`
|
||||
remote.statMtime = 100
|
||||
|
||||
if err := releaseGatewayRenamedSource(filerClient, option, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.deletes) != 0 {
|
||||
t.Errorf("deletes = %+v, want the pending source kept while an entry holds its path", remote.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRemoteOnlyRenameSourceOutOfCoverage: a rename source outside the
|
||||
// gateway's buckets is left untouched; when the destination already holds
|
||||
// the content the rename only refreshes the stamp instead of failing.
|
||||
func TestGatewayRemoteOnlyRenameSourceOutOfCoverage(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-outsrc")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-outsrc") })
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-outsrc", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
oldEntry := &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp}
|
||||
current := &filer_pb.Entry{
|
||||
Name: "new.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5},
|
||||
RemoteEntry: stamp,
|
||||
Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/unmanaged/dir/old.txt")},
|
||||
}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/gold/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: oldEntry, NewParentPath: "/buckets/gold/dir", NewEntry: current,
|
||||
},
|
||||
}
|
||||
filerClient := &stubFilerClient{entries: map[string]*filer_pb.Entry{"/buckets/gold/dir/new.txt": current}}
|
||||
|
||||
remote.objects = map[string][]byte{"/dir/new.txt": []byte("hello")}
|
||||
remote.statETag = `"abc"`
|
||||
remote.statMtime = 100
|
||||
|
||||
if err := gatewayRemoteOnlyRename(filerClient, option, resp, current); err != nil {
|
||||
t.Fatalf("the completed destination should finalize without touching the out-of-coverage source: %v", err)
|
||||
}
|
||||
if filerClient.updates != 1 {
|
||||
t.Errorf("stamped the entry %d times, want 1 to clear the pending-source marker", filerClient.updates)
|
||||
}
|
||||
if len(remote.deletes) != 0 || len(remote.writes) != 0 {
|
||||
t.Errorf("deletes = %+v, writes = %+v, want the unmanaged source and destination left alone", remote.deletes, remote.writes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGatewayRenameOutKeepsRemoteOnlyObject: a remote-only entry renamed out
|
||||
// of the gateway's coverage keeps the remote object: it is the entry's only
|
||||
// content.
|
||||
func TestGatewayRenameOutKeepsRemoteOnlyObject(t *testing.T) {
|
||||
option, remote := gatewayTestOption("gatewaytest-out")
|
||||
t.Cleanup(func() { delete(remote_storage.RemoteStorageClientMakers, "gatewaytest-out") })
|
||||
process, err := option.makeBucketedEventProcessor(&source.FilerSource{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
stamp := &filer_pb.RemoteEntry{StorageName: "gatewaytest-out", RemoteETag: `"abc"`, RemoteSize: 5, RemoteMtime: 100}
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/buckets/gold/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "old.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 100, FileSize: 5}, RemoteEntry: stamp},
|
||||
NewParentPath: "/outside/dir",
|
||||
NewEntry: &filer_pb.Entry{Name: "new.txt", Attributes: &filer_pb.FuseAttributes{Mtime: 200, FileSize: 5}, RemoteEntry: stamp},
|
||||
},
|
||||
}
|
||||
if err := process(resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remote.deletes) != 0 {
|
||||
t.Errorf("deletes = %+v, want the remote-only object kept", remote.deletes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayMetadataOnlyDeleteKeepsTheRemoteObject(t *testing.T) {
|
||||
remote := &recordingRemote{}
|
||||
remote_storage.RemoteStorageClientMakers["gatewaytest"] = recordingRemoteMaker{client: remote}
|
||||
|
||||
@@ -2,11 +2,13 @@ package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -26,6 +28,27 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Which side holds an entry's content, and the two processors that keep the
|
||||
// remote in step with it.
|
||||
//
|
||||
// An entry with local data (chunks or inline content) is authoritative: the
|
||||
// update uploads it. A chunkless entry stamped with a RemoteEntry is
|
||||
// remote-only: its content is the remote object its stamp describes, so the
|
||||
// chunkless entry is never uploaded, since it would write zero bytes over
|
||||
// the only copy, and the object goes only while the stamp still describes it
|
||||
// (remote_storage.StillCurrent). While the entry carries a
|
||||
// filer.ExtRemoteRenameSourceKey marker the content is the object at the
|
||||
// renamed-from path, until the rename's copy or upload restamps the entry
|
||||
// and clears it. A dropped local copy (remote.uncache, eviction,
|
||||
// remote.meta.sync) keeps the remote object's size; a size that moved off
|
||||
// the stamp (a truncate) is new content and uploads.
|
||||
//
|
||||
// processUpdateEvent serves filer remote.sync over one mounted directory;
|
||||
// makeBucketedEventProcessor in filer_remote_gateway_buckets.go serves filer
|
||||
// remote.gateway over the bucketed space. They implement the same protocol
|
||||
// and must change together: a guard added to one and not the other is how
|
||||
// the zero-byte re-upload on remote.uncache happened.
|
||||
|
||||
func followUpdatesAndUploadToRemote(option *RemoteSyncOptions, filerSource *source.FilerSource, mountedDir string) error {
|
||||
|
||||
// read filer remote storage mount mappings
|
||||
@@ -915,18 +938,22 @@ func readRemoteStorageConf(filerClient filer_pb.FilerClient, storageName string)
|
||||
}
|
||||
|
||||
// isSuperseded reports whether the filer has moved past the entry an event
|
||||
// described: it is deleted, or it no longer references every chunk the event
|
||||
// named. Those are the chunks the filer deletes when an entry is updated, so
|
||||
// they are gone from the volume servers, or about to be, and no retry of the
|
||||
// upload can succeed. Chunks are compared by file id, not content: a rewrite
|
||||
// stores even identical bytes under new ids and drops the old ones. A replay
|
||||
// from an earlier offset (-timeAgo) re-emits such events. Failing one holds the
|
||||
// sync offset before it, so every restart of the subscription replays it into
|
||||
// the same dead chunks, and progress on everything after it in the log is never
|
||||
// persisted. Skipping is safe: the event that superseded this one follows in
|
||||
// the log, and the delete removes the remote object or the rewrite uploads the
|
||||
// current content. A lookup that fails for any other reason keeps the write
|
||||
// failure, so the event is retried.
|
||||
// described: it is deleted, it no longer references every chunk the event
|
||||
// named, or it references chunks the event did not. Dropped chunks are the ones
|
||||
// the filer deletes when an entry is updated, so they are gone from the volume
|
||||
// servers, or about to be, and no retry of the upload can succeed. Added chunks
|
||||
// mean the event was a snapshot of a write still in progress. A mount flushes
|
||||
// metadata while it is still uploading chunks in parallel, so such a snapshot
|
||||
// can have holes, and the stream reader stops at the first one: every retry
|
||||
// sends a short body and fails the same way. Chunks are compared by file id,
|
||||
// not content: a rewrite stores even identical bytes under new ids and drops
|
||||
// the old ones. A replay from an earlier offset (-timeAgo) re-emits such
|
||||
// events. Failing one holds the sync offset before it, so every restart of the
|
||||
// subscription replays it into the same failure, and progress on everything
|
||||
// after it in the log is never persisted. Skipping is safe: the event that
|
||||
// superseded this one follows in the log, and the delete removes the remote
|
||||
// object or the later write uploads the current content. A lookup that fails
|
||||
// for any other reason keeps the write failure, so the event is retried.
|
||||
func isSuperseded(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.Entry) bool {
|
||||
current, _, _, err := filer_pb.GetEntry(context.Background(), filerClient, util.NewFullPath(dir, entry.Name))
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
@@ -944,12 +971,47 @@ func isSuperseded(filerClient filer_pb.FilerClient, dir string, entry *filer_pb.
|
||||
if len(entry.Content) > 0 || len(current.Content) > 0 {
|
||||
return !bytes.Equal(entry.Content, current.Content)
|
||||
}
|
||||
return len(filer.DoMinusChunks(entry.GetChunks(), current.GetChunks())) > 0
|
||||
return len(filer.DoMinusChunks(entry.GetChunks(), current.GetChunks())) > 0 ||
|
||||
len(filer.DoMinusChunks(current.GetChunks(), entry.GetChunks())) > 0
|
||||
}
|
||||
|
||||
// errSuperseded marks an upload that failed for an entry the filer has since
|
||||
// moved past (isSuperseded). The caller skips the event instead of failing it.
|
||||
var errSuperseded = errors.New("deleted or rewritten since the event was logged")
|
||||
// hasReadHole reports an entry whose chunks do not cover its declared size: a
|
||||
// snapshot of a write still in progress, flushed while chunk uploads were
|
||||
// still running. The stream reader stops at the gap, so the upload fails on
|
||||
// every retry whether or not the filer ever moves past the entry — a write
|
||||
// that never finishes leaves the gap and wedges the event. Skipping is safe
|
||||
// either way: a finishing write logs its own event and uploads the full
|
||||
// content, and a dead one has nothing readable to lose.
|
||||
func hasReadHole(entry *filer_pb.Entry) bool {
|
||||
size := int64(entry.GetAttributes().GetFileSize())
|
||||
if size == 0 || len(entry.Content) > 0 {
|
||||
return false
|
||||
}
|
||||
chunks := slices.Clone(entry.GetChunks())
|
||||
slices.SortFunc(chunks, func(a, b *filer_pb.FileChunk) int {
|
||||
return cmp.Compare(a.GetOffset(), b.GetOffset())
|
||||
})
|
||||
var next int64
|
||||
for _, chunk := range chunks {
|
||||
if chunk.GetOffset() >= size {
|
||||
break
|
||||
}
|
||||
if chunk.GetOffset() > next {
|
||||
return true
|
||||
}
|
||||
if end := chunk.GetOffset() + int64(chunk.GetSize()); end > next {
|
||||
next = end
|
||||
}
|
||||
}
|
||||
return next < size
|
||||
}
|
||||
|
||||
// errSuperseded marks an upload that cannot produce the entry an event
|
||||
// described: the filer moved past it (isSuperseded), or the entry is a
|
||||
// mid-write snapshot with a gap its chunks do not cover (hasReadHole). The
|
||||
// caller skips the event instead of failing it; a write completing logs a
|
||||
// later event that carries the full content.
|
||||
var errSuperseded = errors.New("superseded or incomplete since the event was logged")
|
||||
|
||||
// retriedWriteFile uploads the entry, retrying transient failures. The filer is
|
||||
// asked whether the entry is superseded before the first attempt and after
|
||||
@@ -960,6 +1022,9 @@ var errSuperseded = errors.New("deleted or rewritten since the event was logged"
|
||||
// still holds is worth sending. After: a dead chunk reads as a transient
|
||||
// "RequestError" from the SDK, and waiting out the backoff on it buys nothing.
|
||||
func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource filer_pb.FilerClient, dir string, newEntry *filer_pb.Entry, dest *remote_pb.RemoteStorageLocation) (remoteEntry *filer_pb.RemoteEntry, err error) {
|
||||
if hasReadHole(newEntry) {
|
||||
return nil, fmt.Errorf("%s %w", util.NewFullPath(dir, newEntry.Name), errSuperseded)
|
||||
}
|
||||
if isSuperseded(filerSource, dir, newEntry) {
|
||||
return nil, fmt.Errorf("%s %w", util.NewFullPath(dir, newEntry.Name), errSuperseded)
|
||||
}
|
||||
|
||||
@@ -517,6 +517,10 @@ func chunk(fileId, etag string) *filer_pb.FileChunk {
|
||||
return &filer_pb.FileChunk{FileId: fileId, Size: 1024, ETag: etag}
|
||||
}
|
||||
|
||||
func chunkAt(fileId, etag string, offset int64) *filer_pb.FileChunk {
|
||||
return &filer_pb.FileChunk{FileId: fileId, Offset: offset, Size: 1024, ETag: etag}
|
||||
}
|
||||
|
||||
func entryWith(name string, remote *filer_pb.RemoteEntry, chunks ...*filer_pb.FileChunk) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1786096669}, RemoteEntry: remote, Chunks: chunks}
|
||||
}
|
||||
@@ -532,6 +536,11 @@ func entryWith(name string, remote *filer_pb.RemoteEntry, chunks ...*filer_pb.Fi
|
||||
// by chunk identity, the way the filer itself decides which chunks an update
|
||||
// leaves for deletion. Content fingerprints would miss a delete-and-recreate
|
||||
// of identical bytes and fail the event forever on its dead chunks.
|
||||
//
|
||||
// Chunks the filer has added since count too. The event was then a snapshot
|
||||
// of a write in progress: a mount flushes metadata while chunk uploads are
|
||||
// still running, so the snapshot can have holes, and the stream reader stops
|
||||
// at the first one on every retry.
|
||||
func TestIsSuperseded(t *testing.T) {
|
||||
const dir = "/buckets/ingest"
|
||||
event := entryWith("tmpjt9req69__Alan_Doe_Resume-1.pdf", nil, chunk("3,01", "e1"), chunk("3,02", "e2"))
|
||||
@@ -549,7 +558,7 @@ func TestIsSuperseded(t *testing.T) {
|
||||
{name: "truncated since", filer: &stubFilerClient{entry: entryWith(event.Name, nil, chunk("3,01", "e1"))}, want: true},
|
||||
{name: "still as described", filer: &stubFilerClient{entry: entryWith(event.Name, nil, chunk("3,01", "e1"), chunk("3,02", "e2"))}, want: false},
|
||||
{name: "still as described, since replicated", filer: &stubFilerClient{entry: entryWith(event.Name, stamped, chunk("3,01", "e1"), chunk("3,02", "e2"))}, want: false},
|
||||
{name: "appended since, chunks still live", filer: &stubFilerClient{entry: entryWith(event.Name, nil, chunk("3,01", "e1"), chunk("3,02", "e2"), chunk("3,03", "e3"))}, want: false},
|
||||
{name: "appended since", filer: &stubFilerClient{entry: entryWith(event.Name, nil, chunk("3,01", "e1"), chunk("3,02", "e2"), chunk("3,03", "e3"))}, want: true},
|
||||
{name: "filer lookup failed", filer: &stubFilerClient{err: errors.New("rpc error: code = Unavailable")}, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
@@ -580,6 +589,17 @@ func TestIsSuperseded(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mid-write snapshot with a hole, filled in since", func(t *testing.T) {
|
||||
snapshot := entryWith("IMG_6526.mov", nil, chunkAt("222,01", "e1", 0), chunkAt("220,03", "e3", 2048))
|
||||
filled := entryWith("IMG_6526.mov", nil, chunkAt("222,01", "e1", 0), chunkAt("216,02", "e2", 1024), chunkAt("220,03", "e3", 2048))
|
||||
if !isSuperseded(&stubFilerClient{entry: filled}, dir, snapshot) {
|
||||
t.Error("isSuperseded = false, want true: the filer holds the finished write, the snapshot can never be read past its hole")
|
||||
}
|
||||
if isSuperseded(&stubFilerClient{entry: filled}, dir, filled) {
|
||||
t.Error("isSuperseded = true, want false for the event that describes the finished write")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inline content rewritten since", func(t *testing.T) {
|
||||
event := &filer_pb.Entry{Name: "note.txt", Content: []byte("v1")}
|
||||
if !isSuperseded(&stubFilerClient{entry: &filer_pb.Entry{Name: "note.txt", Content: []byte("v2")}}, dir, event) {
|
||||
@@ -652,6 +672,39 @@ func TestRetriedWriteFileStopsWhenSuperseded(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mid-write snapshot filled in during the attempt, one write", func(t *testing.T) {
|
||||
snapshot := entryWith("IMG_6526.mov", nil, chunkAt("222,01", "e1", 0), chunkAt("220,03", "e3", 2048))
|
||||
filled := entryWith("IMG_6526.mov", nil, chunkAt("222,01", "e1", 0), chunkAt("216,02", "e2", 1024), chunkAt("220,03", "e3", 2048))
|
||||
// What the S3 SDK reports when the stream reader stops at the hole.
|
||||
shortBody := errors.New("RequestError: send request failed\ncaused by: Put \"https://s3.example.com/tier/IMG_6526.mov?partNumber=12\": net/http: HTTP/1.x transport connection broken: http: ContentLength=8388608 with Body length 4194304")
|
||||
remote := &failingRemote{err: shortBody}
|
||||
filerClient := &supersedingFilerClient{live: snapshot, then: filled}
|
||||
_, err := retriedWriteFile(remote, filerClient, dir, snapshot, dest)
|
||||
if !errors.Is(err, errSuperseded) {
|
||||
t.Errorf("err = %v, want errSuperseded", err)
|
||||
}
|
||||
if remote.writes != 1 {
|
||||
t.Errorf("wrote %d times, want 1: the snapshot reads short on every retry", remote.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mid-write snapshot whose hole never fills, no write", func(t *testing.T) {
|
||||
snapshot := entryWith("IMG_6526.mov", nil, chunkAt("222,01", "e1", 0), chunkAt("220,03", "e3", 2048))
|
||||
snapshot.Attributes.FileSize = 3072
|
||||
remote := &failingRemote{err: errors.New("RequestError: send request failed")}
|
||||
filerClient := &stubFilerClient{entry: snapshot}
|
||||
_, err := retriedWriteFile(remote, filerClient, dir, snapshot, dest)
|
||||
if !errors.Is(err, errSuperseded) {
|
||||
t.Errorf("err = %v, want errSuperseded", err)
|
||||
}
|
||||
if remote.writes != 0 {
|
||||
t.Errorf("wrote %d times, want 0: a snapshot with a hole reads short on every retry", remote.writes)
|
||||
}
|
||||
if filerClient.lookups != 0 {
|
||||
t.Errorf("looked up the filer %d times, want 0: no state makes this uploadable", filerClient.lookups)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("still as described, transient failure keeps retrying", func(t *testing.T) {
|
||||
prev := util.RetryWaitTime
|
||||
util.RetryWaitTime = 1600 * time.Millisecond // two attempts: 1s, then 1.5s
|
||||
@@ -993,6 +1046,7 @@ func TestIsFailedPrecondition(t *testing.T) {
|
||||
type supersedingFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
live *filer_pb.Entry
|
||||
then *filer_pb.Entry // returned after the first lookup; nil means deleted
|
||||
lookups int
|
||||
}
|
||||
|
||||
@@ -1001,6 +1055,9 @@ func (c *supersedingFilerClient) LookupDirectoryEntry(context.Context, *filer_pb
|
||||
if c.lookups == 1 {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.live}, nil
|
||||
}
|
||||
if c.then != nil {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: c.then}, nil
|
||||
}
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -34,6 +34,7 @@ type IamOptions struct {
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
idleTimeout *int
|
||||
selfServiceRequiresGrant *bool
|
||||
}
|
||||
|
||||
@@ -44,6 +45,7 @@ func init() {
|
||||
iamStandaloneOptions.ip = cmdIam.Flag.String("ip", util.DetectedHostAddress(), "iam server http listen ip address")
|
||||
iamStandaloneOptions.ipBind = cmdIam.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
iamStandaloneOptions.port = cmdIam.Flag.Int("port", 8111, "iam server http listen port")
|
||||
iamStandaloneOptions.idleTimeout = cmdIam.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
iamStandaloneOptions.selfServiceRequiresGrant = cmdIam.Flag.Bool("selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
}
|
||||
|
||||
@@ -133,9 +135,10 @@ func (iamopt *IamOptions) startIamServer() bool {
|
||||
if iamopt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *iamopt.listenOnLocalhost
|
||||
}
|
||||
idleTimeout := idleTimeoutSeconds(iamopt.idleTimeout)
|
||||
|
||||
listenAddress := fmt.Sprintf(":%d", *iamopt.port)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(bindIp, *iamopt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(bindIp, *iamopt.port, idleTimeout, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("IAM API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
+17
-3
@@ -21,6 +21,7 @@ import (
|
||||
hashicorpRaft "github.com/hashicorp/raft"
|
||||
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/raft/protobuf"
|
||||
@@ -90,10 +91,16 @@ type MasterOptions struct {
|
||||
// single-master mode, with singleReporterAddr pinning the embedded volume
|
||||
// server as the only admitted reporter: any other volume server is refused,
|
||||
// so the warmup window after a fresh topology id is dead time.
|
||||
// Standalone weed master / weed server can face late-arriving veterans and
|
||||
// must keep the window.
|
||||
// Standalone weed master can face late-arriving veterans and must keep
|
||||
// the window; a single-master weed server releases on its embedded
|
||||
// volume server's clean report through expectedReporterAddr instead.
|
||||
releaseAllocOnFirstReport bool
|
||||
singleReporterAddr string
|
||||
// expectedReporterAddr names the reporter whose first clean inventory
|
||||
// collapses the post-mint allocation hold to a confirm pulse without
|
||||
// refusing others: a single-master weed server points it at its
|
||||
// embedded volume server.
|
||||
expectedReporterAddr string
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -197,7 +204,7 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
func startMaster(masterOption MasterOptions, masterWhiteList []string, masterOut ...*atomic.Pointer[weed_server.MasterServer]) {
|
||||
|
||||
backend.LoadConfiguration(util.GetViper())
|
||||
|
||||
@@ -225,6 +232,12 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
|
||||
r := mux.NewRouter()
|
||||
ms := weed_server.NewMasterServer(r, masterOption.toMasterOption(masterWhiteList), masterPeers)
|
||||
// Embedded setups (weed server) hand the instance back so sibling
|
||||
// components can read cluster-state signals such as a fresh TopologyId
|
||||
// mint.
|
||||
if len(masterOut) > 0 && masterOut[0] != nil {
|
||||
masterOut[0].Store(ms)
|
||||
}
|
||||
listeningAddress := util.JoinHostPort(*masterOption.ipBind, *masterOption.port)
|
||||
glog.V(0).Infof("Start Seaweed Master %s at %s", version.Version(), listeningAddress)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0, listenOnLocalhost)
|
||||
@@ -595,5 +608,6 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
SingleMaster: isSingleMasterMode(*m.peers),
|
||||
ReleaseAllocOnFirstReport: m.releaseAllocOnFirstReport,
|
||||
SingleVolumeReporter: m.singleReporterAddr,
|
||||
ExpectedReporterAddr: m.expectedReporterAddr,
|
||||
}
|
||||
}
|
||||
@@ -487,6 +487,7 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.tusSessionExpiry = cmdMini.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration")
|
||||
miniFilerOptions.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
miniFilerOptions.remoteCacheEvictThreshold = cmdMini.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
miniFilerOptions.idleTimeout = cmdMini.Flag.Int("filer.idleTimeout", 10, "connection idle seconds")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
@@ -578,6 +579,7 @@ func initMiniWebDAVFlags() {
|
||||
miniWebDavOptions.cacheSizeMB = cmdMini.Flag.Int64("webdav.cacheCapacityMB", 0, "local cache capacity in MB")
|
||||
miniWebDavOptions.maxMB = cmdMini.Flag.Int("webdav.maxMB", 4, "split files larger than the limit")
|
||||
miniWebDavOptions.filerRootPath = cmdMini.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
|
||||
miniWebDavOptions.idleTimeout = cmdMini.Flag.Int("webdav.idleTimeout", 10, "connection idle seconds")
|
||||
}
|
||||
|
||||
// initMiniAdminFlags initializes Admin server flag options
|
||||
@@ -1577,6 +1579,7 @@ func runMini(cmd *Command, args []string) bool {
|
||||
singleMaster := isSingleMasterMode(*miniMasterOptions.peers)
|
||||
miniMasterOptions.releaseAllocOnFirstReport = singleMaster
|
||||
miniMasterOptions.singleReporterAddr = ""
|
||||
miniFilerOptions.skipEmptyMembershipConfirm = singleMaster
|
||||
if singleMaster {
|
||||
miniMasterOptions.singleReporterAddr = util.JoinHostPort(*miniIp, *miniOptions.v.port)
|
||||
}
|
||||
|
||||
+266
-90
@@ -5,12 +5,12 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/vector_pb"
|
||||
@@ -36,6 +37,8 @@ import (
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -55,8 +58,6 @@ type S3Options struct {
|
||||
portGrpc *int
|
||||
portIceberg *int
|
||||
portLance *int
|
||||
portVectors *int
|
||||
vectorsGrpc *string
|
||||
icebergCredentialRole *string
|
||||
icebergCredentialDuration *int
|
||||
config *string
|
||||
@@ -115,8 +116,6 @@ func init() {
|
||||
s3StandaloneOptions.portGrpc = cmdS3.Flag.Int("port.grpc", 0, "s3 server grpc listen port")
|
||||
s3StandaloneOptions.portIceberg = cmdS3.Flag.Int("port.iceberg", 8181, "Iceberg REST Catalog server listen port (0 to disable)")
|
||||
s3StandaloneOptions.portLance = cmdS3.Flag.Int("port.lance", 9101, "Lance Namespace server listen port (0 to disable); credential vending uses -iceberg.credentialRole")
|
||||
s3StandaloneOptions.portVectors = cmdS3.Flag.Int("port.vectors", 0, "S3 Vectors API server listen port (0 to disable); requires -vectors.grpc")
|
||||
s3StandaloneOptions.vectorsGrpc = cmdS3.Flag.String("vectors.grpc", "", "weed-vector-server gRPC address for the S3 Vectors API")
|
||||
s3StandaloneOptions.icebergCredentialRole = cmdS3.Flag.String("iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
|
||||
s3StandaloneOptions.icebergCredentialDuration = cmdS3.Flag.Int("iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
|
||||
s3StandaloneOptions.domainName = cmdS3.Flag.String("domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
|
||||
@@ -440,11 +439,19 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Start S3 Vectors API server if enabled
|
||||
if s3opt.portVectors != nil && *s3opt.portVectors > 0 {
|
||||
if httpS := s3opt.startVectorsServer(s3ApiServer, grpcDialOption, listenOnLocalhost); httpS != nil {
|
||||
httpServers = append(httpServers, httpS)
|
||||
}
|
||||
// The Vectors API rides the main -port listener whenever a weed-vector
|
||||
// backend is reachable — /s3vectors/ in the SigV4 credential scope picks
|
||||
// the vectors router.
|
||||
vectorsHandler := http.Handler(router)
|
||||
if vectorsRouter := s3opt.vectorsRouter(s3ApiServer, grpcDialOption, masterAddresses); vectorsRouter != nil {
|
||||
vr, mainRouter := vectorsRouter, router
|
||||
vectorsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if isVectorsRequest(r) {
|
||||
vr.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
mainRouter.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
if runtime.GOOS != "windows" {
|
||||
@@ -454,7 +461,8 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
localSocket = fmt.Sprintf("/tmp/seaweedfs-s3-%d.sock", *s3opt.port)
|
||||
}
|
||||
if s3SocketListener := pb.ListenOnLocalSocket(localSocket); s3SocketListener != nil {
|
||||
socketServer := newHttpServer(router, nil)
|
||||
s3SocketListener = &util.Listener{Listener: s3SocketListener, Timeout: idleTimeoutSeconds(s3opt.idleTimeout)}
|
||||
socketServer := newHttpServer(vectorsHandler, nil)
|
||||
httpServers = append(httpServers, socketServer)
|
||||
go func() {
|
||||
if err := socketServer.Serve(s3SocketListener); err != nil && err != http.ErrServerClosed {
|
||||
@@ -466,7 +474,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.port)
|
||||
s3ApiListener, s3ApiLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.port, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.port, idleTimeoutSeconds(s3opt.idleTimeout), listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
@@ -507,14 +515,9 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
grace.OnInterrupt(certProvider.Close)
|
||||
|
||||
caCertPool := x509.NewCertPool()
|
||||
if *s3opt.tlsCACertificate != "" {
|
||||
// load CA certificate file and add it to list of client CAs
|
||||
caCertFile, err := ioutil.ReadFile(*s3opt.tlsCACertificate)
|
||||
if err != nil {
|
||||
glog.Fatalf("error reading CA certificate: %v", err)
|
||||
}
|
||||
caCertPool.AppendCertsFromPEM(caCertFile)
|
||||
caCertPool, err := loadClientCAPool(*s3opt.tlsCACertificate)
|
||||
if err != nil {
|
||||
glog.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
clientAuth := tls.NoClientCert
|
||||
@@ -534,7 +537,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if *s3opt.portHttps == 0 {
|
||||
glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", version.Version(), *s3opt.port)
|
||||
if s3ApiLocalListener != nil {
|
||||
localServer := newHttpServer(router, tlsConfig)
|
||||
localServer := newHttpServer(vectorsHandler, tlsConfig)
|
||||
httpServers = append(httpServers, localServer)
|
||||
go func() {
|
||||
if err := localServer.ServeTLS(s3ApiLocalListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
@@ -542,7 +545,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
}()
|
||||
}
|
||||
httpS := newHttpServer(router, tlsConfig)
|
||||
httpS := newHttpServer(vectorsHandler, tlsConfig)
|
||||
httpServers = append(httpServers, httpS)
|
||||
shutdown := s3opt.newShutdown(stopGrpcServer, s3ApiServer, httpServers)
|
||||
if err = httpS.ServeTLS(s3ApiListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
@@ -553,12 +556,12 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
} else {
|
||||
glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", version.Version(), *s3opt.portHttps)
|
||||
s3ApiListenerHttps, s3ApiLocalListenerHttps, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portHttps, idleTimeoutSeconds(s3opt.idleTimeout), listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API HTTPS listener on %s:%d error: %v", *s3opt.bindIp, *s3opt.portHttps, err)
|
||||
}
|
||||
if s3ApiLocalListenerHttps != nil {
|
||||
localHttpsServer := newHttpServer(router, tlsConfig)
|
||||
localHttpsServer := newHttpServer(vectorsHandler, tlsConfig)
|
||||
httpServers = append(httpServers, localHttpsServer)
|
||||
go func() {
|
||||
if err := localHttpsServer.ServeTLS(s3ApiLocalListenerHttps, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
@@ -566,7 +569,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
}()
|
||||
}
|
||||
httpsServer := newHttpServer(router, tlsConfig)
|
||||
httpsServer := newHttpServer(vectorsHandler, tlsConfig)
|
||||
httpServers = append(httpServers, httpsServer)
|
||||
go func() {
|
||||
if err := httpsServer.ServeTLS(s3ApiListenerHttps, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
@@ -578,7 +581,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if *s3opt.tlsPrivateKey == "" || *s3opt.portHttps > 0 {
|
||||
glog.V(0).Infof("Start Seaweed S3 API Server %s at http port %d", version.Version(), *s3opt.port)
|
||||
if s3ApiLocalListener != nil {
|
||||
localServer := newHttpServer(router, nil)
|
||||
localServer := newHttpServer(vectorsHandler, nil)
|
||||
httpServers = append(httpServers, localServer)
|
||||
go func() {
|
||||
if err := localServer.Serve(s3ApiLocalListener); err != nil && err != http.ErrServerClosed {
|
||||
@@ -586,7 +589,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
}()
|
||||
}
|
||||
httpS := newHttpServer(router, nil)
|
||||
httpS := newHttpServer(vectorsHandler, nil)
|
||||
httpServers = append(httpServers, httpS)
|
||||
shutdown := s3opt.newShutdown(stopGrpcServer, s3ApiServer, httpServers)
|
||||
if err = httpS.Serve(s3ApiListener); err != nil && err != http.ErrServerClosed {
|
||||
@@ -635,7 +638,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, liste
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portIceberg)
|
||||
icebergListener, icebergLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portIceberg, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portIceberg, idleTimeoutSeconds(s3opt.idleTimeout), listenOnLocalhost)
|
||||
if err != nil {
|
||||
// The catalog is auxiliary to the S3 gateway; a port conflict must not
|
||||
// take the whole server down.
|
||||
@@ -681,7 +684,7 @@ func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer, listenO
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portLance)
|
||||
lanceListener, lanceLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portLance, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portLance, idleTimeoutSeconds(s3opt.idleTimeout), listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Errorf("Lance Namespace listener on %s error: %v", listenAddress, err)
|
||||
return nil
|
||||
@@ -706,84 +709,234 @@ func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer, listenO
|
||||
return httpS
|
||||
}
|
||||
|
||||
// startVectorsServer starts the S3 Vectors API server on a separate port. It
|
||||
// fans index and data calls out to the shared VectorService over gRPC; with no
|
||||
// -vectors.grpc the API is not served.
|
||||
func (s3opt *S3Options) startVectorsServer(s3ApiServer *s3api.S3ApiServer, grpcDialOption grpc.DialOption, listenOnLocalhost bool) *http.Server {
|
||||
if *s3opt.vectorsGrpc == "" {
|
||||
glog.Warningf("port.vectors set without -vectors.grpc; S3 Vectors API disabled")
|
||||
return nil
|
||||
}
|
||||
conn, err := pb.GrpcDial(context.Background(), *s3opt.vectorsGrpc, false, grpcDialOption)
|
||||
if err != nil {
|
||||
glog.Errorf("S3 Vectors: dial %s: %v", *s3opt.vectorsGrpc, err)
|
||||
// vectorsRouter builds the S3 Vectors API router — workers register to the
|
||||
// master and the backend resolves them lazily, so a worker that comes up
|
||||
// after the gateway still gets picked up on first query.
|
||||
func (s3opt *S3Options) vectorsRouter(s3ApiServer *s3api.S3ApiServer, grpcDialOption grpc.DialOption, masterAddresses []pb.ServerAddress) *mux.Router {
|
||||
if len(masterAddresses) == 0 {
|
||||
glog.Warningf("S3 Vectors API disabled: no weed-vector registered on master")
|
||||
return nil
|
||||
}
|
||||
backend := &vectorDiscovery{masters: masterAddresses, grpcDialOption: grpcDialOption}
|
||||
vectorsRouter := mux.NewRouter().SkipClean(true)
|
||||
|
||||
vectorsServer := s3vectors.NewServer(s3ApiServer, s3ApiServer, vector_pb.NewVectorServiceClient(conn))
|
||||
vectorsServer := s3vectors.NewServer(s3ApiServer, s3ApiServer, backend)
|
||||
vectorsServer.SetRegion(s3tables.DefaultRegion)
|
||||
vectorsServer.SetAccountID(s3tables.DefaultAccountID)
|
||||
vectorsServer.RegisterRoutes(vectorsRouter)
|
||||
return vectorsRouter
|
||||
}
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portVectors)
|
||||
vectorsListener, vectorsLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portVectors, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Errorf("S3 Vectors listener on %s error: %v", listenAddress, err)
|
||||
conn.Close()
|
||||
return nil
|
||||
// vectorDiscovery resolves the currently registered weed-vector through the
|
||||
// master and caches the connection; workers joining after gateway startup
|
||||
// are picked up on first query.
|
||||
type vectorDiscovery struct {
|
||||
masters []pb.ServerAddress
|
||||
grpcDialOption grpc.DialOption
|
||||
mu sync.Mutex
|
||||
worker string
|
||||
conn *grpc.ClientConn
|
||||
client vector_pb.VectorServiceClient
|
||||
nextResolve time.Time
|
||||
}
|
||||
|
||||
// reset drops the cached worker so the next call rediscovers — invoked on
|
||||
// transport errors only, and only when the failed client is still the
|
||||
// cached one (a concurrent request may have already re-resolved).
|
||||
func (d *vectorDiscovery) reset(c vector_pb.VectorServiceClient) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if c != d.client {
|
||||
return
|
||||
}
|
||||
if d.conn != nil {
|
||||
d.conn.Close()
|
||||
}
|
||||
d.worker, d.conn, d.client = "", nil, nil
|
||||
d.nextResolve = time.Time{}
|
||||
}
|
||||
|
||||
// Mirror the main API: when TLS is configured the vectors port serves
|
||||
// HTTPS, not a second plaintext endpoint.
|
||||
if *s3opt.tlsPrivateKey != "" {
|
||||
getCert, _, err := security.NewReloadingServerCertificate(*s3opt.tlsCertificate, *s3opt.tlsPrivateKey)
|
||||
// Only Unavailable proves a transport failure — a request deadline or an
|
||||
// application-level error can fire on a healthy connection.
|
||||
func isTransportError(err error) bool {
|
||||
return status.Code(err) == codes.Unavailable
|
||||
}
|
||||
|
||||
func (d *vectorDiscovery) resolve() (vector_pb.VectorServiceClient, error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
worker := discoverVectorWorker(d.masters, d.grpcDialOption)
|
||||
if worker == "" {
|
||||
return nil, fmt.Errorf("no weed-vector registered on master")
|
||||
}
|
||||
if worker != d.worker {
|
||||
if d.conn != nil {
|
||||
d.conn.Close()
|
||||
}
|
||||
conn, err := pb.GrpcDial(context.Background(), worker, false, d.grpcDialOption)
|
||||
if err != nil {
|
||||
glog.Errorf("S3 Vectors: load HTTPS certificate: %v", err)
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
clientAuth := tls.NoClientCert
|
||||
if *s3opt.tlsVerifyClientCert {
|
||||
clientAuth = tls.RequireAndVerifyClientCert
|
||||
}
|
||||
tlsConfig := &tls.Config{GetCertificate: getCert, ClientAuth: clientAuth}
|
||||
if err := security.FixTlsConfig(util.GetViper(), tlsConfig); err != nil {
|
||||
glog.Errorf("S3 Vectors: tls config: %v", err)
|
||||
return nil
|
||||
}
|
||||
httpS := newHttpServer(vectorsRouter, tlsConfig)
|
||||
if vectorsLocalListener != nil {
|
||||
go func() {
|
||||
if err := httpS.ServeTLS(vectorsLocalListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
glog.V(0).Infof("S3 Vectors localhost listener error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
go func() {
|
||||
if err := httpS.ServeTLS(vectorsListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
glog.Errorf("S3 Vectors API Server Fail to serve: %v", err)
|
||||
}
|
||||
}()
|
||||
return httpS
|
||||
d.worker, d.conn = worker, conn
|
||||
d.client = vector_pb.NewVectorServiceClient(conn)
|
||||
}
|
||||
return d.client, nil
|
||||
}
|
||||
|
||||
glog.V(0).Infof("Start S3 Vectors API Server at http://%s", listenAddress)
|
||||
const vectorResolveInterval = 5 * time.Second
|
||||
|
||||
httpS := newHttpServer(vectorsRouter, nil)
|
||||
if vectorsLocalListener != nil {
|
||||
go func() {
|
||||
if err := httpS.Serve(vectorsLocalListener); err != nil && err != http.ErrServerClosed {
|
||||
glog.V(0).Infof("S3 Vectors localhost listener error: %v", err)
|
||||
}
|
||||
}()
|
||||
func (d *vectorDiscovery) cli() (vector_pb.VectorServiceClient, error) {
|
||||
d.mu.Lock()
|
||||
cli := d.client
|
||||
past := !time.Now().Before(d.nextResolve)
|
||||
if cli != nil && !past {
|
||||
d.mu.Unlock()
|
||||
return cli, nil
|
||||
}
|
||||
go func() {
|
||||
if err := httpS.Serve(vectorsListener); err != nil && err != http.ErrServerClosed {
|
||||
glog.Errorf("S3 Vectors API Server Fail to serve: %v", err)
|
||||
if !past && cli == nil {
|
||||
d.mu.Unlock()
|
||||
return nil, fmt.Errorf("no weed-vector registered on master")
|
||||
}
|
||||
d.nextResolve = time.Now().Add(vectorResolveInterval)
|
||||
d.mu.Unlock()
|
||||
return d.resolve()
|
||||
}
|
||||
|
||||
func (d *vectorDiscovery) CreateIndex(ctx context.Context, in *vector_pb.CreateIndexRequest, opts ...grpc.CallOption) (resp *vector_pb.CreateIndexResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}()
|
||||
return httpS
|
||||
if resp, err = c.CreateIndex(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) DropIndex(ctx context.Context, in *vector_pb.DropIndexRequest, opts ...grpc.CallOption) (resp *vector_pb.DropIndexResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.DropIndex(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) PutVectors(ctx context.Context, in *vector_pb.PutVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.PutVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.PutVectors(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) GetVectors(ctx context.Context, in *vector_pb.GetVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.GetVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.GetVectors(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) DeleteVectors(ctx context.Context, in *vector_pb.DeleteVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.DeleteVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.DeleteVectors(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) ListVectors(ctx context.Context, in *vector_pb.ListVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.ListVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.ListVectors(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
func (d *vectorDiscovery) QueryVectors(ctx context.Context, in *vector_pb.QueryVectorsRequest, opts ...grpc.CallOption) (resp *vector_pb.QueryVectorsResponse, err error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
var c vector_pb.VectorServiceClient
|
||||
if c, err = d.cli(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp, err = c.QueryVectors(ctx, in, opts...); err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
if !isTransportError(err) {
|
||||
return nil, err
|
||||
}
|
||||
d.reset(c)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// isVectorsRequest routes by the SigV4 credential scope — the s3vectors
|
||||
// service name lives there, not in the path.
|
||||
func isVectorsRequest(r *http.Request) bool {
|
||||
if v := r.Header.Get("Authorization"); v != "" {
|
||||
return strings.Contains(v, "/s3vectors/")
|
||||
}
|
||||
return strings.Contains(r.URL.Query().Get("X-Amz-Credential"), "/s3vectors/")
|
||||
}
|
||||
|
||||
func loadClientCAPool(caCertFile string) (*x509.CertPool, error) {
|
||||
pool := x509.NewCertPool()
|
||||
if caCertFile == "" {
|
||||
return pool, nil
|
||||
}
|
||||
pem, err := os.ReadFile(caCertFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading CA certificate: %w", err)
|
||||
}
|
||||
if !pool.AppendCertsFromPEM(pem) {
|
||||
return nil, fmt.Errorf("no valid certificates found in %s", caCertFile)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// deriveLanceStorageEndpoint picks the endpoint the Lance namespace puts in
|
||||
@@ -896,3 +1049,26 @@ func (v lanceCredentialVendor) VendTableCredentials(ctx context.Context, princip
|
||||
Expiration: credentials.Expiration,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// discoverVectorWorker resolves one registered weed-vector server through the
|
||||
// master's cluster-nodes list; OSS fans every vector call to that single
|
||||
// backend.
|
||||
func discoverVectorWorker(masters []pb.ServerAddress, grpcDialOption grpc.DialOption) string {
|
||||
for _, master := range masters {
|
||||
conn, err := pb.GrpcDial(context.Background(), master.ToGrpcAddress(), false, grpcDialOption)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
resp, err := master_pb.NewSeaweedClient(conn).ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
|
||||
ClientType: "vector",
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, node := range resp.ClusterNodes {
|
||||
glog.V(0).Infof("S3 Vectors: discovered weed-vector at %s via master %s", node.Address, master)
|
||||
return node.Address
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+46
-2
@@ -3,13 +3,16 @@ package command
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
weed_server "github.com/seaweedfs/seaweedfs/weed/server"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
|
||||
@@ -138,6 +141,7 @@ func init() {
|
||||
filerOptions.tusSessionExpiry = cmdServer.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"")
|
||||
filerOptions.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
filerOptions.remoteCacheEvictThreshold = cmdServer.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
filerOptions.idleTimeout = cmdServer.Flag.Int("filer.idleTimeout", 10, "connection idle seconds")
|
||||
|
||||
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
|
||||
@@ -207,6 +211,7 @@ func init() {
|
||||
s3Options.iamSelfServiceRequiresGrant = cmdServer.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
|
||||
sftpOptions.port = cmdServer.Flag.Int("sftp.port", 2022, "SFTP server listen port")
|
||||
sftpOptions.idleTimeout = cmdServer.Flag.Int("sftp.idleTimeout", 10, "connection idle seconds")
|
||||
sftpOptions.sshPrivateKey = cmdServer.Flag.String("sftp.sshPrivateKey", "", "path to the SSH private key file for host authentication")
|
||||
sftpOptions.hostKeysFolder = cmdServer.Flag.String("sftp.hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
|
||||
sftpOptions.authMethods = cmdServer.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
|
||||
@@ -220,6 +225,7 @@ func init() {
|
||||
sftpOptions.dataCenter = cmdServer.Flag.String("sftp.dataCenter", "", "prefer to read and write to volumes in this data center")
|
||||
sftpOptions.localSocket = cmdServer.Flag.String("sftp.localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
|
||||
iamOptions.port = cmdServer.Flag.Int("iam.port", 8111, "iam server http listen port")
|
||||
iamOptions.idleTimeout = cmdServer.Flag.Int("iam.idleTimeout", 10, "connection idle seconds")
|
||||
iamOptions.selfServiceRequiresGrant = s3Options.iamSelfServiceRequiresGrant
|
||||
|
||||
webdavOptions.port = cmdServer.Flag.Int("webdav.port", 7333, "webdav server http listen port")
|
||||
@@ -232,6 +238,7 @@ func init() {
|
||||
webdavOptions.cacheSizeMB = cmdServer.Flag.Int64("webdav.cacheCapacityMB", 0, "local cache capacity in MB")
|
||||
webdavOptions.maxMB = cmdServer.Flag.Int("webdav.maxMB", 4, "split files larger than the limit")
|
||||
webdavOptions.filerRootPath = cmdServer.Flag.String("webdav.filer.path", "/", "use this remote path from filer server")
|
||||
webdavOptions.idleTimeout = cmdServer.Flag.Int("webdav.idleTimeout", 10, "connection idle seconds")
|
||||
|
||||
mqBrokerOptions.port = cmdServer.Flag.Int("mq.broker.port", 17777, "message queue broker gRPC listen port")
|
||||
mqBrokerOptions.logFlushInterval = cmdServer.Flag.Int("mq.broker.logFlushInterval", 5, "log buffer flush interval in seconds")
|
||||
@@ -293,10 +300,22 @@ func runServer(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
var actualPeersForComponents string
|
||||
var embeddedMaster atomic.Pointer[weed_server.MasterServer]
|
||||
var peerList []pb.ServerAddress
|
||||
if *isStartingMasterServer {
|
||||
// If we are starting a master, validate and complete the peer list
|
||||
_, peerList := checkPeers(*serverIp, *masterOptions.port, *masterOptions.portGrpc, *masterOptions.peers)
|
||||
_, peerList = checkPeers(*serverIp, *masterOptions.port, *masterOptions.portGrpc, *masterOptions.peers)
|
||||
actualPeersForComponents = strings.Join(pb.ToAddressStrings(peerList), ",")
|
||||
if len(peerList) == 1 && *isStartingVolumeServer {
|
||||
// A single-master weed server has one guaranteed reporter: its
|
||||
// embedded volume server, whose first heartbeat already carries the
|
||||
// full inventory. Its clean report collapses the post-mint
|
||||
// allocation hold to a confirm pulse instead of running the whole
|
||||
// warmup window on every fresh start. Other volume servers stay
|
||||
// admitted, so a late veteran still lands its prior-state evidence
|
||||
// inside that pulse.
|
||||
masterOptions.expectedReporterAddr = util.JoinHostPort(*serverIp, *serverOptions.v.port)
|
||||
}
|
||||
} else if *masterOptions.peers != "" {
|
||||
if isSingleMasterMode(*masterOptions.peers) {
|
||||
glog.Fatalf("'-master.peers=none' is only valid when starting a master server, but master is not starting.")
|
||||
@@ -437,6 +456,17 @@ func runServer(cmd *Command, args []string) bool {
|
||||
if *filerOptions.diskType == "" && *serverOptions.v.diskType != "" {
|
||||
filerOptions.diskType = serverOptions.v.diskType
|
||||
}
|
||||
if len(peerList) == 1 && *isStartingMasterServer {
|
||||
// The embedded filer shares the master's process: when the master
|
||||
// mints a fresh TopologyId its persisted state was empty, so the
|
||||
// empty peer scan only has to survive a reconnecting peer's
|
||||
// keepalive retries, not the full membership confirm. Prior state
|
||||
// keeps the full window.
|
||||
filerOptions.clusterFreshHint = func() bool {
|
||||
ms := embeddedMaster.Load()
|
||||
return ms != nil && ms.Topo.FreshMinted()
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
filerOptions.startFiler()
|
||||
@@ -502,12 +532,26 @@ func runServer(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
if *isStartingMasterServer {
|
||||
go startMaster(masterOptions, serverWhiteList)
|
||||
go startMaster(masterOptions, serverWhiteList, &embeddedMaster)
|
||||
}
|
||||
|
||||
select {}
|
||||
}
|
||||
|
||||
// idleTimeoutSeconds converts a seconds flag to the listener activity timeout,
|
||||
// keeping the 10s default when the option was never set. The clamp keeps the
|
||||
// multiplication from overflowing time.Duration; non-positive values disable
|
||||
// the timeout, as before.
|
||||
func idleTimeoutSeconds(seconds *int) time.Duration {
|
||||
if seconds == nil {
|
||||
return 10 * time.Second
|
||||
}
|
||||
if *seconds <= 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(min(int64(*seconds), math.MaxInt64/int64(time.Second))) * time.Second
|
||||
}
|
||||
|
||||
func newHttpServer(h http.Handler, tlsConfig *tls.Config) *http.Server {
|
||||
s := &http.Server{
|
||||
Handler: h,
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package command
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestServerFilerDisableHttpFlag(t *testing.T) {
|
||||
flag := cmdServer.Flag.Lookup("filer.disableHttp")
|
||||
@@ -23,3 +28,31 @@ func TestServerGatewayDataCenterFlags(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdleTimeoutSeconds(t *testing.T) {
|
||||
if got := idleTimeoutSeconds(nil); got != 10*time.Second {
|
||||
t.Fatalf("idleTimeoutSeconds(nil) = %v, want 10s", got)
|
||||
}
|
||||
zero, neg, five := 0, -3, 5
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
seconds *int
|
||||
want time.Duration
|
||||
}{
|
||||
{"zero disables", &zero, 0},
|
||||
{"negative disables", &neg, 0},
|
||||
{"positive converts", &five, 5 * time.Second},
|
||||
} {
|
||||
if got := idleTimeoutSeconds(tc.seconds); got != tc.want {
|
||||
t.Errorf("%s: idleTimeoutSeconds = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
// Only 64-bit int can exceed the clamp threshold.
|
||||
if strconv.IntSize == 64 {
|
||||
huge := math.MaxInt
|
||||
want := time.Duration(math.MaxInt64/int64(time.Second)) * time.Second
|
||||
if got := idleTimeoutSeconds(&huge); got != want {
|
||||
t.Errorf("huge clamps: idleTimeoutSeconds = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ type SftpOptions struct {
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
idleTimeout *int
|
||||
sshPrivateKey *string
|
||||
hostKeysFolder *string
|
||||
authMethods *string
|
||||
@@ -62,6 +63,7 @@ func init() {
|
||||
sftpOptionsStandalone.filer = cmdSftp.Flag.String("filer", "localhost:8888", "filer server address (ip:port)")
|
||||
sftpOptionsStandalone.bindIp = cmdSftp.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to 0.0.0.0.")
|
||||
sftpOptionsStandalone.port = cmdSftp.Flag.Int("port", 2022, "SFTP server listen port")
|
||||
sftpOptionsStandalone.idleTimeout = cmdSftp.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
sftpOptionsStandalone.sshPrivateKey = cmdSftp.Flag.String("sshPrivateKey", "", "path to the SSH private key file for host authentication")
|
||||
sftpOptionsStandalone.hostKeysFolder = cmdSftp.Flag.String("hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
|
||||
sftpOptionsStandalone.authMethods = cmdSftp.Flag.String("authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
|
||||
@@ -112,6 +114,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
if sftpOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *sftpOpt.listenOnLocalhost
|
||||
}
|
||||
idleTimeout := idleTimeoutSeconds(sftpOpt.idleTimeout)
|
||||
if *sftpOpt.bindIp == "" {
|
||||
*sftpOpt.bindIp = "0.0.0.0"
|
||||
}
|
||||
@@ -190,6 +193,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
localSocket = fmt.Sprintf("/tmp/seaweedfs-sftp-%d.sock", *sftpOpt.port)
|
||||
}
|
||||
if sftpSocketListener := pb.ListenOnLocalSocket(localSocket); sftpSocketListener != nil {
|
||||
sftpSocketListener = &util.Listener{Listener: sftpSocketListener, Timeout: idleTimeout}
|
||||
go func() {
|
||||
// start on local unix socket
|
||||
if err := service.Serve(sftpSocketListener); err != nil {
|
||||
@@ -201,7 +205,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
|
||||
// Start the SFTP service on TCP
|
||||
listenAddress := fmt.Sprintf("%s:%d", *sftpOpt.bindIp, *sftpOpt.port)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, idleTimeout, listenOnLocalhost)
|
||||
if err != nil {
|
||||
glog.Fatalf("SFTP server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
@@ -664,7 +664,7 @@ func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerSe
|
||||
func (v VolumeServerOptions) startPublicHttpService(handler http.Handler, listenOnLocalhost bool) httpdown.Server {
|
||||
publicListeningAddress := util.JoinHostPort(*v.bindIp, *v.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed volume server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, idleTimeoutSeconds(v.idleConnectionTimeout), listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
@@ -700,7 +700,7 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler, liste
|
||||
|
||||
listeningAddress := util.JoinHostPort(*v.bindIp, *v.port)
|
||||
glog.V(0).Infof("Start Seaweed volume server %s at %s", version.Version(), listeningAddress)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, idleTimeoutSeconds(v.idleConnectionTimeout), listenOnLocalhost)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ type WebDavOption struct {
|
||||
cacheDir *string
|
||||
cacheSizeMB *int64
|
||||
maxMB *int
|
||||
idleTimeout *int
|
||||
// shutdownCtx, when non-nil, tells startWebDav to gracefully shut down the
|
||||
// HTTP server once the ctx is cancelled. Used by weed mini; nil for
|
||||
// standalone weed webdav.
|
||||
@@ -57,6 +58,7 @@ func init() {
|
||||
webDavStandaloneOptions.cacheSizeMB = cmdWebDav.Flag.Int64("cacheCapacityMB", 0, "local cache capacity in MB")
|
||||
webDavStandaloneOptions.maxMB = cmdWebDav.Flag.Int("maxMB", 4, "split files larger than the limit")
|
||||
webDavStandaloneOptions.filerRootPath = cmdWebDav.Flag.String("filer.path", "/", "use this remote path from filer server")
|
||||
webDavStandaloneOptions.idleTimeout = cmdWebDav.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
}
|
||||
|
||||
var cmdWebDav = &Command{
|
||||
@@ -147,8 +149,10 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
|
||||
httpS := &http.Server{Handler: ws.Handler}
|
||||
|
||||
idleTimeout := idleTimeoutSeconds(wo.idleTimeout)
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *wo.ipBind, *wo.port)
|
||||
webDavListener, err := util.NewListener(listenAddress, time.Duration(10)*time.Second)
|
||||
webDavListener, err := util.NewListener(listenAddress, idleTimeout)
|
||||
if err != nil {
|
||||
glog.Fatalf("WebDav Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
@@ -119,12 +119,15 @@ type VolumeServerJwtFunction func(fileId string) string
|
||||
// refreshUrls lets a fetch loop relearn a chunk's locations inside a single
|
||||
// read: drop the cached entry and look it up again, whether every location
|
||||
// failed or one did while another answered. Nil when there is nothing to
|
||||
// invalidate against.
|
||||
// invalidate against. A cancelled read keeps the cached locations.
|
||||
func refreshUrls(ctx context.Context, invalidator CacheInvalidator, lookupFn wdclient.LookupFileIdFunctionType, fileId string) util_http.RefreshUrlsFunc {
|
||||
if invalidator == nil || lookupFn == nil {
|
||||
return nil
|
||||
}
|
||||
return func() []string {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
invalidator.InvalidateCache(fileId)
|
||||
urls, err := lookupFn(ctx, fileId)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -26,3 +32,27 @@ func TestIsSameDataLeavesChunkOrderAlone(t *testing.T) {
|
||||
assert.Equal(t, "3,ccc", b.Chunks[0].FileId)
|
||||
assert.Equal(t, "4,ddd", b.Chunks[1].FileId)
|
||||
}
|
||||
|
||||
// A client hanging up mid-read must not evict or re-look-up the volume's locations.
|
||||
func TestCancelledFetchKeepsCachedLocations(t *testing.T) {
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
|
||||
inv := &countingInvalidator{}
|
||||
var lookups atomic.Int32
|
||||
lookup := func(ctx context.Context, fileId string) ([]string, error) {
|
||||
lookups.Add(1)
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
fileId := "4,12c8f6c18f"
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(50*time.Millisecond, cancel)
|
||||
_, err := util_http.RetriedFetchChunkData(ctx, make([]byte, 8), []string{volume.URL + "/" + fileId}, nil, false, true, 0, fileId, refreshUrls(ctx, inv, lookup, fileId))
|
||||
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
assert.Equal(t, int32(0), inv.invalidations.Load(), "a cancelled read must not evict the volume's locations")
|
||||
assert.Equal(t, int32(0), lookups.Load(), "a cancelled read must not look the volume up again")
|
||||
}
|
||||
@@ -22,6 +22,7 @@ var IsDebugFileReadWrite = false
|
||||
type FileHandle struct {
|
||||
fh FileHandleId
|
||||
counter int64
|
||||
fhs map[FileHandleId]struct{} // live fh values, one per open; guarded by fhMap's lock
|
||||
entry *LockedEntry
|
||||
entryLock sync.RWMutex
|
||||
entryChunkGroup *filer.ChunkGroup
|
||||
@@ -79,6 +80,7 @@ func newFileHandle(wfs *WFS, handleId FileHandleId, inode uint64, entry *filer_p
|
||||
fh := &FileHandle{
|
||||
fh: handleId,
|
||||
counter: 1,
|
||||
fhs: map[FileHandleId]struct{}{handleId: {}},
|
||||
inode: inode,
|
||||
wfs: wfs,
|
||||
}
|
||||
|
||||
@@ -54,7 +54,10 @@ func (i *FileHandleToInode) MarkInodeRenamed(inode uint64) {
|
||||
// existed. An existing handle only gets its counter bumped: its entry belongs
|
||||
// to whoever holds the handle lock, so callers install there (AcquireHandle)
|
||||
// rather than under this one.
|
||||
func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *filer_pb.Entry, versionTsNs int64, signature int32) (*FileHandle, bool) {
|
||||
// Every open gets its own fh value over the shared FileHandle so that
|
||||
// RELEASE — which identifies nothing else about the dying description — can
|
||||
// scope per-open state (e.g. OFD lock owners) to the open that is closing.
|
||||
func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *filer_pb.Entry, versionTsNs int64, signature int32) (*FileHandle, FileHandleId, bool) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
fh, found := i.inode2fh[inode]
|
||||
@@ -64,10 +67,13 @@ func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *fil
|
||||
fh.entryVersionSignature.Store(signature)
|
||||
i.inode2fh[inode] = fh
|
||||
i.fh2inode[fh.fh] = inode
|
||||
return fh, false
|
||||
return fh, fh.fh, false
|
||||
}
|
||||
fh.counter++
|
||||
return fh, true
|
||||
openFh := FileHandleId(util.RandomUint64())
|
||||
fh.fhs[openFh] = struct{}{}
|
||||
i.fh2inode[openFh] = inode
|
||||
return fh, openFh, true
|
||||
}
|
||||
|
||||
func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
|
||||
@@ -78,12 +84,15 @@ func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
// The released id never resolves again: a duplicate RELEASE on it must
|
||||
// not decrement the counter a second time.
|
||||
delete(i.fh2inode, fh)
|
||||
|
||||
fhHandle, fhFound := i.inode2fh[inode]
|
||||
if !fhFound {
|
||||
delete(i.fh2inode, fh)
|
||||
return nil
|
||||
}
|
||||
delete(fhHandle.fhs, fh)
|
||||
|
||||
// If the counter is already <= 0, a prior Release already started the
|
||||
// drain. Return nil to prevent double-processing.
|
||||
@@ -99,7 +108,10 @@ func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
|
||||
return fhHandle
|
||||
}
|
||||
delete(i.inode2fh, inode)
|
||||
delete(i.fh2inode, fhHandle.fh)
|
||||
for openFh := range fhHandle.fhs {
|
||||
delete(i.fh2inode, openFh)
|
||||
}
|
||||
fhHandle.fhs = nil
|
||||
return fhHandle
|
||||
}
|
||||
return nil
|
||||
@@ -111,6 +123,27 @@ func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
|
||||
func (i *FileHandleToInode) RemoveFileHandle(fh FileHandleId, inode uint64) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
if fhHandle, ok := i.inode2fh[inode]; ok {
|
||||
for openFh := range fhHandle.fhs {
|
||||
delete(i.fh2inode, openFh)
|
||||
}
|
||||
}
|
||||
delete(i.inode2fh, inode)
|
||||
delete(i.fh2inode, fh)
|
||||
}
|
||||
|
||||
// openFhIds returns the live fh values minted for an inode's shared handle —
|
||||
// one per still-open description.
|
||||
func (i *FileHandleToInode) openFhIds(inode uint64) []FileHandleId {
|
||||
i.RLock()
|
||||
defer i.RUnlock()
|
||||
fh := i.inode2fh[inode]
|
||||
if fh == nil {
|
||||
return nil
|
||||
}
|
||||
ids := make([]FileHandleId, 0, len(fh.fhs))
|
||||
for id := range fh.fhs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestReadUncachedRemoteEntryDoesNotDeadlock(t *testing.T) {
|
||||
t.Cleanup(func() { wfs.metaCache.Shutdown() })
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(testServer.content))},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: int64(len(testServer.content))},
|
||||
|
||||
@@ -41,6 +41,53 @@ type lockWaiter struct {
|
||||
wakeRefHeld bool
|
||||
}
|
||||
|
||||
// fhLockOwners maps each open's fh value to the non-flock lock owners that
|
||||
// acquired locks through it. The kernel scopes POSIX fcntl locks to the
|
||||
// process — released on FLUSH by LockOwner — while OFD fcntl locks are scoped
|
||||
// to the open file description and get no cleanup notice: RELEASE carries a
|
||||
// lock_owner only for flock holders. Tracking owners per open lets Release
|
||||
// drop the locks of the description that is closing while sibling opens of
|
||||
// the same inode keep theirs.
|
||||
type fhLockOwners struct {
|
||||
mu sync.Mutex
|
||||
m map[uint64]map[uint64]struct{}
|
||||
}
|
||||
|
||||
func (l *fhLockOwners) add(fh, owner uint64) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.m == nil {
|
||||
l.m = make(map[uint64]map[uint64]struct{})
|
||||
}
|
||||
owners := l.m[fh]
|
||||
if owners == nil {
|
||||
owners = make(map[uint64]struct{})
|
||||
l.m[fh] = owners
|
||||
}
|
||||
owners[owner] = struct{}{}
|
||||
}
|
||||
|
||||
func (l *fhLockOwners) pop(fh uint64) map[uint64]struct{} {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
owners := l.m[fh]
|
||||
delete(l.m, fh)
|
||||
return owners
|
||||
}
|
||||
|
||||
func (l *fhLockOwners) remove(fh, owner uint64) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
owners := l.m[fh]
|
||||
if owners == nil {
|
||||
return
|
||||
}
|
||||
delete(owners, owner)
|
||||
if len(owners) == 0 {
|
||||
delete(l.m, fh)
|
||||
}
|
||||
}
|
||||
|
||||
// PosixLockTable is the per-mount POSIX lock manager.
|
||||
type PosixLockTable struct {
|
||||
mu sync.Mutex
|
||||
|
||||
@@ -160,6 +160,7 @@ type WFS struct {
|
||||
posixSid uint64 // this mount's session id, for routed-lock owner identity
|
||||
posixHint *posixLockHint // local fcntl-lock hint for routed mode
|
||||
posixOwn *posixlock.Manager // mirror of locks this mount holds, re-asserted via keepalive
|
||||
fhLocks fhLockOwners // non-flock lock owners per open fh, drained at release
|
||||
peerRegistrar *PeerRegistrar
|
||||
peerDirectory *PeerDirectory
|
||||
peerGrpcServer *PeerGrpcServer
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestWholeFileServerCopyCandidate(t *testing.T) {
|
||||
srcInode := wfs.inodeToPath.Lookup(srcPath, 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(dstPath, 1, false, false, 0, true)
|
||||
|
||||
srcHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
srcHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -30,7 +30,7 @@ func TestWholeFileServerCopyCandidate(t *testing.T) {
|
||||
},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
dstHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -86,7 +86,7 @@ func TestCopyFileRangeUsesServerSideWholeFileCopy(t *testing.T) {
|
||||
srcInode := wfs.inodeToPath.Lookup(srcPath, 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(dstPath, 1, false, false, 0, true)
|
||||
|
||||
srcHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
srcHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -95,7 +95,7 @@ func TestCopyFileRangeUsesServerSideWholeFileCopy(t *testing.T) {
|
||||
},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
dstHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -171,7 +171,7 @@ func TestCopyFileRangeDoesNotFallbackAfterCommittedServerCopyRefreshFailure(t *t
|
||||
srcInode := wfs.inodeToPath.Lookup(srcPath, 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(dstPath, 1, false, false, 0, true)
|
||||
|
||||
srcHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
srcHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -182,7 +182,7 @@ func TestCopyFileRangeDoesNotFallbackAfterCommittedServerCopyRefreshFailure(t *t
|
||||
},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
dstHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100600,
|
||||
@@ -253,7 +253,7 @@ func TestCopyFileRangeReturnsEIOForAmbiguousServerSideCopy(t *testing.T) {
|
||||
srcInode := wfs.inodeToPath.Lookup(srcPath, 1, false, false, 0, true)
|
||||
dstInode := wfs.inodeToPath.Lookup(dstPath, 1, false, false, 0, true)
|
||||
|
||||
srcHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
srcHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
@@ -262,7 +262,7 @@ func TestCopyFileRangeReturnsEIOForAmbiguousServerSideCopy(t *testing.T) {
|
||||
},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
dstHandle, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
dstHandle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100600,
|
||||
|
||||
@@ -22,7 +22,7 @@ func newOpenFileHandle(t *testing.T, fileSize uint64) (*WFS, *FileHandle) {
|
||||
wfs := newCopyRangeTestWFS()
|
||||
path := util.FullPath("/file.txt")
|
||||
inode := wfs.inodeToPath.Lookup(path, 1, false, false, 0, true)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
|
||||
@@ -65,11 +65,12 @@ import (
|
||||
*/
|
||||
func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut) (status fuse.Status) {
|
||||
var fileHandle *FileHandle
|
||||
var openFh FileHandleId
|
||||
ctx, cancelFunc := ctxFromCancel(cancel)
|
||||
defer cancelFunc()
|
||||
fileHandle, status = wfs.AcquireHandle(ctx, in.NodeId, in.Flags, in.Uid, in.Gid)
|
||||
fileHandle, openFh, status = wfs.AcquireHandle(ctx, in.NodeId, in.Flags, in.Uid, in.Gid)
|
||||
if status == fuse.OK {
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
out.Fh = uint64(openFh)
|
||||
out.OpenFlags = 0
|
||||
|
||||
// For read-only opens, set FOPEN_KEEP_CACHE when the file's mtime
|
||||
@@ -140,12 +141,17 @@ func (wfs *WFS) invalidateOpenMtimeCache(inode uint64) {
|
||||
}
|
||||
|
||||
func (wfs *WFS) Release(cancel <-chan struct{}, in *fuse.ReleaseIn) {
|
||||
// Drop the file description's flock locks first: close() frees them
|
||||
// regardless of how writeback fares, and a flush stuck on an unreachable
|
||||
// filer must not pin a dead holder's lock in the table.
|
||||
// Drop the file description's locks first: close() frees them regardless
|
||||
// of how writeback fares, and a flush stuck on an unreachable filer must
|
||||
// not pin a dead holder's lock in the table. The kernel only reports a
|
||||
// lock_owner for flock holders, so OFD and leftover POSIX locks are
|
||||
// drained through the owners recorded for this open's fh value.
|
||||
if in.ReleaseFlags&fuse.FUSE_RELEASE_FLOCK_UNLOCK != 0 {
|
||||
wfs.releaseFlockOwner(in.NodeId, in.LockOwner)
|
||||
}
|
||||
for owner := range wfs.fhLocks.pop(in.Fh) {
|
||||
wfs.releasePosixOwner(in.NodeId, owner)
|
||||
}
|
||||
// Flush is usually sent before Release, but the FUSE protocol does not
|
||||
// guarantee it. Route every Release through doFlush so a dirty handle
|
||||
// (e.g. a deferred create with no intervening Flush) is not dropped.
|
||||
|
||||
@@ -26,36 +26,66 @@ func (wfs *WFS) GetLk(cancel <-chan struct{}, in *fuse.LkIn, out *fuse.LkOut) fu
|
||||
// SetLk sets or clears a POSIX lock (non-blocking).
|
||||
// Returns EAGAIN if the lock conflicts with an existing lock from another owner.
|
||||
func (wfs *WFS) SetLk(cancel <-chan struct{}, in *fuse.LkIn) fuse.Status {
|
||||
var status fuse.Status
|
||||
if wfs.crossMountLocks() {
|
||||
return wfs.routedSetLk(cancel, in)
|
||||
status = wfs.routedSetLk(cancel, in)
|
||||
} else {
|
||||
lk := lockRange{
|
||||
Start: in.Lk.Start,
|
||||
End: in.Lk.End,
|
||||
Typ: in.Lk.Typ,
|
||||
Owner: in.Owner,
|
||||
Pid: in.Lk.Pid,
|
||||
IsFlock: in.LkFlags&fuse.FUSE_LK_FLOCK != 0,
|
||||
}
|
||||
status = wfs.posixLocks.SetLk(in.NodeId, lk)
|
||||
}
|
||||
lk := lockRange{
|
||||
Start: in.Lk.Start,
|
||||
End: in.Lk.End,
|
||||
Typ: in.Lk.Typ,
|
||||
Owner: in.Owner,
|
||||
Pid: in.Lk.Pid,
|
||||
IsFlock: in.LkFlags&fuse.FUSE_LK_FLOCK != 0,
|
||||
}
|
||||
return wfs.posixLocks.SetLk(in.NodeId, lk)
|
||||
wfs.noteFhLockOwner(in, status)
|
||||
return status
|
||||
}
|
||||
|
||||
// SetLkw sets a POSIX lock (blocking).
|
||||
// Waits until the lock can be acquired or the request is cancelled.
|
||||
func (wfs *WFS) SetLkw(cancel <-chan struct{}, in *fuse.LkIn) fuse.Status {
|
||||
var status fuse.Status
|
||||
if wfs.crossMountLocks() {
|
||||
return wfs.routedSetLkw(cancel, in)
|
||||
status = wfs.routedSetLkw(cancel, in)
|
||||
} else {
|
||||
lk := lockRange{
|
||||
Start: in.Lk.Start,
|
||||
End: in.Lk.End,
|
||||
Typ: in.Lk.Typ,
|
||||
Owner: in.Owner,
|
||||
Pid: in.Lk.Pid,
|
||||
IsFlock: in.LkFlags&fuse.FUSE_LK_FLOCK != 0,
|
||||
}
|
||||
if lk.Typ == f_UNLCK {
|
||||
status = wfs.posixLocks.SetLk(in.NodeId, lk)
|
||||
} else {
|
||||
status = wfs.posixLocks.SetLkw(in.NodeId, lk, cancel)
|
||||
}
|
||||
}
|
||||
wfs.noteFhLockOwner(in, status)
|
||||
return status
|
||||
}
|
||||
|
||||
// noteFhLockOwner remembers a granted non-flock lock owner under the open it
|
||||
// was taken on, so Release can drain every lock the file description held —
|
||||
// the kernel sends no cleanup notice for OFD locks.
|
||||
func (wfs *WFS) noteFhLockOwner(in *fuse.LkIn, status fuse.Status) {
|
||||
if status != fuse.OK || in.Lk.Typ == f_UNLCK || in.LkFlags&fuse.FUSE_LK_FLOCK != 0 {
|
||||
return
|
||||
}
|
||||
wfs.fhLocks.add(in.Fh, in.Owner)
|
||||
}
|
||||
|
||||
// forgetLockOwner drops a lock owner from every recorded open of the inode.
|
||||
// Flush calls it only after the owner's process-wide locks were released, so
|
||||
// keeping the record would let a later Release of an unrelated open drop
|
||||
// locks the process acquired in between — and a failed release keeps its
|
||||
// record so Release can retry.
|
||||
func (wfs *WFS) forgetLockOwner(inode, owner uint64) {
|
||||
for _, openFh := range wfs.fhMap.openFhIds(inode) {
|
||||
wfs.fhLocks.remove(uint64(openFh), owner)
|
||||
}
|
||||
lk := lockRange{
|
||||
Start: in.Lk.Start,
|
||||
End: in.Lk.End,
|
||||
Typ: in.Lk.Typ,
|
||||
Owner: in.Owner,
|
||||
Pid: in.Lk.Pid,
|
||||
IsFlock: in.LkFlags&fuse.FUSE_LK_FLOCK != 0,
|
||||
}
|
||||
if lk.Typ == f_UNLCK {
|
||||
return wfs.posixLocks.SetLk(in.NodeId, lk)
|
||||
}
|
||||
return wfs.posixLocks.SetLkw(in.NodeId, lk, cancel)
|
||||
}
|
||||
@@ -54,20 +54,20 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
return fuse.Status(syscall.EEXIST)
|
||||
}
|
||||
inode = wfs.inodeToPath.Lookup(entryFullPath, newEntry.Attributes.Crtime, false, len(newEntry.HardLinkId) > 0, newEntry.Attributes.Inode, true)
|
||||
fileHandle, status := wfs.AcquireHandle(ctx, inode, in.Flags, in.Uid, in.Gid)
|
||||
fileHandle, openFh, status := wfs.AcquireHandle(ctx, inode, in.Flags, in.Uid, in.Gid)
|
||||
if status != fuse.OK {
|
||||
return status
|
||||
}
|
||||
if in.Flags&syscall.O_TRUNC != 0 && in.Flags&fuse.O_ANYWRITE != 0 {
|
||||
if code = wfs.truncateEntry(entryFullPath, newEntry); code != fuse.OK {
|
||||
wfs.ReleaseHandle(fileHandle.fh)
|
||||
wfs.ReleaseHandle(openFh)
|
||||
return code
|
||||
}
|
||||
newEntry = fileHandle.GetEntry().GetEntry()
|
||||
}
|
||||
|
||||
wfs.outputPbEntry(&out.EntryOut, inode, newEntry)
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
out.Fh = uint64(openFh)
|
||||
out.OpenFlags = 0
|
||||
return fuse.OK
|
||||
}
|
||||
@@ -103,19 +103,19 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
return fuse.EIO
|
||||
}
|
||||
inode = wfs.inodeToPath.Lookup(entryFullPath, newEntry.Attributes.Crtime, false, len(newEntry.HardLinkId) > 0, newEntry.Attributes.Inode, true)
|
||||
fileHandle, status := wfs.AcquireHandle(ctx, inode, in.Flags, in.Uid, in.Gid)
|
||||
fileHandle, openFh, status := wfs.AcquireHandle(ctx, inode, in.Flags, in.Uid, in.Gid)
|
||||
if status != fuse.OK {
|
||||
return status
|
||||
}
|
||||
if in.Flags&syscall.O_TRUNC != 0 && in.Flags&fuse.O_ANYWRITE != 0 {
|
||||
if code = wfs.truncateEntry(entryFullPath, newEntry); code != fuse.OK {
|
||||
wfs.ReleaseHandle(fileHandle.fh)
|
||||
wfs.ReleaseHandle(openFh)
|
||||
return code
|
||||
}
|
||||
newEntry = fileHandle.GetEntry().GetEntry()
|
||||
}
|
||||
wfs.outputPbEntry(&out.EntryOut, inode, newEntry)
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
out.Fh = uint64(openFh)
|
||||
out.OpenFlags = 0
|
||||
return fuse.OK
|
||||
} else if code != fuse.OK {
|
||||
@@ -132,7 +132,7 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
// For deferred creates, bypass AcquireHandle (which calls maybeReadEntry
|
||||
// and would fail since the entry is not yet on the filer or in the meta cache).
|
||||
// We already have the entry from createRegularFile, so create the handle directly.
|
||||
fileHandle, existed := wfs.fhMap.AcquireFileHandle(wfs, inode, newEntry, 0, 0)
|
||||
fileHandle, openFh, existed := wfs.fhMap.AcquireFileHandle(wfs, inode, newEntry, 0, 0)
|
||||
if existed {
|
||||
// A create is authoritative for the entry it just made, so it takes
|
||||
// effect even on a handle that outlived a previous incarnation.
|
||||
@@ -155,7 +155,7 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
|
||||
}
|
||||
}
|
||||
|
||||
out.Fh = uint64(fileHandle.fh)
|
||||
out.Fh = uint64(openFh)
|
||||
out.OpenFlags = 0
|
||||
|
||||
return fuse.OK
|
||||
|
||||
@@ -267,7 +267,7 @@ func TestTruncateEntryClearsDirtyPagesForOpenHandle(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
fh.RememberPath(fullPath)
|
||||
|
||||
if err := fh.dirtyPages.AddPage(0, []byte("hello"), true, time.Now().UnixNano()); err != nil {
|
||||
@@ -315,7 +315,7 @@ func TestAccessChecksPermissions(t *testing.T) {
|
||||
|
||||
fullPath := util.FullPath("/visible.txt")
|
||||
inode := wfs.inodeToPath.Lookup(fullPath, 1, false, false, 0, true)
|
||||
handle, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
handle, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "visible.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0o640,
|
||||
@@ -528,7 +528,7 @@ func TestAcquireHandleHonorsDefaultPermissions(t *testing.T) {
|
||||
}
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/secret.txt"), entry.Attributes.Crtime, false, false, entry.Attributes.Inode, true)
|
||||
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, syscall.O_RDONLY, 999, 999)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, syscall.O_RDONLY, 999, 999)
|
||||
if status != tc.want {
|
||||
t.Fatalf("AcquireHandle status = %v, want %v", status, tc.want)
|
||||
}
|
||||
|
||||
@@ -65,8 +65,8 @@ func (wfs *WFS) Flush(cancel <-chan struct{}, in *fuse.FlushIn) fuse.Status {
|
||||
if fh == nil {
|
||||
// If handle is not found, it might have been already released
|
||||
// This is not an error condition for FLUSH
|
||||
if in.LockOwner != 0 {
|
||||
wfs.releasePosixOwner(in.NodeId, in.LockOwner)
|
||||
if in.LockOwner != 0 && wfs.releasePosixOwner(in.NodeId, in.LockOwner) {
|
||||
wfs.forgetLockOwner(in.NodeId, in.LockOwner)
|
||||
}
|
||||
return fuse.OK
|
||||
}
|
||||
@@ -89,8 +89,8 @@ func (wfs *WFS) Flush(cancel <-chan struct{}, in *fuse.FlushIn) fuse.Status {
|
||||
defer cancelFunc()
|
||||
|
||||
status := wfs.doFlush(ctx, fh, in.Uid, in.Gid, allowAsync)
|
||||
if in.LockOwner != 0 {
|
||||
wfs.releasePosixOwner(in.NodeId, in.LockOwner)
|
||||
if in.LockOwner != 0 && wfs.releasePosixOwner(in.NodeId, in.LockOwner) {
|
||||
wfs.forgetLockOwner(in.NodeId, in.LockOwner)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
@@ -11,18 +11,20 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid uint32) (fileHandle *FileHandle, status fuse.Status) {
|
||||
// AcquireHandle returns the shared handle for inode plus this open's own fh
|
||||
// value — the id handed to the kernel and seen again at RELEASE.
|
||||
func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid uint32) (fileHandle *FileHandle, openFh FileHandleId, status fuse.Status) {
|
||||
// If there is an in-flight async flush for this inode, wait for it to
|
||||
// complete before reopening. Otherwise the new handle would be built
|
||||
// from pre-close filer metadata and its next flush could overwrite the
|
||||
// data that was just written asynchronously.
|
||||
if !wfs.waitForPendingAsyncFlush(ctx, inode) {
|
||||
return nil, fuse.EINTR
|
||||
return nil, 0, fuse.EINTR
|
||||
}
|
||||
|
||||
path, pathStatus := wfs.inodeToPath.GetPath(inode)
|
||||
if pathStatus != fuse.OK {
|
||||
return nil, pathStatus
|
||||
return nil, 0, pathStatus
|
||||
}
|
||||
|
||||
// A fresh lookup returns the entry with the filer log position it
|
||||
@@ -43,12 +45,12 @@ func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid
|
||||
} else {
|
||||
entry, entryVersionTsNs, status = wfs.maybeLoadEntry(ctx, path)
|
||||
if status != fuse.OK {
|
||||
return nil, status
|
||||
return nil, 0, status
|
||||
}
|
||||
freshLookup = true
|
||||
}
|
||||
if wormEnforced, _ := wfs.wormEnforcedForEntry(path, entry); wormEnforced && flags&fuse.O_ANYWRITE != 0 {
|
||||
return nil, fuse.EPERM
|
||||
return nil, 0, fuse.EPERM
|
||||
}
|
||||
// Check unix permission bits for the requested access mode. With
|
||||
// default_permissions the kernel already enforced them before this
|
||||
@@ -59,12 +61,12 @@ func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid
|
||||
fileUid, fileGid = wfs.option.UidGidMapper.FilerToLocal(fileUid, fileGid)
|
||||
}
|
||||
if mask := openFlagsToAccessMask(flags); mask != 0 && !hasAccess(uid, gid, fileUid, fileGid, entry.Attributes.FileMode, mask) {
|
||||
return nil, fuse.EACCES
|
||||
return nil, 0, fuse.EACCES
|
||||
}
|
||||
}
|
||||
// need to AcquireFileHandle again to ensure correct handle counter
|
||||
var existed bool
|
||||
fileHandle, existed = wfs.fhMap.AcquireFileHandle(wfs, inode, entry, entryVersionTsNs.tsNs, entryVersionTsNs.signature)
|
||||
fileHandle, openFh, existed = wfs.fhMap.AcquireFileHandle(wfs, inode, entry, entryVersionTsNs.tsNs, entryVersionTsNs.signature)
|
||||
fileHandle.RememberPath(path)
|
||||
if existed && freshLookup {
|
||||
// Another opener created the handle while our lookup was in flight;
|
||||
@@ -84,12 +86,12 @@ func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid
|
||||
if fileHandle.dlmLock == nil {
|
||||
// No lock server is reachable: proceeding would silently drop
|
||||
// cross-mount write serialization, so fail the open instead.
|
||||
wfs.fhMap.ReleaseByHandle(fileHandle.fh)
|
||||
return nil, fuse.Status(syscall.EAGAIN)
|
||||
wfs.fhMap.ReleaseByHandle(openFh)
|
||||
return nil, 0, fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
glog.V(1).Infof("DLM lock acquired for %s", path)
|
||||
}
|
||||
return fileHandle, fuse.OK
|
||||
return fileHandle, openFh, fuse.OK
|
||||
}
|
||||
|
||||
// ReleaseHandle is called from FUSE Release. For handles with a pending
|
||||
|
||||
@@ -195,7 +195,7 @@ func TestUpdateEventRefreshesOpenFileHandle(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -260,7 +260,7 @@ func TestQueuedEventDoesNotRollBackNewerLocalState(t *testing.T) {
|
||||
wfs.inodeToPath.MarkChildrenCached(util.FullPath("/dir"))
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -302,7 +302,7 @@ func TestBufferedBuildEventReinvalidatesOnCompletion(t *testing.T) {
|
||||
wfs.inodeToPath.Lookup(util.FullPath("/dir"), time.Now().Unix(), true, false, 0, false)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -352,7 +352,7 @@ func TestUncachedDirStaleStoreEntryDoesNotMaskEvent(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -388,7 +388,7 @@ func TestQueuedEventOlderThanFlushedStateIsIgnored(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -424,7 +424,7 @@ func TestSaveEntryKeepsOpenHandleAheadOfOlderEvents(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -462,7 +462,7 @@ func TestQueuedEventDoesNotRollBackHandleOpenedAfterEnqueue(t *testing.T) {
|
||||
// Stall the single invalidation worker on an unrelated handle's lock so
|
||||
// queued events outlive the open below.
|
||||
blockerInode := wfs.inodeToPath.Lookup(util.FullPath("/other/blocker"), time.Now().Unix(), false, false, 0, false)
|
||||
blockerFh, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
blockerFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
Name: "blocker",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 1},
|
||||
}, 0, 0)
|
||||
@@ -499,7 +499,7 @@ func TestQueuedEventDoesNotRollBackHandleOpenedAfterEnqueue(t *testing.T) {
|
||||
// Open now: the lookup reaches the filer, which serves the newer
|
||||
// size-200 state versioned at log position 2000.
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -523,7 +523,7 @@ func TestAbortedBuildEventDoesNotRollBackLaterOpen(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{lookupSize: 200, lookupLogTsNs: 2000})
|
||||
|
||||
blockerInode := wfs.inodeToPath.Lookup(util.FullPath("/other/blocker"), time.Now().Unix(), false, false, 0, false)
|
||||
blockerFh, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
blockerFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
Name: "blocker",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 1},
|
||||
}, 0, 0)
|
||||
@@ -563,7 +563,7 @@ func TestAbortedBuildEventDoesNotRollBackLaterOpen(t *testing.T) {
|
||||
}
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -590,7 +590,7 @@ func TestEventDuringOpenLookupIsFenced(t *testing.T) {
|
||||
startFakeFiler(t, wfs, fake)
|
||||
|
||||
blockerInode := wfs.inodeToPath.Lookup(util.FullPath("/other/blocker"), time.Now().Unix(), false, false, 0, false)
|
||||
blockerFh, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
blockerFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, blockerInode, &filer_pb.Entry{
|
||||
Name: "blocker",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 1},
|
||||
}, 0, 0)
|
||||
@@ -626,7 +626,7 @@ func TestEventDuringOpenLookupIsFenced(t *testing.T) {
|
||||
}
|
||||
opened := make(chan openResult, 1)
|
||||
go func() {
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
opened <- openResult{fh, status}
|
||||
}()
|
||||
|
||||
@@ -667,7 +667,7 @@ func TestRemoteCacheResponseVersionFencesUndeliveredEvents(t *testing.T) {
|
||||
}
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -699,7 +699,7 @@ func TestEventlessSaveAckStillFencesOlderEvents(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{updateEventless: true, updateLogTsNs: 2000})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -755,7 +755,7 @@ func TestLocalAckDoesNotFenceUnrelatedDelayedEvents(t *testing.T) {
|
||||
// Open the file: the cached-store read must not claim position 2000 —
|
||||
// the local ack versioned only its own path.
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -794,14 +794,14 @@ func TestSlowerConcurrentOpenDoesNotOverwriteNewerHandle(t *testing.T) {
|
||||
}
|
||||
slow := make(chan openResult, 1)
|
||||
go func() {
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
slow <- openResult{fh, status}
|
||||
}()
|
||||
<-fake.lookupStarted
|
||||
|
||||
// The faster opener completes with newer state while the slow lookup is
|
||||
// still in flight.
|
||||
fastFh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fastFh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("fast AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -884,7 +884,7 @@ func TestAlreadyReflectedEventDoesNotDestroyDirtyPages(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -925,12 +925,12 @@ func TestSlowerOpenRejectedWhenHandleDirtyOrLookupUnversioned(t *testing.T) {
|
||||
}
|
||||
slow := make(chan openResult, 1)
|
||||
go func() {
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
slow <- openResult{fh, status}
|
||||
}()
|
||||
<-fake.lookupStarted
|
||||
|
||||
fastFh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fastFh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("fast AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -969,12 +969,12 @@ func TestUnversionedSlowerOpenDoesNotOverwrite(t *testing.T) {
|
||||
}
|
||||
slow := make(chan openResult, 1)
|
||||
go func() {
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
slow <- openResult{fh, status}
|
||||
}()
|
||||
<-fake.lookupStarted
|
||||
|
||||
fastFh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fastFh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("fast AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -998,7 +998,7 @@ func TestAlreadyReflectedEventPreservesDirtyWrites(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -1077,7 +1077,7 @@ func TestServerSideCopyInstallEnrollsInBase(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
}, 0, 0)
|
||||
@@ -1198,7 +1198,7 @@ func TestCommittedCopyWithFailedReadbackAdoptsItsEvent(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
}, 0, 0)
|
||||
@@ -1311,7 +1311,7 @@ func TestFlushAckCancelsPendingCopyEventAdoption(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
}, 0, 0)
|
||||
@@ -1356,7 +1356,7 @@ func TestAckedSaveInstallsIntoRacingOpenHandle(t *testing.T) {
|
||||
|
||||
// The handle opened after the setattr path found none, before the ack.
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -1378,7 +1378,7 @@ func TestAckedSaveInstallsIntoRacingOpenHandle(t *testing.T) {
|
||||
|
||||
// A dirty handle is left alone entirely: neither entry nor version.
|
||||
dirtyInode := wfs.inodeToPath.Lookup(util.FullPath("/dir/dirty"), time.Now().Unix(), false, false, 0, false)
|
||||
dirtyFh, _ := wfs.fhMap.AcquireFileHandle(wfs, dirtyInode, &filer_pb.Entry{
|
||||
dirtyFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dirtyInode, &filer_pb.Entry{
|
||||
Name: "dirty",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -1434,7 +1434,7 @@ func TestVacateEventPreservesDirtyPages(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -1469,7 +1469,7 @@ func TestCopyAdoptRejectsForeignEvent(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
}, 0, 0)
|
||||
@@ -1500,7 +1500,7 @@ func TestRemoteDownloadBaseMappedToLocal(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{cacheSize: 200, cacheUid: 2000, cacheLogTsNs: 1000})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 200},
|
||||
@@ -1545,7 +1545,7 @@ func TestForeignDeleteMarksHandleDeleted(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -1603,7 +1603,7 @@ func TestStaleRemoteDownloadDoesNotRollBack(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{cacheSize: 100, cacheLogTsNs: 1000})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 200},
|
||||
@@ -1637,7 +1637,7 @@ func TestRemoteOnlyHandleTakesUnversionedDownload(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{cacheSize: 100})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 100},
|
||||
@@ -1662,7 +1662,7 @@ func TestCopyAdoptRejectsForeignMetadataChange(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200, FileMode: 0100644},
|
||||
}, 0, 0)
|
||||
@@ -1697,7 +1697,7 @@ func TestForeignRenameDoesNotMarkHandleDeleted(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
}, 0, 0)
|
||||
@@ -1752,7 +1752,7 @@ func TestCopyAdoptAppliesForeignTouchToCleanHandle(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200, Mtime: 100},
|
||||
}, 0, 0)
|
||||
@@ -1788,7 +1788,7 @@ func TestUnversionedRemoteDownloadDoesNotOverwriteVersioned(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{cacheSize: 100})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 200},
|
||||
@@ -1820,7 +1820,7 @@ func TestEventFromAnotherFilerIsNotFencedByForeignClock(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{lookupSize: 200, lookupLogTsNs: 5000, lookupSignature: 11})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
fh, _, status := wfs.AcquireHandle(context.Background(), inode, 0, 0, 0)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("AcquireHandle status = %v, want OK", status)
|
||||
}
|
||||
@@ -1860,7 +1860,7 @@ func TestTouchBeforeCopyEventKeepsPostCopyWrites(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100, Mtime: 100},
|
||||
}, 0, 0)
|
||||
@@ -1924,7 +1924,7 @@ func TestRejectedDownloadDoesNotRollBackCache(t *testing.T) {
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "1,ab1", Size: 200}},
|
||||
@@ -1959,7 +1959,7 @@ func TestRemoteOnlyHandleRefusesKnownOlderDownload(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{cacheSize: 100, cacheLogTsNs: 1000})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 200},
|
||||
@@ -1981,7 +1981,7 @@ func TestForeignChmodPreservesDirtyPages(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 200, FileMode: 0100644},
|
||||
}, 0, 0)
|
||||
@@ -2013,12 +2013,12 @@ func TestRenameOverExistingMarksReplacedHandleDeleted(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
srcInode := wfs.inodeToPath.Lookup(util.FullPath("/dir/src"), time.Now().Unix(), false, false, 0, false)
|
||||
srcFh, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
srcFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
|
||||
Name: "src",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 100},
|
||||
}, 0, 0)
|
||||
dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dir/dst"), time.Now().Unix(), false, false, 0, false)
|
||||
dstFh, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
dstFh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
|
||||
Name: "dst",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 900},
|
||||
}, 0, 0)
|
||||
@@ -2053,7 +2053,7 @@ func TestAckFromAnotherFilerIsNotDroppedBehindForeignFence(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
|
||||
@@ -297,13 +297,13 @@ func posixPollAcquire(cancel <-chan struct{}, try func() (bool, error)) fuse.Sta
|
||||
}
|
||||
}
|
||||
|
||||
func (wfs *WFS) routedReleasePosixOwner(inode, owner uint64) {
|
||||
func (wfs *WFS) routedReleasePosixOwner(inode, owner uint64) bool {
|
||||
if !wfs.posixHint.has(inode, owner) {
|
||||
return
|
||||
return true
|
||||
}
|
||||
key, ok := wfs.posixLockKeyForInode(inode)
|
||||
if !ok {
|
||||
return
|
||||
return false
|
||||
}
|
||||
wfs.posixOwn.ReleasePosixOwner(key, wfs.posixSid, owner)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), posixLockReleaseTimeout)
|
||||
@@ -313,9 +313,10 @@ func (wfs *WFS) routedReleasePosixOwner(inode, owner uint64) {
|
||||
// transient failure would strand the lock until the owner filer's
|
||||
// session-lease reaping expires it.
|
||||
glog.Warningf("routed release posix owner %s: %v", key, err)
|
||||
return
|
||||
return false
|
||||
}
|
||||
wfs.posixHint.drop(inode, owner)
|
||||
return true
|
||||
}
|
||||
|
||||
func (wfs *WFS) routedReleaseFlockOwner(inode, owner uint64) {
|
||||
@@ -343,12 +344,16 @@ func (wfs *WFS) crossMountLocks() bool {
|
||||
// authority or the local table based on crossMountLocks, keeping the Flush and
|
||||
// Release call sites flag-agnostic.
|
||||
|
||||
func (wfs *WFS) releasePosixOwner(inode, owner uint64) {
|
||||
// releasePosixOwner reports whether the owner's locks were released. A false
|
||||
// return means a routed release failed and the close-time owner records must
|
||||
// be kept so a later Flush or the final Release retries instead of stranding
|
||||
// a live lock on the owner filer.
|
||||
func (wfs *WFS) releasePosixOwner(inode, owner uint64) bool {
|
||||
if wfs.crossMountLocks() {
|
||||
wfs.routedReleasePosixOwner(inode, owner)
|
||||
return
|
||||
return wfs.routedReleasePosixOwner(inode, owner)
|
||||
}
|
||||
wfs.posixLocks.ReleasePosixOwner(inode, owner)
|
||||
return true
|
||||
}
|
||||
|
||||
func (wfs *WFS) releaseFlockOwner(inode, owner uint64) {
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestReleaseDropsFlockWhileFlushBlocked(t *testing.T) {
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/f"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "f",
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}, 0, 0)
|
||||
@@ -75,3 +75,65 @@ func TestReleaseDropsFlockWhileFlushBlocked(t *testing.T) {
|
||||
t.Fatal("release never completed after the flush unblocked")
|
||||
}
|
||||
}
|
||||
|
||||
// OFD locks are scoped to the open file description, not the process, and the
|
||||
// kernel reports no lock_owner for them at RELEASE — only flock holders carry
|
||||
// one. Draining the owners recorded for the released handle frees them, so a
|
||||
// restarted process (new owner) no longer sees the dead description's write
|
||||
// lock.
|
||||
func TestReleaseDropsOfdLocks(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
wfs.posixLocks = NewPosixLockTable()
|
||||
startFakeFiler(t, wfs, &fakeFilerServer{})
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/f"), time.Now().Unix(), false, false, 0, false)
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "f",
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
}
|
||||
_, openFh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
_, siblingFh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
if siblingFh == openFh {
|
||||
t.Fatal("sibling open must get its own fh value")
|
||||
}
|
||||
|
||||
const ofdOwner = uint64(0x0fd0001)
|
||||
ofd := &fuse.LkIn{
|
||||
InHeader: fuse.InHeader{NodeId: inode},
|
||||
Fh: uint64(openFh),
|
||||
Owner: ofdOwner,
|
||||
Lk: fuse.FileLock{Start: 0, End: math.MaxUint64, Typ: f_RDLCK},
|
||||
}
|
||||
// A second open file description holds a read lock on the same inode;
|
||||
// it must survive the first description's release.
|
||||
const siblingOwner = uint64(0x0fd0002)
|
||||
sibling := &fuse.LkIn{
|
||||
InHeader: fuse.InHeader{NodeId: inode},
|
||||
Fh: uint64(siblingFh),
|
||||
Owner: siblingOwner,
|
||||
Lk: fuse.FileLock{Start: 0, End: math.MaxUint64, Typ: f_RDLCK},
|
||||
}
|
||||
if st := wfs.SetLk(nil, sibling); st != fuse.OK {
|
||||
t.Fatalf("take sibling read lock: %v", st)
|
||||
}
|
||||
if st := wfs.SetLk(nil, ofd); st != fuse.OK {
|
||||
t.Fatalf("take ofd lock: %v", st)
|
||||
}
|
||||
|
||||
wfs.Release(nil, &fuse.ReleaseIn{
|
||||
InHeader: fuse.InHeader{NodeId: inode},
|
||||
Fh: uint64(openFh),
|
||||
})
|
||||
|
||||
// The dead description's read lock is gone: the sibling can upgrade to a
|
||||
// write lock only because nothing else blocks it.
|
||||
var out fuse.LkOut
|
||||
wfs.posixLocks.GetLk(inode, lockRange{Start: 0, End: math.MaxUint64, Typ: f_WRLCK, Owner: 7}, &out)
|
||||
if out.Lk.Typ != f_RDLCK {
|
||||
t.Fatalf("sibling lock lost on release: typ=%d", out.Lk.Typ)
|
||||
}
|
||||
sibling.Lk.Typ = f_WRLCK
|
||||
if st := wfs.SetLk(nil, sibling); st != fuse.OK {
|
||||
t.Fatalf("ofd lock survived release: upgrade got %v", st)
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func TestRemoteRenameReplayLeavesTheTargetAlone(t *testing.T) {
|
||||
oldPath, newPath := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(oldPath, time.Now().Unix(), false, false, 0, true)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
@@ -100,7 +100,7 @@ func TestRenameBelowTheVersionFenceStillMoves(t *testing.T) {
|
||||
oldPath, newPath := util.FullPath("/dir/file"), util.FullPath("/dir/renamed")
|
||||
|
||||
inode := wfs.inodeToPath.Lookup(oldPath, time.Now().Unix(), false, false, 0, true)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 88},
|
||||
}, 0, 0)
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestSetXAttrCopiesValueBuffer(t *testing.T) {
|
||||
|
||||
path := util.FullPath("/aaa.txt")
|
||||
inode := wfs.inodeToPath.Lookup(path, 1, false, false, 0, true)
|
||||
fh, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
fh, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "aaa.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
FileMode: 0100644,
|
||||
|
||||
@@ -527,6 +527,11 @@ message DeleteEntryRequest {
|
||||
int64 if_not_modified_after = 9; // unix time in seconds
|
||||
bool keep_remote_object = 10;
|
||||
int64 if_not_modified_after_ns = 11; // unix time in nanoseconds; overrides if_not_modified_after when set
|
||||
// Optional precondition evaluated against the entry atomically with the
|
||||
// delete, under the filer's per-path lock. The request is routed to the
|
||||
// entry's owner filer for the check to be authoritative.
|
||||
map<string, bytes> expected_extended = 12;
|
||||
bool is_moved = 13; // set on a forwarded request so the owner applies it locally
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
@@ -868,6 +873,7 @@ message Lock {
|
||||
int64 generation = 5;
|
||||
bool is_backup = 6;
|
||||
int64 seq = 7;
|
||||
string prev_renew_token = 8;
|
||||
}
|
||||
message TransferLocksRequest {
|
||||
repeated Lock locks = 1;
|
||||
@@ -882,6 +888,7 @@ message ReplicateLockRequest {
|
||||
int64 generation = 5;
|
||||
bool is_unlock = 6;
|
||||
int64 seq = 7;
|
||||
string prev_renew_token = 8;
|
||||
}
|
||||
message ReplicateLockResponse {
|
||||
}
|
||||
|
||||
+196
-152
@@ -2783,8 +2783,13 @@ type DeleteEntryRequest struct {
|
||||
IfNotModifiedAfter int64 `protobuf:"varint,9,opt,name=if_not_modified_after,json=ifNotModifiedAfter,proto3" json:"if_not_modified_after,omitempty"` // unix time in seconds
|
||||
KeepRemoteObject bool `protobuf:"varint,10,opt,name=keep_remote_object,json=keepRemoteObject,proto3" json:"keep_remote_object,omitempty"`
|
||||
IfNotModifiedAfterNs int64 `protobuf:"varint,11,opt,name=if_not_modified_after_ns,json=ifNotModifiedAfterNs,proto3" json:"if_not_modified_after_ns,omitempty"` // unix time in nanoseconds; overrides if_not_modified_after when set
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
// Optional precondition evaluated against the entry atomically with the
|
||||
// delete, under the filer's per-path lock. The request is routed to the
|
||||
// entry's owner filer for the check to be authoritative.
|
||||
ExpectedExtended map[string][]byte `protobuf:"bytes,12,rep,name=expected_extended,json=expectedExtended,proto3" json:"expected_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
IsMoved bool `protobuf:"varint,13,opt,name=is_moved,json=isMoved,proto3" json:"is_moved,omitempty"` // set on a forwarded request so the owner applies it locally
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *DeleteEntryRequest) Reset() {
|
||||
@@ -2887,6 +2892,20 @@ func (x *DeleteEntryRequest) GetIfNotModifiedAfterNs() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *DeleteEntryRequest) GetExpectedExtended() map[string][]byte {
|
||||
if x != nil {
|
||||
return x.ExpectedExtended
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *DeleteEntryRequest) GetIsMoved() bool {
|
||||
if x != nil {
|
||||
return x.IsMoved
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type DeleteEntryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
|
||||
@@ -5916,16 +5935,17 @@ func (x *FindLockOwnerResponse) GetOwner() string {
|
||||
}
|
||||
|
||||
type Lock struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
RenewToken string `protobuf:"bytes,2,opt,name=renew_token,json=renewToken,proto3" json:"renew_token,omitempty"`
|
||||
ExpiredAtNs int64 `protobuf:"varint,3,opt,name=expired_at_ns,json=expiredAtNs,proto3" json:"expired_at_ns,omitempty"`
|
||||
Owner string `protobuf:"bytes,4,opt,name=owner,proto3" json:"owner,omitempty"`
|
||||
Generation int64 `protobuf:"varint,5,opt,name=generation,proto3" json:"generation,omitempty"`
|
||||
IsBackup bool `protobuf:"varint,6,opt,name=is_backup,json=isBackup,proto3" json:"is_backup,omitempty"`
|
||||
Seq int64 `protobuf:"varint,7,opt,name=seq,proto3" json:"seq,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
RenewToken string `protobuf:"bytes,2,opt,name=renew_token,json=renewToken,proto3" json:"renew_token,omitempty"`
|
||||
ExpiredAtNs int64 `protobuf:"varint,3,opt,name=expired_at_ns,json=expiredAtNs,proto3" json:"expired_at_ns,omitempty"`
|
||||
Owner string `protobuf:"bytes,4,opt,name=owner,proto3" json:"owner,omitempty"`
|
||||
Generation int64 `protobuf:"varint,5,opt,name=generation,proto3" json:"generation,omitempty"`
|
||||
IsBackup bool `protobuf:"varint,6,opt,name=is_backup,json=isBackup,proto3" json:"is_backup,omitempty"`
|
||||
Seq int64 `protobuf:"varint,7,opt,name=seq,proto3" json:"seq,omitempty"`
|
||||
PrevRenewToken string `protobuf:"bytes,8,opt,name=prev_renew_token,json=prevRenewToken,proto3" json:"prev_renew_token,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Lock) Reset() {
|
||||
@@ -6007,6 +6027,13 @@ func (x *Lock) GetSeq() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Lock) GetPrevRenewToken() string {
|
||||
if x != nil {
|
||||
return x.PrevRenewToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type TransferLocksRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Locks []*Lock `protobuf:"bytes,1,rep,name=locks,proto3" json:"locks,omitempty"`
|
||||
@@ -6088,16 +6115,17 @@ func (*TransferLocksResponse) Descriptor() ([]byte, []int) {
|
||||
}
|
||||
|
||||
type ReplicateLockRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
RenewToken string `protobuf:"bytes,2,opt,name=renew_token,json=renewToken,proto3" json:"renew_token,omitempty"`
|
||||
ExpiredAtNs int64 `protobuf:"varint,3,opt,name=expired_at_ns,json=expiredAtNs,proto3" json:"expired_at_ns,omitempty"`
|
||||
Owner string `protobuf:"bytes,4,opt,name=owner,proto3" json:"owner,omitempty"`
|
||||
Generation int64 `protobuf:"varint,5,opt,name=generation,proto3" json:"generation,omitempty"`
|
||||
IsUnlock bool `protobuf:"varint,6,opt,name=is_unlock,json=isUnlock,proto3" json:"is_unlock,omitempty"`
|
||||
Seq int64 `protobuf:"varint,7,opt,name=seq,proto3" json:"seq,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
RenewToken string `protobuf:"bytes,2,opt,name=renew_token,json=renewToken,proto3" json:"renew_token,omitempty"`
|
||||
ExpiredAtNs int64 `protobuf:"varint,3,opt,name=expired_at_ns,json=expiredAtNs,proto3" json:"expired_at_ns,omitempty"`
|
||||
Owner string `protobuf:"bytes,4,opt,name=owner,proto3" json:"owner,omitempty"`
|
||||
Generation int64 `protobuf:"varint,5,opt,name=generation,proto3" json:"generation,omitempty"`
|
||||
IsUnlock bool `protobuf:"varint,6,opt,name=is_unlock,json=isUnlock,proto3" json:"is_unlock,omitempty"`
|
||||
Seq int64 `protobuf:"varint,7,opt,name=seq,proto3" json:"seq,omitempty"`
|
||||
PrevRenewToken string `protobuf:"bytes,8,opt,name=prev_renew_token,json=prevRenewToken,proto3" json:"prev_renew_token,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *ReplicateLockRequest) Reset() {
|
||||
@@ -6179,6 +6207,13 @@ func (x *ReplicateLockRequest) GetSeq() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ReplicateLockRequest) GetPrevRenewToken() string {
|
||||
if x != nil {
|
||||
return x.PrevRenewToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type ReplicateLockResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -7086,7 +7121,7 @@ type LocateBrokerResponse_Resource struct {
|
||||
|
||||
func (x *LocateBrokerResponse_Resource) Reset() {
|
||||
*x = LocateBrokerResponse_Resource{}
|
||||
mi := &file_filer_proto_msgTypes[100]
|
||||
mi := &file_filer_proto_msgTypes[101]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -7098,7 +7133,7 @@ func (x *LocateBrokerResponse_Resource) String() string {
|
||||
func (*LocateBrokerResponse_Resource) ProtoMessage() {}
|
||||
|
||||
func (x *LocateBrokerResponse_Resource) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_proto_msgTypes[100]
|
||||
mi := &file_filer_proto_msgTypes[101]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -7154,7 +7189,7 @@ type FilerConf_PathConf struct {
|
||||
|
||||
func (x *FilerConf_PathConf) Reset() {
|
||||
*x = FilerConf_PathConf{}
|
||||
mi := &file_filer_proto_msgTypes[101]
|
||||
mi := &file_filer_proto_msgTypes[102]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
@@ -7166,7 +7201,7 @@ func (x *FilerConf_PathConf) String() string {
|
||||
func (*FilerConf_PathConf) ProtoMessage() {}
|
||||
|
||||
func (x *FilerConf_PathConf) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_filer_proto_msgTypes[101]
|
||||
mi := &file_filer_proto_msgTypes[102]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
@@ -7569,7 +7604,7 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"entry_name\x18\x02 \x01(\tR\tentryName\x12+\n" +
|
||||
"\x06chunks\x18\x03 \x03(\v2\x13.filer_pb.FileChunkR\x06chunks\"\x17\n" +
|
||||
"\x15AppendToEntryResponse\"\xb1\x03\n" +
|
||||
"\x15AppendToEntryResponse\"\xf2\x04\n" +
|
||||
"\x12DeleteEntryRequest\x12\x1c\n" +
|
||||
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12\x12\n" +
|
||||
"\x04name\x18\x02 \x01(\tR\x04name\x12$\n" +
|
||||
@@ -7583,7 +7618,12 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\x15if_not_modified_after\x18\t \x01(\x03R\x12ifNotModifiedAfter\x12,\n" +
|
||||
"\x12keep_remote_object\x18\n" +
|
||||
" \x01(\bR\x10keepRemoteObject\x126\n" +
|
||||
"\x18if_not_modified_after_ns\x18\v \x01(\x03R\x14ifNotModifiedAfterNs\"w\n" +
|
||||
"\x18if_not_modified_after_ns\x18\v \x01(\x03R\x14ifNotModifiedAfterNs\x12_\n" +
|
||||
"\x11expected_extended\x18\f \x03(\v22.filer_pb.DeleteEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x12\x19\n" +
|
||||
"\bis_moved\x18\r \x01(\bR\aisMoved\x1aC\n" +
|
||||
"\x15ExpectedExtendedEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"w\n" +
|
||||
"\x13DeleteEntryResponse\x12\x14\n" +
|
||||
"\x05error\x18\x01 \x01(\tR\x05error\x12J\n" +
|
||||
"\x0emetadata_event\x18\x02 \x01(\v2#.filer_pb.SubscribeMetadataResponseR\rmetadataEvent\"\xed\x01\n" +
|
||||
@@ -7862,7 +7902,7 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" +
|
||||
"\bis_moved\x18\x02 \x01(\bR\aisMoved\"-\n" +
|
||||
"\x15FindLockOwnerResponse\x12\x14\n" +
|
||||
"\x05owner\x18\x01 \x01(\tR\x05owner\"\xc4\x01\n" +
|
||||
"\x05owner\x18\x01 \x01(\tR\x05owner\"\xee\x01\n" +
|
||||
"\x04Lock\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x1f\n" +
|
||||
"\vrenew_token\x18\x02 \x01(\tR\n" +
|
||||
@@ -7873,10 +7913,11 @@ const file_filer_proto_rawDesc = "" +
|
||||
"generation\x18\x05 \x01(\x03R\n" +
|
||||
"generation\x12\x1b\n" +
|
||||
"\tis_backup\x18\x06 \x01(\bR\bisBackup\x12\x10\n" +
|
||||
"\x03seq\x18\a \x01(\x03R\x03seq\"<\n" +
|
||||
"\x03seq\x18\a \x01(\x03R\x03seq\x12(\n" +
|
||||
"\x10prev_renew_token\x18\b \x01(\tR\x0eprevRenewToken\"<\n" +
|
||||
"\x14TransferLocksRequest\x12$\n" +
|
||||
"\x05locks\x18\x01 \x03(\v2\x0e.filer_pb.LockR\x05locks\"\x17\n" +
|
||||
"\x15TransferLocksResponse\"\xd4\x01\n" +
|
||||
"\x15TransferLocksResponse\"\xfe\x01\n" +
|
||||
"\x14ReplicateLockRequest\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x1f\n" +
|
||||
"\vrenew_token\x18\x02 \x01(\tR\n" +
|
||||
@@ -7887,7 +7928,8 @@ const file_filer_proto_rawDesc = "" +
|
||||
"generation\x18\x05 \x01(\x03R\n" +
|
||||
"generation\x12\x1b\n" +
|
||||
"\tis_unlock\x18\x06 \x01(\bR\bisUnlock\x12\x10\n" +
|
||||
"\x03seq\x18\a \x01(\x03R\x03seq\"\x17\n" +
|
||||
"\x03seq\x18\a \x01(\x03R\x03seq\x12(\n" +
|
||||
"\x10prev_renew_token\x18\b \x01(\tR\x0eprevRenewToken\"\x17\n" +
|
||||
"\x15ReplicateLockResponse\"\xe6\x02\n" +
|
||||
"\x18StreamMutateEntryRequest\x12\x1d\n" +
|
||||
"\n" +
|
||||
@@ -8025,7 +8067,7 @@ func file_filer_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_filer_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
|
||||
var file_filer_proto_msgTypes = make([]protoimpl.MessageInfo, 104)
|
||||
var file_filer_proto_msgTypes = make([]protoimpl.MessageInfo, 105)
|
||||
var file_filer_proto_goTypes = []any{
|
||||
(SSEType)(0), // 0: filer_pb.SSEType
|
||||
(FilerError)(0), // 1: filer_pb.FilerError
|
||||
@@ -8131,11 +8173,12 @@ var file_filer_proto_goTypes = []any{
|
||||
nil, // 101: filer_pb.ObjectMutation.SetExtendedEntry
|
||||
nil, // 102: filer_pb.Recompute.CopyExtendedEntry
|
||||
nil, // 103: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 104: filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
(*LocateBrokerResponse_Resource)(nil), // 105: filer_pb.LocateBrokerResponse.Resource
|
||||
(*FilerConf_PathConf)(nil), // 106: filer_pb.FilerConf.PathConf
|
||||
nil, // 107: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry
|
||||
nil, // 108: filer_pb.LookupDirectoryEntriesResponse.ReadAuthEntry
|
||||
nil, // 104: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
nil, // 105: filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
(*LocateBrokerResponse_Resource)(nil), // 106: filer_pb.LocateBrokerResponse.Resource
|
||||
(*FilerConf_PathConf)(nil), // 107: filer_pb.FilerConf.PathConf
|
||||
nil, // 108: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry
|
||||
nil, // 109: filer_pb.LookupDirectoryEntriesResponse.ReadAuthEntry
|
||||
}
|
||||
var file_filer_proto_depIdxs = []int32{
|
||||
10, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
|
||||
@@ -8175,118 +8218,119 @@ var file_filer_proto_depIdxs = []int32{
|
||||
18, // 34: filer_pb.UpdateEntryRequest.condition:type_name -> filer_pb.WriteCondition
|
||||
59, // 35: filer_pb.UpdateEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
13, // 36: filer_pb.AppendToEntryRequest.chunks:type_name -> filer_pb.FileChunk
|
||||
59, // 37: filer_pb.DeleteEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
12, // 38: filer_pb.StreamRenameEntryResponse.event_notification:type_name -> filer_pb.EventNotification
|
||||
45, // 39: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
|
||||
45, // 40: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
|
||||
1, // 41: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
|
||||
45, // 42: filer_pb.Locations.locations:type_name -> filer_pb.Location
|
||||
104, // 43: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
47, // 44: filer_pb.CollectionListResponse.collections:type_name -> filer_pb.Collection
|
||||
12, // 45: filer_pb.SubscribeMetadataResponse.event_notification:type_name -> filer_pb.EventNotification
|
||||
59, // 46: filer_pb.SubscribeMetadataResponse.events:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
63, // 47: filer_pb.SubscribeMetadataResponse.log_file_refs:type_name -> filer_pb.LogFileChunkRef
|
||||
62, // 48: filer_pb.ListMetadataSubscribersResponse.subscribers:type_name -> filer_pb.MetadataSubscriber
|
||||
13, // 49: filer_pb.LogFileChunkRef.chunks:type_name -> filer_pb.FileChunk
|
||||
10, // 50: filer_pb.TraverseBfsMetadataResponse.entry:type_name -> filer_pb.Entry
|
||||
105, // 51: filer_pb.LocateBrokerResponse.resources:type_name -> filer_pb.LocateBrokerResponse.Resource
|
||||
106, // 52: filer_pb.FilerConf.locations:type_name -> filer_pb.FilerConf.PathConf
|
||||
10, // 53: filer_pb.CacheRemoteObjectToLocalClusterResponse.entry:type_name -> filer_pb.Entry
|
||||
59, // 54: filer_pb.CacheRemoteObjectToLocalClusterResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
84, // 55: filer_pb.TransferLocksRequest.locks:type_name -> filer_pb.Lock
|
||||
17, // 56: filer_pb.StreamMutateEntryRequest.create_request:type_name -> filer_pb.CreateEntryRequest
|
||||
29, // 57: filer_pb.StreamMutateEntryRequest.update_request:type_name -> filer_pb.UpdateEntryRequest
|
||||
35, // 58: filer_pb.StreamMutateEntryRequest.delete_request:type_name -> filer_pb.DeleteEntryRequest
|
||||
39, // 59: filer_pb.StreamMutateEntryRequest.rename_request:type_name -> filer_pb.StreamRenameEntryRequest
|
||||
28, // 60: filer_pb.StreamMutateEntryResponse.create_response:type_name -> filer_pb.CreateEntryResponse
|
||||
30, // 61: filer_pb.StreamMutateEntryResponse.update_response:type_name -> filer_pb.UpdateEntryResponse
|
||||
36, // 62: filer_pb.StreamMutateEntryResponse.delete_response:type_name -> filer_pb.DeleteEntryResponse
|
||||
40, // 63: filer_pb.StreamMutateEntryResponse.rename_response:type_name -> filer_pb.StreamRenameEntryResponse
|
||||
95, // 64: filer_pb.MountListResponse.mounts:type_name -> filer_pb.MountInfo
|
||||
5, // 65: filer_pb.LookupDirectoryEntriesRequest.requests:type_name -> filer_pb.LookupDirectoryEntryRequest
|
||||
10, // 66: filer_pb.LookupDirectoryEntryResult.entry:type_name -> filer_pb.Entry
|
||||
97, // 67: filer_pb.LookupDirectoryEntriesResponse.results:type_name -> filer_pb.LookupDirectoryEntryResult
|
||||
107, // 68: filer_pb.LookupDirectoryEntriesResponse.locations_map:type_name -> filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry
|
||||
108, // 69: filer_pb.LookupDirectoryEntriesResponse.read_auth:type_name -> filer_pb.LookupDirectoryEntriesResponse.ReadAuthEntry
|
||||
3, // 70: filer_pb.WriteCondition.Clause.kind:type_name -> filer_pb.WriteCondition.Kind
|
||||
10, // 71: filer_pb.WriteCondition.Clause.expected_entry:type_name -> filer_pb.Entry
|
||||
44, // 72: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
44, // 73: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
5, // 74: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
96, // 75: filer_pb.SeaweedFiler.LookupDirectoryEntries:input_type -> filer_pb.LookupDirectoryEntriesRequest
|
||||
7, // 76: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
17, // 77: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
29, // 78: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
31, // 79: filer_pb.SeaweedFiler.TouchAccessTime:input_type -> filer_pb.TouchAccessTimeRequest
|
||||
33, // 80: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
|
||||
35, // 81: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
21, // 82: filer_pb.SeaweedFiler.ObjectTransaction:input_type -> filer_pb.ObjectTransactionRequest
|
||||
26, // 83: filer_pb.SeaweedFiler.ObjectTransactionBatch:input_type -> filer_pb.ObjectTransactionBatchRequest
|
||||
24, // 84: filer_pb.SeaweedFiler.PosixLock:input_type -> filer_pb.PosixLockRequest
|
||||
37, // 85: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
|
||||
39, // 86: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
|
||||
89, // 87: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
|
||||
41, // 88: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
43, // 89: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
48, // 90: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
|
||||
50, // 91: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
|
||||
52, // 92: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
|
||||
54, // 93: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
|
||||
56, // 94: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
64, // 95: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
|
||||
58, // 96: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
58, // 97: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
60, // 98: filer_pb.SeaweedFiler.ListMetadataSubscribers:input_type -> filer_pb.ListMetadataSubscribersRequest
|
||||
71, // 99: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
|
||||
73, // 100: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
|
||||
76, // 101: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
|
||||
78, // 102: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
|
||||
80, // 103: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
|
||||
82, // 104: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
|
||||
85, // 105: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
|
||||
87, // 106: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
|
||||
91, // 107: filer_pb.SeaweedFiler.MountRegister:input_type -> filer_pb.MountRegisterRequest
|
||||
93, // 108: filer_pb.SeaweedFiler.MountList:input_type -> filer_pb.MountListRequest
|
||||
6, // 109: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
98, // 110: filer_pb.SeaweedFiler.LookupDirectoryEntries:output_type -> filer_pb.LookupDirectoryEntriesResponse
|
||||
8, // 111: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
28, // 112: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
30, // 113: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
32, // 114: filer_pb.SeaweedFiler.TouchAccessTime:output_type -> filer_pb.TouchAccessTimeResponse
|
||||
34, // 115: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
|
||||
36, // 116: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
22, // 117: filer_pb.SeaweedFiler.ObjectTransaction:output_type -> filer_pb.ObjectTransactionResponse
|
||||
27, // 118: filer_pb.SeaweedFiler.ObjectTransactionBatch:output_type -> filer_pb.ObjectTransactionBatchResponse
|
||||
25, // 119: filer_pb.SeaweedFiler.PosixLock:output_type -> filer_pb.PosixLockResponse
|
||||
38, // 120: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
|
||||
40, // 121: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
|
||||
90, // 122: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
|
||||
42, // 123: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
46, // 124: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
49, // 125: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
|
||||
51, // 126: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
|
||||
53, // 127: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
|
||||
55, // 128: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
|
||||
57, // 129: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
65, // 130: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
|
||||
59, // 131: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
59, // 132: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
61, // 133: filer_pb.SeaweedFiler.ListMetadataSubscribers:output_type -> filer_pb.ListMetadataSubscribersResponse
|
||||
72, // 134: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
|
||||
74, // 135: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
|
||||
77, // 136: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
|
||||
79, // 137: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
|
||||
81, // 138: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
|
||||
83, // 139: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
|
||||
86, // 140: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
|
||||
88, // 141: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
|
||||
92, // 142: filer_pb.SeaweedFiler.MountRegister:output_type -> filer_pb.MountRegisterResponse
|
||||
94, // 143: filer_pb.SeaweedFiler.MountList:output_type -> filer_pb.MountListResponse
|
||||
109, // [109:144] is the sub-list for method output_type
|
||||
74, // [74:109] is the sub-list for method input_type
|
||||
74, // [74:74] is the sub-list for extension type_name
|
||||
74, // [74:74] is the sub-list for extension extendee
|
||||
0, // [0:74] is the sub-list for field type_name
|
||||
104, // 37: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
|
||||
59, // 38: filer_pb.DeleteEntryResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
12, // 39: filer_pb.StreamRenameEntryResponse.event_notification:type_name -> filer_pb.EventNotification
|
||||
45, // 40: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
|
||||
45, // 41: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
|
||||
1, // 42: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
|
||||
45, // 43: filer_pb.Locations.locations:type_name -> filer_pb.Location
|
||||
105, // 44: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
|
||||
47, // 45: filer_pb.CollectionListResponse.collections:type_name -> filer_pb.Collection
|
||||
12, // 46: filer_pb.SubscribeMetadataResponse.event_notification:type_name -> filer_pb.EventNotification
|
||||
59, // 47: filer_pb.SubscribeMetadataResponse.events:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
63, // 48: filer_pb.SubscribeMetadataResponse.log_file_refs:type_name -> filer_pb.LogFileChunkRef
|
||||
62, // 49: filer_pb.ListMetadataSubscribersResponse.subscribers:type_name -> filer_pb.MetadataSubscriber
|
||||
13, // 50: filer_pb.LogFileChunkRef.chunks:type_name -> filer_pb.FileChunk
|
||||
10, // 51: filer_pb.TraverseBfsMetadataResponse.entry:type_name -> filer_pb.Entry
|
||||
106, // 52: filer_pb.LocateBrokerResponse.resources:type_name -> filer_pb.LocateBrokerResponse.Resource
|
||||
107, // 53: filer_pb.FilerConf.locations:type_name -> filer_pb.FilerConf.PathConf
|
||||
10, // 54: filer_pb.CacheRemoteObjectToLocalClusterResponse.entry:type_name -> filer_pb.Entry
|
||||
59, // 55: filer_pb.CacheRemoteObjectToLocalClusterResponse.metadata_event:type_name -> filer_pb.SubscribeMetadataResponse
|
||||
84, // 56: filer_pb.TransferLocksRequest.locks:type_name -> filer_pb.Lock
|
||||
17, // 57: filer_pb.StreamMutateEntryRequest.create_request:type_name -> filer_pb.CreateEntryRequest
|
||||
29, // 58: filer_pb.StreamMutateEntryRequest.update_request:type_name -> filer_pb.UpdateEntryRequest
|
||||
35, // 59: filer_pb.StreamMutateEntryRequest.delete_request:type_name -> filer_pb.DeleteEntryRequest
|
||||
39, // 60: filer_pb.StreamMutateEntryRequest.rename_request:type_name -> filer_pb.StreamRenameEntryRequest
|
||||
28, // 61: filer_pb.StreamMutateEntryResponse.create_response:type_name -> filer_pb.CreateEntryResponse
|
||||
30, // 62: filer_pb.StreamMutateEntryResponse.update_response:type_name -> filer_pb.UpdateEntryResponse
|
||||
36, // 63: filer_pb.StreamMutateEntryResponse.delete_response:type_name -> filer_pb.DeleteEntryResponse
|
||||
40, // 64: filer_pb.StreamMutateEntryResponse.rename_response:type_name -> filer_pb.StreamRenameEntryResponse
|
||||
95, // 65: filer_pb.MountListResponse.mounts:type_name -> filer_pb.MountInfo
|
||||
5, // 66: filer_pb.LookupDirectoryEntriesRequest.requests:type_name -> filer_pb.LookupDirectoryEntryRequest
|
||||
10, // 67: filer_pb.LookupDirectoryEntryResult.entry:type_name -> filer_pb.Entry
|
||||
97, // 68: filer_pb.LookupDirectoryEntriesResponse.results:type_name -> filer_pb.LookupDirectoryEntryResult
|
||||
108, // 69: filer_pb.LookupDirectoryEntriesResponse.locations_map:type_name -> filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry
|
||||
109, // 70: filer_pb.LookupDirectoryEntriesResponse.read_auth:type_name -> filer_pb.LookupDirectoryEntriesResponse.ReadAuthEntry
|
||||
3, // 71: filer_pb.WriteCondition.Clause.kind:type_name -> filer_pb.WriteCondition.Kind
|
||||
10, // 72: filer_pb.WriteCondition.Clause.expected_entry:type_name -> filer_pb.Entry
|
||||
44, // 73: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
44, // 74: filer_pb.LookupDirectoryEntriesResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
|
||||
5, // 75: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
|
||||
96, // 76: filer_pb.SeaweedFiler.LookupDirectoryEntries:input_type -> filer_pb.LookupDirectoryEntriesRequest
|
||||
7, // 77: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
|
||||
17, // 78: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
|
||||
29, // 79: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
|
||||
31, // 80: filer_pb.SeaweedFiler.TouchAccessTime:input_type -> filer_pb.TouchAccessTimeRequest
|
||||
33, // 81: filer_pb.SeaweedFiler.AppendToEntry:input_type -> filer_pb.AppendToEntryRequest
|
||||
35, // 82: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
|
||||
21, // 83: filer_pb.SeaweedFiler.ObjectTransaction:input_type -> filer_pb.ObjectTransactionRequest
|
||||
26, // 84: filer_pb.SeaweedFiler.ObjectTransactionBatch:input_type -> filer_pb.ObjectTransactionBatchRequest
|
||||
24, // 85: filer_pb.SeaweedFiler.PosixLock:input_type -> filer_pb.PosixLockRequest
|
||||
37, // 86: filer_pb.SeaweedFiler.AtomicRenameEntry:input_type -> filer_pb.AtomicRenameEntryRequest
|
||||
39, // 87: filer_pb.SeaweedFiler.StreamRenameEntry:input_type -> filer_pb.StreamRenameEntryRequest
|
||||
89, // 88: filer_pb.SeaweedFiler.StreamMutateEntry:input_type -> filer_pb.StreamMutateEntryRequest
|
||||
41, // 89: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
|
||||
43, // 90: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
|
||||
48, // 91: filer_pb.SeaweedFiler.CollectionList:input_type -> filer_pb.CollectionListRequest
|
||||
50, // 92: filer_pb.SeaweedFiler.DeleteCollection:input_type -> filer_pb.DeleteCollectionRequest
|
||||
52, // 93: filer_pb.SeaweedFiler.Statistics:input_type -> filer_pb.StatisticsRequest
|
||||
54, // 94: filer_pb.SeaweedFiler.Ping:input_type -> filer_pb.PingRequest
|
||||
56, // 95: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
|
||||
64, // 96: filer_pb.SeaweedFiler.TraverseBfsMetadata:input_type -> filer_pb.TraverseBfsMetadataRequest
|
||||
58, // 97: filer_pb.SeaweedFiler.SubscribeMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
58, // 98: filer_pb.SeaweedFiler.SubscribeLocalMetadata:input_type -> filer_pb.SubscribeMetadataRequest
|
||||
60, // 99: filer_pb.SeaweedFiler.ListMetadataSubscribers:input_type -> filer_pb.ListMetadataSubscribersRequest
|
||||
71, // 100: filer_pb.SeaweedFiler.KvGet:input_type -> filer_pb.KvGetRequest
|
||||
73, // 101: filer_pb.SeaweedFiler.KvPut:input_type -> filer_pb.KvPutRequest
|
||||
76, // 102: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:input_type -> filer_pb.CacheRemoteObjectToLocalClusterRequest
|
||||
78, // 103: filer_pb.SeaweedFiler.DistributedLock:input_type -> filer_pb.LockRequest
|
||||
80, // 104: filer_pb.SeaweedFiler.DistributedUnlock:input_type -> filer_pb.UnlockRequest
|
||||
82, // 105: filer_pb.SeaweedFiler.FindLockOwner:input_type -> filer_pb.FindLockOwnerRequest
|
||||
85, // 106: filer_pb.SeaweedFiler.TransferLocks:input_type -> filer_pb.TransferLocksRequest
|
||||
87, // 107: filer_pb.SeaweedFiler.ReplicateLock:input_type -> filer_pb.ReplicateLockRequest
|
||||
91, // 108: filer_pb.SeaweedFiler.MountRegister:input_type -> filer_pb.MountRegisterRequest
|
||||
93, // 109: filer_pb.SeaweedFiler.MountList:input_type -> filer_pb.MountListRequest
|
||||
6, // 110: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
|
||||
98, // 111: filer_pb.SeaweedFiler.LookupDirectoryEntries:output_type -> filer_pb.LookupDirectoryEntriesResponse
|
||||
8, // 112: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
|
||||
28, // 113: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
|
||||
30, // 114: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
|
||||
32, // 115: filer_pb.SeaweedFiler.TouchAccessTime:output_type -> filer_pb.TouchAccessTimeResponse
|
||||
34, // 116: filer_pb.SeaweedFiler.AppendToEntry:output_type -> filer_pb.AppendToEntryResponse
|
||||
36, // 117: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
|
||||
22, // 118: filer_pb.SeaweedFiler.ObjectTransaction:output_type -> filer_pb.ObjectTransactionResponse
|
||||
27, // 119: filer_pb.SeaweedFiler.ObjectTransactionBatch:output_type -> filer_pb.ObjectTransactionBatchResponse
|
||||
25, // 120: filer_pb.SeaweedFiler.PosixLock:output_type -> filer_pb.PosixLockResponse
|
||||
38, // 121: filer_pb.SeaweedFiler.AtomicRenameEntry:output_type -> filer_pb.AtomicRenameEntryResponse
|
||||
40, // 122: filer_pb.SeaweedFiler.StreamRenameEntry:output_type -> filer_pb.StreamRenameEntryResponse
|
||||
90, // 123: filer_pb.SeaweedFiler.StreamMutateEntry:output_type -> filer_pb.StreamMutateEntryResponse
|
||||
42, // 124: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
|
||||
46, // 125: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
|
||||
49, // 126: filer_pb.SeaweedFiler.CollectionList:output_type -> filer_pb.CollectionListResponse
|
||||
51, // 127: filer_pb.SeaweedFiler.DeleteCollection:output_type -> filer_pb.DeleteCollectionResponse
|
||||
53, // 128: filer_pb.SeaweedFiler.Statistics:output_type -> filer_pb.StatisticsResponse
|
||||
55, // 129: filer_pb.SeaweedFiler.Ping:output_type -> filer_pb.PingResponse
|
||||
57, // 130: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
|
||||
65, // 131: filer_pb.SeaweedFiler.TraverseBfsMetadata:output_type -> filer_pb.TraverseBfsMetadataResponse
|
||||
59, // 132: filer_pb.SeaweedFiler.SubscribeMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
59, // 133: filer_pb.SeaweedFiler.SubscribeLocalMetadata:output_type -> filer_pb.SubscribeMetadataResponse
|
||||
61, // 134: filer_pb.SeaweedFiler.ListMetadataSubscribers:output_type -> filer_pb.ListMetadataSubscribersResponse
|
||||
72, // 135: filer_pb.SeaweedFiler.KvGet:output_type -> filer_pb.KvGetResponse
|
||||
74, // 136: filer_pb.SeaweedFiler.KvPut:output_type -> filer_pb.KvPutResponse
|
||||
77, // 137: filer_pb.SeaweedFiler.CacheRemoteObjectToLocalCluster:output_type -> filer_pb.CacheRemoteObjectToLocalClusterResponse
|
||||
79, // 138: filer_pb.SeaweedFiler.DistributedLock:output_type -> filer_pb.LockResponse
|
||||
81, // 139: filer_pb.SeaweedFiler.DistributedUnlock:output_type -> filer_pb.UnlockResponse
|
||||
83, // 140: filer_pb.SeaweedFiler.FindLockOwner:output_type -> filer_pb.FindLockOwnerResponse
|
||||
86, // 141: filer_pb.SeaweedFiler.TransferLocks:output_type -> filer_pb.TransferLocksResponse
|
||||
88, // 142: filer_pb.SeaweedFiler.ReplicateLock:output_type -> filer_pb.ReplicateLockResponse
|
||||
92, // 143: filer_pb.SeaweedFiler.MountRegister:output_type -> filer_pb.MountRegisterResponse
|
||||
94, // 144: filer_pb.SeaweedFiler.MountList:output_type -> filer_pb.MountListResponse
|
||||
110, // [110:145] is the sub-list for method output_type
|
||||
75, // [75:110] is the sub-list for method input_type
|
||||
75, // [75:75] is the sub-list for extension type_name
|
||||
75, // [75:75] is the sub-list for extension extendee
|
||||
0, // [0:75] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_filer_proto_init() }
|
||||
@@ -8307,14 +8351,14 @@ func file_filer_proto_init() {
|
||||
(*StreamMutateEntryResponse_DeleteResponse)(nil),
|
||||
(*StreamMutateEntryResponse_RenameResponse)(nil),
|
||||
}
|
||||
file_filer_proto_msgTypes[101].OneofWrappers = []any{}
|
||||
file_filer_proto_msgTypes[102].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_proto_rawDesc), len(file_filer_proto_rawDesc)),
|
||||
NumEnums: 5,
|
||||
NumMessages: 104,
|
||||
NumMessages: 105,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v3.21.12
|
||||
// - protoc v7.35.0
|
||||
// source: filer.proto
|
||||
|
||||
package filer_pb
|
||||
|
||||
@@ -2491,6 +2491,35 @@ func (m *DeleteEntryRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
|
||||
i -= len(m.unknownFields)
|
||||
copy(dAtA[i:], m.unknownFields)
|
||||
}
|
||||
if m.IsMoved {
|
||||
i--
|
||||
if m.IsMoved {
|
||||
dAtA[i] = 1
|
||||
} else {
|
||||
dAtA[i] = 0
|
||||
}
|
||||
i--
|
||||
dAtA[i] = 0x68
|
||||
}
|
||||
if len(m.ExpectedExtended) > 0 {
|
||||
for k := range m.ExpectedExtended {
|
||||
v := m.ExpectedExtended[k]
|
||||
baseI := i
|
||||
i -= len(v)
|
||||
copy(dAtA[i:], v)
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(len(v)))
|
||||
i--
|
||||
dAtA[i] = 0x12
|
||||
i -= len(k)
|
||||
copy(dAtA[i:], k)
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(len(k)))
|
||||
i--
|
||||
dAtA[i] = 0xa
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(baseI-i))
|
||||
i--
|
||||
dAtA[i] = 0x62
|
||||
}
|
||||
}
|
||||
if m.IfNotModifiedAfterNs != 0 {
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.IfNotModifiedAfterNs))
|
||||
i--
|
||||
@@ -5586,6 +5615,13 @@ func (m *Lock) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
|
||||
i -= len(m.unknownFields)
|
||||
copy(dAtA[i:], m.unknownFields)
|
||||
}
|
||||
if len(m.PrevRenewToken) > 0 {
|
||||
i -= len(m.PrevRenewToken)
|
||||
copy(dAtA[i:], m.PrevRenewToken)
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(len(m.PrevRenewToken)))
|
||||
i--
|
||||
dAtA[i] = 0x42
|
||||
}
|
||||
if m.Seq != 0 {
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.Seq))
|
||||
i--
|
||||
@@ -5743,6 +5779,13 @@ func (m *ReplicateLockRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error)
|
||||
i -= len(m.unknownFields)
|
||||
copy(dAtA[i:], m.unknownFields)
|
||||
}
|
||||
if len(m.PrevRenewToken) > 0 {
|
||||
i -= len(m.PrevRenewToken)
|
||||
copy(dAtA[i:], m.PrevRenewToken)
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(len(m.PrevRenewToken)))
|
||||
i--
|
||||
dAtA[i] = 0x42
|
||||
}
|
||||
if m.Seq != 0 {
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.Seq))
|
||||
i--
|
||||
@@ -7579,6 +7622,18 @@ func (m *DeleteEntryRequest) SizeVT() (n int) {
|
||||
if m.IfNotModifiedAfterNs != 0 {
|
||||
n += 1 + protohelpers.SizeOfVarint(uint64(m.IfNotModifiedAfterNs))
|
||||
}
|
||||
if len(m.ExpectedExtended) > 0 {
|
||||
for k, v := range m.ExpectedExtended {
|
||||
_ = k
|
||||
_ = v
|
||||
l = 1 + len(v) + protohelpers.SizeOfVarint(uint64(len(v)))
|
||||
mapEntrySize := 1 + len(k) + protohelpers.SizeOfVarint(uint64(len(k))) + l
|
||||
n += mapEntrySize + 1 + protohelpers.SizeOfVarint(uint64(mapEntrySize))
|
||||
}
|
||||
}
|
||||
if m.IsMoved {
|
||||
n += 2
|
||||
}
|
||||
n += len(m.unknownFields)
|
||||
return n
|
||||
}
|
||||
@@ -8802,6 +8857,10 @@ func (m *Lock) SizeVT() (n int) {
|
||||
if m.Seq != 0 {
|
||||
n += 1 + protohelpers.SizeOfVarint(uint64(m.Seq))
|
||||
}
|
||||
l = len(m.PrevRenewToken)
|
||||
if l > 0 {
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
}
|
||||
n += len(m.unknownFields)
|
||||
return n
|
||||
}
|
||||
@@ -8862,6 +8921,10 @@ func (m *ReplicateLockRequest) SizeVT() (n int) {
|
||||
if m.Seq != 0 {
|
||||
n += 1 + protohelpers.SizeOfVarint(uint64(m.Seq))
|
||||
}
|
||||
l = len(m.PrevRenewToken)
|
||||
if l > 0 {
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
}
|
||||
n += len(m.unknownFields)
|
||||
return n
|
||||
}
|
||||
@@ -16232,6 +16295,154 @@ func (m *DeleteEntryRequest) UnmarshalVT(dAtA []byte) error {
|
||||
break
|
||||
}
|
||||
}
|
||||
case 12:
|
||||
if wireType != 2 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field ExpectedExtended", wireType)
|
||||
}
|
||||
var msglen int
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
msglen |= int(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if msglen < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postIndex := iNdEx + msglen
|
||||
if postIndex < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postIndex > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if m.ExpectedExtended == nil {
|
||||
m.ExpectedExtended = make(map[string][]byte)
|
||||
}
|
||||
var mapkey string
|
||||
var mapvalue []byte
|
||||
for iNdEx < postIndex {
|
||||
entryPreIndex := iNdEx
|
||||
var wire uint64
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
wire |= uint64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
fieldNum := int32(wire >> 3)
|
||||
if fieldNum == 1 {
|
||||
var stringLenmapkey uint64
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
stringLenmapkey |= uint64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
intStringLenmapkey := int(stringLenmapkey)
|
||||
if intStringLenmapkey < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postStringIndexmapkey := iNdEx + intStringLenmapkey
|
||||
if postStringIndexmapkey < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postStringIndexmapkey > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
|
||||
iNdEx = postStringIndexmapkey
|
||||
} else if fieldNum == 2 {
|
||||
var mapbyteLen uint64
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
mapbyteLen |= uint64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
intMapbyteLen := int(mapbyteLen)
|
||||
if intMapbyteLen < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postbytesIndex := iNdEx + intMapbyteLen
|
||||
if postbytesIndex < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postbytesIndex > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
mapvalue = make([]byte, mapbyteLen)
|
||||
copy(mapvalue, dAtA[iNdEx:postbytesIndex])
|
||||
iNdEx = postbytesIndex
|
||||
} else {
|
||||
iNdEx = entryPreIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if (skippy < 0) || (iNdEx+skippy) < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if (iNdEx + skippy) > postIndex {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
iNdEx += skippy
|
||||
}
|
||||
}
|
||||
m.ExpectedExtended[mapkey] = mapvalue
|
||||
iNdEx = postIndex
|
||||
case 13:
|
||||
if wireType != 0 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field IsMoved", wireType)
|
||||
}
|
||||
var v int
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
v |= int(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
m.IsMoved = bool(v != 0)
|
||||
default:
|
||||
iNdEx = preIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
@@ -24074,6 +24285,38 @@ func (m *Lock) UnmarshalVT(dAtA []byte) error {
|
||||
break
|
||||
}
|
||||
}
|
||||
case 8:
|
||||
if wireType != 2 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field PrevRenewToken", wireType)
|
||||
}
|
||||
var stringLen uint64
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
stringLen |= uint64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
intStringLen := int(stringLen)
|
||||
if intStringLen < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postIndex := iNdEx + intStringLen
|
||||
if postIndex < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postIndex > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
m.PrevRenewToken = string(dAtA[iNdEx:postIndex])
|
||||
iNdEx = postIndex
|
||||
default:
|
||||
iNdEx = preIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
@@ -24434,6 +24677,38 @@ func (m *ReplicateLockRequest) UnmarshalVT(dAtA []byte) error {
|
||||
break
|
||||
}
|
||||
}
|
||||
case 8:
|
||||
if wireType != 2 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field PrevRenewToken", wireType)
|
||||
}
|
||||
var stringLen uint64
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
stringLen |= uint64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
intStringLen := int(stringLen)
|
||||
if intStringLen < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
postIndex := iNdEx + intStringLen
|
||||
if postIndex < 0 {
|
||||
return protohelpers.ErrInvalidLength
|
||||
}
|
||||
if postIndex > l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
m.PrevRenewToken = string(dAtA[iNdEx:postIndex])
|
||||
iNdEx = postIndex
|
||||
default:
|
||||
iNdEx = preIndex
|
||||
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
|
||||
|
||||
@@ -272,7 +272,7 @@ func GrpcDial(ctx context.Context, address string, waitForReady bool, opts ...gr
|
||||
return grpc.DialContext(ctx, address, options...)
|
||||
}
|
||||
|
||||
func getOrCreateConnection(ctx context.Context, address string, waitForReady bool, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
|
||||
func getOrCreateConnection(address string, waitForReady bool, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
|
||||
|
||||
grpcClientsLock.Lock()
|
||||
defer grpcClientsLock.Unlock()
|
||||
@@ -284,6 +284,7 @@ func getOrCreateConnection(ctx context.Context, address string, waitForReady boo
|
||||
}
|
||||
|
||||
glog.V(2).Infof("Creating new gRPC connection to %s", address)
|
||||
ctx := context.Background()
|
||||
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to dial %s: %v", address, err)
|
||||
@@ -467,16 +468,15 @@ func shouldInvalidateConnection(ctx context.Context, err error) bool {
|
||||
}
|
||||
|
||||
// WithGrpcClient In streamingMode, always use a fresh connection. Otherwise, try to reuse an existing connection.
|
||||
// ctx must be the context that bounds this call's connection acquisition and
|
||||
// the RPC fn issues, so that a Canceled/DeadlineExceeded fired by ctx itself
|
||||
// does not tear down the shared cached ClientConn out from under other
|
||||
// concurrent callers. Pass context.Background() when fn picks its own
|
||||
// context: a Canceled/DeadlineExceeded then never invalidates, since nothing
|
||||
// here can attribute it to the channel.
|
||||
// ctx must be the context that bounds the RPC fn issues, so that a
|
||||
// Canceled/DeadlineExceeded fired by ctx itself does not tear down the shared
|
||||
// cached ClientConn out from under other concurrent callers. Pass
|
||||
// context.Background() when fn picks its own context: a Canceled/DeadlineExceeded
|
||||
// then never invalidates, since nothing here can attribute it to the channel.
|
||||
func WithGrpcClient(ctx context.Context, streamingMode bool, signature int32, fn func(*grpc.ClientConn) error, address string, waitForReady bool, opts ...grpc.DialOption) error {
|
||||
|
||||
if !streamingMode {
|
||||
vgc, err := getOrCreateConnection(ctx, address, waitForReady, opts...)
|
||||
vgc, err := getOrCreateConnection(address, waitForReady, opts...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
|
||||
}
|
||||
@@ -498,7 +498,7 @@ func WithGrpcClient(ctx context.Context, streamingMode bool, signature int32, fn
|
||||
}
|
||||
|
||||
// Streaming mode: dedicate a fresh ClientConn to this call.
|
||||
dialCtx := ctx
|
||||
dialCtx := context.Background()
|
||||
if signature != 0 {
|
||||
// Optimize: Use AppendToOutgoingContext instead of creating new map
|
||||
dialCtx = metadata.AppendToOutgoingContext(dialCtx, "sw-client-id", fmt.Sprintf("%d", signature))
|
||||
|
||||
@@ -526,13 +526,18 @@ func (s *s3RemoteStorageClient) RemoveDirectory(loc *remote_pb.RemoteStorageLoca
|
||||
return true
|
||||
}
|
||||
// a listing page holds at most 1000 keys, the DeleteObjects limit
|
||||
resp, batchErr := s.conn.DeleteObjects(&s3.DeleteObjectsInput{
|
||||
req, resp := s.conn.DeleteObjectsRequest(&s3.DeleteObjectsInput{
|
||||
Bucket: aws.String(loc.Bucket),
|
||||
Delete: &s3.Delete{
|
||||
Objects: objects,
|
||||
Quiet: aws.Bool(true),
|
||||
},
|
||||
})
|
||||
// the client-level S3DisableContentMD5Validation also drops the
|
||||
// Content-MD5 header this operation requires; the request config is a
|
||||
// copy, so re-enabling it here leaves other operations untouched
|
||||
req.Config.S3DisableContentMD5Validation = aws.Bool(false)
|
||||
batchErr := req.Send()
|
||||
if batchErr != nil {
|
||||
deleteErr = batchErr
|
||||
return false
|
||||
|
||||
@@ -3,6 +3,8 @@ package s3
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -11,7 +13,9 @@ import (
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/aws/client/metadata"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/request"
|
||||
awss3 "github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3iface"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -165,15 +169,16 @@ func (m *removeDirectoryMock) ListObjectsV2Pages(input *awss3.ListObjectsV2Input
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *removeDirectoryMock) DeleteObjects(input *awss3.DeleteObjectsInput) (*awss3.DeleteObjectsOutput, error) {
|
||||
func (m *removeDirectoryMock) DeleteObjectsRequest(input *awss3.DeleteObjectsInput) (*request.Request, *awss3.DeleteObjectsOutput) {
|
||||
m.deleteInputs = append(m.deleteInputs, input)
|
||||
if m.deleteErr != nil {
|
||||
return nil, m.deleteErr
|
||||
out := m.deleteResp
|
||||
if out == nil {
|
||||
out = &awss3.DeleteObjectsOutput{}
|
||||
}
|
||||
if m.deleteResp != nil {
|
||||
return m.deleteResp, nil
|
||||
}
|
||||
return &awss3.DeleteObjectsOutput{}, nil
|
||||
req := request.New(aws.Config{}, metadata.ClientInfo{}, request.Handlers{}, nil,
|
||||
&request.Operation{Name: "DeleteObjects"}, input, out)
|
||||
req.Error = m.deleteErr
|
||||
return req, out
|
||||
}
|
||||
|
||||
func listPage(keys ...string) *awss3.ListObjectsV2Output {
|
||||
@@ -264,6 +269,43 @@ func TestS3RemoveDirectoryReturnsPerKeyError(t *testing.T) {
|
||||
require.ErrorContains(t, err, "testdir/a.bin")
|
||||
}
|
||||
|
||||
// deleteObjectsProbe answers the listing and delete calls RemoveDirectory
|
||||
// makes against a real *s3.S3 client, and captures the DeleteObjects request
|
||||
// so the test can check the Content-MD5 header AWS requires.
|
||||
type deleteObjectsProbe struct {
|
||||
deleteReq *http.Request
|
||||
deleteBody []byte
|
||||
}
|
||||
|
||||
func (c *deleteObjectsProbe) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
body := `<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Contents><Key>testdir/a.bin</Key></Contents></ListBucketResult>`
|
||||
if strings.Contains(req.URL.RawQuery, "delete") {
|
||||
c.deleteReq = req.Clone(req.Context())
|
||||
if req.Body != nil {
|
||||
c.deleteBody, _ = io.ReadAll(req.Body)
|
||||
_ = req.Body.Close()
|
||||
}
|
||||
body = `<DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Header: http.Header{},
|
||||
Request: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestS3RemoveDirectorySendsContentMD5(t *testing.T) {
|
||||
rt := &deleteObjectsProbe{}
|
||||
client := newS3ClientWithTransport(t, rt, false)
|
||||
loc := &remote_pb.RemoteStorageLocation{Name: "test", Bucket: "bucket", Path: "/testdir"}
|
||||
|
||||
require.NoError(t, client.RemoveDirectory(loc))
|
||||
require.NotNil(t, rt.deleteReq, "DeleteObjects should be issued for the listed keys")
|
||||
sum := md5.Sum(rt.deleteBody)
|
||||
require.Equal(t, base64.StdEncoding.EncodeToString(sum[:]), rt.deleteReq.Header.Get("Content-Md5"))
|
||||
}
|
||||
|
||||
// captureRoundTripper records the PUT request that the s3manager uploader
|
||||
// sends, and short-circuits all calls with a 200 so the SDK is satisfied.
|
||||
type captureRoundTripper struct {
|
||||
|
||||
@@ -68,6 +68,21 @@ func TestCheckAccessByOwnershipDeniesNonOwner(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrNone, s3a.checkAccessByOwnership(owner, "b"), "the actual owner is still allowed")
|
||||
}
|
||||
|
||||
// With auth off nobody has an account id, so the owner check must not deny:
|
||||
// GetBucketOwnershipControls and friends answered AccessDenied to every caller.
|
||||
func TestCheckAccessByOwnershipAllowsWhenAuthDisabled(t *testing.T) {
|
||||
adminOwner := AccountAdmin.Id
|
||||
s3a := &S3ApiServer{
|
||||
bucketRegistry: NewBucketRegistry(nil),
|
||||
iam: &IdentityAccessManagement{},
|
||||
}
|
||||
require.False(t, s3a.iam.isEnabled())
|
||||
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: "b", Owner: &s3.Owner{ID: &adminOwner}})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/b?ownershipControls=", nil)
|
||||
assert.Equal(t, s3err.ErrNone, s3a.checkAccessByOwnership(req, "b"))
|
||||
}
|
||||
|
||||
// An account-less identity's synthesized account must be registered in the
|
||||
// account lookup so its id resolves to a display name. Otherwise ACL grantee
|
||||
// validation and owner display report the id as "not exists" — the regression
|
||||
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user